Skip to content

Fix AES context alignment in heap allocations - #12110

Merged
JacobBarthelmeh merged 1 commit into
wolfSSL:masterfrom
danielinux:fix-aes-alloc-align
Nov 18, 2026
Merged

JacobBarthelmeh merged 1 commit into
wolfSSL:masterfrom
danielinux:fix-aes-alloc-align

Conversation

@danielinux

@danielinux danielinux commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Description

Summary

Fix heap allocation alignment for Aes and Cmac contexts. Both structures carry alignment attributes on members, but XMALLOC only guarantees 8-byte alignment, which faults on 32-bit Arm where the aligned members need 16 bytes.

Root cause

The reported armhf SIGBUS was initially attributed to _sp_div because the runtime PC was translated using the executable's file offset. This PIE executable's text virtual address is 0x10000 higher than that offset. Correcting the translation places the fault in wc_AesSetKeyLocal, at a NEON store to aes->reg that requires 16-byte alignment.

The fault address was only 8-byte aligned. Aes has 16-byte-aligned members, but XMALLOC can return an 8-byte-aligned pointer on 32-bit Arm. Passing that pointer as an Aes* lets the compiler emit an alignment-qualified store that faults. Cmac has the same property: its members are alignment-qualified, so heap-allocated Cmac contexts (EVP CMAC, KDF) carry the same hazard.

Changes

  • Add wc_alloc_aligned/wc_free_aligned in aes.c (WOLFSSL_API, active when WOLFSSL_USE_ALIGN && WC_ALIGNOF && !WOLFSSL_TI_CRYPT). They over-allocate, align to the requested boundary, and keep the original XMALLOC pointer so the matching free uses the correct address, heap, and allocation type. aes.c is compiled exactly where the allocation macros can be active: WOLFSSL_CMAC implies AES, so every consumer (cmac.c, kdf.c, ssl_crypto.c, test.c) has this object linked, including leantls and --disable-memory builds where memory.c is excluded.
  • Add WC_ALLOC_AES/WC_FREE_AES in aes.h and WC_ALLOC_CMAC/WC_FREE_CMAC in cmac.h. The aligned branches route through the helpers; the fallback branches are plain XMALLOC/XFREE macros so builds without the aligned allocator pay no indirection. Free fallbacks are statement-safe (XFREE is a do-while in static-memory builds); alloc fallbacks cast for C++.
  • Keep the prototypes unguarded and inside the extern "C" block. memory.h is included mid-types.h, before WOLFSSL_USE_ALIGN exists in ARMASM/AESNI builds, so a guarded declaration there is invisible exactly where it is needed; a C++-linked declaration would mangle the definition when the library is built as C++.
  • The cmac aligned branch additionally requires WC_ALLOC_AES: in FIPS bundle builds the aes.h/aes.c pair is the frozen module version, so the macro falls back to plain allocation there. FIPS builds with frozen cmac.h use the existing #ifndef WC_ALLOC_CMAC fallback in ssl_crypto.c and test.c.
  • Use the macros in wc_AesNew and the four small-stack AES key-wrap and unwrap wrappers (including the padded variants), wc_CmacNew/cleanup paths, wc_KDF, the EVP CMAC functions, and the test helpers. Add a constructor alignment check to the AES test, update a test comment, and fix AES whitebox test cleanup for aligned allocations.

The helpers apply wherever alignment is enabled, regardless of architecture or assembly settings. The Aes and Cmac structure layouts are unchanged.

Relationship to #11949

PR 11949 adds general aligned-allocation APIs, but it does not switch wc_AesNew, the AES key-wrap wrappers, or the Cmac contexts to those APIs. It converts one test helper that already aligned its allocation manually. Merging PR 11949 alone therefore leaves the faulting allocations unchanged. If PR 11949 lands first, the call sites here switch to its wc_MallocAlign/wc_FreeAlign pair and the local helpers go away; the caller updates are still needed either way.

Validation

  • GCC small-stack AES key-wrap build: wolfCrypt test suite passed.
  • Clang small-stack AES key-wrap build, including padded key wrap: wolfCrypt test suite passed.
  • Clang smoke test with an allocator deliberately returning 8-byte-aligned memory: AES construction, key setup, wrap, and unwrap passed.
  • Full CI matrix green: default + make check, whole-library C++ build (linkage/mangling), CAVP selftest config with frozen aes.h (FIPS bundle fallback), leantls-extra, --disable-memory, --disable-aes, cryptonly, make distcheck, -Wextra -Werror translation units, static-memory and FIPS-fallback units, and an AESNI translation unit covering the late WOLFSSL_USE_ALIGN definition.

Fenrir

  • Fixes F-11986

Copilot AI balanced review requested due to automatic review settings November 12, 2026 11:39

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@github-actions

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

