LoRaWAN end device MAC layer for SX1272 and SX1276. Supports LoRaWAN-1.0 and LoRaWAN-1.1

Dependencies:   sx12xx_hal

Dependents:   LoRaWAN-SanJose_Bootcamp LoRaWAN-grove-cayenne LoRaWAN-classC-demo LoRaWAN-grove-cayenne ... more

radio chip selection

Radio chip driver is not included, because two options are available.
If you're using SX1272 or SX1276, then import sx127x driver into your program.
if you're using SX1261 or SX1262, then import sx126x driver into your program.
If you're using NAmote72 or Murata discovery, then you must import only sx127x driver.

application project requirements

This library requires mbed TLS to be enabled.
The file mbed_app.json must be present in the project using this library:

{
    "macros": [ "MBEDTLS_CMAC_C" ]
}

regional PHY selection

All end device configuration is done in Commissioning.h, define desired radio frequency band of operation in this header file.
Commissioning.h is located in the application using this library.

end device provisioning

End device is provisioned by editing Commissioning.h in the application which is using this library
To use LoRaWAN-1.0 OTA: make sure LORAWAN_ROOT_APPKEY is undefined.
To use LoRaWAN-1.1 OTA, define LORAWAN_ROOT_APPKEY.
To select OTA operation, define LORAWAN_JOIN_EUI, then LORAWAN_DEVICE_EUI must be defined, along with root key(s).
To select ABP operation, undefine LORAWAN_JOIN_EUI: then define session keys

LoRaWAN 1.0 nameLoRaWAN 1.1 nameComissioning.h defnedescription
OTADevEUIDevEUILORAWAN_DEVICE_EUIuniquely identifies end device
OTAAppEUIJoinEUILORAWAN_JOIN_EUI
OTAAppKeyNwkKeyLORAWAN_ROOT_NWKKEYroot key for network server
OTA(note 1)AppKeyLORAWAN_ROOT_APPKEYroot key for application server
ABPNwkSKey(note 3)LORAWAN_FNwkSIntKeynetwork session key
ABP(note 2)SNwkSIntKeyLORAWAN_SNwkSIntKeymac layer network integrity key
ABP(note 2)NwkSEncKeyLORAWAN_NwkSEncKeynetwork session encryption key
ABP(note 2)FNwkSIntKeyLORAWAN_FNwkSIntKeyforwarding network session integrity key
ABPAppSKeyAppSKeyLORAWAN_APPSKEYapplication session encryption key

(note 1): LoRaWAN-1.0 OTA uses a single root key for both network server and application server.

In LoRaWAN-1.0 OTA: the single root AppKey is used to generate NwkSkey and AppSKey.
(note 2): In LoRaWAN-1.0 (both OTA and ABP) SNwkSIntKey, NwkSEncKey. FNwkSIntKey are of same value and are collectively known as NwkSKey.
(note 3): LoRaWAN-1.0 uses single network session key, LoRaWAN-1.1 uses 3 network session keys. Both use a unique application session key.


In LoRaWAN-1.1 OTA: the root NwkKey is used to generate SNwkSIntKey, NwkSEncKey, FNwkSIntKey
In LoRaWAN-1.1 OTA: the root AppKey is used to generate AppSKey


in ABP mode, the DevAddr, and session keys are fixed (never change), and frame counters never reset to zero.
ABP operation has no concept of: root keys, or DevEUI or JoinEUI/AppEUI.
in OTA mode, the DevAddr and session keys are assigned at join procedure, and frame counters reset at join.

eeprom

This library includes eeprom driver to support non-volatile storage required by LoRaWAN specification.
Currently eeprom is implemented for STM32L1 family and STM32L0 family.
Writing of values are wear-leveled to increase endurance; each write operation circulates across several memory locations. A read operation returns the highest value found. This simple method is used for sequence numbers which only increase.

value nameused in
DevNonceOTAfor Join request (note 1)
RJcount1OTAfor ReJoin Type 1 request
FCntUpABPuplink frame counter
NFCntDownABPdownlink frame counter
AFCntDownABPdownlink frame counter

AFCntDown is only used in LoRaWAN-1.1 when application payload is present in downlink and FPort > 0.
NFCntDown is used in LoRaWAN-1.1 when FPort is zero in downlink or application payload not present.
NFCntDown is the only downlink frame counter used in LoRaWAN-1.0
(note 1) OTA DevNonce is random number in LoRaWAN-1.0, therefore not stored in eeprom. DevNonce in LoRaWAN-1.1 is forever increasing (non-volatile) number upon each join request,.
RJcount0 is only stored in RAM because the value resets upon new session from JoinAccept, therefore not stored in eeprom.
Frame counters in OTA mode reset upon new session in join request, therefore are stored in RAM instead of eeprom for OTA.

radio driver support

When SX127x driver is used, both SX1272 and SX1276 are supported without defining at compile time. The chip is detected at start-up.
Supported radio platforms:


Alternately, when SX126x driver is imported, the SX126xDVK1xAS board is used.

low-speed clock oscillator selection

LoRaWAN uses 32768Hz crystal to permit low-power operation.
However, some mbed targets might revert to low-speed internal oscillator, which is not accurate enough for LoRaWAN operation.
An oscillator check is performed at initialization; program will not start if internal oscillator is used.
To force LSE watch crystal, add to mbed_app.json

{
    "macros": [ "MBEDTLS_CMAC_C" ],
    "target_overrides": {
        "<your-target>": {
            "target.lse_available": true
        }
    }
}

mac/LoRaMacCrypto1v1.cpp

Committer:
Wayne Roberts
Date:
2018-08-20
Revision:
12:0f28f2e7c35e
Parent:
11:ce1317758488

File content as of revision 12:0f28f2e7c35e:

#include "lorawan_board.h"
#include "LoRaMacCrypto.h"
#include "cmac.h"
#include "aes.h"

#define LORAMAC_MIC_BLOCK_B0_SIZE                   16
mbedtls_cipher_context_t ctx;

uint32_t LoRaMacComputeMic(
    const block_t* block,
    const uint8_t* pktPayload,
    const uint8_t* key)
{
    uint8_t Mic[16];

    if (block->b.dir == DOWN_LINK) {
        DEBUG_MIC_DOWN("down ");
        DEBUG_MIC_BUF_DOWN(block->octets, LORAMAC_MIC_BLOCK_B0_SIZE, "b0", ROW_MIC+1);
        DEBUG_MIC_BUF_DOWN(key, 16, "b0-key", ROW_MIC+2);
    } else if (block->b.dir == UP_LINK) {
        DEBUG_MIC_UP("  up ");
        DEBUG_MIC_BUF_UP(block->octets, LORAMAC_MIC_BLOCK_B0_SIZE, "b0", ROW_MIC+1);
        DEBUG_MIC_BUF_UP(key, 16, "b0-key", ROW_MIC+2);
    }

    mbedtls_cipher_cmac_starts(&ctx, key, 128);

    mbedtls_cipher_cmac_update(&ctx, block->octets, LORAMAC_MIC_BLOCK_B0_SIZE);

    mbedtls_cipher_cmac_update(&ctx, pktPayload, block->b.lenMsg);

    mbedtls_cipher_cmac_finish(&ctx, Mic);

    return ( uint32_t )( ( uint32_t )Mic[3] << 24 | ( uint32_t )Mic[2] << 16 | ( uint32_t )Mic[1] << 8 | ( uint32_t )Mic[0] );
}

void LoRaMacEncrypt( uint8_t ctr, const uint8_t *buffer, uint16_t size, const uint8_t *key, uint32_t address, uint8_t dir, uint32_t sequenceCounter, uint8_t *encBuffer )
{
    uint8_t aBlock[16];
    uint8_t sBlock[16];
    uint16_t i;
    uint8_t bufferIndex = 0;
    mbedtls_aes_context actx;

    //memset( AesContext.ksch, '\0', 240 );
    mbedtls_aes_init(&actx);
    //aes_set_key( key, 16, &AesContext );
    mbedtls_aes_setkey_enc(&actx, key, 128);

    aBlock[0] = 0x01;

    aBlock[1] = 0x00;
    aBlock[2] = 0x00;
    aBlock[3] = 0x00;
    aBlock[4] = 0x00;

    aBlock[5] = dir;

    aBlock[6] = ( address ) & 0xFF;
    aBlock[7] = ( address >> 8 ) & 0xFF;
    aBlock[8] = ( address >> 16 ) & 0xFF;
    aBlock[9] = ( address >> 24 ) & 0xFF;

    aBlock[10] = ( sequenceCounter ) & 0xFF;
    aBlock[11] = ( sequenceCounter >> 8 ) & 0xFF;
    aBlock[12] = ( sequenceCounter >> 16 ) & 0xFF;
    aBlock[13] = ( sequenceCounter >> 24 ) & 0xFF;

    aBlock[14] = 0;

    while( size >= 16 )
    {
        aBlock[15] = ( ( ctr ) & 0xFF );
        ctr++;
        //aes_encrypt( aBlock, sBlock, &AesContext );
        mbedtls_aes_encrypt(&actx, aBlock, sBlock);
        for( i = 0; i < 16; i++ )
        {
            encBuffer[bufferIndex + i] = buffer[bufferIndex + i] ^ sBlock[i];
        }
        size -= 16;
        bufferIndex += 16;
    }

    if( size > 0 )
    {
        aBlock[15] = ( ( ctr ) & 0xFF );
        //aes_encrypt( aBlock, sBlock, &AesContext );
        mbedtls_aes_encrypt(&actx, aBlock, sBlock);
        for( i = 0; i < size; i++ )
        {
            encBuffer[bufferIndex + i] = buffer[bufferIndex + i] ^ sBlock[i];
        }
    }

    mbedtls_aes_free(&actx);
}

