Skip to content

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

@MadsSFox

Description

@MadsSFox

Summary

Encrypted Kamstrup meters (and potentially other encrypted meters) report "HAN: Unknown data received, check meter config" even when encryption/authentication keys are correctly configured.

Root Cause

lib/AmsDecoder/src/GcmParser.cpp, line 99:

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

The loop variable i is declared but not initialized (uint8_t i instead of uint8_t i = 0). This is undefined behavior in C++.

In practice, i takes whatever value happens to be on the stack at that point. If i starts at a value ≥ 16, the loop body never executes, authenticate stays false, and the code silently takes the unauthenticated decrypt path — even when a valid authentication key is configured.

  • On ESP32 (mbedTLS path): skips mbedtls_gcm_auth_decrypt and falls through to mbedtls_gcm_starts + mbedtls_gcm_update, decrypting without verifying the auth tag → produces garbage output → "unknown data received"
  • On ESP8266 (BearSSL path): skips br_gcm_aad_inject, same effect

Symptom

After upgrading firmware, telnet debug shows:

(E) Context length 65534 > 768

or simply:

(W) HAN: Unknown data received, check meter config

The meter is detected (mt:3) but all frames are discarded.

Affected Hardware

Any meter using GCM encryption with an authentication key (security byte 0x30), including Kamstrup Omnipower with GPK60/GPK61 keys (Danish grid companies).

Fix

Initialize i to 0:

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

See PR #1163.

Related

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions