Skip to content

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

Merged
gskjold merged 1 commit into
UtilitechAS:mainfrom
MadsSFox:fix/encrypted-kamstrup-segmented-frames
Apr 9, 2026
Merged

gskjold merged 1 commit into
UtilitechAS:mainfrom
MadsSFox:fix/encrypted-kamstrup-segmented-frames

Conversation

@MadsSFox

@MadsSFox MadsSFox commented Mar 15, 2026 •

Copy link
Copy Markdown
Contributor

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 <[email protected]>
@gskjold gskjold added this to the v2.5.7 milestone Apr 9, 2026
@gskjold
gskjold merged commit 6011d31 into UtilitechAS:main Apr 9, 2026
6 of 7 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.

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

2 participants