Buffer Overflow Attack Protection in C# .NET
Submitted by Yorkiebar on Wednesday, August 27, 2014 - 09:25.
Introduction:
This tutorial is on how to secure your application in C# from Buffer Overflow Attacks.What's a Buffer Overflow Attack? (BTA)
A buffer overflow attack is when the user purposefully enters too much data in such a way that the program will spill the data across different memory locations which will cause unexpected behaviour such as opening another vulnerability for the attack to exploit. This works through the use of user input. If the data size is not checked correctly before processing the data in certain ways, it can become vulnerable to a buffer overflow attack from an attacker.C# Console App:
We are going to use a simple C# console application for this example, so first create a new C# console application project, give it a name, and click 'Create'.- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace ChaoSQL
- {
- class Program
- {
- static void Main(string[] args)
- {
- }
- }
- }
Byte array:
Next we are going to create a byte array which we store the user input in next, notice that we are giving it a fixed size of 255 bytes...User Input:
Now we are going to get some user input...- Console.Readline()
- Encoding.Default.GetBytes(Console.ReadLine())
- bytes = Encoding.Default.GetBytes(Console.ReadLine());
Vulnerability
The vulnerability here is that the user could be inputting a string of 256+ bytes/characters and so when converted to bytes, it will be much more than the 'bytes' byte array can handle - a maximum of 255. To fix this, we can simply check the byte count first before setting it to the 'bytes' byte array...- string readLine = Console.ReadLine();
- if (Encoding.Default.GetBytes(readLine).Length <= 255) {
- bytes = Encoding.Default.GetBytes(readLine);
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace BTAProtection
- {
- class Program
- {
- static void Main(string[] args)
- {
- // Not Safe > bytes = Encoding.Default.GetBytes(Console.ReadLine());
- string readLine = Console.ReadLine();
- if (Encoding.Default.GetBytes(readLine).Length <= 255) {
- bytes = Encoding.Default.GetBytes(readLine);
- }
- }
- }
- }
Comments
No buffer overflow
I don't see a buffer overflow here.
byte[] bytes = new byte[255]; //allocate a block of memory that is never used
bytes = Encoding.Default.GetBytes(Console.ReadLine()); //point to a new block of memory (appropriately sized) allocated by GetBytes
The variable bytes just points to a new block of memory of the appropriate size allocated by Encoding.Default.GetBytes.Add new comment
- Add new comment
- 1277 views