C++ Buffer Overflow
Solution 1
I modified your program a little bit to make it more illustrative:
#include <iostream>
int main( void )
{
int authentication = 0;
char cUsername[ 10 ];
char cPassword[ 10 ];
std::cout << "Username: ";
std::cin >> cUsername;
std::cout << "Pass: ";
std::cin >> cPassword;
if( std::strcmp( cUsername, "admin" ) == 0 && std::strcmp( cPassword, "adminpass" ) == 0 )
{
authentication = 1;
}
if( authentication )
{
std::cout << "Access granted\n";
std::cout << ( char )authentication;
}
else
{
std::cout << "Wrong username and password\n";
}
return ( 0 );
}
I compiled it with x64 compiler command-line MS compiler, no optimizations. So now we have an exe that we want to "hack". We load the program with WinDbg (really good debugger) and take a look at the disassembly (notice, I've supplied full debug info, for clarity):
00000001`3f1f1710 4883ec68 sub rsp,68h
00000001`3f1f1714 488b0515db0300 mov rax,qword ptr [Prototype_Console!__security_cookie (00000001`3f22f230)]
00000001`3f1f171b 4833c4 xor rax,rsp
00000001`3f1f171e 4889442450 mov qword ptr [rsp+50h],rax
00000001`3f1f1723 c744243800000000 mov dword ptr [rsp+38h],0 // This gives us address of "authentication" on stack.
00000001`3f1f172b 488d156e1c0300 lea rdx,[Prototype_Console!std::_Iosb<int>::end+0x78 (00000001`3f2233a0)]
00000001`3f1f1732 488d0d47f00300 lea rcx,[Prototype_Console!std::cout (00000001`3f230780)]
00000001`3f1f1739 e8fdf9ffff call Prototype_Console!ILT+310(??$?6U?$char_traitsDstdstdYAAEAV?$basic_ostreamDU?$char_traitsDstd (00000001`3f1f113b)
00000001`3f1f173e 488d542428 lea rdx,[rsp+28h] // This gives us address of "cUsername" on stack.
00000001`3f1f1743 488d0df6f00300 lea rcx,[Prototype_Console!std::cin (00000001`3f230840)]
00000001`3f1f174a e823faffff call Prototype_Console!ILT+365(??$?5DU?$char_traitsDstdstdYAAEAV?$basic_istreamDU?$char_traitsDstd (00000001`3f1f1172)
00000001`3f1f174f 488d153e1c0300 lea rdx,[Prototype_Console!std::_Iosb<int>::end+0x6c (00000001`3f223394)]
00000001`3f1f1756 488d0d23f00300 lea rcx,[Prototype_Console!std::cout (00000001`3f230780)]
00000001`3f1f175d e8d9f9ffff call Prototype_Console!ILT+310(??$?6U?$char_traitsDstdstdYAAEAV?$basic_ostreamDU?$char_traitsDstd (00000001`3f1f113b)
00000001`3f1f1762 488d542440 lea rdx,[rsp+40h] // This gives us address of "cPassword" on stack.
00000001`3f1f1767 488d0dd2f00300 lea rcx,[Prototype_Console!std::cin (00000001`3f230840)]
00000001`3f1f176e e8fff9ffff call Prototype_Console!ILT+365(??$?5DU?$char_traitsDstdstdYAAEAV?$basic_istreamDU?$char_traitsDstd (00000001`3f1f1172)
00000001`3f1f1773 488d15321c0300 lea rdx,[Prototype_Console!std::_Iosb<int>::end+0x84 (00000001`3f2233ac)]
00000001`3f1f177a 488d4c2428 lea rcx,[rsp+28h]
00000001`3f1f177f e86c420000 call Prototype_Console!strcmp (00000001`3f1f59f0)
00000001`3f1f1784 85c0 test eax,eax
00000001`3f1f1786 751d jne Prototype_Console!main+0x95 (00000001`3f1f17a5)
00000001`3f1f1788 488d15291c0300 lea rdx,[Prototype_Console!std::_Iosb<int>::end+0x90 (00000001`3f2233b8)]
00000001`3f1f178f 488d4c2440 lea rcx,[rsp+40h]
00000001`3f1f1794 e857420000 call Prototype_Console!strcmp (00000001`3f1f59f0)
00000001`3f1f1799 85c0 test eax,eax
00000001`3f1f179b 7508 jne Prototype_Console!main+0x95 (00000001`3f1f17a5)
00000001`3f1f179d c744243801000000 mov dword ptr [rsp+38h],1
00000001`3f1f17a5 837c243800 cmp dword ptr [rsp+38h],0
00000001`3f1f17aa 7426 je Prototype_Console!main+0xc2 (00000001`3f1f17d2)
00000001`3f1f17ac 488d15151c0300 lea rdx,[Prototype_Console!std::_Iosb<int>::end+0xa0 (00000001`3f2233c8)]
00000001`3f1f17b3 488d0dc6ef0300 lea rcx,[Prototype_Console!std::cout (00000001`3f230780)]
00000001`3f1f17ba e87cf9ffff call Prototype_Console!ILT+310(??$?6U?$char_traitsDstdstdYAAEAV?$basic_ostreamDU?$char_traitsDstd (00000001`3f1f113b)
00000001`3f1f17bf 0fb6542438 movzx edx,byte ptr [rsp+38h]
00000001`3f1f17c4 488d0db5ef0300 lea rcx,[Prototype_Console!std::cout (00000001`3f230780)]
00000001`3f1f17cb e825f9ffff call Prototype_Console!ILT+240(??$?6U?$char_traitsDstdstdYAAEAV?$basic_ostreamDU?$char_traitsDstd (00000001`3f1f10f5)
00000001`3f1f17d0 eb13 jmp Prototype_Console!main+0xd5 (00000001`3f1f17e5)
00000001`3f1f17d2 488d15ff1b0300 lea rdx,[Prototype_Console!std::_Iosb<int>::end+0xb0 (00000001`3f2233d8)]
00000001`3f1f17d9 488d0da0ef0300 lea rcx,[Prototype_Console!std::cout (00000001`3f230780)]
00000001`3f1f17e0 e856f9ffff call Prototype_Console!ILT+310(??$?6U?$char_traitsDstdstdYAAEAV?$basic_ostreamDU?$char_traitsDstd (00000001`3f1f113b)
00000001`3f1f17e5 33c0 xor eax,eax
00000001`3f1f17e7 488b4c2450 mov rcx,qword ptr [rsp+50h]
00000001`3f1f17ec 4833cc xor rcx,rsp
00000001`3f1f17ef e8bc420000 call Prototype_Console!__security_check_cookie (00000001`3f1f5ab0)
00000001`3f1f17f4 4883c468 add rsp,68h
00000001`3f1f17f8 c3 ret
Now, since we know how x64 stack works we can start "hacking". RSP
is stack pointer, function stack is addresses above RSP
value (stack grows into smaller addresses). So, we see that RSP+28h
is where cUsername
, RSP+38h
is authentication
, and RSP+40h
is cPassword
, where 28h, 38h and 40h are hexadecimal offsets. Here is little image to illustrate:
-----> old RSP value // Stack frame of caller of `main` is above, stack frame of main is below
16 bytes of
"cPassword"
+40h
8 bytes of "authentication"
+38h
16 bytes of
"cUsername"
+28h
-----> RSP value = old RSP-68h
What do we see from here? We see that compiler aligned data on 8 byte boundary: for example, we asked to allocate 10 bytes for cUsername
, but we got 16 bytes - x64 bit stack is aligned on 8-byte boundary, naturally. That means in order to write into authentication
we need to write into cUsername
MORE that 16 bytes (symbols). Notice also, that compiler put cPassword
higher that authentication
- we cannot overwrite authentication
using cPassword
, only cUsername
.
So now we run our program and input Username: 0123456789abcdef1
. 0123456789abcdef
= 16 bytes, the next 1
is going to be put into lower byte of authentication
- good enough for us:
Username: 0123456789abcdef1
Pass: whatever
Access granted
1
Solution 2
It is overwriting your authentication
variable. This means that authentication
is positive even before your code checks the username and password. To check this, print out authentication prior to the checks.
I'll expand a little further: When you type is a very long username, that long username is copied, by your strcpy
, into cUsername
. That variable cUsername
is immediately after authentication
and hence it is overwritten by the overly-long username.
If you type a very very long username, then (again) the authentication variable will be overwritten. But also now the items further up the stack, such as the return value, will be overwritten. If your program overwrites too high up the stack, then it will be very badly broken and anything can happen. You essentially execute random code at this point.
Solution 3
Proposed solution to detect NULL pointer and buffer overflow in memcpy, memset, strcpy before hand and print out the location (file:line) where the problem occurs:
http://htvdanh.blogspot.com/2016/09/proposed-solution-to-detect-null.html
Solution 4
If you use std::string
, you'll find that your program will be much simpler:
int main()
{
bool authenticated = false;
while(!authenticated)
{
string username;
string password;
cout << "Username: ";
getline(cin, username); // you may want to read input differently
cout << "Pass: ";
getline(cin, password); // same as above
// you'll need to check cin.fail() to see whether the stream
// had failed to read data, and exit the loop with "break".
if(username == "admin" && password == "adminpass")
{
authenticated = true;
}
else
{
cout << "Wrong username and password, try again\n";
}
}
if(authenticated)
{
cout << "Access granted\n";
}
}
Edit:
With regards to your recent question, I think by default, cin >> string
will stop reading at the first whitespace character (i.e. space), so if you input a space, cin
will stop before it corrupts any data, and so you don't get the access violation. If you want to be able to read spaces, then you'll need to use getline
like I have above so that it will read the entire line of text, spaces included.
sraboy
I got started with QBASIC in middle school and have been a passionate technologist ever since. I love solving problems and enjoy learning new things. I code for fun, build and break things daily and try to discover something new daily. Rather than specialize, I embrace the Jack of All Trades mentality when it comes to technology and like to develop ways to help teams integrate experience across the various specialties.
Updated on October 08, 2020Comments
-
sraboy over 3 years
I'm trying to teach myself about buffer overflows and exploitation in C++. I'm an intermediate C++ guy, at best, so bear with me. I've followed a few tutorials, but here's some example code to illustrate my question:
#include <string> #include <iostream> using namespace std; int main() { begin: int authentication = 0; char cUsername[10], cPassword[10]; char cUser[10], cPass[10]; cout << "Username: "; cin >> cUser; cout << "Pass: "; cin >> cPass; strcpy(cUsername, cUser); strcpy(cPassword, cPass); if(strcmp(cUsername, "admin") == 0 && strcmp(cPassword, "adminpass") == 0) { authentication = 1; } if(authentication) { cout << "Access granted\n"; cout << (char)authentication; } else { cout << "Wrong username and password\n"; } system("pause"); goto begin; }
I know there's all kinds of bad juju in here with
cin << String
, etc... Anyhow, when I enter too many letters (a ton ofA
's for instance) intocUser
andcPass
, I just get an Access Violation from Visual Studio. If, however, I type 20ishA
's, then a space, then anotherA
intocUser
, it skips asking me forcPass
(assuming because it's been filled after the space character caused the previous call tocin
to return) and just grants me access.At what point, and why, is data overflowing into "authentication" and why does it only happen when I have the space and not when I have a million
A
's... I never get the "Access Violation" when I use a space in the input forcUser
. -
Niklas B. over 12 years"forward" engineering :D I have to remember that.
-
sraboy over 12 yearsI'll be sure to work on my forward engineering... appreciate the witticism. I'm trying to understand why I get an "Access Violation" in one instance and not in the other (with the space).
-
sraboy over 12 yearsWhy does having a space in there prevent an "Access Violation" from being identified as opposed to simply overwriting authentication?
-
sraboy over 12 yearsThanks. I know how to avoid this issue altogether, but I'm trying to figure out the specifics behind the difference in supplying a space to cin. Without the space, I get an Access Violation. With the space, I get my exploit.
-
Aaron McDaid over 12 yearsI don't think the space is relevant. All whitespace is treated the same by
cin
. I think your question is "When I have about 20 chars in the username, then the program proceeds to authentication, and when I have many more characters (say 100) then I get an access violation. Why this difference?" -
sraboy over 12 yearsAh! Thanks. I hadn't realized that. So cin simply ceases reading at the whitespace and this keeps it from reading too much into memory when I try cin >> uPass. I knew that it stopped at whitespace but didn't put 2 and 2 together on a few things. Running through with the debugger I can see what's going on now. Thanks!
-
sraboy over 12 yearsAlrighty then. Thanks for the reply... being self-taught, I can write code from here to kingdom-come, but I can't debug for my life and don't know much about the stack and memory allocation. Appreciate the info.
-
Potatoswatter over 12 years@sraboy Not intended as a witticism or a jab… anyway the results are unpredictable because you didn't start with enough information to make a prediction. You're shooting in the dark, do you really expect to obtain definite results?
-
Aaron McDaid over 12 years@sraboy, which compiler were you using? I did experiments and g++ and clang. Where you using clang? Which version of which compiler?
-
sraboy over 12 yearsThanks so much for going through all the trouble to explain what was apparently an incredibly simple question. I appreciate the ASM breakout and the example. You're quite the instructor!
-
sraboy over 12 yearsI just used Visual Studio 2010, so MSVC++... whichever compiler I'm at now, not sure what updates/service packs I have at this point. I generally just go with C# or VB.NET/GDI for my apps, so this C++ stuff with memory management, etc is quite new to me. I'm used to all the managed code.
-
sraboy over 12 yearsI didn't know what to expect. It was all new to me. Your response didn't quite explain it. I had a practical question; your answer was abstract. Combined with AzzA's, it helps, especially knowing that your reference to "local variables may appear in any order" was explained better by him informing me that the compiler simply chose to place cPassword above authentication. I don't know much about the stack and just program until it works. This is my first attempt at figuring this stuff out from a practical perspective. I'm a .NET (and QBASIC) guy, so memory management, etc is new to me.
-
Aaron McDaid over 12 yearsTHanks for that, I noticed that the relative layout of the variables was different between different compilers. (I think that's just a case of optimization differences.) I was able to get your behaviour with code compiled by clang, but not by g++. I'm running on Linux. Anyway, Azza's answer is great!
-
lapk over 12 years@sraboy If you are interested in how compiler generates code, memory layout etc, then little test programs like yours are the way to go. Just read a little bit about most common assembler instructions and stack layout for your CPU, and get a debugger that will allow you to disassemble. Then you'll be able to see how your C/C++ code is transformed into actual machine instructions. It allows not only to use some "tricks", but also gives you idea, for example, about what things compiler is able to optimize etc.
-
overshadow over 9 yearsHi, I am new to c++. I got a silly question to ask, how can we limit the user input to the variable size that we have declared? For example, cUsername is only accepting 10 chars, but user can enter more than that right? It is possible to prevent overflow from this variable?
-
lapk over 9 years@overshadow Yes. For example, you can use
std::setw()
:std::cin >> std::setw(9) >> cUsername;
. -
Server Overflow about 5 yearsIt is AMAZING how a ancient/obnoxious language as C++ survived that long. Maybe it is time for its reign to end, to make room to modern languages (not so prone to errors such as buffer overflow).