MemBrowse Memory Report · Explore what changed →

zephyr-frdm_rw612

  • FLASH: datas +16 B, log_const_area -8 B, rodata +104 B, text +13,208 B (+4.7%, 295,784 B / 67,108,864 B, total: 0% used)
  • RAM: bss +49 B, datas +16 B (+0.1%, 58,423 B / 983,040 B, total: 6% used)

No memory changes detected for:


Catch memory regressions in CI with MemBrowse. Free for open source.

@wolfSSL-Fenrir-bot wolfSSL-Fenrir-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fenrir Automated Review — PR #12110

Scan targets checked: wolfcrypt-src, wolfcrypt-bugs
Coverage: 2 of 2 in-scope changed file(s) opened by the reviewer

Findings: 1
1 finding(s) posted as inline comments (see file-level comments below)

This review was generated automatically by Fenrir. Reported findings require changes before merge.

Review tier: Max

Comment thread wolfcrypt/test/test.c Resolved

@wolfSSL-Fenrir-bot wolfSSL-Fenrir-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fenrir Automated Review — PR #12110

Scan targets checked: wolfcrypt-src, wolfcrypt-bugs, wolfssl-bugs
Coverage: 2 of 2 in-scope changed file(s) opened by the reviewer

Fenrir result: Approved ✅

No new issues found in the changed files.

Advisory only — this automated result does not count as a GitHub approval.

Review tier: Lite

@wolfSSL-Fenrir-bot
wolfSSL-Fenrir-bot dismissed their stale review November 12, 2026 11:58

Fenrir's latest completed scan found no issues; clearing the prior automated change request.

@philljj

philljj commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

@claude review

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Beyond the inline findings, I also checked the pointer arithmetic in AesAlloc/AesAllocFree and found no problem with it. Rounding raw + sizeof(void*) up leaves room for the stored base pointer. The Aes object fits in the extra align - 1 + sizeof(void*) bytes. The base-pointer slot is pointer-aligned. The key-wrap allocation-failure paths return before reaching out:, so they never free a NULL aes.

Extended reasoning...

I checked the AesAlloc/AesAllocFree pointer arithmetic and the key-wrap small-stack cleanup paths in wolfcrypt/src/aes.c and found no problem in either. The inline comments already cover the open problems.

Findings marked 🟡 are optional suggestions and need no follow-up push.

Comment thread wolfcrypt/src/aes.c Resolved
Comment thread wolfcrypt/src/aes.c Resolved
Comment thread wolfcrypt/src/aes.c Resolved
@dgarske dgarske self-assigned this Nov 12, 2026

@dgarske dgarske left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced F-11986 on a Raspberry Pi 4 (32-bit armhf binary, clang 18, -march=armv8-a -mfpu=crypto-neon-fp-armv8) and under qemu-arm. gcc 13 does not fault: it only puts :64 hints on stores into Aes. clang emits vst1.64 {d16-d17}, [r0 :128] on the iv == NULL branch of wc_AesSetIV() and in wc_AesKeyWrap(), so any NULL-IV wc_AesSetKey()/wc_AesSetIV() on a heap Aes that is 8 mod 16 faults.

With this PR applied and an allocator returning blocks at 8 mod 16, these still SIGBUS on the Pi 4:

  • wc_AesSetKey(aes, key, len, NULL, dir) on an XMALLOC(sizeof(Aes))
  • wc_InitCmac() on an XMALLOC(sizeof(Cmac)), as in kdf.c and ssl_crypto.c
  • wc_AesCmacGenerate() with WOLFSSL_SMALL_STACK
  • wc_SRTP_KDF()

So this fixes key wrap and wc_AesNew(), but the class stays open across the other heap Aes/Cmac allocations (TLS record layer, DTLS 1.3, PKCS7, ECIES, HPKE, SHE, KDF, EVP).

The root cause is the declaration rather than the call sites. On 32-bit Arm, ALIGN16 promises the compiler more than malloc guarantees, and the 32-bit Arm AES/GCM assembly uses no alignment hints, so the over-alignment buys nothing there. Capping WOLFSSL_ALIGN() at 8 on 32-bit Arm with NEON, next to the existing IAR cap in types.h, removes every one of these faults on the Pi 4 and under qemu, and AES/GCM/CMAC throughput on the Pi 4 is unchanged. It leaves Cortex-M alone (no NEON). It does change the Aes/Cmac/Gcm layout on those builds, so it needs to land at a release boundary. With it in place, the helper in this PR is not needed.

Suggested patch, against current master:

diff --git a/wolfssl/wolfcrypt/types.h b/wolfssl/wolfcrypt/types.h
--- a/wolfssl/wolfcrypt/types.h
+++ b/wolfssl/wolfcrypt/types.h
@@ -2005,6 +2005,10 @@ WOLFSSL_API word32 CheckRunTimeSettings(void);
         * higher alignment. */
     #if defined(__ICCARM__)
         #define WOLFSSL_ALIGN(x) XALIGNED(8)
