An out-of-bounds write can overwrite a saved return address and let an attacker run code with the program’s privileges. Binary hardening adds checks that can stop some invalid copies before they write, along with memory protections that can block execution from writable regions such as the stack.

I started with a small C program that copies its argument into a 32-byte stack buffer. With the build protections disabled, I passed it an 80-byte argument. It printed the first 32 bytes and exited with status 0. By then, memcpy had written past the end of the buffer.

The vulnerable program

The record contains a 32-byte string field. One byte must hold the string terminator, leaving 31 bytes for text. Save this as record.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

__attribute__((noinline))
static int show_record(const char *input)
{
    char field[32] = {0};
    size_t length = strlen(input);
#ifdef CHECK_LENGTH
    if (length >= sizeof field) {
        fputs("record too long\n", stderr);
        return 2;
    }
#endif
    memcpy(field, input, length);
    printf("record: %.32s\n", field);
    return 0;
}

int main(int argc, char **argv)
{
    if (argc != 2) {
        fputs("usage: record TEXT\n", stderr);
        return 2;
    }
#ifdef PRINT_ADDRESS
    if (strcmp(argv[1], "--address") == 0) {
        printf("show_record: %p\n", (void *)show_record);
        return 0;
    }
#endif
    return show_record(argv[1]);
}

The zero-initialized array retains a terminator when at most 31 bytes are copied. The bounded printf avoids a separate out-of-bounds read, and noinline keeps show_record visible in disassembly. I’ll use CHECK_LENGTH for the repair and PRINT_ADDRESS for the PIE test. Converting a function pointer to void * works in this GCC/Linux environment but isn’t portable ISO C.

I ran the examples on AArch64 with Ubuntu 26.04 LTS and GCC 15. The reproduction notes give the container setup and exact toolchain versions.

I’ll disable the protections explicitly so the baseline is independent of compiler and distribution defaults. Use this build for the experiment only. To follow along, run the commands in one Bash session with set -e off so the shell keeps the flag arrays and continues after the probes that abort.

ulimit -c 0
CC=gcc-15
base=(
  -std=c17 -O2 -g -Wall -Wextra -march=armv8-a -DPRINT_ADDRESS
  -U_FORTIFY_SOURCE                     # no fortified library calls
  -fno-stack-protector                  # no stack guard
  -mbranch-protection=none              # exclude Arm branch protection
  -fno-pie -no-pie                      # non-position-independent executable
  -Wl,-z,norelro,-z,lazy,-z,execstack  # no RELRO; executable stack
)
repeat_x() {
  local padding
  printf -v padding '%*s' "$1" ''
  printf '%s' "${padding// /x}"
}
long_input=$(repeat_x 80)
short_overflow=$(repeat_x 33)

"$CC" "${base[@]}" record.c -o baseline
./baseline hello
./baseline "$long_input"
printf 'exit status: %d\n' "$?"

In the recorded build, the 80-byte input printed the first 32 bytes and exited normally:

record: hello
record: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
exit status: 0

Although the program exited normally, memcpy wrote beyond field. Only the printed output was limited to 32 bytes. An out-of-bounds write is undefined behavior, whether or not it causes a crash.

I’ll enable the protections cumulatively. The tests show what each defense does; they don’t prove that this overflow can be turned into every attack used in the probes.

ProtectionWhat it changesWhat it doesn’t stop
Stack canaryDetects some stack overwrites before a protected function returnsThe write itself, or corruption used before the check
FortificationChecks bounds of supported library operations when the compiler can determine themArbitrary pointer writes or unknown object bounds
PIE + ASLRMakes the main executable’s address less predictableAddress leaks or code-reuse attacks
Non-executable stackPrevents instruction fetch from stack pagesData corruption or reuse of existing executable code
Full RELROMakes selected relocation data read-only after relocationWritable application-controlled function pointers

1. Detect stack overwrites with canaries

A stack overflow can damage local variables or saved function state, including a return address if the write reaches it. GCC’s -fstack-protector-strong adds a guard to eligible functions. The function checks it before returning and calls __stack_chk_fail if it has changed.

In the recorded stack frame, the 32-byte field spans offsets 24 through 55. The 33rd input byte changes the guard at offset 56. After printf, the guard check aborts.

Figure 1. In the recorded AArch64 stack frame, the 33rd byte reaches the guard. The function detects the change before returning.

I’ll enable the canary and use a 33-byte input, which reaches the guard in the observed frame layout:

canary_flags=(-fstack-protector-strong)
"$CC" "${base[@]}" "${canary_flags[@]}" record.c -o canary
./canary "$short_overflow"
printf 'exit status: %d\n' "$?"
objdump -d --disassemble=show_record canary

The recorded run produced:

*** stack smashing detected ***: terminated
Aborted
exit status: 134

Exit status 134 indicates SIGABRT (128 + signal 6). In this GCC 15.2 build, field occupies stack-pointer offsets 24–55, followed by the guard at offset 56. The generated instructions load __stack_chk_guard, save it in the frame, and call __stack_chk_fail on a mismatch.

The check runs after memcpy and printf. It detects only writes that alter the guard and reach the check. It cannot undo the write or prevent earlier use of corrupted data.

2. Check library-copy bounds with fortification

glibc’s source fortification checks supported library calls when the compiler can determine the destination’s size. I’ll enable _FORTIFY_SOURCE=3 at -O2 and keep the canary:

A plain memcpy writes 33 bytes into a 32-byte field. The fortified call receives the field size and aborts before writing.

Figure 2. Fortification checks the requested copy size before writing, unlike post-write canary detection.

fortify_flags=("${canary_flags[@]}" -D_FORTIFY_SOURCE=3)
"$CC" "${base[@]}" "${fortify_flags[@]}" record.c -o fortified
./fortified "$short_overflow"
printf 'exit status: %d\n' "$?"
objdump -d --disassemble=show_record fortified

GCC emitted __memcpy_chk. Under the AArch64 calling convention, GCC passes the 32-byte destination capacity in x3, the fourth argument register. With 33 bytes requested, the check aborts before the copy:

*** buffer overflow detected ***: terminated
Aborted
exit status: 134

This also exits with SIGABRT, but the fortification check runs before the invalid write. The canary is not involved.

At fortification level 3, GCC can use __builtin_dynamic_object_size to find bounds that aren’t compile-time constants. Fortification still covers only supported operations with usable size information; it doesn’t catch arbitrary pointer writes. GCC may also remove a check when it can prove the operation is safe.

3. Randomize code locations with PIE and ASLR

An attacker who can change a return address or function pointer still needs a usable code address. Linux address space layout randomization (ASLR) varies memory mappings between processes. Building a position-independent executable (PIE) with -fPIE -pie lets the main executable load at different base addresses.

Three non-PIE launches report the same show_record address. Three PIE launches report different addresses under ASLR.

Figure 3. PIE permits a variable load address; ASLR selects it on each launch.

pie_flags=("${fortify_flags[@]}" -fPIE -pie)
"$CC" "${base[@]}" "${pie_flags[@]}" record.c -o pie
cat /proc/sys/kernel/randomize_va_space
printf 'non-PIE:\n'
for i in 1 2 3; do ./fortified --address; done
printf 'PIE:\n'
for i in 1 2 3; do ./pie --address; done
readelf -hW pie | grep 'Type:'

The original runs reported randomize_va_space as 2 and produced these addresses:

non-PIE:
show_record: 0x400980
show_record: 0x400980
show_record: 0x400980
PIE:
show_record: 0xaaaae12e0a80
show_record: 0xaaaad99d0a80
show_record: 0xaaaad9ca0a80
Type:                              DYN (Position-Independent Executable file)

The non-PIE address remained fixed while the PIE address changed. Shared objects also use the ELF type ET_DYN. I can confirm PIE by checking for PIE in the dynamic section’s FLAGS_1 entry.

readelf -dW pie | grep 'FLAGS_1.*PIE'

Three launches establish address variation, not the amount of randomness. An address leak can reveal the base. PRINT_ADDRESS serves this test only and won’t appear in the final build.

4. Prevent execution from the stack

An attacker who redirects execution to bytes placed on the stack needs an executable stack page. The GNU_STACK program header records whether the executable requests one. I’ll use -Wl,-z,noexecstack to request a non-executable stack:

Both stacks hold the same AArch64 return instruction. It executes on the RWE stack, while instruction fetch from the RW stack causes SIGSEGV.

Figure 4. The same stack-resident AArch64 instruction succeeds with RWE permissions and faults with RW permissions.

nx_flags=("${pie_flags[@]}" -Wl,-z,noexecstack)
"$CC" "${base[@]}" "${nx_flags[@]}" record.c -o nx
readelf -lW nx | grep 'GNU_STACK'

In the recorded binary, the GNU_STACK program header requests RW rather than RWE:

GNU_STACK      0x000000 0x0000000000000000 0x0000000000000000 0x000000 0x000000 RW  0x10

The record overflow hasn’t been shown to control the program counter. To test stack execution separately, I’ll use this AArch64-specific probe, saved as stack.c:

#include <stdio.h>

int main(void)
{
    volatile unsigned char code[] __attribute__((aligned(4))) =
        {0xc0, 0x03, 0x5f, 0xd6}; /* A64: RET X30 */
    __builtin___clear_cache((char *)code, (char *)code + sizeof code);
    ((void (*)(void))code)();
    puts("stack code returned");
}

The bytes encode the AArch64 RET X30 instruction in little-endian order. The array is four-byte aligned; __builtin___clear_cache synchronizes instruction caches where needed. Executing an array through a function pointer is intentionally nonportable.

"$CC" "${base[@]}" stack.c -o stack-exec
"$CC" "${base[@]}" -Wl,-z,noexecstack stack.c -o stack-nx
./stack-exec
printf 'exit status: %d\n' "$?"
./stack-nx
printf 'exit status: %d\n' "$?"

In the recorded environment:

stack code returned
exit status: 0
Segmentation fault
exit status: 139

stack-exec returned normally; stack-nx failed with SIGSEGV (exit status 139). A system with a stricter execution policy might reject both. NX prevents execution from the stack, not data corruption or reuse of existing executable code.

5. Make relocation data read-only with full RELRO

Dynamically linked binaries use relocation data to resolve symbols in shared libraries. Some indirect calls use entries in the Global Offset Table (GOT). If an attacker can overwrite such an entry, they may redirect a call.

Relocation read-only (RELRO) makes selected relocation data read-only after dynamic linking. Full RELRO uses eager binding (-z now) to resolve the affected function relocations before application code runs, so their GOT entries can be protected.

A writable puts GOT slot can be overwritten to redirect a call with partial RELRO. With full RELRO, the loader resolves the slot at startup and makes it read-only, so the write faults.

Figure 5. With full RELRO, the dynamic loader resolves the GOT entry before making its page read-only.

I’ll add full RELRO to the cumulative build:

linked_flags=("${nx_flags[@]}" -Wl,-z,relro,-z,now)
"$CC" "${base[@]}" "${linked_flags[@]}" record.c -o linked
readelf -lW linked | grep 'GNU_RELRO'
readelf -dW linked | grep -E 'BIND_NOW|FLAGS'

The output shows GNU_RELRO, BIND_NOW, and FLAGS_1: NOW PIE. I’ll also test whether a GOT slot is writable at runtime.

This probe assumes an arbitrary-address write, which the overflow in record.c has not demonstrated. It calls puts, replaces that call’s GOT entry, and calls puts again. Save it as relro.c:

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

static int replacement(const char *text)
{
    (void)text;
    const char message[] = "redirected call\n";
    /* Avoid calling through the puts slot being tested. */
    return write(STDOUT_FILENO, message, sizeof message - 1) < 0;
}

int main(int argc, char **argv)
{
    if (argc != 2)
        return 2;
    puts("original call");
    fflush(stdout);
    volatile uintptr_t *slot =
        (uintptr_t *)strtoull(argv[1], NULL, 0);
    *slot = (uintptr_t)replacement;
    puts("original call");
    return 0;
}

