Skip to content

Fix uninitialized loop variable in GcmParser (undefined behavior in authentication check)#1163

Open
MadsSFox wants to merge 1 commit intoUtilitechAS:mainfrom
MadsSFox:fix/encrypted-kamstrup-segmented-frames
Open

Fix uninitialized loop variable in GcmParser (undefined behavior in authentication check)#1163
MadsSFox wants to merge 1 commit intoUtilitechAS:mainfrom
MadsSFox:fix/encrypted-kamstrup-segmented-frames

Conversation

@MadsSFox
Copy link
Copy Markdown

@MadsSFox MadsSFox commented Mar 15, 2026

Problem

Encrypted Kamstrup meters (and other meters with authentication keys) report "HAN: Unknown data received" even when keys are correctly configured.

Closes #1164

Root Cause

lib/AmsDecoder/src/GcmParser.cpp line 99 has an uninitialized loop variable:

// Before (bug):
for(uint8_t i; i < 16; i++) authenticate |= authentication_key[i] > 0;

i is declared but never initialized — undefined behavior in C++. When i starts at ≥ 16 (depending on stack contents), the loop never executes, authenticate stays false, and decryption proceeds without authentication even when an auth key is configured. This produces garbage output that fails all subsequent parsing.

Fix

// After (fix):
for(uint8_t i = 0; i < 16; i++) authenticate |= authentication_key[i] > 0;

Testing

Verified against a Kamstrup Omnipower meter (Danish grid, GPK60 auth key) running on ESP8266. Before fix: "Unknown data received". After fix: frames decrypt and parse correctly.

Related

In GcmParser::parse(), the authentication check loop used an uninitialized
loop counter: `for(uint8_t i; i < 16; i++)`. This is undefined behavior in
C++ because `i` has an indeterminate value, potentially causing the
authentication check to be skipped entirely or to read out-of-bounds memory.

Fix: initialize `i` to 0 so the loop correctly iterates all 16 bytes of
the authentication key.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
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.

GcmParser: uninitialized loop variable causes authentication to be randomly skipped on encrypted Kamstrup meters

1 participant