+    #elif defined(__arm__) && (defined(__ARM_NEON) || defined(__ARM_NEON__))
+        /* 32-bit Arm malloc only guarantees 8 bytes. Over-aligned heap
+         * contexts let the compiler emit faulting :128 NEON stores. */
+        #define WOLFSSL_ALIGN(x) XALIGNED(((x) > 8) ? 8 : (x))
     #else
         #define WOLFSSL_ALIGN(x) XALIGNED(x)
     #endif

Notes on the patch:

  • min(x, 8) rather than the flat XALIGNED(8) used for IAR, so ALIGN4 members keep their layout. Only types that were over-aligned change.
  • Every ALIGNxx macro is still #ifndef-guarded, so a port that really needs a 16-byte buffer on armhf can override it.
  • On armhf with the patch: no :128/:256-hinted stores remain in the library, all of the cases above pass on the Pi 4 with every allocation at 8 mod 16, and --enable-all --enable-smallstack testwolfcrypt and the API tests pass under the same allocator.
  • One port to check: se050_port.c declares alignedIn/alignedOut as ALIGN16, and they become 8-aligned on an armhf NEON host build.
  • #11969 documents 16-byte alignment for these contexts. On 32-bit Arm with NEON that becomes 8, so the note needs that exception.

@dgarske dgarske assigned danielinux and unassigned dgarske and douzzer Nov 12, 2026
@dgarske dgarske mentioned this pull request Nov 12, 2026
4 tasks done
@danielinux
danielinux requested a review from dgarske November 16, 2026 18:41
Comment thread wolfcrypt/src/aes.c Resolved
@danielinux

Copy link
Copy Markdown
Member Author

jenkins retest this please

@danielinux
danielinux requested a review from dgarske November 17, 2026 14:19
@danielinux danielinux assigned dgarske and unassigned danielinux Nov 17, 2026
Comment thread wolfcrypt/src/alloc_align.h Resolved
@dgarske dgarske removed their assignment Nov 17, 2026
@dgarske
dgarske self-requested a review November 17, 2026 16:47
dgarske
dgarske previously approved these changes Nov 18, 2026
@danielinux
danielinux dismissed dgarske’s stale review November 18, 2026 09:20

The merge-base changed after approval.

@danielinux

Copy link
Copy Markdown
Member Author

Squashed after @dgarske 's approval, as requested.

@danielinux

Copy link
Copy Markdown
Member Author

jenkins retest this please

@danielinux danielinux removed their assignment Nov 18, 2026
dgarske
dgarske previously approved these changes Nov 18, 2026
Comment thread IDE/WIN/wolfssl-fips.vcxproj Resolved
Aes and Cmac contexts carry alignment attributes on members, but malloc
only guarantees 8-byte alignment: on 32-bit Arm the contexts are
misaligned and the AES-NI/NEON paths SIGBUS (Fenrir F-11986).

Over-allocate, align, and keep the original pointer for XFREE:
- wc_alloc_aligned/wc_free_aligned in aes.c, WOLFSSL_API, guarded by
  WOLFSSL_USE_ALIGN && WC_ALIGNOF && !WOLFSSL_TI_CRYPT. aes.c is
  compiled exactly where the allocation macros can be active:
  WOLFSSL_CMAC implies AES, so every consumer has this object linked.
- WC_ALLOC_AES/WC_FREE_AES in aes.h, WC_ALLOC_CMAC/WC_FREE_CMAC in
  cmac.h, with plain XMALLOC/XFREE fallback macros so builds without
  the aligned allocator pay no indirection. The free fallbacks are
  statement-safe (XFREE is a do-while in static-memory builds) and the
  alloc fallbacks cast for C++.
- Prototypes are unguarded and inside the extern "C" block: memory.h
  is included mid-types.h, before WOLFSSL_USE_ALIGN exists in
  ARMASM/AESNI builds, so a guarded declaration there is invisible
  exactly where it is needed, and a C++-linked declaration would
  mangle the definition.
- The cmac aligned branch additionally requires WC_ALLOC_AES: in FIPS
  bundle builds the aes.h/aes.c pair is the frozen module version, so
  the macro falls back to plain allocation there.

Call sites: aes.c, cmac.c, kdf.c, ssl_crypto.c, test.c, plus AES
whitebox test cleanup for aligned allocations.

Bridge to wolfSSL#11949 (generic aligned allocators) when it lands: the
call sites then switch to wc_MallocAlign/wc_FreeAlign.
@JacobBarthelmeh
JacobBarthelmeh merged commit dfb6574 into wolfSSL:master Nov 18, 2026
456 of 457 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants