summaryrefslogtreecommitdiffstats
path: root/epan/dissectors/packet-rf4ce-secur.c
blob: 9538dbc1b3c147447653df875cb900132ca02cd1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
/* packet-rf4ce-secur.c
 * Security related functions and objects for RF4CE dissector
 * Copyright (C) Atmosic 2023
 *
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 1998 Gerald Combs
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

#include "packet-rf4ce-secur.h"
#include "packet-zbee-security.h"
#include "packet-ieee802154.h"
#include <wsutil/wsgcrypt.h>
#include <epan/proto_data.h>

#ifdef RF4CE_DEBUG_EN
void rf4ce_print_arr(const char *str, uint8_t *ptr, uint16_t len);
#define RF4CE_PRINT_ARR(s, p, l) rf4ce_print_arr(s, p, l)
#else
#define RF4CE_PRINT_ARR(s, p, l)
#endif /* RF4CE_DEBUG_EN */

static keypair_context_t keypair_context;
static key_exchange_context_t key_exchange_context;
static addr_entry_t addr_table[RF4CE_ADDR_TABLE_SIZE];
static nwk_key_entry_t nwk_key_storage[RF4CE_NWK_KEY_STORAGE_SIZE];
static vendor_secret_entry_t vendor_secret_storage[RF4CE_VENDOR_SECRET_STORAGE_SIZE];

static void keypair_context_calc_key(uint8_t *nwk_key);
static nwk_key_entry_t *nwk_key_storage_get_entry_by_key(uint8_t *nwk_key, bool key_from_gui);

static void reverse(uint8_t *dest, uint8_t *src, uint16_t size);

/* RF4CE GDP 2.0 spec, part 7.4.1 Key Exchange negotiation
 * Default secret: This is a 128bit "secret" that is known to all devices that are certified to
 * conform to this specification. The value shall be set to the following octet string (lowest order
 * octet first)
 * Note that this value should be expected to be widely known and the overall link security
 * should not depend on this value remaining a secret.
 */
uint8_t DEFAULT_SECRET[SEC_STR_LEN] =
    {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
     0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF};

void keypair_context_init(const uint8_t *controller_ieee, const uint8_t *target_ieee, uint8_t expected_transfer_count)
{
    if ((controller_ieee == NULL) || (target_ieee == NULL))
    {
        return;
    }
    memset(&keypair_context, 0, sizeof(keypair_context_t));

    memcpy(keypair_context.controller_addr, controller_ieee, RF4CE_IEEE_ADDR_LEN);
    memcpy(keypair_context.target_addr, target_ieee, RF4CE_IEEE_ADDR_LEN);

    keypair_context.nwk_key_exchange_transfer_expected = expected_transfer_count;
}

static void keypair_context_calc_key(uint8_t *nwk_key)
{
    for (int i = 0; i < keypair_context.nwk_key_exchange_transfer_received; i++)
    {
        for (int j = 0; j < KEY_LEN; j++)
        {
            keypair_context.nwk_key_seed[(i + 1) * KEY_LEN + j] ^= keypair_context.nwk_key_seed[i * KEY_LEN + j];
        }
    }

    memcpy(nwk_key, &keypair_context.nwk_key_seed[RF4CE_NWK_KEY_SEED_DATA_LENGTH - KEY_LEN], KEY_LEN);
}

void keypair_context_update_seed(uint8_t *seed, uint8_t seed_seqn)
{
    bool is_retransmit = (seed_seqn == keypair_context.nwk_key_exchange_transfer_received - 1);
    bool is_latest_seed = (seed_seqn + 1 == keypair_context.nwk_key_exchange_transfer_expected);

    /* retransmitt of the latest key seed - we must to re-calculate a NWK key */
    if (is_retransmit && is_latest_seed)
    {
        memcpy(keypair_context.nwk_key_seed, keypair_context.nwk_key_seed_prev, RF4CE_NWK_KEY_SEED_DATA_LENGTH);
    }

    if (seed_seqn == 0)
    {
        memcpy(keypair_context.nwk_key_seed_latest, seed, RF4CE_NWK_KEY_SEED_DATA_LENGTH);
        keypair_context.nwk_key_exchange_transfer_received = 1;
        return;
    }

    /* Retransmit of the previous key seed. Should take this one */
    if (is_retransmit)
    {
        /* save this one as a candidate */
        memcpy(keypair_context.nwk_key_seed_latest, seed, RF4CE_NWK_KEY_SEED_DATA_LENGTH);

        /* move on if it's the latest seed to re-calculate a NWK key */
        if (!is_latest_seed)
        {
            return;
        }
    }

    if (seed_seqn == keypair_context.nwk_key_exchange_transfer_received)
    {
        /* Apply previous key seed, it has been accepted since we received the next one */
        for (int i = 0; i < RF4CE_NWK_KEY_SEED_DATA_LENGTH; i++)
        {
            keypair_context.nwk_key_seed[i] ^= keypair_context.nwk_key_seed_latest[i];
        }

        /* save this one as a candidate */
        memcpy(keypair_context.nwk_key_seed_latest, seed, RF4CE_NWK_KEY_SEED_DATA_LENGTH);
        keypair_context.nwk_key_exchange_transfer_received += 1;
    }

    if (is_latest_seed)
    {
        uint8_t nwk_key[KEY_LEN] = {0};
        addr_entry_t *controller_addr_ent = rf4ce_addr_table_get_addr_entry_by_ieee(keypair_context.controller_addr);
        addr_entry_t *target_addr_ent = rf4ce_addr_table_get_addr_entry_by_ieee(keypair_context.target_addr);

        /* save the current key seed to avoid retransmitts of the latest one in future */
        memcpy(keypair_context.nwk_key_seed_prev, keypair_context.nwk_key_seed, RF4CE_NWK_KEY_SEED_DATA_LENGTH);

        for (int i = 0; i < RF4CE_NWK_KEY_SEED_DATA_LENGTH; i++)
        {
            keypair_context.nwk_key_seed[i] ^= keypair_context.nwk_key_seed_latest[i];
        }

        keypair_context_calc_key(nwk_key);

        nwk_key_storage_add_entry(
            nwk_key,
            controller_addr_ent,
            target_addr_ent,
            false, /* key from commissioning session */
            true); /* is_pairing_key                 */
    }
}

static nwk_key_entry_t *nwk_key_storage_get_entry_by_key(uint8_t *nwk_key, bool key_from_gui)
{
    nwk_key_entry_t *entry = NULL;
    int idx = 0;

    while (idx < RF4CE_NWK_KEY_STORAGE_SIZE)
    {
        if (nwk_key_storage[idx].is_used && (nwk_key_storage[idx].key_from_gui == key_from_gui) && (memcmp(nwk_key_storage[idx].nwk_key, nwk_key, KEY_LEN) == 0))
        {
            entry = nwk_key_storage + idx;
            break;
        }

        idx++;
    }

    return entry;
}

void nwk_key_storage_add_entry(uint8_t *nwk_key, addr_entry_t *controller_addr_ent, addr_entry_t *target_addr_ent, bool key_from_gui, bool is_pairing_key)
{
    /* find an existing entry so as not to add duplicates */
    nwk_key_entry_t *nwk_key_entry = nwk_key_storage_get_entry_by_key(nwk_key, key_from_gui);

    if (nwk_key_entry == NULL)
    {
        int idx = 0;

        while (idx < RF4CE_NWK_KEY_STORAGE_SIZE)
        {
            if (!nwk_key_storage[idx].is_used)
            {
                memcpy(nwk_key_storage[idx].nwk_key, nwk_key, KEY_LEN);
                nwk_key_storage[idx].controller_addr_ent = controller_addr_ent;
                nwk_key_storage[idx].target_addr_ent = target_addr_ent;
                nwk_key_storage[idx].key_from_gui = key_from_gui;
                nwk_key_storage[idx].is_used = true;
                nwk_key_storage[idx].is_pairing_key = is_pairing_key;
                break;
            }

            idx++;
        }
    }
}

void nwk_key_storage_release_entry(uint8_t *nwk_key, bool key_from_gui)
{
    nwk_key_entry_t *nwk_key_entry = nwk_key_storage_get_entry_by_key(nwk_key, key_from_gui);

    if (nwk_key_entry != NULL)
    {
        nwk_key_entry->is_used = false;
    }
}

