Tags: aes-cbc 

Rating: 4.6

# __Kaspersky Industrial CTF Quals 2017.__
## __decrypt the message__

## Information
**Category:** Crypto
**Points:** 700
**Description:**
> Could your decrypt the message? http://95.85.51.183

## Solution

All we have is a web page asking for a name and setting some strange cookie (obviously, in base64).

![cooikie](./images/cookie.png)

Decrypting it doesn't give anything, so let's try to vary name and cookie.
Varying the cookie we may bump into exception with a plenty of useful information.
```
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/var/www/FlaskApp/FlaskApp/__init__.py", line 53, in index
user_info_decrypted = json.loads(aes_decrypt(user_info).decode())
File "/var/www/FlaskApp/FlaskApp/__init__.py", line 35, in aes_decrypt
return unpad(cipher.decrypt( enc[16:] ))
File "/var/www/FlaskApp/FlaskApp/__init__.py", line 23, in unpad
return s[:-ord(s[-1])]
IndexError: string index out of range
```

From here we know that server uses Python 2.7 with Flask, it decrypts user data, decodes it into a string and loads into json. Function name (aes_decrypt) shows us the direction of research. Researching different tracebacks we find this line.

```
File "/var/www/FlaskApp/FlaskApp/__init__.py", line 34, in aes_decrypt
cipher = AES.new(base64.b64decode(hardcoded_key), AES.MODE_CBC, iv )
```