void LoRaMacPayloadDecrypt( const uint8_t *buffer, uint16_t size, const uint8_t *key, uint32_t address, uint8_t dir, uint32_t sequenceCounter, uint8_t *decBuffer )
{
    LoRaMacEncrypt(1, buffer, size, key, address, dir, sequenceCounter, decBuffer );
}

void
LoRaMacCryptoInit()
{
    //int ret;
    const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_type( MBEDTLS_CIPHER_AES_128_ECB );
    if (cipher_info == NULL) {
        MAC_PRINTF("mbedtls_cipher_info_from_type() failed\n");
        return;
    }
    mbedtls_cipher_init(&ctx);
    /*ret = */mbedtls_cipher_setup(&ctx, cipher_info);
    //MAC_PRINTF("mbedtls_cipher_setup returned %d, type %d\r\n", ret, ctx.cipher_info->type);
    /* always using same ctx --- mbedtls_cipher_free(&ctx) */
}

#ifdef LORAWAN_JOIN_EUI
void LoRaMacJoinComputeSKeys_1v1( const uint8_t *nwk_root_key, const uint8_t *app_root_key, const uint8_t *joinNonce, const uint8_t *joinEUI, uint16_t devNonce, skey_t* keys)
{
    uint8_t buff[16];
    uint8_t *pDevNonce = ( uint8_t * )&devNonce;
    uint8_t* bufPtr;
    mbedtls_aes_context actx;

    mbedtls_aes_init(&actx);
    //memset( AesContext.ksch, '\0', 240 );
    DEBUG_CRYPT_BUF(app_root_key, 16, "AppSKey-root", 0);
    //aes_set_key( app_root_key, 16, &AesContext );
    mbedtls_aes_setkey_enc(&actx, app_root_key, 128);

    memset(buff, 0, sizeof(buff));
    bufPtr = buff + 1;
    memcpy(bufPtr, joinNonce, 3);
    bufPtr += 3;
    memcpyr(bufPtr, joinEUI, 8);
    bufPtr += 8;
    memcpy(bufPtr, pDevNonce, 2);
    bufPtr += 2;

    /* generate AppSKey */
    buff[0] = 0x02;
    DEBUG_CRYPT_BUF(buff, 16, "AppSKey-in", 0);
    //aes_encrypt(buff, keys->AppSKey, &AesContext );
    mbedtls_aes_encrypt(&actx, buff, keys->AppSKey);
    DEBUG_CRYPT_BUF(keys->AppSKey, 16, "AppSKey", 0);

    //memset( AesContext.ksch, '\0', 240 );
    //aes_set_key( nwk_root_key, 16, &AesContext );
    mbedtls_aes_setkey_enc(&actx, nwk_root_key, 128);

    /* generate FNwkSIntKey */
    buff[0] = 0x01;
    DEBUG_CRYPT_BUF(buff, sizeof(buff), "in-FNwkSIntKey", 0);
    //aes_encrypt(buff, keys->FNwkSIntKey, &AesContext );
    mbedtls_aes_encrypt(&actx, buff, keys->FNwkSIntKey);
    DEBUG_CRYPT_BUF(keys->FNwkSIntKey, 16, "FNwkSIntKey", 0);

    /* generate SNwkSIntKey */
    buff[0] = 0x03;
    //aes_encrypt(buff, keys->SNwkSIntKey, &AesContext );
    mbedtls_aes_encrypt(&actx, buff, keys->SNwkSIntKey);
    DEBUG_CRYPT_BUF(keys->SNwkSIntKey, 16, "SNwkSIntKey", 0);

    /* generate NwkSEncKey */
    buff[0] = 0x04;
    //aes_encrypt(buff, keys->NwkSEncKey, &AesContext );
    mbedtls_aes_encrypt(&actx, buff, keys->NwkSEncKey);
    DEBUG_CRYPT_BUF(keys->NwkSEncKey, 16, "NwkSEncKey", 0);

    mbedtls_aes_free(&actx);
}

void LoRaMacJoinComputeSKeys_1v0(const uint8_t *nwk_root_key, const uint8_t *ja_rx, uint16_t devNonce, skey_t* keys)
{
    /* ja_rx: joinNonce + NetID, 6bytes */
    uint8_t nonce[16];
    uint8_t *pDevNonce = ( uint8_t * )&devNonce;
    mbedtls_aes_context actx;

    mbedtls_aes_init(&actx);
    //memset( AesContext.ksch, '\0', 240 );
    //aes_set_key( nwk_root_key, 16, &AesContext );
    mbedtls_aes_setkey_enc(&actx, nwk_root_key, 128);

    memset( nonce, 0, sizeof( nonce ) );
    nonce[0] = 0x01;
    memcpy( nonce + 1, ja_rx, 6 );
    memcpy( nonce + 7, pDevNonce, 2 );
    //aes_encrypt( nonce, keys->FNwkSIntKey, &AesContext );
    mbedtls_aes_encrypt(&actx, nonce, keys->FNwkSIntKey);

    memcpy(keys->SNwkSIntKey, keys->FNwkSIntKey, 16);
    memcpy(keys->NwkSEncKey, keys->FNwkSIntKey, 16);

    memset( nonce, 0, sizeof( nonce ) );
    nonce[0] = 0x02;
    memcpy( nonce + 1, ja_rx, 6 );
    memcpy( nonce + 7, pDevNonce, 2 );
    //aes_encrypt( nonce, keys->AppSKey, &AesContext );
    mbedtls_aes_encrypt(&actx, nonce, keys->AppSKey);

    mbedtls_aes_free(&actx);
}

int LoRaMacJoinComputeMic(bool verbose, const uint8_t *buffer, uint16_t size, const uint8_t *key, uint32_t *mic )
{
    int ret;
    uint8_t Mic[LORAMAC_MIC_BLOCK_B0_SIZE];

#ifndef ENABLE_VT100
    if (verbose) {
        print_buf(key, 16, "mic-key");
        print_buf(buffer, size, "mic-in-buf");
    }
#endif /* ENABLE_VT100 */

    ret = mbedtls_cipher_cmac_starts(&ctx, key, 128);
    if (ret != 0) {
        MAC_PRINTF("0x%x = mbedtls_cipher_cmac_starts()\r\n", ret);
        return ret;
    }

    ret = mbedtls_cipher_cmac_update(&ctx, buffer, size & 0xff);
    if (ret != 0) {
        MAC_PRINTF("%d = mbedtls_cipher_cmac_update()\r\n", ret);
        return ret;
    }

    ret = mbedtls_cipher_cmac_finish(&ctx, Mic);
    if (ret != 0) {
        MAC_PRINTF("%d = mbedtls_cipher_cmac_finish()\r\n", ret);
        return ret;
    }

    *mic = ( uint32_t )( ( uint32_t )Mic[3] << 24 | ( uint32_t )Mic[2] << 16 | ( uint32_t )Mic[1] << 8 | ( uint32_t )Mic[0] );
    return 0;
}

void LoRaMacJoinDecrypt( const uint8_t *buffer, uint16_t size, const uint8_t *key, uint8_t *decBuffer )
{
    mbedtls_aes_context actx;
    mbedtls_aes_init(&actx);
    if (mbedtls_aes_setkey_enc(&actx, key, 128) < 0) {
        MAC_PRINTF("%d = mbedtls_aes_setkey_enc()\r\n");
    }
    mbedtls_aes_encrypt(&actx, buffer, decBuffer);
    // Check if optional CFList is included
    if (size >= 16)
    {
        mbedtls_aes_encrypt(&actx, buffer + 16, decBuffer + 16);
    }

    mbedtls_aes_free(&actx);
}

void LoRaMacGenerateJoinKey(uint8_t token, const uint8_t* root_key, const uint8_t* devEui, uint8_t* output)
{
    int i;
    uint8_t input[16];
    uint8_t* ptr = input;
    mbedtls_aes_context actx;

    mbedtls_aes_init(&actx);

    memset(ptr, 0, sizeof(input));

    *ptr++ = token;

    /* EUI put into buffer in same order that it appears over-the-air */
    for (i = LORA_EUI_LENGTH - 1; i >= 0; i--)
        *ptr++ = devEui[i];

    DEBUG_CRYPT_BUF(root_key, 16, "generate-join-key-root_key", 0);
    DEBUG_CRYPT_BUF(input, 16, "generate-join-key-input", 0);

    mbedtls_aes_setkey_enc(&actx, root_key, 128);
    mbedtls_aes_encrypt(&actx, input, output);

    mbedtls_aes_free(&actx);
}
#endif /* LORAWAN_JOIN_EUI */