用过C#的朋友可能认为它是一种十分安全的语言,其实C#也可以做到经典的缓冲区溢出。 本文章将用一个实例来描述C#究竟是如何发生缓冲区溢出的! 首先建立一个C# Console工程,并开启工程的“允许

来源:互联网 发布:安卓限速软件 编辑:程序博客网 时间:2024/06/05 18:20

用过C#的朋友可能认为它是一种十分安全的语言,其实C#也可以做到经典的缓冲区溢出。

本文章将用一个实例来描述C#究竟是如何发生缓冲区溢出的!


首先建立一个C# Console工程,并开启工程的“允许不安全代码”选项

键入代码:

[csharp] view plain copy
 print?
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace ConsoleTest  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             char ori = 'A';  
  13.             StackOverflow();  
  14.               
  15.             Console.WriteLine(ori);  
  16.             Console.ReadLine();  
  17.         }  
  18.   
  19.         static unsafe void StackOverflow()  
  20.         {  
  21.             int* p = stackalloc int[1]; //声明一个int数组指针  
  22.             int i = sizeof(int); //指针增量  
  23.   
  24.             while (*p != (int)'A'//找到Main函数中的ori变量  
  25.             {  
  26.                 p += i;  
  27.                 Console.ForegroundColor = ConsoleColor.Yellow;  
  28.                 Console.WriteLine("Address: {0}", (int)p); //输出当前指针所指向的地址  
  29.                 Console.ForegroundColor = ConsoleColor.Gray;  
  30.                 try  
  31.                 {  
  32.                     Console.WriteLine("Value: {0}", *p);  
  33.                 }  
  34.                 catch  
  35.                 {  
  36.                     Console.WriteLine("We can't reach the system area"); //触及系统变量,无权限访问跳出  
  37.                     break;  
  38.                 }  
  39.                 Console.WriteLine();  
  40.             };  
  41.         }  
  42.     }  
  43. }  


大家可以先运行一下:

程序在找到‘A’的ASCII码后跳出循环。

其实程序的原理是:

p指针指向int数组的第一个元素,指针每次增加一个int的内存空间,由于数组的大小为1,所以两次循环后就溢出并指向在其前面的内存变量。最终找到ori所在的内存地址。


下面我们尝试修改ori的值,将其从‘A’修改为‘!’,there we Go:

这样修改代码:


经过这样的修改,再次运行:



可以看到ori被彻底修改为‘!’了。如果用这种方式将函数的地址进行修改就可以达到执行远程代码的目的了。

阅读全文
0 0
原创粉丝点击