void rf4ce_addr_table_add_addrs(const void *ieee_addr, uint16_t short_addr)
{
    unsigned idx = 0;

    if (ieee_addr == NULL)
    {
        return;
    }

    /* search for addresses so as not to add duplicates */
    while (idx < RF4CE_ADDR_TABLE_SIZE)
    {
        if (addr_table[idx].is_used && (memcmp(addr_table[idx].ieee_addr, ieee_addr, RF4CE_IEEE_ADDR_LEN) == 0) && addr_table[idx].short_addr == short_addr)
        {
            return;
        }

        idx++;
    }

    /* no duplicates found, search for a free slot */
    idx = 0;
    while (idx < RF4CE_ADDR_TABLE_SIZE && addr_table[idx].is_used)
    {
        idx++;
    }

    if (idx < RF4CE_ADDR_TABLE_SIZE)
    {
        memcpy(addr_table[idx].ieee_addr, ieee_addr, RF4CE_IEEE_ADDR_LEN);
        addr_table[idx].short_addr = short_addr;
        addr_table[idx].is_used = true;
    }
}

bool rf4ce_addr_table_get_ieee_addr(uint8_t *ieee_addr, packet_info *pinfo, bool is_src)
{
    bool addr_found = false;
    address_type addr_type;
    ieee802154_hints_t *hints;
    const void *p_addr = NULL;
    uint16_t short_addr = 0xffff;

    /* Check inputs */
    if ((ieee_addr == NULL) || (pinfo == NULL))
    {
        return false;
    }
    if (is_src)
    {
        addr_type = pinfo->dl_src.type;
        p_addr = pinfo->dl_src.data;
    }
    else
    {
        addr_type = pinfo->dl_dst.type;
        p_addr = pinfo->dl_dst.data;
    }
    if (addr_type == AT_EUI64)
    {
        if (p_addr == NULL)
        {
            return false;
        }
    }
    else
    {
        /* Get addresses */
        hints = (ieee802154_hints_t *)p_get_proto_data(wmem_file_scope(),
                                                       pinfo,
                                                       proto_get_id_by_filter_name(IEEE802154_PROTOABBREV_WPAN),
                                                       0
        );
        if (hints == NULL)
        {
            return false;
        }
        short_addr = (is_src) ? hints->src16 : hints->dst16;
    }
    /* Search address in address table */
    for (unsigned idx = 0; idx < RF4CE_ADDR_TABLE_SIZE; idx++)
    {
        if (addr_table[idx].is_used)
        {
            if (addr_type == AT_EUI64)
            {
                if (memcmp(addr_table[idx].ieee_addr, p_addr, RF4CE_IEEE_ADDR_LEN) == 0) {
                    addr_found = true;
                }
            }
            else
            {
                if (addr_table[idx].short_addr == short_addr) {
                    addr_found = true;
                }
            }
            if (addr_found)
            {
                memcpy(ieee_addr, addr_table[idx].ieee_addr, RF4CE_IEEE_ADDR_LEN);
                break;
            }
        }
    }
    return addr_found;
}

addr_entry_t *rf4ce_addr_table_get_addr_entry_by_ieee(uint8_t *ieee_addr)
{
    addr_entry_t *entry = NULL;
    unsigned idx = 0;

    while (ieee_addr != NULL && idx < RF4CE_ADDR_TABLE_SIZE)
    {
        if (addr_table[idx].is_used && memcmp(addr_table[idx].ieee_addr, ieee_addr, RF4CE_IEEE_ADDR_LEN) == 0)
        {
            entry = addr_table + idx;
            break;
        }

        idx++;
    }

    return entry;
}

void key_exchange_context_init(void)
{
    memset(&key_exchange_context.rand_a, 0, RF4CE_PROFILE_CMD_KEY_EXCHANGE_RAND_A_LENGTH);
    memset(&key_exchange_context.rand_b, 0, RF4CE_PROFILE_CMD_KEY_EXCHANGE_RAND_B_LENGTH);
    memset(&key_exchange_context.mac_a, 0, RF4CE_IEEE_ADDR_LEN);
    memset(&key_exchange_context.mac_b, 0, RF4CE_IEEE_ADDR_LEN);
}

void key_exchange_context_start_procedure(void)
{
    if (!key_exchange_context.is_proc_started)
    {
        key_exchange_context.is_proc_started = true;
    }
}

void key_exchange_context_stop_procedure(void)
{
    if (key_exchange_context.is_proc_started)
    {
        key_exchange_context.is_proc_started = false;
    }
}

bool key_exchange_context_is_procedure_started(void)
{
    return key_exchange_context.is_proc_started;
}

void key_exchange_context_set_rand_a(uint8_t *rand_a)
{
    if (rand_a != NULL)
    {
        memcpy(key_exchange_context.rand_a, rand_a, RF4CE_PROFILE_CMD_KEY_EXCHANGE_RAND_A_LENGTH);
    }
}

void key_exchange_context_set_rand_b(uint8_t *rand_b)
{
    if (rand_b != NULL)
    {
        memcpy(key_exchange_context.rand_b, rand_b, RF4CE_PROFILE_CMD_KEY_EXCHANGE_RAND_B_LENGTH);
    }
}

void key_exchange_context_set_mac_a(uint8_t *mac_a)
{
    if (mac_a != NULL)
    {
        memcpy(key_exchange_context.mac_a, mac_a, RF4CE_IEEE_ADDR_LEN);
    }
}

void key_exchange_context_set_mac_b(uint8_t *mac_b)
{
    if (mac_b != NULL)
    {
        memcpy(key_exchange_context.mac_b, mac_b, RF4CE_IEEE_ADDR_LEN);
    }
}

#ifdef RF4CE_DEBUG_EN
void rf4ce_print_arr(const char *str, uint8_t *ptr, uint16_t len)
{
  g_print("%s: ", str);
  for (uint16_t i = 0; i < len-1; i++)
  {
    g_print("%02x:", *(ptr+i));
  }
  g_print("%02x\n", *(ptr+len-1));
}
#endif /* RF4CE_DEBUG_EN */

static bool calc_key_cmac(uint8_t *secret, uint8_t *nwk_key, uint32_t tag_b_pack, uint8_t *key_out)
{
    uint8_t mac_a[RF4CE_IEEE_ADDR_LEN];
    uint8_t mac_b[RF4CE_IEEE_ADDR_LEN];

    uint8_t *rand_a = key_exchange_context.rand_a;
    uint8_t *rand_b = key_exchange_context.rand_b;

    rf4ce_key_dk_tag_t k_dk_data;
    rf4ce_key_dk_tag_t k_dk_data_reversed;

    rf4ce_key_context_t context_data;

    uint8_t k_dk_key[KEY_LEN];
    uint8_t new_key[KEY_LEN];

    uint8_t dummy[KEY_LEN];
    uint32_t tag_b_calc;

    reverse(mac_a, key_exchange_context.mac_a, RF4CE_IEEE_ADDR_LEN);
    reverse(mac_b, key_exchange_context.mac_b, RF4CE_IEEE_ADDR_LEN);

    memcpy(k_dk_data.a, rand_a, RF4CE_PROFILE_CMD_KEY_EXCHANGE_RAND_A_LENGTH);
    memcpy(k_dk_data.b, rand_b, RF4CE_PROFILE_CMD_KEY_EXCHANGE_RAND_B_LENGTH);

    memcpy(k_dk_data_reversed.a, rand_b, RF4CE_PROFILE_CMD_KEY_EXCHANGE_RAND_B_LENGTH);
    memcpy(k_dk_data_reversed.b, rand_a, RF4CE_PROFILE_CMD_KEY_EXCHANGE_RAND_A_LENGTH);

    memcpy(context_data.context, CONTEXT_STR, CONTEXT_STR_LEN);
    memcpy(context_data.mac_a, mac_a, RF4CE_IEEE_ADDR_LEN);
    memcpy(context_data.mac_b, mac_b, RF4CE_IEEE_ADDR_LEN);
    memcpy(context_data.pairing_key, nwk_key, KEY_LEN);

    /* Generic Device Profile Version 2.0
     * 7.4.2 Key generation
     * Calculate derivation key
     * K_dk = AES-128-CMAC (RAND-A || RAND-B, Shared secret)
     */
    rf4ce_aes_cmac(secret, SEC_STR_LEN, (uint8_t *)&k_dk_data, k_dk_key);

    /* Calculate new link key
     * Link key = AES-128-CMAC (K_dk, context || label || pairing key)
     */
    rf4ce_aes_cmac((uint8_t *)&context_data, sizeof(context_data), k_dk_key, new_key);

    /* Calculate TAG-B value
     * TAG-B = AES-128-CMAC(link key, RAND-B || RAND-A)
     */
    rf4ce_aes_cmac((uint8_t *)&k_dk_data_reversed, sizeof(k_dk_data_reversed), new_key, dummy);
    memcpy((uint8_t *)&tag_b_calc, dummy, RF4CE_PROFILE_CMD_KEY_EXCHANGE_TAG_A_LENGTH);

    RF4CE_PRINT_ARR("tag_b_calc", (uint8_t *)&tag_b_calc, 4);
    RF4CE_PRINT_ARR("   new_key", new_key, 16);

    if (tag_b_pack == tag_b_calc)
    {
        memcpy(key_out, new_key, KEY_LEN);
        return true;
    }

    return false;
}

static bool key_exchange_calc_key_cont(uint8_t *secret, uint32_t tag_b_pack, bool try_pairing_key, uint8_t *new_key_out)
{
    bool is_new_key_found = false;

    for (unsigned i = 0; i < RF4CE_NWK_KEY_STORAGE_SIZE; i++)
    {
        if (nwk_key_storage[i].is_used && ((try_pairing_key && nwk_key_storage[i].is_pairing_key) || (!try_pairing_key && nwk_key_storage[i].key_from_gui)))
        {
            is_new_key_found = calc_key_cmac(secret, nwk_key_storage[i].nwk_key, tag_b_pack, new_key_out);

            if (is_new_key_found)
            {
                break;
            }
        }
    }

    return is_new_key_found;
}

void key_exchange_calc_key(uint32_t tag_b_pack)
{
    uint8_t *controller_addr = key_exchange_context.mac_a;
    uint8_t *target_addr = key_exchange_context.mac_b;

    addr_entry_t *controller_addr_ent = rf4ce_addr_table_get_addr_entry_by_ieee(controller_addr);
    addr_entry_t *target_addr_ent = rf4ce_addr_table_get_addr_entry_by_ieee(target_addr);

    uint8_t *secret;

    uint8_t new_key[KEY_LEN];
    bool is_new_key_found = false;

    for (unsigned i = 0; i < RF4CE_VENDOR_SECRET_STORAGE_SIZE; i++)
    {
        if (!vendor_secret_storage[i].is_used)
        {
            continue;
        }

        secret = vendor_secret_storage[i].secret;

        /* try all the pairing keys first */
        is_new_key_found = key_exchange_calc_key_cont(secret, tag_b_pack, true, new_key);

        /* try other keys */
        if (!is_new_key_found)
        {
            is_new_key_found = key_exchange_calc_key_cont(secret, tag_b_pack, false, new_key);
        }

        if (is_new_key_found)
        {
            nwk_key_storage_add_entry(
                new_key,
                controller_addr_ent,
                target_addr_ent,
                false,  /* key from the Key Exchange procedure */
                false); /* !is_pairing_key */

            break;
        }
    }
}

static vendor_secret_entry_t *vendor_secret_storage_get_entry(uint8_t *secret)
{
    vendor_secret_entry_t *entry = NULL;
    int idx = 0;

    while (idx < RF4CE_VENDOR_SECRET_STORAGE_SIZE)
    {
        if (vendor_secret_storage[idx].is_used && (memcmp(vendor_secret_storage[idx].secret, secret, SEC_STR_LEN) == 0))
        {
            entry = vendor_secret_storage + idx;
            break;
        }

        idx++;
    }

    return entry;
}

void vendor_secret_storage_add_entry(uint8_t *secret)
{
    unsigned idx = 0;
    vendor_secret_entry_t *entry = vendor_secret_storage_get_entry(secret);

    if (entry != NULL)
    {
        return;
    }

    while (idx < RF4CE_VENDOR_SECRET_STORAGE_SIZE && vendor_secret_storage[idx].is_used)
    {
        idx++;
    }

    if (idx < RF4CE_VENDOR_SECRET_STORAGE_SIZE)
    {
        memcpy(vendor_secret_storage[idx].secret, secret, SEC_STR_LEN);
        vendor_secret_storage[idx].is_used = true;
    }
}

void vendor_secret_storage_release_entry(uint8_t *secret)
{
    vendor_secret_entry_t *entry = vendor_secret_storage_get_entry(secret);

    if (entry != NULL)
    {
        entry->is_used = false;
    }
}

void rf4ce_secur_cleanup(void)
{
    int idx = 0;

    memset(&keypair_context, 0, sizeof(keypair_context));
    memset(addr_table, 0, sizeof(addr_table));

    while (idx < RF4CE_NWK_KEY_STORAGE_SIZE)
    {
        if (nwk_key_storage[idx].is_used && !nwk_key_storage[idx].key_from_gui)
        {
            nwk_key_storage[idx].is_used = false;
        }

        idx++;
    }
}

static void reverse(uint8_t *dest, uint8_t *src, uint16_t size)
{
    for (int i = 0; i < size; i++)
    {
        dest[size - i - 1] = src[i];
    }
}

bool decrypt_data(
    const uint8_t *in, uint8_t *out,
    uint16_t payload_offset,
    uint16_t *len,
    uint8_t src_ieee[RF4CE_IEEE_ADDR_LEN], uint8_t dst_ieee[RF4CE_IEEE_ADDR_LEN])
{
    bool ret = false;
    uint8_t frame_control = *in;
    int idx = 0;

    if (*len < RF4CE_MIN_NWK_LENGTH || *len > RF4CE_MAX_NWK_LENGTH)
    {
        return false;
    }

    while (idx < RF4CE_NWK_KEY_STORAGE_SIZE)
    {
        if (nwk_key_storage[idx].is_used)
        {
            /* Form the nonce (3.5.11.3 Outgoing frame security) */
            rf4ce_secur_ccm_nonce_t nonce =
                (rf4ce_secur_ccm_nonce_t){
                    .secur_control = RF4CE_SECUR_CONTROL};

            /* Fetch counter from the packet (don't check) */
            memcpy(&(nonce.frame_counter), in + 1, sizeof(uint32_t));
            reverse(&(nonce.source_address[0]), src_ieee, 8);

            /* Form the auth string (3.5.11.3 Outgoing frame security) */
            rf4ce_secur_ccm_auth_t auth =
                (rf4ce_secur_ccm_auth_t){
                    .frame_control = frame_control};

            /* Fetch counter from the packet (don't check) */
            memcpy(&(auth.frame_counter), in + 1, sizeof(uint32_t));
            reverse(&(auth.dest_address[0]), dst_ieee, 8);

            ret = zbee_sec_ccm_decrypt(nwk_key_storage[idx].nwk_key,
                                       (uint8_t *)&nonce,
                                       (uint8_t *)&auth,
                                       in + payload_offset,
                                       out,
                                       sizeof(auth),
                                       *len - payload_offset - RF4CE_CCM_M,
                                       RF4CE_CCM_M);

            if (ret)
            {
                *len = *len - payload_offset - RF4CE_CCM_M;
                break;
            }
        }

        idx++;
    }

    return ret;
}

// Calculate the CMAC
void rf4ce_aes_cmac(unsigned char *input, unsigned long length, unsigned char *key, unsigned char *mac_value)
{
    gcry_mac_hd_t mac_hd;
    size_t l = length;

    if (gcry_mac_open(&mac_hd, GCRY_MAC_CMAC_AES, 0, NULL))
    {
        return;
    }
    if (gcry_mac_setkey(mac_hd, key, KEY_LEN))
    {
        gcry_mac_close(mac_hd);
        return;
    }
    if (gcry_mac_write(mac_hd, input, length))
    {
        gcry_mac_close(mac_hd);
        return;
    }
    if (gcry_mac_read(mac_hd, mac_value, &l))
    {
        gcry_mac_close(mac_hd);
        return;
    }
    gcry_mac_close(mac_hd);
}