Civil Ximp; amp; Structural Engineering
How tu Write Secure C Code te Prevect Buffer Overflows
Table of Contents
Buffer overflos remain on of they mest persistent and dangerous security deflabilities in C programming. Despite being well-documented for decades, they continue to cause serious issues such as data depration, system crashes, and demote code execution. Writing security C code code code code causes a deep conceping of how buffer overflows occur and a disciplined approvidache to preventing them. This articlie providesions a conclusive guides, consering robuss, oresive C core, convenantal conceptes, accepts, vatis, validaties, vatis, comprice techniques, comfile, comfile proteverevents
Przepływy z Buffer understanding
Buffer overflow has when a program writes more data to a contiguous block of memory (a buffer) than the buffer was allocated to hold. Since buffers residee in stack stack or heat memory, exceedin their ir boundaries overwrites adjacent memory locations. Thi s deruption can alter program state, inpute unpresticor, or be exploited by an attacker to inject and executute dirisarary code.
To jest konsekwencja zależy od tego, co dostaje nadpisarstwa. Overwriting a return adress on thee stack can redirect execution to o attacker-controlled code. Overwriting pointers can lead to dirisaary memory writes. Even simply crashes can be leveraged for denial-of- services attacks. Understanding the mechanics it thee first step to prevention.
Overflows Stack- Based
Local variables, including ding buffers prepared inside functions, are stored on thee stack. The stack also holds the return adress, saved frame pointers, and tell control data. When a linear buffer like present 1; British 1; FLT: 0 presenta3; Is overrun, data spills into the return adres and beyond. Classic exploits like the Morris worm (1988) used stack overflows to gain unauthorized.
Przepływy z głowicy - Based
Dynamically allocated buffers (via envi1; invi1; FLT: 1 envi3; environ3;, environ1; FLT: 2 envisate3; invi3;, etc.) residene on thee heap heap. Overflows here can derupt metadata used by ty the allocator, leading to crashes or exploitation via heap spraying or use- after-free attacks. Heat overflows are harder to exploit but equally dangerous.
Common Vulnerable Functions and Their Safe Alternatives
Te C standard library provides sevelal functions that do nott perfom bounds checking. Using them im e most concorn cause of buffer over floves. Replacing them with safer controparts is a fundamentamental best practice.
String Copy andConcatenation
- W przypadku gdy w odniesieniu do danego produktu nie ma zastosowania art. 3 ust. 1 lit. a), należy podać numer identyfikacyjny, w którym należy podać numer identyfikacyjny, a w przypadku tego produktu podać numer identyfikacyjny, w którym należy podać numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer, numer,
- Better yet: Xi1; Xi1; FLT: 5 Xi3; Xi3; - acvailable on BSD and many Linux systems; always s null- terminates and d returns the length of the source string for truncation devition.
- W przypadku gdy w wyniku badania nie można określić, czy dany produkt jest zgodny z wymogami określonymi w pkt 1, należy podać numer identyfikacyjny produktu, który ma być dostarczony, oraz podać numer identyfikacyjny produktu.
Formatted Output and Input
- (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (3); (3); (1); (1): (1): (1): (1); (1): (1): (1): (1); (1): (1): (1); (1): (1); (1): (1); (1): (1); (1): (1); (1): (1); (4); (3); (1); (1); (1); (1); (1); (1): (9); (3); (3); (- (3); (1) (1) (1)).
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Xi1; FLT: 10 Xi3; Xi3; Xi1; FLT: 1 Xi3; Xi3; - Xiair risk; use Xi1; Xi1; FLT: 11 XI3; Xi3; instead.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Xi1; FLT: 12 Xi3; Xi1; Xi1; FLT: 1 Xi3; Xi3; - Extremely dangerous; removed frem C11 standard. Usie Xi1; Xi1; FLT: 13 Xi3; Xi3; instead.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Xi1; FLT: 14 Xi3; Xi1; Xi1; FLT: 1 XI3; Xi3; - No bounds check. Usie Xi1; FLT: 15 XI3; XI3; or Xi1; Xi1; FLT: 16 Xi3; Xi3; Xi3; - With field width specifier.
Memory Copy andMove
- Xi1; Xi1; FLT: 0 XI3; XI3; XI1; FLT: 17 XI3; XI1; FLT: 1 XI3; XI3; - Safe only if n is verified note to XI1; FLT: 1; FLT: 2 XI3; FLT: 3; FLT: 1; FLT: 1; FLT: 3 XI3; FLT: 3; FLE; 3; Safer XIF: XI1; FLT: 4 XI3; FLT: 4 XI3; FLT; FLT: 18 X3; FLT: 1; FLT: 1; FLT: 3; (handles acquiapping) and always ensure n ≤ deser size.
- Some platforms provide the Xion1; Xion1; FLT: 19 Xion3; Xion3; frem Annex K (optional in C11), but adoption is limited.
Validation andSize Management
Even wigh safe functions, you mutt validate input lengths, ensure proper buffer sizes, and handle potential truncation gracefuly.
Czek Input Lengths
Before copying or processing external input (user input, network data, file contents), determinate it s maximum accepte length tod reject or truncate data that exceeds it. For example:
#define MAX_INPUT 255
char buffer[MAX_INPUT + 1]; // +1 for null
if (strlen(user_input) > MAX_INPUT) {
// Handle error: reject or truncate
fputs("Input too long", stderr);
return -1;
}
strncpy(buffer, user_input, sizeof(buffer) - 1);
buffer[sizeof(buffer) - 1] = '\0';
Usie Fixed- Size Buffers with Known Limits
Kiedy można, zdefiniować buffers with a constant size and enforcee it through out thee code. Avoid variable-length arrays (VLAs) that can cause stack overflows if large size are sumlied. Instad, allocate dynamically with explicit size checks.
Handle Truncation Explicitly
Functions like since; eng1; FLT: 21 size 3; eng3; and signal; eng1; FLT: 22 signal 3; eng3; can truncate data. Be aware of the return value to decret truncation and decide if the tricated data is acceptable or if an error should be raise. Ignoring truncation cain leave buvers in an unexpected state.
Kompilar Security Flags andRuntime Protections
Modern compilers offer flags that add buffer overflow detection and d liquation without out code changes.
- Wg danych zawartych w tabeli 1, FLT: 1, FLT: 0, 0, 3; VIS: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, - Wstawki Stack canaries (random values) before return andexes. If a buffer overflow overwrites the canary before modifying thee return andexs, thee program aborts before exploit exploit completes.
- Xi1; Xi1; FLT: 0 XX3; Xi3; Xi1; FLT: 25 XI3; XI1; XI1; FLT: 1 XI3; XI3; - Replaces calls to unsafe functions like 1; XI1; FLT: 26 XI3; XI3; FLT: 27 XI1; FLT: 27 XI3; FLT: 27 XI3; FLT: 27 XI3; FLT: Witch checked versions that abort if thee destination buffer is too small. XIXIX1; FLT: 28 X3; XIX3; OR higher optization.
- (zob. pkt 2.1.1.1 niniejszego załącznika)
- (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1) (1); (1) (1); (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (2) (2) (2
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Xi1; FLT: 31 Xi3; Xi1; Xi1; FLT: 1 Xi3; Xi3; - Xiphizing optimizing way overflow checks (use with caution).
Operating System Protections
Stack canaries are just one le layer. Exploit leximation technologies in modern OSes include:
- Xion1; FLT: 0 Xion3; Xion3; Data Execution Prevention (DEP) / NX bit Xion1; Xion1; FLT: 1 Xion3; Xion3; - Marks stack and heap as non-execututable, preventing shellcode execution.
- Adresaci: 0, 0, 3, 3, Adresaci: Space Layout Randomization (ASLR), 1, 1, 3, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7
- Relocation Read- Only (RELRO) Relation1; Relation1; FLT: 1 Relation3; Elay3; - Protects GOT (Global Offset Table) from overwriting.
Umożliwia to ochronę (usually default) raises the bar for exploitation but does not t replacee secfe coding.
Code Audits andStatic Analysis
Human review combined with automate static analysis can catch buffer overflow issues arly. Integrate these into your development workflow.
- Review: 1; Xi1; FLT: 0 Xi3; Xi3; Manual Code review Xi1; Xi1; FLT: 1 Xi3; Xi3; - Look for uses of unsafe functions, missing size checs, and loops that write beyond buffer boundaries.
- Xi1; Xi1; FLT: 0 X3; Xi3; Static analysis tools Xi1; Xi1; FLT: 1 XI3; XI3; - Tools like Xi1; XI1; FLT: 32 XI3; XI3;, XI1; FLT: 33 XI3; FLT: XI3;, XI1; FLT: XI1; XI3; FLT: 35 XI3; XI3; XIXL; XIXL; FLT: 33S, use of dangerous functions, and of- by- one errors. They can bee run in CI.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Fuzzing Xi1; Xi1; FLT: 1 Xi3; Xi3; - Usie libFuzzer, AFL, or Xir fuzzers to automatically tect handling with unexpected data that may trigger overflows.
Practical Examples of Secure Code
Safe String Copy with Bounds Checking
#include <stdio.h>
#include <string.h>
int safe_string_copy(char *dest, size_t dest_size, const char *src) {
if (!dest || !src || dest_size == 0) {
return -1; // Invalid parameters
}
size_t src_len = strlen(src);
if (src_len >= dest_size) {
// Source too large; truncation or error
// Option: copy what fits and null-terminate
strncpy(dest, src, dest_size - 1);
dest[dest_size - 1] = '\0';
return 1; // Truncation occurred
}
strncpy(dest, src, dest_size);
// strncpy fills remaining with null, so dest_size fits; no need to null-terminate if src shorter
return 0; // Success, no truncation
}
Safe Integer Handling for Buffer Sizes
Buffer overflow can also result from integer overflows when computing sizes. Always check arthimmetic before allocation.
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
void *safe_malloc_array(size_t nmemb, size_t size) {
if (nmemb == 0 || size == 0) {
return NULL; // Or handle zero-size allocation
}
if (nmemb > SIZE_MAX / size) {
// Integer overflow would occur
errno = ENOMEM;
return NULL;
}
return malloc(nmemb * size);
}
Using snprintf for Formatted Strings
char log_message[256];
int ret = snprintf(log_message, sizeof(log_message),
"User %s logged in from %s", username, ip_address);
if (ret < 0) {
// Output error
} else if ((size_t)ret >= sizeof(log_message)) {
// Truncation occurred; handle if needed
}
Dodatek Beszt Praktycs
- (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (2); (2) (2); (2) (4); (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4)
- Xiv1; Xiv1; FLT: 0 Xiv3; Xiv3; Avoid recursion with unbounded depth Xiv1; Xiv1; FLT: 1 Xiv3; Xiv3; - Stack overflows can occur frem deep recursion; use iteration or limit depth.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Usie Xi1; Xi1; FLT: 39 Xi3; Xi3; qualifier Xi1; Xi1; FLT: 1 XI3; Xi3; - Helps the compiler optimize andd may catch aliasing issues, though not directly preventing overflows.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Prefer Xi1; Xi1; FLT: 40 Xi3; Xi3; -correctness Xi1; Xi1; FLT: 1 Xi3; Xi3; - Prevents criminant modification of input strings andforces intent.
- Xiv1; FLT: 0 X3; Xiv3; Implement error handling Xiv1; Xiv1; FLT: 1 XIv3; Xiv3; - Do not ignon return values from functions lik1; Xiv1; FLT: 41 XI3; XIV3;, XI1; FLT: 42 XIV3; XIV3;, XIV1; FLT: 43 XIX3; X3;, etc.
Resources for Further Learning
- Xi1; Xi1; FLT: 0 Xi3; Xi3; SEI CERT C Coding Standard Xi1; Xi1; FLT: 1 Xi3; Xi3; - Comfixsive rules for secfe C coding.
- Bül1; Bür1; FLT: 0 X3; CWE- 120: Büffer Copy without out Checking Size of Input prefecses; Bür1; FLT: 1 X3; Bür3; - MITRE 's classification of buffer overflow weaknesses.
- BL1; BLT: 0 X3; BLT: 0 X3; BL3; OWASP Buffer Overflow XI1; BLT: 1 X3; BLT: XI3; - Practical guidance frem the Open Web Application Security Project.
- Reg.
- (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1); (1) (2); (2) (2) (2) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4) (4
Konkluzja
Prevesting buffer overflos in C is nott optional; it is a fundamentaltal responsibility of any developer working with the language. Byzrozumiag thee mechanisms of overflows, reveting dangerous functions with safer confidentives, rigorousy validating inputs andsizes, enabling compiler protections, andd empliing static analysis and testing, you can dramatically reduce thee risk of these deflabilities. No single techniques is nevent; defense depense deptin depth - comming coding disciintere, comfiles, our, OS, ouggie, and thougne tougne - existhine - provine et et et et entiestings, en.