From 55b7570701e7ac4109526325963b0ab2888394fd Mon Sep 17 00:00:00 2001 From: Bryan Biedenkapp Date: Wed, 14 Oct 2026 16:26:35 -0400 Subject: [PATCH] implement Change-RSI KMM encoding/decoding; recover from authenticated invalid-MN rekey NAKs using Change-RSI; resume rekeying after successful message-number resynchronization; optionally issue keyset changeover after rekey completion; --- configs/fne-config.example.yml | 2 + src/common/p25/kmm/KMMChangeRSI.cpp | 116 ++++++++++ src/common/p25/kmm/KMMChangeRSI.h | 95 ++++++++ src/common/p25/kmm/KMMFactory.cpp | 27 ++- src/common/p25/kmm/KMMFactory.h | 1 + src/fne/network/P25OTARService.cpp | 335 ++++++++++++++++++++-------- src/fne/network/P25OTARService.h | 22 +- src/fne/network/TrafficNetwork.cpp | 3 + src/fne/network/TrafficNetwork.h | 1 + tests/p25/P25_KMM_Tests.cpp | 155 ++++++++++++- 10 files changed, 655 insertions(+), 102 deletions(-) create mode 100644 src/common/p25/kmm/KMMChangeRSI.cpp create mode 100644 src/common/p25/kmm/KMMChangeRSI.h diff --git a/configs/fne-config.example.yml b/configs/fne-config.example.yml index edb7f253..821fb66e 100644 --- a/configs/fne-config.example.yml +++ b/configs/fne-config.example.yml @@ -241,6 +241,8 @@ master: # Flag indicating whether or not P25 OTAR KMF services will allow a warm start rekey request. warmStart: true + # Flag indicating whether or not a keyset changeover should occur automatically after a rekey. + changeoverAfterRekey: true # Flag indicating whether or not verbose debug logging for P25 OTAR KMF services is enabled. debug: false diff --git a/src/common/p25/kmm/KMMChangeRSI.cpp b/src/common/p25/kmm/KMMChangeRSI.cpp new file mode 100644 index 00000000..b2519074 --- /dev/null +++ b/src/common/p25/kmm/KMMChangeRSI.cpp @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Digital Voice Modem - Common Library + * GPLv2 Open Source. Use is subject to license terms. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright (C) 2026 Bryan Biedenkapp, N2PLL + * + */ +#include "Defines.h" +#include "p25/P25Defines.h" +#include "p25/kmm/KMMChangeRSI.h" + +using namespace p25; +using namespace p25::defines; +using namespace p25::kmm; + +#include + +// --------------------------------------------------------------------------- +// Public Class Members +// --------------------------------------------------------------------------- + +/* Initializes a new instance of the KMMChangeRSI class. */ + +KMMChangeRSI::KMMChangeRSI() : KMMFrame(), + m_oldRSI(0U), + m_newRSI(0U), + m_initialMessageNumber(0U), + m_status(KMM_Status::CMD_NOT_PERFORMED) +{ + m_messageId = KMM_MessageType::CHANGE_RSI_CMD; + m_respKind = KMM_ResponseKind::IMMEDIATE; +} + +/* Finalizes a instance of the KMMChangeRSI class. */ + +KMMChangeRSI::~KMMChangeRSI() = default; + +/* Gets the byte length of this KMM frame. */ + +uint32_t KMMChangeRSI::length() const +{ + // Count + old RSI + new RSI + (new MN for command | status for response). + return KMMFrame::length() + + (m_messageId == KMM_MessageType::CHANGE_RSI_RSP ? 8U : 9U); +} + +/* Decode a KMM Change-RSI command or response. */ + +bool KMMChangeRSI::decode(const uint8_t* data) +{ + assert(data != nullptr); + + decodeHeader(data); + + if (data[10U + m_bodyOffset] == 0U) + return false; + + m_oldRSI = GET_UINT24(data, 11U + m_bodyOffset); + m_newRSI = GET_UINT24(data, 14U + m_bodyOffset); + + if (m_messageId == KMM_MessageType::CHANGE_RSI_RSP) + m_status = data[17U + m_bodyOffset]; + else + m_initialMessageNumber = GET_UINT16(data, 17U + m_bodyOffset); + + return true; +} + +/* Encode a KMM Change-RSI command or response. */ + +void KMMChangeRSI::encode(uint8_t* data) +{ + assert(data != nullptr); + + m_messageLength = length(); + encodeHeader(data); + + data[10U + m_bodyOffset] = 1U; + SET_UINT24(m_oldRSI, data, 11U + m_bodyOffset); + SET_UINT24(m_newRSI, data, 14U + m_bodyOffset); + + if (m_messageId == KMM_MessageType::CHANGE_RSI_RSP) { + data[17U + m_bodyOffset] = m_status; + } + else { + SET_UINT16(m_initialMessageNumber, data, 17U + m_bodyOffset); + } +} + +/* Returns a string that represents the current KMM frame. */ + +std::string KMMChangeRSI::toString() +{ + if (m_messageId == KMM_MessageType::CHANGE_RSI_RSP) + return std::string("KMM, CHANGE_RSI_RSP (Change RSI Response)"); + + return std::string("KMM, CHANGE_RSI_CMD (Change RSI Command)"); +} + +// --------------------------------------------------------------------------- +// Protected Class Members +// --------------------------------------------------------------------------- + +/* Internal helper to copy the the class. */ + +void KMMChangeRSI::copy(const KMMChangeRSI& data) +{ + KMMFrame::copy(data); + + m_oldRSI = data.m_oldRSI; + m_newRSI = data.m_newRSI; + m_initialMessageNumber = data.m_initialMessageNumber; + m_status = data.m_status; +} diff --git a/src/common/p25/kmm/KMMChangeRSI.h b/src/common/p25/kmm/KMMChangeRSI.h new file mode 100644 index 00000000..8a68a78a --- /dev/null +++ b/src/common/p25/kmm/KMMChangeRSI.h @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Digital Voice Modem - Common Library + * GPLv2 Open Source. Use is subject to license terms. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright (C) 2026 Bryan Biedenkapp, N2PLL + * + */ +/** + * @file KMMChangeRSI.h + * @ingroup p25_kmm + * @file KMMChangeRSI.cpp + * @ingroup p25_kmm + */ +#if !defined(__P25_KMM__KMM_CHANGE_RSI_H__) +#define __P25_KMM__KMM_CHANGE_RSI_H__ + +#include "common/Defines.h" +#include "common/p25/kmm/KMMFrame.h" +#include "common/Utils.h" + +#include + +namespace p25 +{ + namespace kmm + { + // --------------------------------------------------------------------------- + // Class Declaration + // --------------------------------------------------------------------------- + + /** + * @brief Represents a KMM Change-RSI command or response. + * @ingroup p25_kmm + */ + class DVM_COMMON_API KMMChangeRSI : public KMMFrame { + public: + /** + * @brief Initializes a new instance of the KMMChangeRSI class. + */ + KMMChangeRSI(); + /** + * @brief Finalizes a instance of the KMMChangeRSI class. + */ + ~KMMChangeRSI(); + + /** + * @brief Gets the byte length of this KMM frame. + * @returns uint32_t Length of this KMM frame. + */ + uint32_t length() const override; + + /** + * @brief Decode a KMM Change-RSI command or response. + * @param data Buffer containing KMM frame data. + * @returns bool True, if KMM frame decoded; otherwise, false. + */ + bool decode(const uint8_t* data) override; + /** + * @brief Encode a KMM Change-RSI command or response. + * @param data Buffer to encode KMM frame data to. + */ + void encode(uint8_t* data) override; + + /** + * @brief Returns a string that represents the current KMM frame. + * @returns std::string String representation of the KMM frame. + */ + std::string toString() override; + + public: + /** + * @brief Old RSI. + */ + DECLARE_PROPERTY(uint32_t, oldRSI, OldRSI); + /** + * @brief New RSI. + */ + DECLARE_PROPERTY(uint32_t, newRSI, NewRSI); + /** + * @brief Initial message number. + */ + DECLARE_PROPERTY(uint16_t, initialMessageNumber, InitialMessageNumber); + /** + * @brief Command execution status. + */ + DECLARE_PROPERTY(uint8_t, status, Status); + + DECLARE_COPY(KMMChangeRSI); + }; + } // namespace kmm +} // namespace p25 + +#endif // __P25_KMM__KMM_CHANGE_RSI_H__ diff --git a/src/common/p25/kmm/KMMFactory.cpp b/src/common/p25/kmm/KMMFactory.cpp index 61f92d79..d9402001 100644 --- a/src/common/p25/kmm/KMMFactory.cpp +++ b/src/common/p25/kmm/KMMFactory.cpp @@ -40,6 +40,9 @@ std::unique_ptr KMMFactory::create(const uint8_t* data) uint8_t messageId = data[0U]; // Message ID switch (messageId) { + case KMM_MessageType::CHANGE_RSI_CMD: + case KMM_MessageType::CHANGE_RSI_RSP: + return decode(new KMMChangeRSI(), data); case KMM_MessageType::CHANGEOVER_CMD: case KMM_MessageType::CHANGEOVER_RSP: return decode(new KMMChangeover(), data); @@ -137,6 +140,14 @@ std::unique_ptr KMMFactory::create(const uint8_t* data, uint32_t len) const uint32_t available = bodyEnd - body; switch (data[0U]) { + case KMM_MessageType::CHANGE_RSI_CMD: + if (available != 9U || data[body] != 1U) + return nullptr; + break; + case KMM_MessageType::CHANGE_RSI_RSP: + if (available != 8U || data[body] != 1U) + return nullptr; + break; case KMM_MessageType::CHANGEOVER_CMD: case KMM_MessageType::CHANGEOVER_RSP: if (available < 1U || data[body] == 0U || @@ -165,26 +176,26 @@ std::unique_ptr KMMFactory::create(const uint8_t* data, uint32_t len) break; case KMM_MessageType::WARM_START_CMD: { - if (available < 11U || mnCode != 2U || macType != KMM_MAC::ENH_MAC || - ((data[3U] >> 6U) & 0x03U) != KMM_ResponseKind::IMMEDIATE) + if (available < 11U || mnCode != 2U || macType != KMM_MAC::ENH_MAC || ((data[3U] >> 6U) & 0x03U) != KMM_ResponseKind::IMMEDIATE) return nullptr; + const uint8_t decryptFormat = data[body]; if (decryptFormat != KMM_DECRYPT_INSTRUCT_NONE && decryptFormat != KMM_DECRYPT_INSTRUCT_MI) return nullptr; + const uint32_t miLength = decryptFormat == KMM_DECRYPT_INSTRUCT_MI ? MI_LENGTH_BYTES : 0U; if (available < 11U + miLength) return nullptr; + const uint32_t keyLengthOffset = body + 4U + miLength; const uint8_t keyLength = data[keyLengthOffset]; const uint32_t keyFormatOffset = keyLengthOffset + 2U; - const uint16_t sln = (uint16_t)(((uint16_t)data[keyFormatOffset + 1U] << 8U) | - data[keyFormatOffset + 2U]); - const uint16_t temporaryKId = (uint16_t)(((uint16_t)data[keyFormatOffset + 3U] << 8U) | - data[keyFormatOffset + 4U]); + const uint16_t sln = (uint16_t)(((uint16_t)data[keyFormatOffset + 1U] << 8U) | data[keyFormatOffset + 2U]); + const uint16_t temporaryKId = (uint16_t)(((uint16_t)data[keyFormatOffset + 3U] << 8U) | data[keyFormatOffset + 4U]); + if (data[body + 1U] != ALGO_AES_256 || keyLength != P25DEF::MAX_WRAPPED_ENC_KEY_LENGTH_BYTES || data[keyLengthOffset + 1U] != ALGO_AES_256 || temporaryKId == 0U || - available != 11U + miLength + keyLength || - (data[keyFormatOffset] & 0xE0U) != KMM_KEY_FORMAT_TEK || + available != 11U + miLength + keyLength || (data[keyFormatOffset] & 0xE0U) != KMM_KEY_FORMAT_TEK || (data[keyFormatOffset] & 0x1FU) != 0U || sln != 0U) return nullptr; } diff --git a/src/common/p25/kmm/KMMFactory.h b/src/common/p25/kmm/KMMFactory.h index c2ad95db..15116af3 100644 --- a/src/common/p25/kmm/KMMFactory.h +++ b/src/common/p25/kmm/KMMFactory.h @@ -21,6 +21,7 @@ #include "common/p25/kmm/KeysetItem.h" #include "common/p25/kmm/KMMFrame.h" +#include "common/p25/kmm/KMMChangeRSI.h" #include "common/p25/kmm/KMMChangeover.h" #include "common/p25/kmm/KMMDeregistrationCommand.h" #include "common/p25/kmm/KMMDeregistrationResponse.h" diff --git a/src/fne/network/P25OTARService.cpp b/src/fne/network/P25OTARService.cpp index 13692bfa..ba2169be 100644 --- a/src/fne/network/P25OTARService.cpp +++ b/src/fne/network/P25OTARService.cpp @@ -93,6 +93,8 @@ static void eraseBytes(uint8_t* data, size_t length) bool isSupportedKMM(uint8_t messageId) { switch (messageId) { + case KMM_MessageType::CHANGE_RSI_CMD: + case KMM_MessageType::CHANGE_RSI_RSP: case KMM_MessageType::CHANGEOVER_CMD: case KMM_MessageType::CHANGEOVER_RSP: case KMM_MessageType::HELLO: @@ -403,7 +405,8 @@ void P25OTARService::clock(uint32_t ms) const uint64_t now = monotonicMilliseconds(); std::vector timedOutWarmStarts; - if (m_network->m_kmfWarmStart) { + // scope is intentional + { // scope is intentional { std::lock_guard lock(m_warmStartMutex); @@ -988,12 +991,11 @@ UInt8Array P25OTARService::processKMM(const uint8_t* data, uint32_t len, uint32_ if (!frame->verifyMAC(tek, buffer.get(), len)) { if (frame->getMessageId() == KMM_MessageType::NAK) { KMMNegativeAck* nack = static_cast(frame.get()); - LogWarning(LOG_P25, P25_KMM_STR ", received unauthenticated KMM NACK, RSI = %u, rejectedMessageId = $%02X, rejectedMN = %u, status = $%02X, headerMN = %u, macKId = $%04X, macFormat = $%02X", - frame->getSrcLLId(), nack->getNakMessageId(), nack->getMessageNumber(), - nack->getStatus(), nack->KMMFrame::getMessageNumber(), frame->getMACKId(), - frame->getMACFormat()); - logResponseStatus(llId, nack->toString(), nack->getStatus()); + LogWarning(LOG_P25, P25_KMM_STR ", received unauthenticated KMM NACK, RSI = %u, rejectedMessageId = $%02X, rejectedMN = %u, status = $%02X (%s), headerMN = %u, macKId = $%04X, macFormat = $%02X", + frame->getSrcLLId(), nack->getNakMessageId(), nack->getMessageNumber(), nack->getStatus(), statusToString(nack->getStatus()).c_str(), + nack->KMMFrame::getMessageNumber(), frame->getMACKId(), frame->getMACFormat()); } + LogWarning(LOG_P25, P25_KMM_STR ", invalid MAC, RSI = %u", frame->getSrcLLId()); return makeNack(KMM_Status::INVALID_MAC); } @@ -1052,16 +1054,21 @@ UInt8Array P25OTARService::processKMM(const uint8_t* data, uint32_t len, uint32_ KMMHello* kmm = static_cast(frame.get()); uint8_t respKind = kmm->getResponseKind(); if (m_verbose) { - LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, flag = $%02X, auth = %u", kmm->toString().c_str(), - llId, kmm->getFlag(), auth.authenticated); + std::string flagStr; switch (kmm->getFlag()) { case KMM_HelloFlag::REKEY_REQUEST_UKEK: - LogInfoEx(LOG_P25, P25_KMM_STR ", %s, rekey requested with UKEK, llId = %u", kmm->toString().c_str(), llId); + flagStr = "rekey requested with UKEK"; break; case KMM_HelloFlag::REKEY_REQUEST_NO_UKEK: - LogInfoEx(LOG_P25, P25_KMM_STR ", %s, rekey requested with no UKEK, llId = %u", kmm->toString().c_str(), llId); + flagStr = "rekey requested with no UKEK"; + break; + default: + flagStr = "unknown flag"; break; } + + LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, flag = $%02X (%s), auth = %u, MN = %u", kmm->toString().c_str(), + llId, kmm->getFlag(), flagStr.c_str(), auth.authenticated, kmm->getMessageNumber()); } // ignore Response Kind 2 command requests initiated from a SU @@ -1129,24 +1136,90 @@ UInt8Array P25OTARService::processKMM(const uint8_t* data, uint32_t len, uint32_ case KMM_MessageType::NAK: { KMMNegativeAck* kmm = static_cast(frame.get()); - LogWarning(LOG_P25, P25_KMM_STR ", authenticated %s, llId = %u, rejectedMessageId = $%02X, rejectedMN = %u, status = $%02X, headerMN = %u", - kmm->toString().c_str(), llId, kmm->getNakMessageId(), - kmm->getMessageNumber(), kmm->getStatus(), kmm->KMMFrame::getMessageNumber()); - logResponseStatus(llId, kmm->toString(), kmm->getStatus()); + LogWarning(LOG_P25, P25_KMM_STR ", authenticated %s, llId = %u, rejectedMessageId = $%02X, rejectedMN = %u, status = $%02X (%s), headerMN = %u", + kmm->toString().c_str(), llId, kmm->getNakMessageId(), kmm->getMessageNumber(), kmm->getStatus(), statusToString(kmm->getStatus()).c_str(), + kmm->KMMFrame::getMessageNumber()); + + // AACA-D 8.2.1: an authenticated Invalid Message Number NAK for + // an outstanding Rekey starts a same-RSI Change-RSI procedure. + // The NAK header supplies the current authenticated SU MN; the + // body identifies the exact rejected outbound transaction. + if (auth.authenticated && kmm->getStatus() == KMM_Status::INVALID_MSG_NUMBER && + kmm->getNakMessageId() == KMM_MessageType::REKEY_CMD && + kmm->getHasMessageNumber()) { + bool correlated = false; + { + std::lock_guard lock(m_warmStartMutex); + auto it = m_warmStartTransactions.find(kmm->getSrcLLId()); + correlated = it != m_warmStartTransactions.end() && + it->second.state == WarmStartState::WAIT_REKEY_ACK && + std::find(it->second.pendingRekeyMNs.begin(), it->second.pendingRekeyMNs.end(), kmm->getMessageNumber()) != it->second.pendingRekeyMNs.end(); + } + + // if the NAK is correlated with an outstanding Rekey transaction, initiate a Change-RSI procedure + if (correlated) { + const uint16_t currentSUMN = kmm->KMMFrame::getMessageNumber(); + const uint16_t initialMN = (uint16_t)(currentSUMN + 1U); + return write_KMM_ChangeRSI_Command(llId, kmm->getSrcLLId(), currentSUMN, initialMN, payloadSize, auth); + } + + LogWarning(LOG_P25, P25_KMM_STR ", ignoring uncorrelated Invalid-MN NAK, RSI = %u, rejectedMN = %u", kmm->getSrcLLId(), kmm->getMessageNumber()); + } + } + break; + + case KMM_MessageType::CHANGE_RSI_RSP: + { + KMMChangeRSI* kmm = static_cast(frame.get()); + bool resynchronized = false; + uint16_t initialMN = 0U; + + // scope is intentional + { + std::lock_guard lock(m_warmStartMutex); + auto it = m_warmStartTransactions.find(kmm->getSrcLLId()); + if (it != m_warmStartTransactions.end() && it->second.state == WarmStartState::WAIT_CHANGE_RSI_RSP && + kmm->getOldRSI() == kmm->getSrcLLId() && kmm->getNewRSI() == kmm->getSrcLLId() && + kmm->getStatus() == KMM_Status::CMD_PERFORMED && auth.authenticated && + auth.keyId == it->second.changeRsiMACKId && kmm->KMMFrame::getMessageNumber() == it->second.resynchronizedMN) { + initialMN = it->second.resynchronizedMN; + resynchronized = true; + } + } + + if (!resynchronized) { + LogWarning(LOG_P25, P25_KMM_STR ", unsolicited or failed Change-RSI resynchronization response, RSI = %u", kmm->getSrcLLId()); + return nullptr; + } + + // Change-RSI establishes the body MN as the initial value for both + // directions. The response just consumed that value inbound; the + // next KMF-originated command therefore starts at initial + 1. + { + std::lock_guard lock(m_outboundMessageNumberMutex); + m_rsiMessageNumber[kmm->getSrcLLId()] = (uint16_t)(initialMN + 1U); + } + m_rsiInboundMessageNumber[kmm->getSrcLLId()] = kmm->KMMFrame::getMessageNumber(); + + LogInfoEx(LOG_P25, P25_KMM_STR ", Change-RSI MN resynchronization completed, RSI = %u, initialMN = %u", kmm->getSrcLLId(), initialMN); + + return write_KMM_Rekey_Command(llId, kmm->getSrcLLId(), + KMM_HelloFlag::REKEY_REQUEST_UKEK, payloadSize, auth, + additionalResponses, false); } break; case KMM_MessageType::REKEY_ACK: { KMMRekeyAck* kmm = static_cast(frame.get()); + bool rekeyComplete = false; LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, ackMessageId = $%02X, numOfStatus = %u", kmm->toString().c_str(), llId, kmm->getAckMessageId(), kmm->getNumberOfKeyStatus()); if (kmm->getNumberOfKeyStatus() > 0U) { for (auto entry : kmm->getKeyStatus()) { - LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, algId = $%02X, kId = $%04X, status = $%02X", kmm->toString().c_str(), - llId, entry.algId(), entry.kId(), entry.status()); - logResponseStatus(llId, kmm->toString(), entry.status()); + LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, algId = $%02X, kId = $%04X, status = $%02X (%s)", kmm->toString().c_str(), + llId, entry.algId(), entry.kId(), entry.status(), statusToString(entry.status()).c_str()); } } @@ -1229,12 +1302,21 @@ UInt8Array P25OTARService::processKMM(const uint8_t* data, uint32_t len, uint32_ // if there are no more pending rekey message numbers, clean up the warm start transaction if (it->second.pendingRekeyMNs.empty()) { + rekeyComplete = true; eraseBytes(it->second.temporaryTEK.data(), it->second.temporaryTEK.size()); m_warmStartTransactions.erase(it); } } } } + + // if the rekey process is complete, issue a changeover command + if (rekeyComplete && m_network->m_kmfChangeoverAfterRekey) { + // bryanb: should these be hardcoded? as this causes whatever SU on a DVM system to swap to keyset 1 + static constexpr uint8_t SUPERSEDED_KEYSET_ID = 1U; + static constexpr uint8_t ACTIVE_KEYSET_ID = 1U; + return write_KMM_Changeover_Command(llId, kmm->getSrcLLId(), SUPERSEDED_KEYSET_ID, ACTIVE_KEYSET_ID, payloadSize); + } } break; @@ -1286,18 +1368,16 @@ UInt8Array P25OTARService::processKMM(const uint8_t* data, uint32_t len, uint32_ case KMM_MessageType::REG_RSP: { KMMRegistrationResponse* kmm = static_cast(frame.get()); - LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, status = $%02X", kmm->toString().c_str(), - llId, kmm->getStatus()); - logResponseStatus(llId, kmm->toString(), kmm->getStatus()); + LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, status = $%02X (%s)", kmm->toString().c_str(), + llId, kmm->getStatus(), statusToString(kmm->getStatus()).c_str()); } break; case KMM_MessageType::UNABLE_TO_DECRYPT: { KMMUnableToDecrypt* kmm = static_cast(frame.get()); - LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, status = $%02X", kmm->toString().c_str(), - llId, kmm->getStatus()); - logResponseStatus(llId, kmm->toString(), kmm->getStatus()); + LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, status = $%02X (%s)", kmm->toString().c_str(), + llId, kmm->getStatus(), statusToString(kmm->getStatus()).c_str()); } break; @@ -1831,6 +1911,7 @@ UInt8Array P25OTARService::write_KMM_Rekey_Command(uint32_t llId, uint32_t kmmRS if (batchIndex == 0U) { if (payloadSize != nullptr) *payloadSize = frameLength; + firstFrame = std::make_unique(frameLength); ::memcpy(firstFrame.get(), encoded.data(), frameLength); } @@ -1839,12 +1920,30 @@ UInt8Array P25OTARService::write_KMM_Rekey_Command(uint32_t llId, uint32_t kmmRS } } - // if using the Warm Start TEK, update the corresponding warm start transaction with the pending rekey message numbers and deadline - if (useWarmStartTEK) { + // track every Rekey transaction so changeover is issued only after all of its + // batches are acknowledged; warm start reuses its existing transaction + // direct Rekey creates the transaction here + { std::lock_guard lock(m_warmStartMutex); - // look up the warm start transaction for the given RSI + // look up the Warm Start transaction, or replace any stale direct-rekey + // transaction with the newly emitted command sequence. auto it = m_warmStartTransactions.find(kmmRSI); + if (!useWarmStartTEK) { + if (it != m_warmStartTransactions.end()) + eraseBytes(it->second.temporaryTEK.data(), it->second.temporaryTEK.size()); + + WarmStartTransaction transaction; + transaction.state = WarmStartState::WAIT_REKEY_ACK; + transaction.llId = llId; + transaction.rsi = kmmRSI; + for (const p25::kmm::KeyItem& deliveredKey : keys) + transaction.permittedFinalKIds.push_back(deliveredKey.kId()); + + m_warmStartTransactions[kmmRSI] = std::move(transaction); + it = m_warmStartTransactions.find(kmmRSI); + } + if (it != m_warmStartTransactions.end()) { it->second.pendingRekeyMNs.clear(); @@ -1956,30 +2055,32 @@ UInt8Array P25OTARService::write_KMM_WarmStart_Command(uint32_t llId, uint32_t k warmKey.kId(transaction.temporaryKId); warmKey.setKey(wrapped.get(), P25DEF::MAX_WRAPPED_ENC_KEY_LENGTH_BYTES); - KMMWarmStartCommand command; - command.setSrcLLId(m_network->m_kmfRsi); - command.setDstLLId(kmmRSI); - command.setResponseKind(KMM_ResponseKind::IMMEDIATE); - command.setHasMessageNumber(true); - command.setMessageNumber(transaction.warmStartMN); - command.setMACType(KMM_MAC::ENH_MAC); - command.setMACAlgId(ALGO_AES_256); + // build the Warm-Start command with the wrapped TEK and associated metadata + KMMWarmStartCommand outKmm; + outKmm.setSrcLLId(m_network->m_kmfRsi); + outKmm.setDstLLId(kmmRSI); + outKmm.setResponseKind(KMM_ResponseKind::IMMEDIATE); + outKmm.setHasMessageNumber(true); + outKmm.setMessageNumber(transaction.warmStartMN); + outKmm.setMACType(KMM_MAC::ENH_MAC); + outKmm.setMACAlgId(ALGO_AES_256); // AACA-D defines the Warm-Start MAC trailer KID as undefined. Correlation is // performed from the RSI transaction; do not expose a meaningful lookup ID. - command.setMACKId(0U); - command.setMACFormat(KMM_MAC_FORMAT_CBC); - command.setDecryptInfoFmt(KMM_DECRYPT_INSTRUCT_NONE); - command.setKEKAlgId(ukek.algId()); - command.setKEKKId((uint16_t)ukek.kId()); - command.setKeyLength(P25DEF::MAX_WRAPPED_ENC_KEY_LENGTH_BYTES); - command.setTEKAlgId(ALGO_AES_256); - command.setKey(warmKey); - - const uint32_t length = command.fullLength(); + outKmm.setMACKId(0U); + outKmm.setMACFormat(KMM_MAC_FORMAT_CBC); + outKmm.setDecryptInfoFmt(KMM_DECRYPT_INSTRUCT_NONE); + outKmm.setKEKAlgId(ukek.algId()); + outKmm.setKEKKId((uint16_t)ukek.kId()); + outKmm.setKeyLength(P25DEF::MAX_WRAPPED_ENC_KEY_LENGTH_BYTES); + outKmm.setTEKAlgId(ALGO_AES_256); + outKmm.setKey(warmKey); + + // encode the Warm-Start command and generate its MAC + const uint32_t length = outKmm.fullLength(); UInt8Array encoded = std::make_unique(length); ::memset(encoded.get(), 0x00U, length); - command.encode(encoded.get()); - command.generateMAC(transaction.temporaryTEK.data(), encoded.get()); + outKmm.encode(encoded.get()); + outKmm.generateMAC(transaction.temporaryTEK.data(), encoded.get()); // scope is intentional { @@ -1998,7 +2099,79 @@ UInt8Array P25OTARService::write_KMM_WarmStart_Command(uint32_t llId, uint32_t k if (payloadSize != nullptr) *payloadSize = length; - LogInfoEx(LOG_P25, P25_KMM_STR ", Warm-Start Command issued, llId = %u, RSI = %u, temporaryKId = $%04X", llId, kmmRSI, warmKey.kId()); + if (m_verbose) { + LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, RSI = %u, temporaryKId = $%04X", + outKmm.toString().c_str(), llId, kmmRSI, warmKey.kId()); + } + + return encoded; +} + +/* Builds a same-RSI Change-RSI Command used to resynchronize message numbers. */ + +UInt8Array P25OTARService::write_KMM_ChangeRSI_Command(uint32_t llId, uint32_t kmmRSI, + uint16_t currentSUMN, uint16_t initialMN, uint32_t* payloadSize, + const KMMAuthContext& auth) +{ + if (payloadSize != nullptr) + *payloadSize = 0U; + if (!auth.authenticated || auth.algorithmId != ALGO_AES_256 || auth.keyId == 0U) + return nullptr; + + // resolve the TEK to be used for generating the MAC of the Change-RSI command + EKCKeyItem macTekItem = resolveTEK(auth.keyId, auth.algorithmId, kmmRSI); + if (macTekItem.isInvalid()) { + LogError(LOG_P25, P25_KMM_STR ", cannot build Change-RSI Command; authenticated TEK unavailable, RSI = %u", kmmRSI); + return nullptr; + } + + // build the Change-RSI command structure + KMMChangeRSI outKmm; + outKmm.setSrcLLId(m_network->m_kmfRsi); + outKmm.setDstLLId(kmmRSI); + outKmm.setOldRSI(kmmRSI); + outKmm.setNewRSI(kmmRSI); + outKmm.setInitialMessageNumber(initialMN); + outKmm.setHasMessageNumber(true); + outKmm.setMessageNumber(currentSUMN); + outKmm.setMACType(KMM_MAC::ENH_MAC); + outKmm.setMACAlgId(auth.algorithmId); + outKmm.setMACKId(auth.keyId); + outKmm.setMACFormat(auth.format); + + // encode the Change-RSI command and prepare it for MAC generation + const uint32_t frameLength = outKmm.fullLength(); + UInt8Array encoded = std::make_unique(frameLength); + ::memset(encoded.get(), 0x00U, frameLength); + outKmm.encode(encoded.get()); + + uint8_t macTek[P25DEF::MAX_ENC_KEY_LENGTH_BYTES] = { 0U }; + macTekItem.getKey(macTek); + outKmm.generateMAC(macTek, encoded.get()); + eraseBytes(macTek, sizeof(macTek)); + + // scope is intentional + { + std::lock_guard lock(m_warmStartMutex); + auto it = m_warmStartTransactions.find(kmmRSI); + if (it == m_warmStartTransactions.end()) + return nullptr; + + it->second.state = WarmStartState::WAIT_CHANGE_RSI_RSP; + it->second.changeRsiCommandMN = currentSUMN; + it->second.resynchronizedMN = initialMN; + it->second.changeRsiMACKId = auth.keyId; + it->second.deadline = monotonicMilliseconds() + WARM_START_TIMEOUT_MS; + } + + if (payloadSize != nullptr) + *payloadSize = frameLength; + + if (m_verbose) { + LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, RSI = %u, currentSUMN = %u, initialMN = %u", + outKmm.toString().c_str(), llId, kmmRSI, currentSUMN, initialMN); + } + return encoded; } @@ -2010,6 +2183,7 @@ UInt8Array P25OTARService::write_KMM_Changeover_Command(uint32_t llId, uint32_t if (payloadSize != nullptr) *payloadSize = 0U; + // look up the RID entry for the given RSI and verify its eligibility for a Changeover command lookups::RadioId ridEntry = m_network->m_ridLookup->find(kmmRSI); if (ridEntry.radioDefault() || !ridEntry.radioEnabled() || !ridEntry.canRekey()) { LogWarning(LOG_P25, P25_KMM_STR ", cannot build Changeover Command; RID %u has no eligible key policy", kmmRSI); @@ -2044,6 +2218,7 @@ UInt8Array P25OTARService::write_KMM_Changeover_Command(uint32_t llId, uint32_t const uint16_t mn = reserveOutboundMessageNumbers(llId); + // build the KMM Changeover command using the determined MAC TEK and message number KMMChangeover outKmm; outKmm.setSrcLLId(m_network->m_kmfRsi); outKmm.setDstLLId(kmmRSI); @@ -2056,6 +2231,7 @@ UInt8Array P25OTARService::write_KMM_Changeover_Command(uint32_t llId, uint32_t outKmm.setMACKId((uint16_t)macTekItem.kId()); outKmm.setMACFormat(KMM_MAC_FORMAT_CBC); + // encode the Changeover command and generate its MAC const uint32_t frameLength = outKmm.fullLength(); UInt8Array encoded = std::make_unique(frameLength); ::memset(encoded.get(), 0x00U, frameLength); @@ -2067,6 +2243,7 @@ UInt8Array P25OTARService::write_KMM_Changeover_Command(uint32_t llId, uint32_t if (payloadSize != nullptr) *payloadSize = frameLength; + if (m_verbose) { LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, RSI = %u, supersededKeysetId = $%02X, activeKeysetId = $%02X", outKmm.toString().c_str(), llId, kmmRSI, supersededKeysetId, activeKeysetId); @@ -2084,14 +2261,14 @@ UInt8Array P25OTARService::write_KMM_Reg_Command(uint32_t llId, uint32_t kmmRSI, outKmm.setDstLLId(kmmRSI); if (m_verbose) { - LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, RSI = %u", outKmm.toString().c_str(), - outKmm.getSrcLLId(), outKmm.getDstLLId()); + LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, RSI = %u", outKmm.toString().c_str(), outKmm.getSrcLLId(), outKmm.getDstLLId()); } const uint32_t frameLength = outKmm.fullLength(); if (payloadSize != nullptr) *payloadSize = frameLength; + // encode the Registration-Command KMM and prepare it for transmission UInt8Array kmmFrame = std::make_unique(frameLength); outKmm.encode(kmmFrame.get()); return kmmFrame; @@ -2108,8 +2285,7 @@ UInt8Array P25OTARService::write_KMM_Dereg_Response(uint32_t llId, uint32_t kmmR outKmm.setStatus(KMM_Status::CMD_PERFORMED); if (m_verbose) { - LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, RSI = %u", outKmm.toString().c_str(), - outKmm.getSrcLLId(), outKmm.getDstLLId()); + LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, RSI = %u", outKmm.toString().c_str(), outKmm.getSrcLLId(), outKmm.getDstLLId()); } return encode_KMM_Response(outKmm, payloadSize, auth); @@ -2125,8 +2301,7 @@ UInt8Array P25OTARService::write_KMM_NoService(uint32_t llId, uint32_t kmmRSI, u outKmm.setDstLLId(kmmRSI); if (m_verbose) { - LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, RSI = %u", outKmm.toString().c_str(), - outKmm.getSrcLLId(), outKmm.getDstLLId()); + LogInfoEx(LOG_P25, P25_KMM_STR ", %s, llId = %u, RSI = %u", outKmm.toString().c_str(), outKmm.getSrcLLId(), outKmm.getDstLLId()); } return encode_KMM_Response(outKmm, payloadSize, auth); @@ -2147,8 +2322,8 @@ UInt8Array P25OTARService::write_KMM_NegativeAck(uint32_t kmmRSI, uint8_t messag outKmm.setMessageNumber(messageNumber); outKmm.setStatus(status); - LogWarning(LOG_P25, P25_KMM_STR ", sending NACK, RSI = %u, messageId = $%02X, MN = %u, status = $%02X", - kmmRSI, messageId, messageNumber, status); + LogWarning(LOG_P25, P25_KMM_STR ", %s, RSI = %u, messageId = $%02X, MN = %u, status = $%02X", + outKmm.toString().c_str(), kmmRSI, messageId, messageNumber, status); return encode_KMM_Response(outKmm, payloadSize, auth); } @@ -2177,6 +2352,7 @@ UInt8Array P25OTARService::encode_KMM_Response(KMMFrame& frame, uint32_t* payloa } } + // encode the KMM response and generate its MAC if authenticated const uint32_t frameLength = frame.fullLength(); if (payloadSize != nullptr) *payloadSize = frameLength; @@ -2203,6 +2379,7 @@ UInt8Array P25OTARService::write_KMM_Zeroize(uint32_t llId, uint32_t kmmRSI, uin outKmm.getSrcLLId(), outKmm.getDstLLId()); } + // encode the Zeroize KMM and prepare it for transmission const uint32_t frameLength = outKmm.fullLength(); if (payloadSize != nullptr) *payloadSize = frameLength; @@ -2212,60 +2389,44 @@ UInt8Array P25OTARService::write_KMM_Zeroize(uint32_t llId, uint32_t kmmRSI, uin return kmmFrame; } -/* Helper used to log a KMM response. */ +/* Helper used to convert a KMM response to a human-readable string. */ -void P25OTARService::logResponseStatus(uint32_t llId, std::string kmmString, uint8_t status) +std::string P25OTARService::statusToString(uint8_t status) { switch (status) { case KMM_Status::CMD_PERFORMED: - if (m_verbose) { - LogInfoEx(LOG_P25, P25_KMM_STR ", %s, command performed, llId = %u", kmmString.c_str(), llId); - } - break; + return std::string("CMD_PERFORMED (Command Performed)"); case KMM_Status::CMD_NOT_PERFORMED: - LogWarning(LOG_P25, P25_KMM_STR ", %s, command not performed, llId = %u", kmmString.c_str(), llId); - break; + return std::string("CMD_NOT_PERFORMED (Command Not Performed)"); case KMM_Status::ITEM_NOT_EXIST: - LogWarning(LOG_P25, P25_KMM_STR ", %s, item does not exist, llId = %u", kmmString.c_str(), llId); - break; + return std::string("ITEM_NOT_EXIST (Item Does Not Exist)"); case KMM_Status::INVALID_MSG_ID: - LogWarning(LOG_P25, P25_KMM_STR ", %s, invalid message ID, llId = %u", kmmString.c_str(), llId); - break; + return std::string("INVALID_MSG_ID (Invalid Message ID)"); case KMM_Status::INVALID_MAC: - LogWarning(LOG_P25, P25_KMM_STR ", %s, invalid auth code, llId = %u", kmmString.c_str(), llId); - break; + return std::string("INVALID_MAC (Invalid MAC)"); case KMM_Status::OUT_OF_MEMORY: - LogWarning(LOG_P25, P25_KMM_STR ", %s, out of memory, llId = %u", kmmString.c_str(), llId); - break; + return std::string("OUT_OF_MEMORY (Out of Memory)"); case KMM_Status::FAILED_TO_DECRYPT: - LogWarning(LOG_P25, P25_KMM_STR ", %s, failed to decrypt message, llId = %u", kmmString.c_str(), llId); - break; + return std::string("FAILED_TO_DECRYPT (Failed to Decrypt)"); case KMM_Status::INVALID_MSG_NUMBER: - LogWarning(LOG_P25, P25_KMM_STR ", %s, invalid message number, llId = %u", kmmString.c_str(), llId); - break; + return std::string("INVALID_MSG_NUMBER (Invalid Message Number)"); case KMM_Status::INVALID_KID: - LogWarning(LOG_P25, P25_KMM_STR ", %s, invalid key ID, llId = %u", kmmString.c_str(), llId); - break; + return std::string("INVALID_KID (Invalid Key ID)"); case KMM_Status::INVALID_ALGID: - LogWarning(LOG_P25, P25_KMM_STR ", %s, invalid algorithm ID, llId = %u", kmmString.c_str(), llId); - break; + return std::string("INVALID_ALGID (Invalid Algorithm ID)"); case KMM_Status::INVALID_MFID: - LogWarning(LOG_P25, P25_KMM_STR ", %s, invalid manufacturer ID, llId = %u", kmmString.c_str(), llId); - break; + return std::string("INVALID_MFID (Invalid Manufacturer ID)"); case KMM_Status::MI_ALL_ZERO: - LogWarning(LOG_P25, P25_KMM_STR ", %s, message indicator was all zeros, llId = %u", kmmString.c_str(), llId); - break; + return std::string("MI_ALL_ZERO (Message Indicator All Zero)"); case KMM_Status::KEY_FAIL: - LogWarning(LOG_P25, P25_KMM_STR ", %s, key identified by algo/key is erased, llId = %u", kmmString.c_str(), llId); - break; + return std::string("KEY_FAIL (Key Failure)"); case KMM_Status::UNKNOWN: default: - LogWarning(LOG_P25, P25_KMM_STR ", llId = %u, status = $%02X; unknown status", llId, status); - break; + return std::string("UNKNOWN (Unknown Status)"); } } diff --git a/src/fne/network/P25OTARService.h b/src/fne/network/P25OTARService.h index 3250e6f0..127e5032 100644 --- a/src/fne/network/P25OTARService.h +++ b/src/fne/network/P25OTARService.h @@ -163,7 +163,11 @@ namespace network /** * @brief Waiting for the rekey acknowledgment from the master. */ - WAIT_REKEY_ACK + WAIT_REKEY_ACK, + /** + * @brief Waiting for the Change-RSI response used to resynchronize MNs. + */ + WAIT_CHANGE_RSI_RSP }; /** @@ -183,6 +187,9 @@ namespace network std::array temporaryTEK{}; //!< Temporary TEK used in the warm start transaction. std::vector permittedFinalKIds; //!< Permitted final key IDs for the warm start transaction. std::vector pendingRekeyMNs; //!< Pending rekey message numbers for the warm start transaction. + uint16_t changeRsiCommandMN = 0U; //!< Header MN used by the Change-RSI command. + uint16_t resynchronizedMN = 0U; //!< New initial inbound/outbound MN carried by Change-RSI. + uint16_t changeRsiMACKId = 0U; //!< TEK used to authenticate the Change-RSI transaction. }; network::udp::Socket* m_socket; @@ -335,6 +342,13 @@ namespace network UInt8Array write_KMM_Changeover_Command(uint32_t llId, uint32_t kmmRSI, uint8_t supersededKeysetId, uint8_t activeKeysetId, uint32_t* payloadSize); + /** + * @brief Builds an authenticated same-RSI Change-RSI command for MN resynchronization. + */ + UInt8Array write_KMM_ChangeRSI_Command(uint32_t llId, uint32_t kmmRSI, + uint16_t currentSUMN, uint16_t initialMN, uint32_t* payloadSize, + const KMMAuthContext& auth); + /** * @brief Helper used to return a Registration-Command KMM to the calling SU. * @param llId Logical Link Address. @@ -398,12 +412,10 @@ namespace network UInt8Array write_KMM_Zeroize(uint32_t llId, uint32_t kmmRSI, uint32_t* payloadSize); /** - * @brief Helper used to log a KMM response. - * @param llId Logical Link Address. - * @param kmmString + * @brief Helper used to convert a KMM response to a human-readable string. * @param status Status. */ - void logResponseStatus(uint32_t llId, std::string kmmString, uint8_t status); + std::string statusToString(uint8_t status); }; } // namespace network diff --git a/src/fne/network/TrafficNetwork.cpp b/src/fne/network/TrafficNetwork.cpp index 07d52ed0..294bc8de 100644 --- a/src/fne/network/TrafficNetwork.cpp +++ b/src/fne/network/TrafficNetwork.cpp @@ -95,6 +95,7 @@ TrafficNetwork::TrafficNetwork(HostFNE* host, const std::string& address, uint16 m_kmfEncKeyRequest(false), m_kmfPresharedKey(nullptr), m_kmfWarmStart(true), + m_kmfChangeoverAfterRekey(true), m_kmfDebug(kmfDebug), m_ridLookup(nullptr), m_ridAliasLookup(nullptr), @@ -362,6 +363,7 @@ void TrafficNetwork::setOptions(yaml::Node& conf, bool printOptions) m_kmfAllowRID0 = kmfConf["allowRID0"].as(false); m_kmfForgeSrcLLId = kmfConf["forgeSrcLLId"].as(false); m_kmfWarmStart = kmfConf["warmStart"].as(true); + m_kmfChangeoverAfterRekey = kmfConf["changeoverAfterRekey"].as(true); // scope is intentional { @@ -549,6 +551,7 @@ void TrafficNetwork::setOptions(yaml::Node& conf, bool printOptions) LogWarning(LOG_P25, "We are configured to forge the source LLID on KMM packets, this is a security risk and shouldn't be used outside of testing environments."); } LogInfo(" OTAR KMF Warm Start Requests Allowed: %s", m_kmfWarmStart ? "yes" : "no"); + LogInfo(" OTAR KMF Changeover After Rekey: %s", m_kmfChangeoverAfterRekey ? "yes" : "no"); LogInfo(" OTAR KMF Peer Request Encrypted: %s", m_kmfEncKeyRequest ? "yes" : "no"); if (!m_encryptedTrafficConn && !m_kmfEncKeyRequest) { LogWarning(LOG_MASTER, "Peers can make key requests, but the encrypted traffic connection is not enabled and KMF requests are not encrypted! Key requests will be sent in the clear."); diff --git a/src/fne/network/TrafficNetwork.h b/src/fne/network/TrafficNetwork.h index 09cd0210..2a3dd77c 100644 --- a/src/fne/network/TrafficNetwork.h +++ b/src/fne/network/TrafficNetwork.h @@ -384,6 +384,7 @@ namespace network bool m_kmfEncKeyRequest; uint8_t* m_kmfPresharedKey; bool m_kmfWarmStart; + bool m_kmfChangeoverAfterRekey; bool m_kmfDebug; lookups::RadioIdLookup* m_ridLookup; diff --git a/tests/p25/P25_KMM_Tests.cpp b/tests/p25/P25_KMM_Tests.cpp index e95e8eb6..e51edc9b 100644 --- a/tests/p25/P25_KMM_Tests.cpp +++ b/tests/p25/P25_KMM_Tests.cpp @@ -288,8 +288,20 @@ TEST_CASE("P25 OTAR Warm Start transitions through temporary TEK Rekey", "[p25][ std::vector finalAckBytes = encodeKMM(finalAck); finalAck.generateMAC(finalKey, finalAckBytes.data()); uint32_t finalResponseLength = 0U; - REQUIRE(FNETestHooks::processOTARKMM(harness.traffic, finalAckBytes, SU_RSI, - finalResponseLength, ALGO_AES_256, FINAL_KID) == nullptr); + UInt8Array finalResponse = FNETestHooks::processOTARKMM(harness.traffic, + finalAckBytes, SU_RSI, finalResponseLength, ALGO_AES_256, FINAL_KID); + REQUIRE(finalResponse != nullptr); + + std::unique_ptr changeoverBase = KMMFactory::create(finalResponse.get(), + finalResponseLength); + KMMChangeover* changeover = dynamic_cast(changeoverBase.get()); + REQUIRE(changeover != nullptr); + CHECK(changeover->getMessageId() == KMM_MessageType::CHANGEOVER_CMD); + CHECK(changeover->getSupersededKeysetId() == 1U); + CHECK(changeover->getActiveKeysetId() == 1U); + CHECK(changeover->getMessageNumber() == rekey->getMessageNumber() + 1U); + CHECK(changeover->getMACKId() == FINAL_KID); + CHECK(changeover->verifyMAC(finalKey, finalResponse.get(), finalResponseLength)); CHECK_FALSE(FNETestHooks::hasOTARWarmStart(harness.traffic, SU_RSI)); } @@ -311,6 +323,145 @@ TEST_CASE("KMM air-facing factory rejects malformed lengths", "[p25][kmm][securi REQUIRE(KMMFactory::create(bytes.data(), (uint32_t)bytes.size()) == nullptr); } +TEST_CASE("P25 OTAR direct Rekey issues Changeover after its final acknowledgment", + "[p25][kmm][otar][rekey][changeover]") +{ + KMMFNEHarness harness; + constexpr uint32_t SU_RSI = 0x654321U; + constexpr uint16_t FINAL_KID = 0x2001U; + const char* finalHex = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"; + + EKCKeyItem finalTEK; + finalTEK.id(1U); + finalTEK.algId(ALGO_AES_256); + finalTEK.kId(FINAL_KID); + finalTEK.sln(1U); + finalTEK.keyMaterial(finalHex); + FNETestHooks::addCryptoKey(harness.traffic, finalTEK); + harness.rid.addEntry(SU_RSI, true, "direct-rekey-test", "", true, true, + { FINAL_KID }); + + const std::vector> rekeyFrames = + FNETestHooks::buildOTARRekey(harness.traffic, SU_RSI, SU_RSI); + REQUIRE(rekeyFrames.size() == 1U); + + std::unique_ptr rekeyBase = KMMFactory::create(rekeyFrames[0U].data()); + KMMRekeyCommand* rekey = dynamic_cast(rekeyBase.get()); + REQUIRE(rekey != nullptr); + + uint8_t finalKey[P25DEF::MAX_ENC_KEY_LENGTH_BYTES] = { 0U }; + finalTEK.getKey(finalKey); + KeyStatus status; + status.algId(ALGO_AES_256); + status.kId(FINAL_KID); + status.status(KMM_Status::CMD_PERFORMED); + + KMMRekeyAck ack; + ack.setDstLLId(KMF_RSI); + ack.setSrcLLId(SU_RSI); + ack.setHasMessageNumber(true); + ack.setMessageNumber(rekey->getMessageNumber()); + ack.setMACType(KMM_MAC::ENH_MAC); + ack.setMACAlgId(ALGO_AES_256); + ack.setMACKId(FINAL_KID); + ack.setMACFormat(KMM_MAC_FORMAT_CMAC); + ack.setAckMessageId(KMM_MessageType::REKEY_CMD); + ack.setNumberOfKeyStatus(1U); + ack.setKeyStatus({ status }); + std::vector ackBytes = encodeKMM(ack); + ack.generateMAC(finalKey, ackBytes.data()); + + uint32_t responseLength = 0U; + UInt8Array response = FNETestHooks::processOTARKMM(harness.traffic, ackBytes, + SU_RSI, responseLength, ALGO_AES_256, FINAL_KID); + REQUIRE(response != nullptr); + + std::unique_ptr changeoverBase = KMMFactory::create(response.get(), + responseLength); + KMMChangeover* changeover = dynamic_cast(changeoverBase.get()); + REQUIRE(changeover != nullptr); + CHECK(changeover->getSupersededKeysetId() == 1U); + CHECK(changeover->getActiveKeysetId() == 1U); + CHECK(changeover->getMessageNumber() == rekey->getMessageNumber() + 1U); + CHECK(changeover->getMACKId() == FINAL_KID); + CHECK(changeover->verifyMAC(finalKey, response.get(), responseLength)); +} + +TEST_CASE("P25 OTAR resynchronizes Rekey message numbers with same-RSI Change-RSI", + "[p25][kmm][otar][rekey][change-rsi]") +{ + KMMFNEHarness harness; + constexpr uint32_t SU_RSI = 0x654321U; + constexpr uint16_t TEK_KID = 0x2001U; + + EKCKeyItem tek; + tek.id(1U); tek.algId(ALGO_AES_256); tek.kId(TEK_KID); tek.sln(1U); + tek.keyMaterial("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"); + FNETestHooks::addCryptoKey(harness.traffic, tek); + EKCKeyItem ukek; + ukek.id(2U); ukek.rsiId(SU_RSI); ukek.algId(ALGO_AES_256); + ukek.kId(0x1001U); ukek.sln(0U); + ukek.keyMaterial("101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F"); + FNETestHooks::addCryptoUKEK(harness.traffic, ukek); + harness.rid.addEntry(SU_RSI, true, "change-rsi-test", "", true, true, + { TEK_KID }); + + const std::vector> frames = + FNETestHooks::buildOTARRekey(harness.traffic, SU_RSI, SU_RSI); + REQUIRE(frames.size() == 1U); + std::unique_ptr rekeyBase = KMMFactory::create(frames[0U].data()); + KMMRekeyCommand* rekey = dynamic_cast(rekeyBase.get()); + REQUIRE(rekey != nullptr); + + uint8_t key[P25DEF::MAX_ENC_KEY_LENGTH_BYTES] = { 0U }; + tek.getKey(key); + KMMNegativeAck nack; + nack.setDstLLId(KMF_RSI); nack.setSrcLLId(SU_RSI); + nack.setHasMessageNumber(true); nack.KMMFrame::setMessageNumber(10U); + nack.setMACType(KMM_MAC::ENH_MAC); nack.setMACAlgId(ALGO_AES_256); + nack.setMACKId(TEK_KID); nack.setMACFormat(KMM_MAC_FORMAT_CMAC); + nack.setNakMessageId(KMM_MessageType::REKEY_CMD); + nack.setMessageNumber(rekey->getMessageNumber()); + nack.setStatus(KMM_Status::INVALID_MSG_NUMBER); + std::vector nackBytes = encodeKMM(nack); + nack.generateMAC(key, nackBytes.data()); + + uint32_t commandLength = 0U; + UInt8Array commandBytes = FNETestHooks::processOTARKMM(harness.traffic, + nackBytes, SU_RSI, commandLength, ALGO_AES_256, TEK_KID); + REQUIRE(commandBytes != nullptr); + std::unique_ptr commandBase = KMMFactory::create(commandBytes.get(), + commandLength); + KMMChangeRSI* command = dynamic_cast(commandBase.get()); + REQUIRE(command != nullptr); + CHECK(command->getMessageId() == KMM_MessageType::CHANGE_RSI_CMD); + CHECK(command->getOldRSI() == SU_RSI); + CHECK(command->getNewRSI() == SU_RSI); + CHECK(command->KMMFrame::getMessageNumber() == 10U); + CHECK(command->getInitialMessageNumber() == 11U); + CHECK(command->verifyMAC(key, commandBytes.get(), commandLength)); + + KMMChangeRSI response; + response.setMessageId(KMM_MessageType::CHANGE_RSI_RSP); + response.setDstLLId(KMF_RSI); response.setSrcLLId(SU_RSI); + response.setHasMessageNumber(true); response.setMessageNumber(11U); + response.setMACType(KMM_MAC::ENH_MAC); response.setMACAlgId(ALGO_AES_256); + response.setMACKId(TEK_KID); response.setMACFormat(KMM_MAC_FORMAT_CMAC); + response.setOldRSI(SU_RSI); response.setNewRSI(SU_RSI); + response.setStatus(KMM_Status::CMD_PERFORMED); + std::vector responseBytes = encodeKMM(response); + response.generateMAC(key, responseBytes.data()); + + uint32_t retryLength = 0U; + UInt8Array retryBytes = FNETestHooks::processOTARKMM(harness.traffic, + responseBytes, SU_RSI, retryLength, ALGO_AES_256, TEK_KID); + REQUIRE(retryBytes != nullptr); + std::unique_ptr retryBase = KMMFactory::create(retryBytes.get()); + KMMRekeyCommand* retry = dynamic_cast(retryBase.get()); + REQUIRE(retry != nullptr); + CHECK(retry->getMessageNumber() == 12U); +} + TEST_CASE("FNE OTAR dispatcher follows AACA response-kind procedures", "[p25][kmm][otar]") { KMMFNEHarness harness;