This probe relies on platform-specific function-pointer and address handling. replacement uses write so it doesn’t call through the slot being modified.

I’ll compare partial RELRO with lazy binding against full RELRO with eager binding. Both builds are non-PIE, so the offsets reported by readelf can be used as runtime addresses here.

"$CC" "${base[@]}" -Wl,-z,relro,-z,lazy relro.c -o partial
"$CC" "${base[@]}" -Wl,-z,relro,-z,now relro.c -o full
for binary in partial full; do
  slot=$(readelf -rW "$binary" |
    awk '/JUMP_SLOT/ && /puts@/ { print "0x" $1; exit }')
  test -n "$slot" || { printf 'puts slot missing\n'; break; }
  printf '[%s RELRO: puts slot %s]\n' "$binary" "$slot"
  ./"$binary" "$slot"
  printf 'exit status: %d\n\n' "$?"
done

The recorded run showed:

[partial RELRO: puts slot 0x420020]
original call
redirected call
exit status: 0

[full RELRO: puts slot 0x41ffc8]
original call
Segmentation fault
exit status: 139

Under partial RELRO, the second call was redirected. Under full RELRO, the write faulted. The addresses are specific to these builds. RELRO protects selected relocation data, not arbitrary writable function pointers or other application data.

Fix the input validation

None of these protections enforces the record format. A 32-byte copy fits the 32-byte array, so fortification may allow it even though it leaves no terminating zero. The record permits only 31 bytes of text. I’ll enable CHECK_LENGTH, retain the protections, and remove PRINT_ADDRESS:

"$CC" -std=c17 -O2 -g -Wall -Wextra -march=armv8-a \
  -DCHECK_LENGTH -D_FORTIFY_SOURCE=3 -fstack-protector-strong \
  -fPIE -pie -Wl,-z,relro,-z,now,-z,noexecstack \
  record.c -o record

printf '[repaired: 80 bytes]\n'
./record "$long_input"
printf 'exit status: %d\n\n' "$?"
printf '[repaired: 31 bytes]\n'
./record "$(repeat_x 31)"
printf 'exit status: %d\n\n' "$?"
printf '[repaired: 32 bytes]\n'
./record "$(repeat_x 32)"
printf 'exit status: %d\n\n' "$?"
printf '[fortified but unrepaired: 32 bytes]\n'
./fortified "$(repeat_x 32)"
printf 'exit status: %d\n' "$?"

The original run produced:

[repaired: 80 bytes]
record too long
exit status: 2

[repaired: 31 bytes]
record: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
exit status: 0

[repaired: 32 bytes]
record too long
exit status: 2

[fortified but unrepaired: 32 bytes]
record: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
exit status: 0

The repaired program accepts 31 bytes and rejects 32 or more. The fortified, unrepaired build accepts 32 because fortification checks memory bounds, not the record’s required terminator.

I’ll also inspect the linked executable rather than assuming that the requested flags took effect:

readelf -hW record | grep 'Type:'
readelf -lW record | grep -E 'GNU_STACK|GNU_RELRO'
readelf -dW record | grep -E 'BIND_NOW|FLAGS'
objdump -d --disassemble=show_record record |
  grep -E 'cmp.*0x1f|memcpy@plt|__stack_chk_fail@plt'

The ELF metadata confirms PIE, a non-executable GNU_STACK, GNU_RELRO, and eager binding. In the recorded build, the disassembly contains the 31-byte check, a plain memcpy, and the stack-canary failure path.

GCC used plain memcpy because the explicit length check proves that the copy fits. The absence of __memcpy_chk doesn’t mean fortification was disabled. Inspect the optimized control flow, not just the names of called functions.

Verify the production binary

I used explicit flags to isolate each protection. For production, I’d start with the compiler’s hardening options and check what they enable:

gcc-15 --help=hardened

GCC 15’s -fhardened combines several options used here with other mitigations, including stack-clash protection and automatic-variable initialization. The bundle varies by release and target; -fcf-protection=full, for example, applies to x86 GNU/Linux rather than this AArch64 test. An explicit weaker option can prevent -fhardened from enabling the corresponding stronger one, so don’t combine it with the disabling flags from the baseline.

For the dynamically linked ELF executable used here, verify-elf.sh checks the expected metadata:

#!/usr/bin/env bash
set -euo pipefail
binary=${1:?usage: verify-elf.sh BINARY}

header=$(readelf -hW "$binary")
segments=$(readelf -lW "$binary")
dynamic=$(readelf -dW "$binary")

[[ $header =~ Type:[[:space:]]+DYN ]] || {
  echo 'missing ET_DYN' >&2; exit 1;
}
[[ $dynamic =~ FLAGS_1.*PIE ]] || {
  echo 'missing PIE flag' >&2; exit 1;
}
awk '$1 == "GNU_STACK" { found=1; executable=($(NF-1) ~ /E/) }
     END { exit !(found && !executable) }' <<< "$segments" || {
  echo 'stack is executable or GNU_STACK is missing' >&2; exit 1;
}
[[ $segments == *GNU_RELRO* ]] || {
  echo 'missing GNU_RELRO' >&2; exit 1;
}
[[ $dynamic == *BIND_NOW* || $dynamic =~ FLAGS_1.*NOW ]] || {
  echo 'missing eager binding' >&2; exit 1;
}

echo 'ELF metadata checks passed'
chmod +x verify-elf.sh
./verify-elf.sh record

The script is specific to this kind of ELF executable. It doesn’t verify canary coverage, fortified calls, or source correctness. Static PIE, custom linker scripts, and other toolchains need different checks. I’d also test 31-, 32-, and 80-byte inputs, asserting the expected exit status rather than just checking for a crash.

Binary inspection complements source review and memory-error testing. A build flag alone doesn’t prove that the protection made it into the executable.

Conclusion

Stack canaries detect some overwrites on return; fortification stops some invalid copies before they write. PIE and ASLR make code addresses less predictable. NX prevents instruction fetch from the stack, while full RELRO protects selected relocation data. None enforces the record’s length limit.

The explicit length check fixes that defect. I’d keep the compiler and linker protections as additional defenses and verify them in CI. Hardening a Process covers the next layer: restricting what a compromised process can access.

Reproducing the experiments

I ran the experiments in an Ubuntu 26.04 container on Docker Desktop for Arm64. From the host directory containing the source files:

docker pull --platform linux/arm64 ubuntu:26.04
docker image inspect ubuntu:26.04 \
  --format '{{index .RepoDigests 0}}' | tee image-digest.txt
docker run --rm -it --platform linux/arm64 \
  --mount "type=bind,src=$PWD,dst=/work" -w /work ubuntu:26.04 bash

Inside the container:

apt-get update
apt-get install -y --no-install-recommends gcc-15 libc6-dev binutils
CC=gcc-15
{
  "$CC" -dumpfullversion
  "$CC" -dumpmachine
  getconf GNU_LIBC_VERSION
  ld --version | head -n 1
  dpkg-query -W -f='${binary:Package}\t${Version}\n' gcc-15 libc6 binutils
} | tee toolchain.txt
uname -m
uname -r

The recorded run also used apt-get upgrade -y before installing the tools. Its versions were:

Ubuntu image digest:
ubuntu@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a8198759f7

GCC:      15.2.0 (aarch64-linux-gnu)
glibc:    2.43
binutils: 2.46
Packages: gcc-15 15.2.0-16ubuntu1
          libc6:arm64 2.43-2ubuntu2.4
          binutils 2.46-3ubuntu2
Kernel:   7.0.14-linuxkit (aarch64)

The kernel is supplied by Docker Desktop’s Linux VM; Ubuntu supplies the userspace. The image digest pins only the base image, not packages installed later through APT. Reproducing the exact package set also requires version pins and an Ubuntu archive snapshot.

Instruction sequences, offsets, and addresses depend on the compiler, libraries, and platform. The outputs above are from GCC 15.2; yours may differ.