# Protecting against buffer overrun attacks

### Buffer overrun types

Although many overflows occurs when the program receives more data than it expects, in fact there are many kinds of overflows. It is important to distinguish among various classes of overflows to be able to develop good test cases to identify specific types of overflows:

* **Integer overflow:** Occurs when a specific data type of a CPU register that is meant to hold values within a certain range is to be assigned a value outside that range. Integer overflow often leads to buffer overflow for cases in which integer overflow occurs when computing the size of the memory to allocate.
* **Stack Overflows:** such overflows occur when data is written past the end of buffers allocated on the stack.
* **Heap Overflow:** It occurs when data is written outside the space that was allocated for it on the heap.&#x20;
* **Format String Attacks:** Format String attacks occur when the %n parameter of the format string is used to write data outside the target buffer.

### **Protection Mechanisms**

**For C++**

We must to enable these compiler checks at leas&#x74;**:**

* Buffer Security check (/GS)
* Runtime Library check (Both /RTC1…)
* Basic Runtime checks (Enable VC++ Run time Library)
* DEP

![](https://3408508746-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lis5JLcnSD2vdYdyQ3U%2F-LjKNLusUYH45pkVDW34%2F-LjKP1UIcrFa2yn2Knqp%2Fbuffer%20security%20check.jpg?alt=media\&token=0c3fef1d-9cfd-4e35-aeb8-b8f8fa5a5007)

Also in Windows settings:

![](https://3408508746-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lis5JLcnSD2vdYdyQ3U%2F-LjKNLusUYH45pkVDW34%2F-LjKPE2YU_5nUUUb71lk%2Fdep-windows.jpg?alt=media\&token=560def43-8b83-4d5f-bbf8-c0c846412c63)

#### **For C#**

Yes, buffer overflow exploits are still possible in C#, but they are much harder to produce. You can only get buffer overflows if you use certain unsafe constructs, and not with "normal" C# code. Memory corrupting code shouldn't be possible at all, when your code is running with lowered trust.

A few possibilities for buffer overflows:

1. Using the `unsafe` keyword, which allows pointers. Unsafe code is just as easy to get wrong, as pointer based code in c or c++.
2. Using unsafe APIs, such as the methods from the `Marshal` class
3. (Mono only) You can disable array range checking (safety vs. performance trade-off)

```csharp
unsafe void bufferOverflow(string s)
{
    char* ptr = stackalloc char[10];

    foreach (var c in s)
    {
        *ptr++ = c; // Bufferoverflow if s.Length > 10
    }
}
```

You can't a traditional buffer-overflow with an array. It will do bounds-checking before accessing an array unless it (CLR) can guarantee it is safe.

![](https://3408508746-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lis5JLcnSD2vdYdyQ3U%2F-LjKQyy3AdibQfybKiIX%2F-LjKRD0B1WcquQo22MMp%2Fdefense-against-buffer-overflow.png?alt=media\&token=7fe037e1-b607-4803-aee3-a20c3d5f7884)
