xref: /btstack/src/mesh/mesh_network.c (revision c1f227d5a936962d6e55c44c9d87cefcf091091d)
1 /*
2  * Copyright (C) 2018 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define __BTSTACK_FILE__ "mesh_network.c"
39 
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 
44 #include "btstack_debug.h"
45 #include "btstack_event.h"
46 #include "btstack_memory.h"
47 #include "btstack_util.h"
48 
49 #include "mesh/beacon.h"
50 #include "mesh/mesh_foundation.h"
51 #include "mesh/mesh_iv_index_seq_number.h"
52 #include "mesh/mesh_keys.h"
53 #include "mesh/mesh_node.h"
54 #include "mesh/provisioning.h"
55 #include "mesh/provisioning_device.h"
56 
57 #ifdef ENABLE_MESH_ADV_BEARER
58 #include "mesh/adv_bearer.h"
59 #endif
60 
61 #ifdef ENABLE_MESH_GATT_BEARER
62 #include "mesh/gatt_bearer.h"
63 #endif
64 
65 // configuration
66 #define MESH_NETWORK_CACHE_SIZE 2
67 // #define ENABLE_MESH_RELAY
68 
69 // debug config
70 // #define LOG_NETWORK
71 
72 // structs
73 
74 // globals
75 
76 static void (*mesh_network_higher_layer_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu);
77 static void (*mesh_network_proxy_message_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu);
78 
79 #ifdef ENABLE_MESH_GATT_BEARER
80 static hci_con_handle_t gatt_bearer_con_handle;
81 #endif
82 
83 // shared send/receive crypto
84 static int mesh_crypto_active;
85 
86 // crypto requests
87 static union {
88     btstack_crypto_ccm_t         ccm;
89     btstack_crypto_aes128_t      aes128;
90 } mesh_network_crypto_request;
91 
92 static const mesh_network_key_t *  current_network_key;
93 
94 // PECB calculation
95 static uint8_t encryption_block[16];
96 static uint8_t obfuscation_block[16];
97 
98 // Subnets
99 static btstack_linked_list_t subnets;
100 
101 // Network Nonce
102 static uint8_t network_nonce[13];
103 
104 // INCOMING //
105 
106 // unprocessed network pdu - added by mesh_network_pdus_received_message
107 static btstack_linked_list_t        network_pdus_received;
108 
109 // in validation
110 static mesh_network_pdu_t *         network_pdu_in_validation;
111 static mesh_network_key_iterator_t  validation_network_key_it;
112 
113 // OUTGOING //
114 
115 // Network PDUs queued by mesh_network_send
116 static btstack_linked_list_t network_pdus_queued;
117 
118 // Network PDUs ready to send
119 static btstack_linked_list_t network_pdus_outgoing;
120 
121 #ifdef ENABLE_MESH_ADV_BEARER
122 static mesh_network_pdu_t * adv_bearer_network_pdu;
123 #endif
124 
125 #ifdef ENABLE_MESH_GATT_BEARER
126 static mesh_network_pdu_t * gatt_bearer_network_pdu;
127 #endif
128 
129 // mesh network cache - we use 32-bit 'hashes'
130 static uint32_t mesh_network_cache[MESH_NETWORK_CACHE_SIZE];
131 static int      mesh_network_cache_index;
132 
133 // prototypes
134 
135 static void mesh_network_run(void);
136 static void process_network_pdu_validate(mesh_network_pdu_t * network_pdu);
137 
138 // network caching
139 static uint32_t mesh_network_cache_hash(mesh_network_pdu_t * network_pdu){
140     // - The SEQ field is a 24-bit integer that when combined with the IV Index,
141     // shall be a unique value for each new Network PDU originated by this node (=> SRC)
142     // - IV updates only rarely
143     // => 16 bit SRC, 1 bit IVI, 15 bit SEQ
144     uint8_t  ivi = network_pdu->data[0] >> 7;
145     uint16_t seq = big_endian_read_16(network_pdu->data, 3);
146     uint16_t src = big_endian_read_16(network_pdu->data, 5);
147     return (src << 16) | (ivi << 15) | (seq & 0x7fff);
148 }
149 
150 static int mesh_network_cache_find(uint32_t hash){
151     int i;
152     for (i = 0; i < MESH_NETWORK_CACHE_SIZE; i++) {
153         if (mesh_network_cache[i] == hash) {
154             return 1;
155         }
156     }
157     return 0;
158 }
159 
160 static void mesh_network_cache_add(uint32_t hash){
161     mesh_network_cache[mesh_network_cache_index++] = hash;
162     if (mesh_network_cache_index >= MESH_NETWORK_CACHE_SIZE){
163         mesh_network_cache_index = 0;
164     }
165 }
166 
167 // common helper
168 int mesh_network_address_unicast(uint16_t addr){
169     return addr != MESH_ADDRESS_UNSASSIGNED && (addr < 0x8000);
170 }
171 
172 int mesh_network_address_virtual(uint16_t addr){
173     return (addr & 0xC000) == 0x8000;   // 0b10xx xxxx xxxx xxxx
174 }
175 
176 int mesh_network_address_group(uint16_t addr){
177     return (addr & 0xC000) == 0xC000;   // 0b11xx xxxx xxxx xxxx
178 }
179 
180 int mesh_network_address_all_proxies(uint16_t addr){
181     return addr == MESH_ADDRESS_ALL_PROXIES;
182 }
183 
184 int mesh_network_address_all_nodes(uint16_t addr){
185     return addr == MESH_ADDRESS_ALL_NODES;
186 }
187 
188 int mesh_network_address_all_friends(uint16_t addr){
189     return addr == MESH_ADDRESS_ALL_FRIENDS;
190 }
191 
192 int mesh_network_address_all_relays(uint16_t addr){
193     return addr == MESH_ADDRESS_ALL_RELAYS;
194 }
195 
196 int mesh_network_addresses_valid(uint8_t ctl, uint16_t src, uint16_t dst){
197     // printf("CTL: %u\n", ctl);
198     // printf("SRC: %04x\n", src);
199     // printf("DST: %04x\n", dst);
200     if (src == 0){
201         // printf("SRC Unassigned Addr -> ignore\n");
202         return 0;
203     }
204     if ((src & 0xC000) == 0x8000){
205         // printf("SRC Virtual Addr -> ignore\n");
206         return 0;
207     }
208     if ((src & 0xC000) == 0xC000){
209         // printf("SRC Group Addr -> ignore\n");
210         return 0;
211     }
212     if (dst == 0){
213         // printf("DST Unassigned Addr -> ignore\n");
214         return 0;
215     }
216     if ( ((dst & 0xC000) == 0x8000) && (ctl == 1)){
217         // printf("DST Virtual Addr in CONTROL -> ignore\n");
218         return 0;
219     }
220     if ( (0xFF00 <= dst) && (dst <= 0xfffb) && (ctl == 0) ){
221         // printf("DST RFU Group Addr in MESSAGE -> ignore\n");
222         return 0;
223     }
224     // printf("SRC + DST Addr valid\n");
225     return 1;
226 }
227 
228 static void mesh_network_create_nonce(uint8_t * nonce, const mesh_network_pdu_t * pdu, uint32_t iv_index){
229     unsigned int pos = 0;
230     nonce[pos++] = 0x0;      // Network Nonce
231     memcpy(&nonce[pos], &pdu->data[1], 6);
232     pos += 6;
233     big_endian_store_16(nonce, pos, 0);
234     pos += 2;
235     big_endian_store_32(nonce, pos, iv_index);
236 }
237 
238 static void mesh_proxy_create_nonce(uint8_t * nonce, const mesh_network_pdu_t * pdu, uint32_t iv_index){
239     unsigned int pos = 0;
240     nonce[pos++] = 0x3;      // Proxy Nonce
241     nonce[pos++] = 0;
242     memcpy(&nonce[pos], &pdu->data[2], 5);
243     pos += 5;
244     big_endian_store_16(nonce, pos, 0);
245     pos += 2;
246     big_endian_store_32(nonce, pos, iv_index);
247 }
248 
249 // NID/IVI | obfuscated (CTL/TTL, SEQ (24), SRC (16) ), encrypted ( DST(16), TransportPDU), MIC(32 or 64)
250 
251 static void mesh_network_send_d(mesh_network_pdu_t * network_pdu){
252 
253 #ifdef LOG_NETWORK
254     printf("TX-D-NetworkPDU (%p): ", network_pdu);
255     printf_hexdump(network_pdu->data, network_pdu->len);
256 #endif
257 
258     // add to queue
259     btstack_linked_list_add_tail(&network_pdus_outgoing, (btstack_linked_item_t *) network_pdu);
260 
261     // go
262     mesh_network_run();
263 }
264 
265 // new
266 static void mesh_network_send_c(void *arg){
267     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) arg;
268 
269     // obfuscate
270     unsigned int i;
271     for (i=0;i<6;i++){
272         network_pdu->data[1+i] ^= obfuscation_block[i];
273     }
274 
275 #ifdef LOG_NETWORK
276     printf("TX-C-NetworkPDU (%p): ", network_pdu);
277     printf_hexdump(network_pdu->data, network_pdu->len);
278 #endif
279 
280     // crypto done
281     mesh_crypto_active = 0;
282 
283     // done
284     (network_pdu->callback)(network_pdu);
285 }
286 
287 static void mesh_network_send_b(void *arg){
288     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) arg;
289 
290     uint32_t iv_index = mesh_get_iv_index_for_tx();
291 
292     // store NetMIC
293     uint8_t net_mic[8];
294     btstack_crypto_ccm_get_authentication_value(&mesh_network_crypto_request.ccm, net_mic);
295 
296     // store MIC
297     uint8_t net_mic_len = network_pdu->data[1] & 0x80 ? 8 : 4;
298     memcpy(&network_pdu->data[network_pdu->len], net_mic, net_mic_len);
299     network_pdu->len += net_mic_len;
300 
301 #ifdef LOG_NETWORK
302     printf("TX-B-NetworkPDU (%p): ", network_pdu);
303     printf_hexdump(network_pdu->data, network_pdu->len);
304 #endif
305 
306     // calc PECB
307     memset(encryption_block, 0, 5);
308     big_endian_store_32(encryption_block, 5, iv_index);
309     memcpy(&encryption_block[9], &network_pdu->data[7], 7);
310     btstack_crypto_aes128_encrypt(&mesh_network_crypto_request.aes128, current_network_key->privacy_key, encryption_block, obfuscation_block, &mesh_network_send_c, network_pdu);
311 }
312 
313 static void mesh_network_send_a(mesh_network_pdu_t * network_pdu){
314 
315     mesh_crypto_active = 1;
316 
317     uint32_t iv_index = mesh_get_iv_index_for_tx();
318 
319     // lookup subnet by netkey_index
320     mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(network_pdu->netkey_index);
321     if (!subnet) {
322         mesh_crypto_active = 0;
323         // notify upper layer
324         (*mesh_network_higher_layer_handler)(MESH_NETWORK_PDU_SENT, network_pdu);
325         // run again
326         mesh_network_run();
327         return;
328     }
329 
330     // get network key to use for sending
331     current_network_key = mesh_subnet_get_outgoing_network_key(subnet);
332 
333 #ifdef LOG_NETWORK
334     printf("TX-A-NetworkPDU (%p): ", network_pdu);
335     printf_hexdump(network_pdu->data, network_pdu->len);
336 #endif
337 
338     // get network nonce
339     if (network_pdu->flags & MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION){
340         mesh_proxy_create_nonce(network_nonce, network_pdu, iv_index);
341 #ifdef LOG_NETWORK
342         printf("TX-ProxyNonce:  ");
343         printf_hexdump(network_nonce, 13);
344 #endif
345     } else {
346         mesh_network_create_nonce(network_nonce, network_pdu, iv_index);
347 #ifdef LOG_NETWORK
348         printf("TX-NetworkNonce:  ");
349         printf_hexdump(network_nonce, 13);
350 #endif
351     }
352 
353 #ifdef LOG_NETWORK
354    printf("TX-EncryptionKey: ");
355     printf_hexdump(current_network_key->encryption_key, 16);
356 #endif
357 
358     // start ccm
359     uint8_t cypher_len  = network_pdu->len - 7;
360     uint8_t net_mic_len = network_pdu->data[1] & 0x80 ? 8 : 4;
361     btstack_crypto_ccm_init(&mesh_network_crypto_request.ccm, current_network_key->encryption_key, network_nonce, cypher_len, 0, net_mic_len);
362     btstack_crypto_ccm_encrypt_block(&mesh_network_crypto_request.ccm, cypher_len, &network_pdu->data[7], &network_pdu->data[7], &mesh_network_send_b, network_pdu);
363 }
364 
365 #if defined(ENABLE_MESH_RELAY) || defined (ENABLE_MESH_PROXY_SERVER)
366 static void mesh_network_relay_message(mesh_network_pdu_t * network_pdu){
367     uint8_t ctl_ttl     = network_pdu->data[1];
368     uint8_t ctl         = ctl_ttl & 0x80;
369     uint8_t ttl         = ctl_ttl & 0x7f;
370     uint8_t net_mic_len = ctl ? 8 : 4;
371 
372     // prepare pdu for resending
373     network_pdu->len    -= net_mic_len;
374     network_pdu->data[1] = (ctl << 7) | (ttl - 1);
375     network_pdu->flags |= MESH_NETWORK_PDU_FLAGS_RELAY;
376 
377     // queue up
378     network_pdu->callback = &mesh_network_send_d;
379     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
380 }
381 #endif
382 
383 void mesh_network_message_processed_by_higher_layer(mesh_network_pdu_t * network_pdu){
384 
385 #if defined(ENABLE_MESH_RELAY) || defined (ENABLE_MESH_PROXY_SERVER)
386 
387     // check if address does not matches elements on our node and TTL >= 2
388     uint16_t src     = mesh_network_src(network_pdu);
389     uint8_t  ttl     = mesh_network_ttl(network_pdu);
390 
391     uint16_t mesh_network_primary_address = mesh_node_get_primary_element_address();
392 
393     if (((src < mesh_network_primary_address) || (src > (mesh_network_primary_address + mesh_node_element_count()))) && (ttl >= 2)){
394 
395         if ((network_pdu->flags & MESH_NETWORK_PDU_FLAGS_GATT_BEARER) == 0){
396 
397             // message received via ADV bearer are relayed:
398 
399 #ifdef ENABLE_MESH_RELAY
400             if (mesh_foundation_relay_get() != 0){
401                 // - to ADV bearer, if Relay supported and enabled
402                 mesh_network_relay_message(network_pdu);
403                 mesh_network_run();
404                 return;
405             }
406 #endif
407 
408 #ifdef ENABLE_MESH_PROXY_SERVER
409             if (mesh_foundation_gatt_proxy_get() != 0){
410                 // - to GATT bearer, if Proxy supported and enabled
411                 mesh_network_relay_message(network_pdu);
412                 mesh_network_run();
413                 return;
414             }
415 #endif
416 
417         } else {
418 
419             // messages received via GATT bearer are relayed:
420 
421 #ifdef ENABLE_MESH_PROXY_SERVER
422             if (mesh_foundation_gatt_proxy_get() != 0){
423                 // - to ADV bearer, if Proxy supported and enabled
424                 mesh_network_relay_message(network_pdu);
425                 mesh_network_run();
426                 return;
427             }
428 #endif
429 
430         }
431     }
432 #endif
433 
434     // otherwise, we're done
435     btstack_memory_mesh_network_pdu_free(network_pdu);
436 }
437 
438 static void process_network_pdu_done(void){
439     btstack_memory_mesh_network_pdu_free(network_pdu_in_validation);
440     network_pdu_in_validation = NULL;
441     mesh_crypto_active = 0;
442 
443     mesh_network_run();
444 }
445 
446 static void process_network_pdu_validate_d(void * arg){
447     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) arg;
448 
449     uint8_t ctl_ttl     = network_pdu->data[1];
450     uint8_t ctl         = ctl_ttl >> 7;
451     uint8_t net_mic_len = (ctl_ttl & 0x80) ? 8 : 4;
452 
453     // store NetMIC
454     uint8_t net_mic[8];
455     btstack_crypto_ccm_get_authentication_value(&mesh_network_crypto_request.ccm, net_mic);
456 #ifdef LOG_NETWORK
457     printf("RX-NetMIC: ");
458     printf_hexdump(net_mic, net_mic_len);
459 #endif
460     // store in pdu
461     memcpy(&network_pdu->data[network_pdu->len-net_mic_len], net_mic, net_mic_len);
462 
463 #ifdef LOG_NETWORK
464     uint8_t cypher_len  = network_pdu->len - 9 - net_mic_len;
465     printf("RX-Decrypted DST/TransportPDU: ");
466     printf_hexdump(&network_pdu->data[7], 2 + cypher_len);
467 
468     printf("RX-Decrypted: ");
469     printf_hexdump(network_pdu->data, network_pdu->len);
470 #endif
471 
472     // validate network mic
473     if (memcmp(net_mic, &network_pdu_in_validation->data[network_pdu->len-net_mic_len], net_mic_len) != 0){
474         // fail
475         printf("RX-NetMIC mismatch, try next key\n");
476         process_network_pdu_validate(network_pdu);
477         return;
478     }
479 
480     // remove NetMIC from payload
481     network_pdu->len -= net_mic_len;
482 
483 #ifdef LOG_NETWORK
484     // match
485     printf("RX-NetMIC matches\n");
486     printf("RX-TTL: 0x%02x\n", network_pdu->data[1] & 0x7f);
487 #endif
488 
489     // set netkey_index
490     network_pdu->netkey_index = current_network_key->netkey_index;
491 
492     if (network_pdu->flags & MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION){
493 
494         // no additional checks for proxy messages
495         (*mesh_network_proxy_message_handler)(MESH_NETWORK_PDU_RECEIVED, network_pdu);
496 
497     } else {
498 
499         // validate src/dest addresses
500         uint16_t src = big_endian_read_16(network_pdu->data, 5);
501         uint16_t dst = big_endian_read_16(network_pdu->data, 7);
502         int valid = mesh_network_addresses_valid(ctl, src, dst);
503         if (!valid){
504             printf("RX Address invalid\n");
505             btstack_memory_mesh_network_pdu_free(network_pdu);
506             process_network_pdu_done();
507             return;
508         }
509 
510         // check cache
511         uint32_t hash = mesh_network_cache_hash(network_pdu);
512 #ifdef LOG_NETWORK
513         printf("RX-Hash: %08x\n", hash);
514 #endif
515         if (mesh_network_cache_find(hash)){
516             // found in cache, drop
517             printf("Found in cache -> drop packet\n");
518             btstack_memory_mesh_network_pdu_free(network_pdu);
519             process_network_pdu_done();
520             return;
521         }
522 
523         // store in network cache
524         mesh_network_cache_add(hash);
525 
526         // forward to lower transport layer. message is freed by call to mesh_network_message_processed_by_upper_layer
527         (*mesh_network_higher_layer_handler)(MESH_NETWORK_PDU_RECEIVED, network_pdu);
528     }
529 
530     // done
531     process_network_pdu_done();
532 }
533 
534 static uint32_t iv_index_for_pdu(const mesh_network_pdu_t * network_pdu){
535     // get IV Index and IVI
536     uint32_t iv_index = mesh_get_iv_index();
537     int ivi = network_pdu->data[0] >> 7;
538 
539     // if least significant bit differs, use previous IV Index
540     if ((iv_index & 1 ) ^ ivi){
541         iv_index--;
542 #ifdef LOG_NETWORK
543         printf("RX-IV: IVI indicates previous IV index, using 0x%08x\n", iv_index);
544 #endif
545     }
546     return iv_index;
547 }
548 
549 static void process_network_pdu_validate_b(void * arg){
550     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) arg;
551 
552 #ifdef LOG_NETWORK
553     printf("RX-PECB: ");
554     printf_hexdump(obfuscation_block, 6);
555 #endif
556 
557     // de-obfuscate
558     unsigned int i;
559     for (i=0;i<6;i++){
560         network_pdu->data[1+i] = network_pdu_in_validation->data[1+i] ^ obfuscation_block[i];
561     }
562 
563     uint32_t iv_index = iv_index_for_pdu(network_pdu);
564 
565     if (network_pdu->flags & MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION){
566         // create network nonce
567         mesh_proxy_create_nonce(network_nonce, network_pdu, iv_index);
568 #ifdef LOG_NETWORK
569         printf("RX-Proxy Nonce: ");
570         printf_hexdump(network_nonce, 13);
571 #endif
572     } else {
573         // create network nonce
574         mesh_network_create_nonce(network_nonce, network_pdu, iv_index);
575 #ifdef LOG_NETWORK
576         printf("RX-Network Nonce: ");
577         printf_hexdump(network_nonce, 13);
578 #endif
579     }
580 
581     //
582     uint8_t ctl_ttl     = network_pdu->data[1];
583     uint8_t net_mic_len = (ctl_ttl & 0x80) ? 8 : 4;
584     uint8_t cypher_len  = network_pdu->len - 7 - net_mic_len;
585 
586 #ifdef LOG_NETWORK
587     printf("RX-Cyper len %u, mic len %u\n", cypher_len, net_mic_len);
588 
589     printf("RX-Encryption Key: ");
590     printf_hexdump(current_network_key->encryption_key, 16);
591 
592 #endif
593 
594     btstack_crypto_ccm_init(&mesh_network_crypto_request.ccm, current_network_key->encryption_key, network_nonce, cypher_len, 0, net_mic_len);
595     btstack_crypto_ccm_decrypt_block(&mesh_network_crypto_request.ccm, cypher_len, &network_pdu_in_validation->data[7], &network_pdu->data[7], &process_network_pdu_validate_d, network_pdu);
596 }
597 
598 static void process_network_pdu_validate(mesh_network_pdu_t * network_pdu){
599     if (!mesh_network_key_nid_iterator_has_more(&validation_network_key_it)){
600         printf("No valid network key found\n");
601         btstack_memory_mesh_network_pdu_free(network_pdu);
602         process_network_pdu_done();
603         return;
604     }
605 
606     current_network_key = mesh_network_key_nid_iterator_get_next(&validation_network_key_it);
607 
608     // calc PECB
609     uint32_t iv_index = iv_index_for_pdu(network_pdu);
610     memset(encryption_block, 0, 5);
611     big_endian_store_32(encryption_block, 5, iv_index);
612     memcpy(&encryption_block[9], &network_pdu_in_validation->data[7], 7);
613     btstack_crypto_aes128_encrypt(&mesh_network_crypto_request.aes128, current_network_key->privacy_key, encryption_block, obfuscation_block, &process_network_pdu_validate_b, network_pdu);
614 }
615 
616 
617 static void process_network_pdu(mesh_network_pdu_t * network_pdu){
618     //
619     uint8_t nid_ivi = network_pdu_in_validation->data[0];
620 
621     // setup pdu object
622     network_pdu->data[0] = nid_ivi;
623     network_pdu->len     = network_pdu_in_validation->len;
624     network_pdu->flags   = network_pdu_in_validation->flags;
625 
626     // init provisioning data iterator
627     uint8_t nid = nid_ivi & 0x7f;
628     // uint8_t iv_index = network_pdu_data[0] >> 7;
629     mesh_network_key_nid_iterator_init(&validation_network_key_it, nid);
630 
631     process_network_pdu_validate(network_pdu);
632 }
633 
634 // static void mesh_network_encrypt_and_obfuscate(mesh_network_pdu_t * network_pdu, void (*callback)(mesh_network_pdu_t * network_pdu)){
635 //     network_pdu->callback = callback;
636 // }
637 
638 static void mesh_network_run(void){
639     if (!btstack_linked_list_empty(&network_pdus_outgoing)){
640         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_outgoing);
641 
642 #ifdef ENABLE_MESH_GATT_BEARER
643         // request to send via gatt if:
644         // proxy active and connected
645         // packet wasn't received via gatt bearer
646         printf("mesh_network_run: pdu %p, proxy %u, con handle %4x\n", network_pdu, mesh_foundation_gatt_proxy_get(), gatt_bearer_con_handle);
647         if (network_pdu != NULL &&
648             (mesh_foundation_gatt_proxy_get() != 0) &&
649             (gatt_bearer_con_handle != HCI_CON_HANDLE_INVALID) &&
650             ((network_pdu->flags & MESH_NETWORK_PDU_FLAGS_GATT_BEARER) == 0)
651         ){
652             gatt_bearer_network_pdu = network_pdu;
653             network_pdu = NULL;
654             gatt_bearer_request_can_send_now_for_network_pdu();
655         }
656 #endif
657 #ifdef ENABLE_MESH_ADV_BEARER
658          // request to send via adv
659         if (network_pdu != NULL){
660             adv_bearer_network_pdu = network_pdu;
661             network_pdu = NULL;
662             adv_bearer_request_can_send_now_for_network_pdu();
663         }
664 #endif
665         if (network_pdu !=  NULL){
666             // notify upper layer
667             (*mesh_network_higher_layer_handler)(MESH_NETWORK_PDU_SENT, network_pdu);
668         }
669     }
670 
671     if (mesh_crypto_active) return;
672 
673     if (!btstack_linked_list_empty(&network_pdus_received)){
674         mesh_network_pdu_t * decode_pdu = mesh_network_pdu_get();
675         if (!decode_pdu) return;
676         // get encoded network pdu and start processing
677         mesh_crypto_active = 1;
678         network_pdu_in_validation = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_received);
679         process_network_pdu(decode_pdu);
680         return;
681     }
682 
683     if (!btstack_linked_list_empty(&network_pdus_queued)){
684         // get queued network pdu and start processing
685         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_queued);
686         mesh_network_send_a(network_pdu);
687         return;
688     }
689 }
690 
691 #ifdef ENABLE_MESH_ADV_BEARER
692 static void mesh_adv_bearer_handle_network_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
693     UNUSED(channel);
694     mesh_network_pdu_t * network_pdu;
695     uint8_t  transmission_count;
696     uint16_t transmission_interval;
697     uint8_t  transmit_config;
698 
699     switch (packet_type){
700         case MESH_NETWORK_PACKET:
701             // check len. minimal transport PDU len = 1, 32 bit NetMIC -> 13 bytes
702             if (size < 13) break;
703 
704 #ifdef LOG_NETWORK
705             printf("received network pdu from adv (len %u): ", size);
706             printf_hexdump(packet, size);
707 #endif
708             mesh_network_received_message(packet, size, 0);
709             break;
710 
711         case HCI_EVENT_PACKET:
712             switch(packet[0]){
713                 case HCI_EVENT_MESH_META:
714                     switch(packet[2]){
715                         case MESH_SUBEVENT_CAN_SEND_NOW:
716                             if (adv_bearer_network_pdu == NULL) break;
717 
718                             // Get Transmission config depending on relay flag
719                             if (adv_bearer_network_pdu->flags & MESH_NETWORK_PDU_FLAGS_RELAY){
720                                 transmit_config = mesh_foundation_relay_get();
721                             } else {
722                                 transmit_config = mesh_foundation_network_transmit_get();
723                             }
724                             transmission_count     = (transmit_config & 0x07) + 1;
725                             transmission_interval = (transmit_config >> 3) * 10;
726 
727 #ifdef LOG_NETWORK
728                             printf("TX-E-NetworkPDU count %u, interval %u ms (%p): ", adv_bearer_network_pdu, transmission_count, transmission_interval);
729                             printf_hexdump(adv_bearer_network_pdu->data, adv_bearer_network_pdu->len);
730 #endif
731 
732                             adv_bearer_send_network_pdu(adv_bearer_network_pdu->data, adv_bearer_network_pdu->len, transmission_count, transmission_interval);
733                             network_pdu = adv_bearer_network_pdu;
734                             adv_bearer_network_pdu = NULL;
735 
736                             // notify upper layer
737                             (*mesh_network_higher_layer_handler)(MESH_NETWORK_PDU_SENT, network_pdu);
738 
739                             // check if more to send
740                             mesh_network_run();
741                             break;
742                         default:
743                             break;
744                     }
745                     break;
746                 default:
747                     break;
748             }
749             break;
750     }
751 }
752 #endif
753 
754 #ifdef ENABLE_MESH_GATT_BEARER
755 static void mesh_network_gatt_bearer_outgoing_complete(void){
756 
757     if (gatt_bearer_network_pdu == NULL) return;
758 
759 #ifdef ENABLE_MESH_ADV_BEARER
760     // forward to adv bearer
761     adv_bearer_network_pdu = gatt_bearer_network_pdu;
762     gatt_bearer_network_pdu = NULL;
763     adv_bearer_request_can_send_now_for_network_pdu();
764     return;
765 #endif
766 
767     // done, notify upper layer
768      mesh_network_pdu_t * network_pdu = gatt_bearer_network_pdu;
769     gatt_bearer_network_pdu = NULL;
770     (*mesh_network_higher_layer_handler)(MESH_NETWORK_PDU_SENT, network_pdu);
771 }
772 
773 static void mesh_network_gatt_bearer_handle_network_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
774     UNUSED(channel);
775     switch (packet_type){
776         case MESH_PROXY_DATA_PACKET:
777             if (mesh_foundation_gatt_proxy_get() == 0) break;
778 #ifdef LOG_NETWORK
779             printf("received network pdu from gatt (len %u): ", size);
780             printf_hexdump(packet, size);
781 #endif
782             mesh_network_received_message(packet, size, MESH_NETWORK_PDU_FLAGS_GATT_BEARER);
783             break;
784         case HCI_EVENT_PACKET:
785             switch (hci_event_packet_get_type(packet)){
786                 case HCI_EVENT_MESH_META:
787                     switch (hci_event_mesh_meta_get_subevent_code(packet)){
788                         case MESH_SUBEVENT_PROXY_CONNECTED:
789                             gatt_bearer_con_handle = mesh_subevent_proxy_connected_get_con_handle(packet);
790                             break;
791                         case MESH_SUBEVENT_PROXY_DISCONNECTED:
792                             gatt_bearer_con_handle = HCI_CON_HANDLE_INVALID;
793                             mesh_network_gatt_bearer_outgoing_complete();
794                             break;
795                         case MESH_SUBEVENT_CAN_SEND_NOW:
796                             if (gatt_bearer_network_pdu == NULL) break;
797 #ifdef LOG_NETWORK
798                             printf("G-TX-E-NetworkPDU (%p): ", gatt_bearer_network_pdu);
799                             printf_hexdump(gatt_bearer_network_pdu->data, gatt_bearer_network_pdu->len);
800 #endif
801                             gatt_bearer_send_network_pdu(gatt_bearer_network_pdu->data, gatt_bearer_network_pdu->len);
802                             break;
803 
804                         case MESH_SUBEVENT_MESSAGE_SENT:
805                             mesh_network_gatt_bearer_outgoing_complete();
806                             break;
807                         default:
808                             break;
809                     }
810                     break;
811                 default:
812                     break;
813             }
814             break;
815         default:
816             break;
817     }
818 }
819 #endif
820 
821 #ifdef ENABLE_MESH_GATT_BEARER
822 static void mesh_netework_gatt_bearer_handle_proxy_configuration(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
823     UNUSED(channel);
824     switch (packet_type){
825         case MESH_PROXY_DATA_PACKET:
826             mesh_network_process_proxy_configuration_message(packet, size);
827             break;
828         case HCI_EVENT_PACKET:
829             switch (hci_event_packet_get_type(packet)){
830                 case HCI_EVENT_MESH_META:
831                     switch (hci_event_mesh_meta_get_subevent_code(packet)){
832                         case MESH_SUBEVENT_CAN_SEND_NOW:
833                             // forward to higher layer
834                             (*mesh_network_proxy_message_handler)(MESH_NETWORK_CAN_SEND_NOW, NULL);
835                             break;
836                         default:
837                             break;
838                     }
839                     break;
840                 default:
841                     break;
842             }
843             break;
844         default:
845             break;
846     }
847 }
848 #endif
849 
850 void mesh_network_init(void){
851 #ifdef ENABLE_MESH_ADV_BEARER
852     adv_bearer_register_for_network_pdu(&mesh_adv_bearer_handle_network_event);
853 #endif
854 #ifdef ENABLE_MESH_GATT_BEARER
855     gatt_bearer_con_handle = HCI_CON_HANDLE_INVALID;
856     gatt_bearer_register_for_network_pdu(&mesh_network_gatt_bearer_handle_network_event);
857     gatt_bearer_register_for_mesh_proxy_configuration(&mesh_netework_gatt_bearer_handle_proxy_configuration);
858 #endif
859 }
860 
861 void mesh_network_set_higher_layer_handler(void (*packet_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu)){
862     mesh_network_higher_layer_handler = packet_handler;
863 }
864 
865 void mesh_network_set_proxy_message_handler(void (*packet_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu)){
866     mesh_network_proxy_message_handler = packet_handler;
867 }
868 
869 void mesh_network_received_message(const uint8_t * pdu_data, uint8_t pdu_len, uint8_t flags){
870     // verify len
871     if (pdu_len > 29) return;
872 
873     // allocate network_pdu
874     mesh_network_pdu_t * network_pdu = mesh_network_pdu_get();
875     if (!network_pdu) return;
876 
877     // store data
878     memcpy(network_pdu->data, pdu_data, pdu_len);
879     network_pdu->len = pdu_len;
880     network_pdu->flags = flags;
881 
882     // add to list and go
883     btstack_linked_list_add_tail(&network_pdus_received, (btstack_linked_item_t *) network_pdu);
884     mesh_network_run();
885 
886 }
887 
888 void mesh_network_process_proxy_configuration_message(const uint8_t * pdu_data, uint8_t pdu_len){
889     // verify len
890     if (pdu_len > 29) return;
891 
892     // allocate network_pdu
893     mesh_network_pdu_t * network_pdu = mesh_network_pdu_get();
894     if (!network_pdu) return;
895 
896     // store data
897     memcpy(network_pdu->data, pdu_data, pdu_len);
898     network_pdu->len = pdu_len;
899     network_pdu->flags = MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION; // Network PDU
900 
901     // add to list and go
902     btstack_linked_list_add_tail(&network_pdus_received, (btstack_linked_item_t *) network_pdu);
903     mesh_network_run();
904 }
905 
906 void mesh_network_send_pdu(mesh_network_pdu_t * network_pdu){
907 #ifdef LOG_NETWORK
908     printf("TX-NetworkPDU (%p):   ", network_pdu);
909     printf_hexdump(network_pdu->data, network_pdu->len);
910 #endif
911 
912     if (network_pdu->len > 29){
913         printf("too long, %u\n", network_pdu->len);
914         return;
915     }
916 
917     // setup callback
918     network_pdu->callback = &mesh_network_send_d;
919     network_pdu->flags    = 0;
920 
921     // queue up
922     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
923 
924     // go
925     mesh_network_run();
926 }
927 
928 void mesh_network_encrypt_proxy_configuration_message(mesh_network_pdu_t * network_pdu, void (* callback)(mesh_network_pdu_t * callback)){
929     printf("ProxyPDU(unencrypted): ");
930     printf_hexdump(network_pdu->data, network_pdu->len);
931 
932     // setup callback
933     network_pdu->callback = callback;
934     network_pdu->flags    = MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION;
935 
936     // queue up
937     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
938 
939     // go
940     mesh_network_run();
941 }
942 
943 /*
944  * @brief Setup network pdu header
945  * @param netkey_index
946  * @param ctl
947  * @param ttl
948  * @param seq
949  * @param dest
950  */
951 void mesh_network_setup_pdu(mesh_network_pdu_t * network_pdu, uint16_t netkey_index, uint8_t nid, uint8_t ctl, uint8_t ttl, uint32_t seq, uint16_t src, uint16_t dest, const uint8_t * transport_pdu_data, uint8_t transport_pdu_len){
952     memset(network_pdu, 0, sizeof(mesh_network_pdu_t));
953     // set netkey_index
954     network_pdu->netkey_index = netkey_index;
955     // setup header
956     network_pdu->data[network_pdu->len++] = (mesh_get_iv_index_for_tx() << 7) |  nid;
957     uint8_t ctl_ttl = (ctl << 7) | (ttl & 0x7f);
958     network_pdu->data[network_pdu->len++] = ctl_ttl;
959     big_endian_store_24(network_pdu->data, 2, seq);
960     network_pdu->len += 3;
961     big_endian_store_16(network_pdu->data, network_pdu->len, src);
962     network_pdu->len += 2;
963     big_endian_store_16(network_pdu->data, network_pdu->len, dest);
964     network_pdu->len += 2;
965     memcpy(&network_pdu->data[network_pdu->len], transport_pdu_data, transport_pdu_len);
966     network_pdu->len += transport_pdu_len;
967 }
968 
969 /*
970  * @brief Setup network pdu header
971  * @param netkey_index
972  * @param ctl
973  * @param ttl
974  * @param seq
975  * @param dest
976  */
977 void mesh_network_setup_pdu_header(mesh_network_pdu_t * network_pdu, uint16_t netkey_index, uint8_t nid, uint8_t ctl, uint8_t ttl, uint32_t seq, uint16_t src, uint16_t dest){
978     // set netkey_index
979     network_pdu->netkey_index = netkey_index;
980     // setup header
981     network_pdu->data[0] = (mesh_get_iv_index_for_tx() << 7) |  nid;
982     uint8_t ctl_ttl = (ctl << 7) | (ttl & 0x7f);
983     network_pdu->data[1] = ctl_ttl;
984     big_endian_store_24(network_pdu->data, 2, seq);
985     big_endian_store_16(network_pdu->data, 5, src);
986     big_endian_store_16(network_pdu->data, 7, dest);
987 }
988 
989 // Network PDU Getter
990 uint8_t  mesh_network_nid(mesh_network_pdu_t * network_pdu){
991     return network_pdu->data[0] & 0x7f;
992 }
993 uint16_t mesh_network_control(mesh_network_pdu_t * network_pdu){
994     return network_pdu->data[1] & 0x80;
995 }
996 uint8_t mesh_network_ttl(mesh_network_pdu_t * network_pdu){
997     return network_pdu->data[1] & 0x7f;
998 }
999 uint32_t mesh_network_seq(mesh_network_pdu_t * network_pdu){
1000     return big_endian_read_24(network_pdu->data, 2);
1001 }
1002 uint16_t mesh_network_src(mesh_network_pdu_t * network_pdu){
1003     return big_endian_read_16(network_pdu->data, 5);
1004 }
1005 uint16_t mesh_network_dst(mesh_network_pdu_t * network_pdu){
1006     return big_endian_read_16(network_pdu->data, 7);
1007 }
1008 int mesh_network_segmented(mesh_network_pdu_t * network_pdu){
1009     return network_pdu->data[9] & 0x80;
1010 }
1011 uint8_t * mesh_network_pdu_data(mesh_network_pdu_t * network_pdu){
1012     return &network_pdu->data[9];
1013 }
1014 uint8_t   mesh_network_pdu_len(mesh_network_pdu_t * network_pdu){
1015     return network_pdu->len - 9;
1016 }
1017 
1018 static void mesh_network_dump_network_pdu(mesh_network_pdu_t * network_pdu){
1019     if (network_pdu){
1020         printf("- %p: ", network_pdu); printf_hexdump(network_pdu->data, network_pdu->len);
1021     }
1022 }
1023 static void mesh_network_dump_network_pdus(const char * name, btstack_linked_list_t * list){
1024     printf("List: %s:\n", name);
1025     btstack_linked_list_iterator_t it;
1026     btstack_linked_list_iterator_init(&it, list);
1027     while (btstack_linked_list_iterator_has_next(&it)){
1028         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t*) btstack_linked_list_iterator_next(&it);
1029         mesh_network_dump_network_pdu(network_pdu);
1030     }
1031 }
1032 static void mesh_network_reset_network_pdus(btstack_linked_list_t * list){
1033     while (!btstack_linked_list_empty(list)){
1034         mesh_network_pdu_t * pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(list);
1035         btstack_memory_mesh_network_pdu_free(pdu);
1036     }
1037 }
1038 void mesh_network_dump(void){
1039     mesh_network_dump_network_pdus("network_pdus_received", &network_pdus_received);
1040     mesh_network_dump_network_pdus("network_pdus_queued", &network_pdus_queued);
1041     mesh_network_dump_network_pdus("network_pdus_outgoing", &network_pdus_outgoing);
1042     printf("network_pdu_in_validation: \n");
1043     mesh_network_dump_network_pdu(network_pdu_in_validation);
1044 }
1045 void mesh_network_reset(void){
1046     mesh_network_reset_network_pdus(&network_pdus_received);
1047     mesh_network_reset_network_pdus(&network_pdus_queued);
1048     mesh_network_reset_network_pdus(&network_pdus_outgoing);
1049 }
1050 
1051 // buffer pool
1052 mesh_network_pdu_t * mesh_network_pdu_get(void){
1053     mesh_network_pdu_t * network_pdu = btstack_memory_mesh_network_pdu_get();
1054     if (network_pdu) {
1055         memset(network_pdu, 0, sizeof(mesh_network_pdu_t));
1056         network_pdu->pdu_header.pdu_type = MESH_PDU_TYPE_NETWORK;
1057     }
1058     return network_pdu;
1059 }
1060 
1061 void mesh_network_pdu_free(mesh_network_pdu_t * network_pdu){
1062     btstack_memory_mesh_network_pdu_free(network_pdu);
1063 }
1064 
1065 // Mesh Subnet Management
1066 
1067 void mesh_subnet_add(mesh_subnet_t * subnet){
1068     btstack_linked_list_add_tail(&subnets, (btstack_linked_item_t *) subnet);
1069 }
1070 
1071 void mesh_subnet_remove(mesh_subnet_t * subnet){
1072     btstack_linked_list_remove(&subnets, (btstack_linked_item_t *) subnet);
1073 }
1074 
1075 mesh_subnet_t * mesh_subnet_get_by_netkey_index(uint16_t netkey_index){
1076     btstack_linked_list_iterator_t it;
1077     btstack_linked_list_iterator_init(&it, &subnets);
1078     while (btstack_linked_list_iterator_has_next(&it)){
1079         mesh_subnet_t * item = (mesh_subnet_t *) btstack_linked_list_iterator_next(&it);
1080         if (item->netkey_index == netkey_index) return item;
1081     }
1082     return NULL;
1083 }
1084 
1085 int mesh_subnet_list_count(void){
1086     return btstack_linked_list_count(&subnets);
1087 }
1088 
1089 // mesh network key iterator over all keys
1090 void mesh_subnet_iterator_init(mesh_subnet_iterator_t *it){
1091     btstack_linked_list_iterator_init(&it->it, &subnets);
1092 }
1093 
1094 int mesh_subnet_iterator_has_more(mesh_subnet_iterator_t *it){
1095     return btstack_linked_list_iterator_has_next(&it->it);
1096 }
1097 
1098 mesh_subnet_t * mesh_subnet_iterator_get_next(mesh_subnet_iterator_t *it){
1099     return (mesh_subnet_t *) btstack_linked_list_iterator_next(&it->it);
1100 }
1101 
1102 mesh_network_key_t * mesh_subnet_get_outgoing_network_key(mesh_subnet_t * subnet){
1103     switch (subnet->key_refresh){
1104         case MESH_KEY_REFRESH_SECOND_PHASE:
1105             return subnet->new_key;
1106         case MESH_KEY_REFRESH_NOT_ACTIVE:
1107         case MESH_KEY_REFRESH_FIRST_PHASE:
1108         default:
1109             return subnet->old_key;
1110     }
1111 }
1112 
1113 /**
1114  * @brief Setup subnet for given netkey index
1115  */
1116 void mesh_subnet_setup_for_netkey_index(uint16_t netkey_index){
1117     mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(netkey_index);
1118     if (subnet != NULL) return;
1119 
1120     // find old / new keys
1121     mesh_network_key_t * old_key = NULL;
1122     mesh_network_key_t * new_key = NULL;
1123     mesh_network_key_iterator_t it;
1124     mesh_network_key_iterator_init(&it);
1125     while (mesh_network_key_iterator_has_more(&it)){
1126         mesh_network_key_t * network_key = mesh_network_key_iterator_get_next(&it);
1127         if (network_key->netkey_index != netkey_index) continue;
1128         if (old_key == NULL){
1129             old_key = network_key;
1130             continue;
1131         }
1132         // assign current key depending on key version
1133         if (((int8_t) (network_key->version - new_key->version)) > 0) {
1134             new_key = network_key;
1135         } else {
1136             new_key = old_key;
1137             old_key = network_key;
1138         }
1139     }
1140 
1141     // create subnet for netkey index
1142     subnet = btstack_memory_mesh_subnet_get();
1143     if (subnet == NULL) return;
1144     subnet->netkey_index = netkey_index;
1145     mesh_subnet_add(subnet);
1146 
1147     // set keys
1148     subnet->old_key = old_key;
1149     subnet->new_key = new_key;
1150 
1151     // key refresh
1152     if (new_key == NULL){
1153         // single key -> key refresh not active
1154         subnet->key_refresh = MESH_KEY_REFRESH_NOT_ACTIVE;
1155     }
1156     else {
1157         // two keys -> at least phase 1
1158         subnet->key_refresh = MESH_KEY_REFRESH_FIRST_PHASE;
1159     }
1160 }
1161