xref: /btstack/src/mesh/mesh_network.c (revision a6fcac7c46d75d9a688bbacc6668e6f0263745b2)
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 <stdint.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include "mesh/beacon.h"
45 #include "provisioning.h"
46 #include "provisioning_device.h"
47 #include "mesh_keys.h"
48 #include "mesh_foundation.h"
49 #include "btstack_util.h"
50 #include "btstack_debug.h"
51 #include "btstack_event.h"
52 #include "btstack_memory.h"
53 #include "mesh_iv_index_seq_number.h"
54 #include "mesh_node.h"
55 
56 #ifdef ENABLE_MESH_ADV_BEARER
57 #include "mesh/adv_bearer.h"
58 #endif
59 
60 #ifdef ENABLE_MESH_GATT_BEARER
61 #include "mesh/gatt_bearer.h"
62 #endif
63 
64 // configuration
65 #define MESH_NETWORK_CACHE_SIZE 2
66 // #define ENABLE_MESH_RELAY
67 
68 // debug config
69 // #define LOG_NETWORK
70 
71 // structs
72 
73 // globals
74 
75 static uint16_t mesh_network_num_elements;
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     // get network nonce
334     if (network_pdu->flags & MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION){
335         mesh_proxy_create_nonce(network_nonce, network_pdu, iv_index);
336 #ifdef LOG_NETWORK
337         printf("TX-ProxyNonce:  ");
338         printf_hexdump(network_nonce, 13);
339 #endif
340     } else {
341         mesh_network_create_nonce(network_nonce, network_pdu, iv_index);
342 #ifdef LOG_NETWORK
343         printf("TX-NetworkNonce:  ");
344         printf_hexdump(network_nonce, 13);
345 #endif
346     }
347 
348 #ifdef LOG_NETWORK
349    printf("TX-EncryptionKey: ");
350     printf_hexdump(current_network_key->encryption_key, 16);
351 #endif
352 
353     // start ccm
354     uint8_t cypher_len  = network_pdu->len - 7;
355     uint8_t net_mic_len = network_pdu->data[1] & 0x80 ? 8 : 4;
356     btstack_crypto_ccm_init(&mesh_network_crypto_request.ccm, current_network_key->encryption_key, network_nonce, cypher_len, 0, net_mic_len);
357     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);
358 }
359 
360 #if defined(ENABLE_MESH_RELAY) || defined (ENABLE_MESH_PROXY_SERVER)
361 static void mesh_network_relay_message(mesh_network_pdu_t * network_pdu){
362     uint8_t ctl_ttl     = network_pdu->data[1];
363     uint8_t ctl         = ctl_ttl & 0x80;
364     uint8_t ttl         = ctl_ttl & 0x7f;
365     uint8_t net_mic_len = ctl ? 8 : 4;
366 
367     // prepare pdu for resending
368     network_pdu->len    -= net_mic_len;
369     network_pdu->data[1] = (ctl << 7) | (ttl - 1);
370     network_pdu->flags |= MESH_NETWORK_PDU_FLAGS_RELAY;
371 
372     // queue up
373     network_pdu->callback = &mesh_network_send_d;
374     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
375 }
376 #endif
377 
378 void mesh_network_message_processed_by_higher_layer(mesh_network_pdu_t * network_pdu){
379 
380 #if defined(ENABLE_MESH_RELAY) || defined (ENABLE_MESH_PROXY_SERVER)
381 
382     // check if address does not matches elements on our node and TTL >= 2
383     uint16_t src     = mesh_network_src(network_pdu);
384     uint8_t  ttl     = mesh_network_ttl(network_pdu);
385 
386     uint16_t mesh_network_primary_address = mesh_node_primary_element_address_get();
387 
388     if (((src < mesh_network_primary_address) || (src > (mesh_network_primary_address + mesh_network_num_elements))) && (ttl >= 2)){
389 
390         if ((network_pdu->flags & MESH_NETWORK_PDU_FLAGS_GATT_BEARER) == 0){
391 
392             // message received via ADV bearer are relayed:
393 
394 #ifdef ENABLE_MESH_RELAY
395             if (mesh_foundation_relay_get() != 0){
396                 // - to ADV bearer, if Relay supported and enabled
397                 mesh_network_relay_message(network_pdu);
398                 mesh_network_run();
399                 return;
400             }
401 #endif
402 
403 #ifdef ENABLE_MESH_PROXY_SERVER
404             if (mesh_foundation_gatt_proxy_get() != 0){
405                 // - to GATT bearer, if Proxy supported and enabled
406                 mesh_network_relay_message(network_pdu);
407                 mesh_network_run();
408                 return;
409             }
410 #endif
411 
412         } else {
413 
414             // messages received via GATT bearer are relayed:
415 
416 #ifdef ENABLE_MESH_PROXY_SERVER
417             if (mesh_foundation_gatt_proxy_get() != 0){
418                 // - to ADV bearer, if Proxy supported and enabled
419                 mesh_network_relay_message(network_pdu);
420                 mesh_network_run();
421                 return;
422             }
423 #endif
424 
425         }
426     }
427 #endif
428 
429     // otherwise, we're done
430     btstack_memory_mesh_network_pdu_free(network_pdu);
431 }
432 
433 static void process_network_pdu_done(void){
434     btstack_memory_mesh_network_pdu_free(network_pdu_in_validation);
435     network_pdu_in_validation = NULL;
436     mesh_crypto_active = 0;
437 
438     mesh_network_run();
439 }
440 
441 static void process_network_pdu_validate_d(void * arg){
442     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) arg;
443 
444     uint8_t ctl_ttl     = network_pdu->data[1];
445     uint8_t ctl         = ctl_ttl >> 7;
446     uint8_t net_mic_len = (ctl_ttl & 0x80) ? 8 : 4;
447 
448     // store NetMIC
449     uint8_t net_mic[8];
450     btstack_crypto_ccm_get_authentication_value(&mesh_network_crypto_request.ccm, net_mic);
451 #ifdef LOG_NETWORK
452     printf("RX-NetMIC: ");
453     printf_hexdump(net_mic, net_mic_len);
454 #endif
455     // store in pdu
456     memcpy(&network_pdu->data[network_pdu->len-net_mic_len], net_mic, net_mic_len);
457 
458 #ifdef LOG_NETWORK
459     uint8_t cypher_len  = network_pdu->len - 9 - net_mic_len;
460     printf("RX-Decrypted DST/TransportPDU: ");
461     printf_hexdump(&network_pdu->data[7], 2 + cypher_len);
462 
463     printf("RX-Decrypted: ");
464     printf_hexdump(network_pdu->data, network_pdu->len);
465 #endif
466 
467     // validate network mic
468     if (memcmp(net_mic, &network_pdu_in_validation->data[network_pdu->len-net_mic_len], net_mic_len) != 0){
469         // fail
470         printf("RX-NetMIC mismatch, try next key\n");
471         process_network_pdu_validate(network_pdu);
472         return;
473     }
474 
475     // remove NetMIC from payload
476     network_pdu->len -= net_mic_len;
477 
478 #ifdef LOG_NETWORK
479     // match
480     printf("RX-NetMIC matches\n");
481     printf("RX-TTL: 0x%02x\n", network_pdu->data[1] & 0x7f);
482 #endif
483 
484     // set netkey_index
485     network_pdu->netkey_index = current_network_key->netkey_index;
486 
487     if (network_pdu->flags & MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION){
488 
489         // no additional checks for proxy messages
490         (*mesh_network_proxy_message_handler)(MESH_NETWORK_PDU_RECEIVED, network_pdu);
491 
492     } else {
493 
494         // validate src/dest addresses
495         uint16_t src = big_endian_read_16(network_pdu->data, 5);
496         uint16_t dst = big_endian_read_16(network_pdu->data, 7);
497         int valid = mesh_network_addresses_valid(ctl, src, dst);
498         if (!valid){
499             printf("RX Address invalid\n");
500             btstack_memory_mesh_network_pdu_free(network_pdu);
501             process_network_pdu_done();
502             return;
503         }
504 
505         // check cache
506         uint32_t hash = mesh_network_cache_hash(network_pdu);
507 #ifdef LOG_NETWORK
508         printf("RX-Hash: %08x\n", hash);
509 #endif
510         if (mesh_network_cache_find(hash)){
511             // found in cache, drop
512             printf("Found in cache -> drop packet\n");
513             btstack_memory_mesh_network_pdu_free(network_pdu);
514             process_network_pdu_done();
515             return;
516         }
517 
518         // store in network cache
519         mesh_network_cache_add(hash);
520 
521         // forward to lower transport layer. message is freed by call to mesh_network_message_processed_by_upper_layer
522         (*mesh_network_higher_layer_handler)(MESH_NETWORK_PDU_RECEIVED, network_pdu);
523     }
524 
525     // done
526     process_network_pdu_done();
527 }
528 
529 static uint32_t iv_index_for_pdu(const mesh_network_pdu_t * network_pdu){
530     // get IV Index and IVI
531     uint32_t iv_index = mesh_get_iv_index();
532     int ivi = network_pdu->data[0] >> 7;
533 
534     // if least significant bit differs, use previous IV Index
535     if ((iv_index & 1 ) ^ ivi){
536         iv_index--;
537 #ifdef LOG_NETWORK
538         printf("RX-IV: IVI indicates previous IV index, using 0x%08x\n", iv_index);
539 #endif
540     }
541     return iv_index;
542 }
543 
544 static void process_network_pdu_validate_b(void * arg){
545     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) arg;
546 
547 #ifdef LOG_NETWORK
548     printf("RX-PECB: ");
549     printf_hexdump(obfuscation_block, 6);
550 #endif
551 
552     // de-obfuscate
553     unsigned int i;
554     for (i=0;i<6;i++){
555         network_pdu->data[1+i] = network_pdu_in_validation->data[1+i] ^ obfuscation_block[i];
556     }
557 
558     uint32_t iv_index = iv_index_for_pdu(network_pdu);
559 
560     if (network_pdu->flags & MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION){
561         // create network nonce
562         mesh_proxy_create_nonce(network_nonce, network_pdu, iv_index);
563 #ifdef LOG_NETWORK
564         printf("RX-Proxy Nonce: ");
565         printf_hexdump(network_nonce, 13);
566 #endif
567     } else {
568         // create network nonce
569         mesh_network_create_nonce(network_nonce, network_pdu, iv_index);
570 #ifdef LOG_NETWORK
571         printf("RX-Network Nonce: ");
572         printf_hexdump(network_nonce, 13);
573 #endif
574     }
575 
576     //
577     uint8_t ctl_ttl     = network_pdu->data[1];
578     uint8_t net_mic_len = (ctl_ttl & 0x80) ? 8 : 4;
579     uint8_t cypher_len  = network_pdu->len - 7 - net_mic_len;
580 
581 #ifdef LOG_NETWORK
582     printf("RX-Cyper len %u, mic len %u\n", cypher_len, net_mic_len);
583 
584     printf("RX-Encryption Key: ");
585     printf_hexdump(current_network_key->encryption_key, 16);
586 
587 #endif
588 
589     btstack_crypto_ccm_init(&mesh_network_crypto_request.ccm, current_network_key->encryption_key, network_nonce, cypher_len, 0, net_mic_len);
590     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);
591 }
592 
593 static void process_network_pdu_validate(mesh_network_pdu_t * network_pdu){
594     if (!mesh_network_key_nid_iterator_has_more(&validation_network_key_it)){
595         printf("No valid network key found\n");
596         btstack_memory_mesh_network_pdu_free(network_pdu);
597         process_network_pdu_done();
598         return;
599     }
600 
601     current_network_key = mesh_network_key_nid_iterator_get_next(&validation_network_key_it);
602 
603     // calc PECB
604     uint32_t iv_index = iv_index_for_pdu(network_pdu);
605     memset(encryption_block, 0, 5);
606     big_endian_store_32(encryption_block, 5, iv_index);
607     memcpy(&encryption_block[9], &network_pdu_in_validation->data[7], 7);
608     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);
609 }
610 
611 
612 static void process_network_pdu(mesh_network_pdu_t * network_pdu){
613     //
614     uint8_t nid_ivi = network_pdu_in_validation->data[0];
615 
616     // setup pdu object
617     network_pdu->data[0] = nid_ivi;
618     network_pdu->len     = network_pdu_in_validation->len;
619     network_pdu->flags   = network_pdu_in_validation->flags;
620 
621     // init provisioning data iterator
622     uint8_t nid = nid_ivi & 0x7f;
623     // uint8_t iv_index = network_pdu_data[0] >> 7;
624     mesh_network_key_nid_iterator_init(&validation_network_key_it, nid);
625 
626     process_network_pdu_validate(network_pdu);
627 }
628 
629 // static void mesh_network_encrypt_and_obfuscate(mesh_network_pdu_t * network_pdu, void (*callback)(mesh_network_pdu_t * network_pdu)){
630 //     network_pdu->callback = callback;
631 // }
632 
633 static void mesh_network_run(void){
634     if (!btstack_linked_list_empty(&network_pdus_outgoing)){
635         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_outgoing);
636 
637 #ifdef ENABLE_MESH_GATT_BEARER
638         // request to send via gatt if:
639         // proxy active and connected
640         // packet wasn't received via gatt bearer
641         printf("mesh_network_run: pdu %p, proxy %u, con handle %4x\n", network_pdu, mesh_foundation_gatt_proxy_get(), gatt_bearer_con_handle);
642         if (network_pdu != NULL &&
643             (mesh_foundation_gatt_proxy_get() != 0) &&
644             (gatt_bearer_con_handle != HCI_CON_HANDLE_INVALID) &&
645             ((network_pdu->flags & MESH_NETWORK_PDU_FLAGS_GATT_BEARER) == 0)
646         ){
647             gatt_bearer_network_pdu = network_pdu;
648             network_pdu = NULL;
649             gatt_bearer_request_can_send_now_for_network_pdu();
650         }
651 #endif
652 #ifdef ENABLE_MESH_ADV_BEARER
653          // request to send via adv
654         if (network_pdu != NULL){
655             adv_bearer_network_pdu = network_pdu;
656             network_pdu = NULL;
657             adv_bearer_request_can_send_now_for_network_pdu();
658         }
659 #endif
660         if (network_pdu !=  NULL){
661             // notify upper layer
662             (*mesh_network_higher_layer_handler)(MESH_NETWORK_PDU_SENT, network_pdu);
663         }
664     }
665 
666     if (mesh_crypto_active) return;
667 
668     if (!btstack_linked_list_empty(&network_pdus_received)){
669         mesh_network_pdu_t * decode_pdu = mesh_network_pdu_get();
670         if (!decode_pdu) return;
671         // get encoded network pdu and start processing
672         mesh_crypto_active = 1;
673         network_pdu_in_validation = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_received);
674         process_network_pdu(decode_pdu);
675         return;
676     }
677 
678     if (!btstack_linked_list_empty(&network_pdus_queued)){
679         // get queued network pdu and start processing
680         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&network_pdus_queued);
681         mesh_network_send_a(network_pdu);
682         return;
683     }
684 }
685 
686 #ifdef ENABLE_MESH_ADV_BEARER
687 static void mesh_adv_bearer_handle_network_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
688     mesh_network_pdu_t * network_pdu;
689 
690     switch (packet_type){
691         case MESH_NETWORK_PACKET:
692             // check len. minimal transport PDU len = 1, 32 bit NetMIC -> 13 bytes
693             if (size < 13) break;
694 
695 #ifdef LOG_NETWORK
696             printf("received network pdu from adv (len %u): ", size);
697             printf_hexdump(packet, size);
698 #endif
699             mesh_network_received_message(packet, size, 0);
700             break;
701 
702         case HCI_EVENT_PACKET:
703             switch(packet[0]){
704                 case HCI_EVENT_MESH_META:
705                     switch(packet[2]){
706                         case MESH_SUBEVENT_CAN_SEND_NOW:
707                             if (adv_bearer_network_pdu == NULL) break;
708 #ifdef LOG_NETWORK
709                             printf("TX-E-NetworkPDU (%p): ", adv_bearer_network_pdu);
710                             printf_hexdump(adv_bearer_network_pdu->data, adv_bearer_network_pdu->len);
711 #endif
712                             adv_bearer_send_network_pdu(adv_bearer_network_pdu->data, adv_bearer_network_pdu->len);
713                             network_pdu = adv_bearer_network_pdu;
714                             adv_bearer_network_pdu = NULL;
715 
716                             // notify upper layer
717                             (*mesh_network_higher_layer_handler)(MESH_NETWORK_PDU_SENT, network_pdu);
718 
719                             // check if more to send
720                             mesh_network_run();
721                             break;
722                         default:
723                             break;
724                     }
725                     break;
726                 default:
727                     break;
728             }
729             break;
730     }
731 }
732 #endif
733 
734 #ifdef ENABLE_MESH_GATT_BEARER
735 static void mesh_network_gatt_bearer_outgoing_complete(void){
736 
737     if (gatt_bearer_network_pdu == NULL) return;
738 
739 #ifdef ENABLE_MESH_ADV_BEARER
740     // forward to adv bearer
741     adv_bearer_network_pdu = gatt_bearer_network_pdu;
742     gatt_bearer_network_pdu = NULL;
743     adv_bearer_request_can_send_now_for_network_pdu();
744     return;
745 #endif
746 
747     // done, notify upper layer
748      mesh_network_pdu_t * network_pdu = gatt_bearer_network_pdu;
749     gatt_bearer_network_pdu = NULL;
750     (*mesh_network_higher_layer_handler)(MESH_NETWORK_PDU_SENT, network_pdu);
751 }
752 
753 static void mesh_network_gatt_bearer_handle_network_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
754     switch (packet_type){
755         case MESH_PROXY_DATA_PACKET:
756             if (mesh_foundation_gatt_proxy_get() == 0) break;
757 #ifdef LOG_NETWORK
758             printf("received network pdu from gatt (len %u): ", size);
759             printf_hexdump(packet, size);
760 #endif
761             mesh_network_received_message(packet, size, MESH_NETWORK_PDU_FLAGS_GATT_BEARER);
762             break;
763         case HCI_EVENT_PACKET:
764             switch (hci_event_packet_get_type(packet)){
765                 case HCI_EVENT_MESH_META:
766                     switch (hci_event_mesh_meta_get_subevent_code(packet)){
767                         case MESH_SUBEVENT_PROXY_CONNECTED:
768                             gatt_bearer_con_handle = mesh_subevent_proxy_connected_get_con_handle(packet);
769                             break;
770                         case MESH_SUBEVENT_PROXY_DISCONNECTED:
771                             gatt_bearer_con_handle = HCI_CON_HANDLE_INVALID;
772                             mesh_network_gatt_bearer_outgoing_complete();
773                             break;
774                         case MESH_SUBEVENT_CAN_SEND_NOW:
775                             if (gatt_bearer_network_pdu == NULL) break;
776 #ifdef LOG_NETWORK
777                             printf("G-TX-E-NetworkPDU (%p): ", gatt_bearer_network_pdu);
778                             printf_hexdump(gatt_bearer_network_pdu->data, gatt_bearer_network_pdu->len);
779 #endif
780                             gatt_bearer_send_network_pdu(gatt_bearer_network_pdu->data, gatt_bearer_network_pdu->len);
781                             break;
782 
783                         case MESH_SUBEVENT_MESSAGE_SENT:
784                             mesh_network_gatt_bearer_outgoing_complete();
785                             break;
786                         default:
787                             break;
788                     }
789                     break;
790                 default:
791                     break;
792             }
793             break;
794         default:
795             break;
796     }
797 }
798 #endif
799 
800 #ifdef ENABLE_MESH_GATT_BEARER
801 static void mesh_netework_gatt_bearer_handle_proxy_configuration(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
802     switch (packet_type){
803         case MESH_PROXY_DATA_PACKET:
804             mesh_network_process_proxy_configuration_message(packet, size);
805             break;
806         case HCI_EVENT_PACKET:
807             switch (hci_event_packet_get_type(packet)){
808                 case HCI_EVENT_MESH_META:
809                     switch (hci_event_mesh_meta_get_subevent_code(packet)){
810                         case MESH_SUBEVENT_CAN_SEND_NOW:
811                             // forward to higher layer
812                             (*mesh_network_proxy_message_handler)(MESH_NETWORK_CAN_SEND_NOW, NULL);
813                             break;
814                         default:
815                             break;
816                     }
817                     break;
818                 default:
819                     break;
820             }
821             break;
822         default:
823             break;
824     }
825 }
826 #endif
827 
828 void mesh_network_init(void){
829 #ifdef ENABLE_MESH_ADV_BEARER
830     adv_bearer_register_for_network_pdu(&mesh_adv_bearer_handle_network_event);
831 #endif
832 #ifdef ENABLE_MESH_GATT_BEARER
833     gatt_bearer_con_handle = HCI_CON_HANDLE_INVALID;
834     gatt_bearer_register_for_network_pdu(&mesh_network_gatt_bearer_handle_network_event);
835     gatt_bearer_register_for_mesh_proxy_configuration(&mesh_netework_gatt_bearer_handle_proxy_configuration);
836 #endif
837     mesh_network_num_elements = 1;
838 }
839 
840 void mesh_network_set_higher_layer_handler(void (*packet_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu)){
841     mesh_network_higher_layer_handler = packet_handler;
842 }
843 
844 void mesh_network_set_proxy_message_handler(void (*packet_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu)){
845     mesh_network_proxy_message_handler = packet_handler;
846 }
847 
848 void mesh_network_received_message(const uint8_t * pdu_data, uint8_t pdu_len, uint8_t flags){
849     // verify len
850     if (pdu_len > 29) return;
851 
852     // allocate network_pdu
853     mesh_network_pdu_t * network_pdu = mesh_network_pdu_get();
854     if (!network_pdu) return;
855 
856     // store data
857     memcpy(network_pdu->data, pdu_data, pdu_len);
858     network_pdu->len = pdu_len;
859     network_pdu->flags = flags;
860 
861     // add to list and go
862     btstack_linked_list_add_tail(&network_pdus_received, (btstack_linked_item_t *) network_pdu);
863     mesh_network_run();
864 
865 }
866 
867 void mesh_network_process_proxy_configuration_message(const uint8_t * pdu_data, uint8_t pdu_len){
868     // verify len
869     if (pdu_len > 29) return;
870 
871     // allocate network_pdu
872     mesh_network_pdu_t * network_pdu = mesh_network_pdu_get();
873     if (!network_pdu) return;
874 
875     // store data
876     memcpy(network_pdu->data, pdu_data, pdu_len);
877     network_pdu->len = pdu_len;
878     network_pdu->flags = MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION; // Network PDU
879 
880     // add to list and go
881     btstack_linked_list_add_tail(&network_pdus_received, (btstack_linked_item_t *) network_pdu);
882     mesh_network_run();
883 }
884 
885 void mesh_network_send_pdu(mesh_network_pdu_t * network_pdu){
886 #ifdef LOG_NETWORK
887     printf("TX-A-NetworkPDU (%p): ", network_pdu);
888     printf_hexdump(network_pdu->data, network_pdu->len);
889 #endif
890 
891     if (network_pdu->len > 29){
892         printf("too long, %u\n", network_pdu->len);
893         return;
894     }
895 
896     // setup callback
897     network_pdu->callback = &mesh_network_send_d;
898     network_pdu->flags    = 0;
899 
900     // queue up
901     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
902 
903     // go
904     mesh_network_run();
905 }
906 
907 void mesh_network_encrypt_proxy_configuration_message(mesh_network_pdu_t * network_pdu, void (* callback)(mesh_network_pdu_t * callback)){
908     printf("ProxyPDU(unencrypted): ");
909     printf_hexdump(network_pdu->data, network_pdu->len);
910 
911     // setup callback
912     network_pdu->callback = callback;
913     network_pdu->flags    = MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION;
914 
915     // queue up
916     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
917 
918     // go
919     mesh_network_run();
920 }
921 
922 /*
923  * @brief Setup network pdu header
924  * @param netkey_index
925  * @param ctl
926  * @param ttl
927  * @param seq
928  * @param dest
929  */
930 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){
931     memset(network_pdu, 0, sizeof(mesh_network_pdu_t));
932     // set netkey_index
933     network_pdu->netkey_index = netkey_index;
934     // setup header
935     network_pdu->data[network_pdu->len++] = (mesh_get_iv_index_for_tx() << 7) |  nid;
936     uint8_t ctl_ttl = (ctl << 7) | (ttl & 0x7f);
937     network_pdu->data[network_pdu->len++] = ctl_ttl;
938     big_endian_store_24(network_pdu->data, 2, seq);
939     network_pdu->len += 3;
940     big_endian_store_16(network_pdu->data, network_pdu->len, src);
941     network_pdu->len += 2;
942     big_endian_store_16(network_pdu->data, network_pdu->len, dest);
943     network_pdu->len += 2;
944     memcpy(&network_pdu->data[network_pdu->len], transport_pdu_data, transport_pdu_len);
945     network_pdu->len += transport_pdu_len;
946 }
947 
948 /*
949  * @brief Setup network pdu header
950  * @param netkey_index
951  * @param ctl
952  * @param ttl
953  * @param seq
954  * @param dest
955  */
956 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){
957     // set netkey_index
958     network_pdu->netkey_index = netkey_index;
959     // setup header
960     network_pdu->data[0] = (mesh_get_iv_index_for_tx() << 7) |  nid;
961     uint8_t ctl_ttl = (ctl << 7) | (ttl & 0x7f);
962     network_pdu->data[1] = ctl_ttl;
963     big_endian_store_24(network_pdu->data, 2, seq);
964     big_endian_store_16(network_pdu->data, 5, src);
965     big_endian_store_16(network_pdu->data, 7, dest);
966 }
967 
968 // Network PDU Getter
969 uint8_t  mesh_network_nid(mesh_network_pdu_t * network_pdu){
970     return network_pdu->data[0] & 0x7f;
971 }
972 uint16_t mesh_network_control(mesh_network_pdu_t * network_pdu){
973     return network_pdu->data[1] & 0x80;
974 }
975 uint8_t mesh_network_ttl(mesh_network_pdu_t * network_pdu){
976     return network_pdu->data[1] & 0x7f;
977 }
978 uint32_t mesh_network_seq(mesh_network_pdu_t * network_pdu){
979     return big_endian_read_24(network_pdu->data, 2);
980 }
981 uint16_t mesh_network_src(mesh_network_pdu_t * network_pdu){
982     return big_endian_read_16(network_pdu->data, 5);
983 }
984 uint16_t mesh_network_dst(mesh_network_pdu_t * network_pdu){
985     return big_endian_read_16(network_pdu->data, 7);
986 }
987 int mesh_network_segmented(mesh_network_pdu_t * network_pdu){
988     return network_pdu->data[9] & 0x80;
989 }
990 uint8_t * mesh_network_pdu_data(mesh_network_pdu_t * network_pdu){
991     return &network_pdu->data[9];
992 }
993 uint8_t   mesh_network_pdu_len(mesh_network_pdu_t * network_pdu){
994     return network_pdu->len - 9;
995 }
996 
997 static void mesh_network_dump_network_pdu(mesh_network_pdu_t * network_pdu){
998     if (network_pdu){
999         printf("- %p: ", network_pdu); printf_hexdump(network_pdu->data, network_pdu->len);
1000     }
1001 }
1002 static void mesh_network_dump_network_pdus(const char * name, btstack_linked_list_t * list){
1003     printf("List: %s:\n", name);
1004     btstack_linked_list_iterator_t it;
1005     btstack_linked_list_iterator_init(&it, list);
1006     while (btstack_linked_list_iterator_has_next(&it)){
1007         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t*) btstack_linked_list_iterator_next(&it);
1008         mesh_network_dump_network_pdu(network_pdu);
1009     }
1010 }
1011 static void mesh_network_reset_network_pdus(btstack_linked_list_t * list){
1012     while (!btstack_linked_list_empty(list)){
1013         mesh_network_pdu_t * pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(list);
1014         btstack_memory_mesh_network_pdu_free(pdu);
1015     }
1016 }
1017 void mesh_network_dump(void){
1018     mesh_network_dump_network_pdus("network_pdus_received", &network_pdus_received);
1019     mesh_network_dump_network_pdus("network_pdus_queued", &network_pdus_queued);
1020     mesh_network_dump_network_pdus("network_pdus_outgoing", &network_pdus_outgoing);
1021     printf("network_pdu_in_validation: \n");
1022     mesh_network_dump_network_pdu(network_pdu_in_validation);
1023 }
1024 void mesh_network_reset(void){
1025     mesh_network_reset_network_pdus(&network_pdus_received);
1026     mesh_network_reset_network_pdus(&network_pdus_queued);
1027     mesh_network_reset_network_pdus(&network_pdus_outgoing);
1028 }
1029 
1030 // buffer pool
1031 mesh_network_pdu_t * mesh_network_pdu_get(void){
1032     mesh_network_pdu_t * network_pdu = btstack_memory_mesh_network_pdu_get();
1033     if (network_pdu) {
1034         memset(network_pdu, 0, sizeof(mesh_network_pdu_t));
1035         network_pdu->pdu_header.pdu_type = MESH_PDU_TYPE_NETWORK;
1036     }
1037     return network_pdu;
1038 }
1039 
1040 void mesh_network_pdu_free(mesh_network_pdu_t * network_pdu){
1041     btstack_memory_mesh_network_pdu_free(network_pdu);
1042 }
1043 
1044 // Mesh Subnet Management
1045 
1046 void mesh_subnet_add(mesh_subnet_t * subnet){
1047     btstack_linked_list_add_tail(&subnets, (btstack_linked_item_t *) subnet);
1048 }
1049 
1050 void mesh_subnet_remove(mesh_subnet_t * subnet){
1051     btstack_linked_list_remove(&subnets, (btstack_linked_item_t *) subnet);
1052 }
1053 
1054 mesh_subnet_t * mesh_subnet_get_by_netkey_index(uint16_t netkey_index){
1055     btstack_linked_list_iterator_t it;
1056     btstack_linked_list_iterator_init(&it, &subnets);
1057     while (btstack_linked_list_iterator_has_next(&it)){
1058         mesh_subnet_t * item = (mesh_subnet_t *) btstack_linked_list_iterator_next(&it);
1059         if (item->netkey_index == netkey_index) return item;
1060     }
1061     return NULL;
1062 }
1063 
1064 int mesh_subnet_list_count(void){
1065     return btstack_linked_list_count(&subnets);
1066 }
1067 
1068 // mesh network key iterator over all keys
1069 void mesh_subnet_iterator_init(mesh_subnet_iterator_t *it){
1070     btstack_linked_list_iterator_init(&it->it, &subnets);
1071 }
1072 
1073 int mesh_subnet_iterator_has_more(mesh_subnet_iterator_t *it){
1074     return btstack_linked_list_iterator_has_next(&it->it);
1075 }
1076 
1077 mesh_subnet_t * mesh_subnet_iterator_get_next(mesh_subnet_iterator_t *it){
1078     return (mesh_subnet_t *) btstack_linked_list_iterator_next(&it->it);
1079 }
1080 
1081 mesh_network_key_t * mesh_subnet_get_outgoing_network_key(mesh_subnet_t * subnet){
1082     switch (subnet->key_refresh){
1083         case MESH_KEY_REFRESH_SECOND_PHASE:
1084             return subnet->new_key;
1085         case MESH_KEY_REFRESH_NOT_ACTIVE:
1086         case MESH_KEY_REFRESH_FIRST_PHASE:
1087         default:
1088             return subnet->old_key;
1089     }
1090 }
1091 
1092 /**
1093  * @brief Setup subnet for given netkey index
1094  */
1095 void mesh_subnet_setup_for_netkey_index(uint16_t netkey_index){
1096     mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(netkey_index);
1097     if (subnet != NULL) return;
1098 
1099     // find old / new keys
1100     mesh_network_key_t * old_key = NULL;
1101     mesh_network_key_t * new_key = NULL;
1102     mesh_network_key_iterator_t it;
1103     mesh_network_key_iterator_init(&it);
1104     while (mesh_network_key_iterator_has_more(&it)){
1105         mesh_network_key_t * network_key = mesh_network_key_iterator_get_next(&it);
1106         if (network_key->netkey_index != netkey_index) continue;
1107         if (old_key == NULL){
1108             old_key = network_key;
1109             continue;
1110         }
1111         // assign current key depending on key version
1112         if (((int8_t) (network_key->version - new_key->version)) > 0) {
1113             new_key = network_key;
1114         } else {
1115             new_key = old_key;
1116             old_key = network_key;
1117         }
1118     }
1119 
1120     // create subnet for netkey index
1121     subnet = btstack_memory_mesh_subnet_get();
1122     if (subnet == NULL) return;
1123     subnet->netkey_index = netkey_index;
1124     mesh_subnet_add(subnet);
1125 
1126     // set keys
1127     subnet->old_key = old_key;
1128     subnet->new_key = new_key;
1129 
1130     // key refresh
1131     if (new_key == NULL){
1132         // single key -> key refresh not active
1133         subnet->key_refresh = MESH_KEY_REFRESH_NOT_ACTIVE;
1134     }
1135     else {
1136         // two keys -> at least phase 1
1137         subnet->key_refresh = MESH_KEY_REFRESH_FIRST_PHASE;
1138     }
1139 }
1140