栈缓冲区溢出

栈缓冲区溢出（stack buffer overflow或stack buffer overrun）是计算机程序把数据写入调用栈上的内存时超出了数据结构的边界。栈缓冲区溢出是缓冲区溢出的一种。 这会损坏相邻数据的值，引发程序崩溃或者修改了函数返回地址从而导致执行恶意的程序。这种攻击方式称为stack smashing。可被用于注入可执行代码、接管进程的执行。是最为古老的黑客攻击行为之一。
例子.
下例可用于覆盖函数返回地址。 通过函数 codice_1 :
void foo (char *bar)
 char c[12];
 strcpy(c, bar); // no bounds checking
int main (int argc, char **argv)
 foo(argv[1]);
 return 0;
当命令行参数少于12个字符时（例子B时）该程序是安全的。 
codice_2函数的不同输入下的调用栈，下图展示32位元小端序(little-endian)系统发生栈缓冲区溢出的记忆体状态:
例子C中, 命令行参数多于11个字符，导致codice_2覆盖了本地调用栈的数据、存储的栈指针（EBP）以及最重要的返回地址。 
攻击也可以修改内部变量值：
void foo (char *bar)
 float My_Float = 10.5; // Addr = 0x0023FF4C
 char c[28]; // Addr = 0x0023FF30
 // Will print 10.500000
 printf("My Float value = %f\n", My_Float);
 Memory map:
 @ : c allocated memory
 # : My_Float allocated memory
 *c *My_Float
 0x0023FF30 0x0023FF4C
 @@@@@@@@@@@@@@@@@@@@@@@@@@@@#####
 foo("my string is too long !!!!! XXXXX");
 memcpy will put 0x1010C042 (little endian) in My_Float value.
 memcpy(c, bar, strlen(bar)); // no bounds checking...
 // Will print 96.031372
 printf("My Float value = %f\n", My_Float);
int main (int argc, char **argv)
 foo("my string is too long !!!!! \x10\x10\xc0\x42");
 return 0;
平台相关.
A number of platforms have subtle differences in their implementation of the call stack that can affect the way a stack buffer overflow exploit will work. Some machine architectures store the top level return address of the call stack in a register. This means that any overwritten return address will not be used until a later unwinding of the call stack. Another example of a machine specific detail that can affect the choice of exploitation techniques is the fact that most RISC style machine architectures will not allow unaligned access to memory. Combined with a fixed length for machine opcodes this machine limitation can make the jump to ESP technique almost impossible to implement (with the one exception being when the program actually contains the unlikely code to explicitly jump to the stack register).
Stacks that grow up.
Within the topic of stack buffer overflows, an often discussed but rarely seen architecture is one in which the stack grows in the opposite direction. This change in architecture is frequently suggested as a solution to the stack buffer overflow problem because any overflow of a stack buffer that occurs within the same stack frame can not overwrite the return pointer. Further investigation of this claimed protection finds it to be a naive solution at best. Any overflow that occurs in a buffer from a previous stack frame will still overwrite a return pointer and allow for malicious exploitation of the bug. For instance, in the example above, the return pointer for codice_4 will not be overwritten because the overflow actually occurs within the stack frame for codice_5. However, because the buffer that overflows during the call to codice_5 resides in a previous stack frame, the return pointer for codice_5 will have a numerically higher memory address than the buffer. This means that instead of the return pointer for codice_4 being overwritten, the return pointer for codice_5 will be overwritten. At most this means that growing the stack in the opposite direction will change some details of how stack buffer overflows are exploitable, but it will not reduce significantly the number of exploitable bugs.
保护方式.
常用三种方式来对抗栈缓冲区溢出攻击。 
检查栈缓冲区溢出的发生.
栈的警惕标志（stack canary），得名于，用于探测该灾难的发生。具体办法是在栈的返回地址的存储位置之前放置一个整形值，该值在装入程序时随机确定。栈缓冲区攻击时从低地址向高地址覆盖栈空间，因此会在覆盖返回地址之前就覆盖了警惕标志。返回返回前会检查该警惕标志是否被篡改。
栈数据不可执行.
采取了“写异或执行”策略（, "Write XOR Execute"），即内存要么可写，要么可执行，但二者不能兼得。这是最常用的方法，大部分桌面处理器都硬件支持不可执行标志（no-execute flag）。
此方案一定可以让利用栈缓冲区溢出漏洞的方式失效，但本身也有缺点。首先，很容易找到方式将shellcode储存在不受保护的记忆体区（例如heap），而且几乎不用修改其利用方式。
就算上述方式无效，也有其他的方式。最不好处理的是所谓的Return-to-libc攻击，以此方式产生 shellcode。此攻击方式中，会将恶意内容用一般的呼叫堆叠载入，因此会执行到标准函式库呼叫，一般也会同时关闭记忆体执行保护，因此可以正常执行shellcode。
A variant of return-to-libc is return-oriented programming, which sets up a series of return addresses, each of which executes a small sequence of cherry-picked machine instructions within the existing program code or system libraries, sequence which ends with a return. These so-called "gadgets" each accomplish some simple register manipulation or similar execution before returning, and stringing them together achieves the attacker's ends. It is even possible to use "returnless" return-oriented programming by exploiting instructions or groups of instructions that behave much like a return instruction.
随机化内存空间布局.
Instead of separating the code from the data another mitigation technique is to introduce randomization to the memory space of the executing program. Since the attacker needs to determine where executable code that can be used resides, either an executable payload is provided (with an executable stack) or one is constructed using code reuse such as in ret2libc or ROP (Return Oriented Programming) randomizing the memory layout will as a concept prevent the attacker from knowing where any code is. However implementations typically will not randomize everything, usually the executable itself is loaded at a fixed address and hence even when ASLR (Address Space Layout Randomization) is combined with a nonexecutable stack the attacker can use this fixed region of memory. Therefore all programs should be compiled with PIE (position-independent executables) such that even this region of memory is randomized. The entropy of the randomization is different from implementation to implementation and a low enough entropy can in itself be a problem in terms of brute forcing the memory space that is randomized.
随机化内存空间布局（ASLR）会对处理程序的记忆体区段地址进行随机化，阻止攻击者进行返回导向编程与跳至Shellcode的攻击手法，因为攻击者需要知道可执行区段与 Shellcode 的记忆体地址。执行档如果不是地址无关代码（PIE）的格式，会导致执行档载入成处理程序之后，部分区段地址为固定的(如 .text 区段)，攻击者在Linux系统上，依然可以 return 到 0x400000 地址。ASLR受到资讯熵的影响，不同的实作会有不同的资讯熵，过低的资讯熵使攻击者更容易猜测到地址，也因此32位元比起64位元的更容易受到威胁。也因此在2015年发生Stagefright漏洞，在32位元系统下，ASLR仅有8位元的资讯熵，因此每次漏洞利用，只需要从256种组合猜测可能的记忆体地址进行利用。