So, we finally know that cipher is AES CBC. The most popular attack on it that can be googled is [Padding Oracle Attack](https://blog.gdssecurity.com/labs/2010/9/14/automated-padding-oracle-attacks-with-padbuster.html). Trying automated scripts doesn't make any sense, so let's try to repeat something similar.

#### A piece of theory

After decoding the cookie we get a bytestring 64 bytes long.
``` \xa1d\xd6"\xdc1\x00R\r@\x1a\xe8\xcd4\x8d\xa9m\xaa\xe0{\x9c;\xa9\xc5\x8d?\x92HS-\xe2c\xbd\xe09\xb83\xe7q1)-\x89\x1b\xfe\xf3\xcbU\xb7\xcd\xbb)2\xd0\xad\xbb\xba\xbfef\x92/NK ```

AES CBC is block cipher, knowing the block size is 16 (wich we know from another traceback), we understand that first block is [IV](https://en.wikipedia.org/wiki/Initialization_vector), while three others are data (and the last block is padded).

The first thing we try is bruteforcing IV byte by byte (starting from first) and concating it with the rest of ciphertext using simple script.

```py
import requests
from base64 import b64encode, b64decode

def main():
ciphertext = 'oWTWItwxAFINQBrozTSNqW2q4HucO6nFjT+SSFMt4mO94Dm4M+dxMSktiRv+88tVt827KTLQrbu6v2Vmki9OSw=='
decoded_cipher = b64decode(ciphertext)
for pos in range(0, 16):
for i in range(0, 256):
data = decoded_cipher[:pos] + bytes([i]) + decoded_cipher[pos + 1:]
make_request(b64encode(data).decode())

def make_request(cookie):
url = 'http://95.85.51.183/'
headers = {'Cookie': 'user_info={}'.format(cookie)}
r = requests.get(url, headers=headers)
print(r.text[-100:])

if __name__ == '__main__':
main()
```

What we receive are exception messages
```
UnicodeDecodeError: 'ascii' codec can't decode byte 0xda in position 0: ordinal not in range(128)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xdb in position 0: ordinal not in range(128)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd8 in position 0: ordinal not in range(128)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd9 in position 0: ordinal not in range(128)
```

Oh, what is it? Server says _which_ character stands on 0 position. And we can use it to restore the plaintext.

### A piece of theory

We know that AES CBC decrypts each block and then XORes it with previous (or IV for the first one). So, knowing wrong character ![p'](./images/p.png) and current IV byte ![iv'](./images/iv_2.png), we can XOR them and get intermediary byte, then, by XORing it with original IV byte ![iv](./images/iv.png), we get the plaintext byte. Then we may use the first block as IV for the second and so on.
Modify our [script](./iv_brute.py) to speed up the process.
And we get the plaintext: `{"name": "a", "show_flag": false}`.

So we see json object with `"show_flag"` property set to `false`. Obviously, we should try to set it to `true`. We've got such a name value that the word `false` is placed in the end of the second block, whereas `}` symbol is the beginning of the third. It makes task a bit easier, allowing us not to worry about paddings.

So we replace "`false`" value with `"true "` (space is added to keep the text length). Knowing that second block is XORed with encrypted first one, we may set such values in the first block that give `true` in the second after decryption. We do this by xorig each byte of `false` with byte of `'true '` and byte of first block on the corresponding places. Now, as the first block has changed, server can't decrypt the cookie. But this is not a problem, we just bruteforce IV again byte by byte from the 0th to 15th. We XOR byte on each place (again, server sends us DecodeErrors) with bruteforced IV and byte of the plaintext (which we know up to each symbol). The goal is to get valid json object. Bruteforce IV until we get valid answer from the server or until we construct valid cookie.
We got the new cookie:
``` b'\xd0F\x12`\xbd"7\xbf\x1d6cB#\xfb6\xd2m\xaa\xe0{\x9c;\xa9\xc5\x8d?\x92Z@4\xf4&\xbd\xe09\xb83\xe7q1)-\x89\x1b\xfe\xf3\xcbU\xb7\xcd\xbb)2\xd0\xad\xbb\xba\xbfef\x92/NK' ```

Encoding it with base64 and sending it to the server gives us the flag

![flag](./images/flag.png)

Script for getting the cookie: [get_cookie.py](./get_cookie.py)

Original writeup (https://github.com/VoidHack/write-ups/tree/master/Kaspersky%202017/crypto/decrypt%20the%20message).
AllanopkinsJune 23, 2018, 11:38 a.m.

This blog with the title of decrypt the message is easily a useful and creative blog by all means. Some people who are new in the field of <a href="https://writing-reviews.com/essaybox-com-review">essaybox.com review</a> can read this blog and try to understand the value of this blog. This blog is really good and a creative blog so that readers will read it.


itsalinaoliveJuly 26, 2018, 10:22 a.m.

A debt of gratitude is in order for composing this astounding post about the contemplation for tranquility and inward peace and I take in numerous things from this article.I see that numerous clients visit <a href="https://www.assignmentdone.co.uk">assignment help uk</a> a give their criticism about this post.


zoepeterson02Aug. 6, 2018, 9:30 a.m.

Keep linking it to the next level to make it more popular with the strong skills make sure <a href="https://www.hjackets.com/blog/harley-quinn-costume">Suicide Squad Harley Quinn Costume</a> that brings a gigantic change.


zoepeterson02Aug. 6, 2018, 12:29 p.m.

its an expert things to do an decryption but people can do it with the expert try <a href="https://www.moviesjacket.com/detroit-become-human-markus-jacket">Detroit Become Human Jacket</a> & get to resolve their problem.


heatherrosado4Aug. 21, 2018, 9:53 a.m.

GitHub Inc is one of the great online hosting Sarwar we can find different software coding free of cost and share each other, I think GitHub is only one coding hub that allows us to find different developer logic and programs codes, so every professional developer had touch with it. last time i had to find complete e-commerce website coding sources now i am going to some changes with these codes because i want to my personal website. <a href="https://www.getmyleather.com/product/mission-impossible-rogue-nation-tom-cruise-leather-jacket">Getmyleather.com</a>


sheerazmir1597Sept. 2, 2018, 10:29 a.m.

Super site! I am Loving it!! Will return once more, Im taking your food likewise, Thanks. <a href="https://www.naturalfoodseries.com/12-benefits-seaweed">Seaweed</a>


sheerazmir1597Sept. 2, 2018, 10:30 a.m.

It is extremely nice to see the greatest details presented in an easy and understanding manner. <a href="https://www.naturalfoodseries.com/11-benefits-prunes">Prunes</a>


sheerazmir1597Sept. 2, 2018, 10:30 a.m.

Great Information sharing .. I am very happy to read this article .. thanks for giving us go through info.Fantastic nice. I appreciate this post. <a href="https://www.naturalfoodseries.com/13-health-benefits-molasses">Molasses</a>


sheerazmir1597Sept. 2, 2018, 10:44 a.m.

If your looking for Online Illinois license plate sticker renewals then you have need to come to the right place.We offer the fastest Illinois license plate sticker renewals in the state. <a href="https://www.naturalfoodseries.com/13-benefits-plums">Plum</a>


sheerazmir1597Sept. 2, 2018, 10:44 a.m.

I just found this blog and have high hopes for it to continue. Keep up the great work, its hard to find good ones. I have added to my favorites. Thank You. <a href="https://www.naturalfoodseries.com/10-home-remedies-back-pain">Back Pain</a>


sheerazmir1597Sept. 2, 2018, 7:28 p.m.

It is perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or tips. Perhaps you could write next articles referring to this article. I want to read more things about it! <a href="https://www.naturalfoodseries.com/13-benefits-cocoa">Cocoa</a>


sheerazmir1597Sept. 3, 2018, 8:34 a.m.

I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts. <a href="https://www.naturalfoodseries.com/13-health-benefits-nutmeg">Nutmeg</a>


sheerazmir1597Sept. 3, 2018, 8:55 a.m.

Very useful post. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. Really its great article. Keep it up. <a href="https://www.naturalfoodseries.com/aging-muscles-strong">Aging Muscles</a>


zoepeterson02Sept. 4, 2018, 10:32 a.m.

Decrypt is a good art that not be an easy task to perform with the great hard work of coding to make it more <a href="https://www.harleyquinnjacket.com">Harley Quinn Jacket</a> possible.


heatherrosado4Sept. 6, 2018, 8:29 a.m.

Well, this is really latest news for i don't know about it yet how its possible you can tell us with details I had to try to find you on GitHub. <a href="https://www.getmyleather.com/product/hadi-tabbal-the-brave-tv-series-jacket">Amazing Biker Leather Jacket</a>


deannawilliam12Sept. 10, 2018, 10:59 a.m.

Unscrambling is the way toward taking encoded or scrambled content or other information and changing over it once again into content that you or the PC can read and get it. This term could be utilized to portray a strategy for un-encoding the information physically or with un-scrambling the information utilizing the best possible codes or keys. <a href="https://www.buymoviejackets.com/product/tv-series-bates-motel-max-thieriot-leather-jacket">TV Series Bates Motel Max Thieriot Jacket</a>


sagarharish999Sept. 18, 2018, 7:06 a.m.

the nice <a href="http://google.com/">game</a> post


kathleenaswaffordOct. 3, 2018, 11:37 a.m.

Many thanks for getting enough time to discuss this <a href="https://www.hjackets.com/buy/wonder-woman-jacket/">Wonder Woman Jacket</a>, They have been a giant help for us. Thanks a whole lot.


bautistafurniture1Oct. 11, 2018, 8:42 a.m.

Very good post.
<a href=”https://bautistaupholstery.com/”>Couch Cushion Repair</a>
<a href=”https://bautistaupholstery.com/furniture-repair/”>Upholstery Services Near Me</a>
<a href=”https://bautistaupholstery.com/”>Furniture Upholstery Near Me</a>


bautistafurniture1Oct. 17, 2018, 6:14 a.m.

Very good post. Looking forward to see more.
<a href=”https://bautistaupholstery.com/”>Furniture Repair And Upholstery</a>
<a href=”https://bautistaupholstery.com/”>Furniture Refurbishing Near Me</a>
<a href=”https://bautistaupholstery.com”>Reupholstery Services Near Me</a>


sheerazmir1597Oct. 30, 2018, 4:40 p.m.

With so many books and articles coming up to give gateway to make-money-online field and confusing reader even more on the actual way of earning money, <a href="http://www.hopeonthehill.org/food-pantry.html">Church on the hill mcminnville</a>


sheerazmir1597Nov. 6, 2018, 11:43 a.m.

i am for the first time here. I found this board and I in finding It truly helpful & it helped me out a lot. I hope to present something back and help others such as you helped me. <a href="https://www.naturalfoodseries.com/">Natural Food</a>


sheerazmir1597Nov. 6, 2018, 11:43 a.m.

Hey There. I found your blog using msn. This is a very well written article. I’ll be sure to bookmark it and come back to read more of your useful info. Thanks for the post. I’ll definitely return. <a href="https://www.naturalfoodseries.com/">Natural Food</a>


MuhammadSheerazNov. 17, 2018, 7:23 p.m.

Admiring the time and effort you put into your blog and detailed information you offer!.. <a href="https://www.jamesbauers.com">Relationship Coach</a>


MuhammadSheerazNov. 28, 2018, 8:02 a.m.

U - No - Snow is a premier snow removal company that offers snow removal for starta’s, strip malls, hospitals, commercial and residential properties. With snow plow trucks, bobcats, and spreaders for salting sidewalks and mall parking lots. We aim to deliver the U no Snow in your business or home when you want it. We have specialty bookings for priority clients that demand the best from us to deliver a snow and ice cleared property. Our commercial grade equipment and professional staff will make sure your experience is unmatched in every industry. <a href="http://unosnow.com/">salting services</a>


seoservice225Dec. 2, 2018, 8:37 a.m.

For bathroom renovation contractors that specialize in bathroom remodelling and design get the pros at bathroom remodel Vancouver. For great prices and professional workmanship from the plumbing to the tile and everything in between. Serving Vancouver for many years and delivering the best bathrooms in Vancouver area. <a href="http://bathroomremodel.ca/">Bathroom renovations</a>


sheerazmeer4Dec. 30, 2018, 5:02 p.m.

i am for the first time here. I found this board and I in finding It truly helpful & it helped me out a lot. I hope to present something back and help others such as you helped me. <a href="https://www.languageofdesires.com">Language of Desire</a>


sheerazmeer4Dec. 31, 2018, 5:26 p.m.

Very nice blog and articles. I am realy very happy to visit your blog. Now I am found which I actually want. I check your blog everyday and try to learn something from your blog. Thank you and waiting for your new post. <a href="https://www.languageofdesires.com/knock-knock-jokes/">knock knock Jokes</a>


sheerazmeer4Jan. 4, 2019, 6:34 a.m.

Thanks for your post. I’ve been thinking about writing a very comparable post over the last couple of weeks, I’ll probably keep it short and sweet and link to this instead if thats cool. Thanks. <a href="https://www.naturalfoodseries.com/red-tea-detox-review">Red Tea Detox</a>


nehasharma7057March 13, 2019, 5:04 a.m.

I really like this post it was excellent and integrating post. I must say I enjoy reading this article thanks a lot for sharing this article and continue to good work.
http://www.dwarkaescortgirls.com/delhi-call-girl.html
http://www.callgirlsinkarolbagh.com/delhi-escorts-bookings.php


thomas.adaam19Nov. 23, 2019, 6:08 a.m.

this post is really impressive I want to say you thanks.


singhisking9371Dec. 17, 2019, 2:30 p.m.

This teeny-tiny, grain-like seed packs some serious nutritional prowess. With a mild, nutty flavor and a texture similar to rice or couscous, quinoa is one of the only grains or seeds that provides all nine essential amino acids our bodies can't produce themselves . And it's filled with protein— eight grams per one-cup serving, to be exact!
http://www.ultraomegaburnstore.com/


singhisking9371Dec. 17, 2019, 2:31 p.m.

Don’t worry; these berries won't cause an oompa-loompa-like reaction. In fact, they're nutritional superstars, filled with fiber, vitamin C, and cancer-fighting compounds. And studies suggest blueberries may even improve memory !
[url=https://www.iorganifireviews.com/]organifi green juice[/url]


emmarobetDec. 20, 2019, 10:32 a.m.

Your blog was good and it was informative for me and others. Thank you for sharing this type of informative blog and It gives me so many ideas of fashion and it tell me what is fashion. Thank you for this blog.
https://www.newamericanjackets.com/product/r-a-f-b3-shearling-sheepskin-bomber-leather-jacket.html


anushaasif0099Nov. 23, 2020, 5:45 a.m.

I Was Eagerly Looking For Content Like This, Right To The Point And Detailed As Well Accordingly Depending Upon The Matter/Topic. You Have Managed This Greatly For Sure. <a href="https://www.celebstyleoutfits.com/">Celebrity Style Leather Jacket</a>