xref: /btstack/src/mesh/mesh_network.c (revision 94dc8eb321a7f7f0a210fd842516b5c13a7033ec)
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     // 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_get_primary_element_address();
387 
388     if (((src < mesh_network_primary_address) || (src > (mesh_network_primary_address + mesh_node_element_count()))) && (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     UNUSED(channel);
689     mesh_network_pdu_t * network_pdu;
690 
691     switch (packet_type){
692         case MESH_NETWORK_PACKET:
693             // check len. minimal transport PDU len = 1, 32 bit NetMIC -> 13 bytes
694             if (size < 13) break;
695 
696 #ifdef LOG_NETWORK
697             printf("received network pdu from adv (len %u): ", size);
698             printf_hexdump(packet, size);
699 #endif
700             mesh_network_received_message(packet, size, 0);
701             break;
702 
703         case HCI_EVENT_PACKET:
704             switch(packet[0]){
705                 case HCI_EVENT_MESH_META:
706                     switch(packet[2]){
707                         case MESH_SUBEVENT_CAN_SEND_NOW:
708                             if (adv_bearer_network_pdu == NULL) break;
709 #ifdef LOG_NETWORK
710                             printf("TX-E-NetworkPDU (%p): ", adv_bearer_network_pdu);
711                             printf_hexdump(adv_bearer_network_pdu->data, adv_bearer_network_pdu->len);
712 #endif
713                             adv_bearer_send_network_pdu(adv_bearer_network_pdu->data, adv_bearer_network_pdu->len);
714                             network_pdu = adv_bearer_network_pdu;
715                             adv_bearer_network_pdu = NULL;
716 
717                             // notify upper layer
718                             (*mesh_network_higher_layer_handler)(MESH_NETWORK_PDU_SENT, network_pdu);
719 
720                             // check if more to send
721                             mesh_network_run();
722                             break;
723                         default:
724                             break;
725                     }
726                     break;
727                 default:
728                     break;
729             }
730             break;
731     }
732 }
733 #endif
734 
735 #ifdef ENABLE_MESH_GATT_BEARER
736 static void mesh_network_gatt_bearer_outgoing_complete(void){
737 
738     if (gatt_bearer_network_pdu == NULL) return;
739 
740 #ifdef ENABLE_MESH_ADV_BEARER
741     // forward to adv bearer
742     adv_bearer_network_pdu = gatt_bearer_network_pdu;
743     gatt_bearer_network_pdu = NULL;
744     adv_bearer_request_can_send_now_for_network_pdu();
745     return;
746 #endif
747 
748     // done, notify upper layer
749      mesh_network_pdu_t * network_pdu = gatt_bearer_network_pdu;
750     gatt_bearer_network_pdu = NULL;
751     (*mesh_network_higher_layer_handler)(MESH_NETWORK_PDU_SENT, network_pdu);
752 }
753 
754 static void mesh_network_gatt_bearer_handle_network_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
755     UNUSED(channel);
756     switch (packet_type){
757         case MESH_PROXY_DATA_PACKET:
758             if (mesh_foundation_gatt_proxy_get() == 0) break;
759 #ifdef LOG_NETWORK
760             printf("received network pdu from gatt (len %u): ", size);
761             printf_hexdump(packet, size);
762 #endif
763             mesh_network_received_message(packet, size, MESH_NETWORK_PDU_FLAGS_GATT_BEARER);
764             break;
765         case HCI_EVENT_PACKET:
766             switch (hci_event_packet_get_type(packet)){
767                 case HCI_EVENT_MESH_META:
768                     switch (hci_event_mesh_meta_get_subevent_code(packet)){
769                         case MESH_SUBEVENT_PROXY_CONNECTED:
770                             gatt_bearer_con_handle = mesh_subevent_proxy_connected_get_con_handle(packet);
771                             break;
772                         case MESH_SUBEVENT_PROXY_DISCONNECTED:
773                             gatt_bearer_con_handle = HCI_CON_HANDLE_INVALID;
774                             mesh_network_gatt_bearer_outgoing_complete();
775                             break;
776                         case MESH_SUBEVENT_CAN_SEND_NOW:
777                             if (gatt_bearer_network_pdu == NULL) break;
778 #ifdef LOG_NETWORK
779                             printf("G-TX-E-NetworkPDU (%p): ", gatt_bearer_network_pdu);
780                             printf_hexdump(gatt_bearer_network_pdu->data, gatt_bearer_network_pdu->len);
781 #endif
782                             gatt_bearer_send_network_pdu(gatt_bearer_network_pdu->data, gatt_bearer_network_pdu->len);
783                             break;
784 
785                         case MESH_SUBEVENT_MESSAGE_SENT:
786                             mesh_network_gatt_bearer_outgoing_complete();
787                             break;
788                         default:
789                             break;
790                     }
791                     break;
792                 default:
793                     break;
794             }
795             break;
796         default:
797             break;
798     }
799 }
800 #endif
801 
802 #ifdef ENABLE_MESH_GATT_BEARER
803 static void mesh_netework_gatt_bearer_handle_proxy_configuration(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
804     UNUSED(channel);
805     switch (packet_type){
806         case MESH_PROXY_DATA_PACKET:
807             mesh_network_process_proxy_configuration_message(packet, size);
808             break;
809         case HCI_EVENT_PACKET:
810             switch (hci_event_packet_get_type(packet)){
811                 case HCI_EVENT_MESH_META:
812                     switch (hci_event_mesh_meta_get_subevent_code(packet)){
813                         case MESH_SUBEVENT_CAN_SEND_NOW:
814                             // forward to higher layer
815                             (*mesh_network_proxy_message_handler)(MESH_NETWORK_CAN_SEND_NOW, NULL);
816                             break;
817                         default:
818                             break;
819                     }
820                     break;
821                 default:
822                     break;
823             }
824             break;
825         default:
826             break;
827     }
828 }
829 #endif
830 
831 void mesh_network_init(void){
832 #ifdef ENABLE_MESH_ADV_BEARER
833     adv_bearer_register_for_network_pdu(&mesh_adv_bearer_handle_network_event);
834 #endif
835 #ifdef ENABLE_MESH_GATT_BEARER
836     gatt_bearer_con_handle = HCI_CON_HANDLE_INVALID;
837     gatt_bearer_register_for_network_pdu(&mesh_network_gatt_bearer_handle_network_event);
838     gatt_bearer_register_for_mesh_proxy_configuration(&mesh_netework_gatt_bearer_handle_proxy_configuration);
839 #endif
840 }
841 
842 void mesh_network_set_higher_layer_handler(void (*packet_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu)){
843     mesh_network_higher_layer_handler = packet_handler;
844 }
845 
846 void mesh_network_set_proxy_message_handler(void (*packet_handler)(mesh_network_callback_type_t callback_type, mesh_network_pdu_t * network_pdu)){
847     mesh_network_proxy_message_handler = packet_handler;
848 }
849 
850 void mesh_network_received_message(const uint8_t * pdu_data, uint8_t pdu_len, uint8_t flags){
851     // verify len
852     if (pdu_len > 29) return;
853 
854     // allocate network_pdu
855     mesh_network_pdu_t * network_pdu = mesh_network_pdu_get();
856     if (!network_pdu) return;
857 
858     // store data
859     memcpy(network_pdu->data, pdu_data, pdu_len);
860     network_pdu->len = pdu_len;
861     network_pdu->flags = flags;
862 
863     // add to list and go
864     btstack_linked_list_add_tail(&network_pdus_received, (btstack_linked_item_t *) network_pdu);
865     mesh_network_run();
866 
867 }
868 
869 void mesh_network_process_proxy_configuration_message(const uint8_t * pdu_data, uint8_t pdu_len){
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 = MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION; // Network PDU
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 void mesh_network_send_pdu(mesh_network_pdu_t * network_pdu){
888 #ifdef LOG_NETWORK
889     printf("TX-A-NetworkPDU (%p): ", network_pdu);
890     printf_hexdump(network_pdu->data, network_pdu->len);
891 #endif
892 
893     if (network_pdu->len > 29){
894         printf("too long, %u\n", network_pdu->len);
895         return;
896     }
897 
898     // setup callback
899     network_pdu->callback = &mesh_network_send_d;
900     network_pdu->flags    = 0;
901 
902     // queue up
903     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
904 
905     // go
906     mesh_network_run();
907 }
908 
909 void mesh_network_encrypt_proxy_configuration_message(mesh_network_pdu_t * network_pdu, void (* callback)(mesh_network_pdu_t * callback)){
910     printf("ProxyPDU(unencrypted): ");
911     printf_hexdump(network_pdu->data, network_pdu->len);
912 
913     // setup callback
914     network_pdu->callback = callback;
915     network_pdu->flags    = MESH_NETWORK_PDU_FLAGS_PROXY_CONFIGURATION;
916 
917     // queue up
918     btstack_linked_list_add_tail(&network_pdus_queued, (btstack_linked_item_t *) network_pdu);
919 
920     // go
921     mesh_network_run();
922 }
923 
924 /*
925  * @brief Setup network pdu header
926  * @param netkey_index
927  * @param ctl
928  * @param ttl
929  * @param seq
930  * @param dest
931  */
932 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){
933     memset(network_pdu, 0, sizeof(mesh_network_pdu_t));
934     // set netkey_index
935     network_pdu->netkey_index = netkey_index;
936     // setup header
937     network_pdu->data[network_pdu->len++] = (mesh_get_iv_index_for_tx() << 7) |  nid;
938     uint8_t ctl_ttl = (ctl << 7) | (ttl & 0x7f);
939     network_pdu->data[network_pdu->len++] = ctl_ttl;
940     big_endian_store_24(network_pdu->data, 2, seq);
941     network_pdu->len += 3;
942     big_endian_store_16(network_pdu->data, network_pdu->len, src);
943     network_pdu->len += 2;
944     big_endian_store_16(network_pdu->data, network_pdu->len, dest);
945     network_pdu->len += 2;
946     memcpy(&network_pdu->data[network_pdu->len], transport_pdu_data, transport_pdu_len);
947     network_pdu->len += transport_pdu_len;
948 }
949 
950 /*
951  * @brief Setup network pdu header
952  * @param netkey_index
953  * @param ctl
954  * @param ttl
955  * @param seq
956  * @param dest
957  */
958 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){
959     // set netkey_index
960     network_pdu->netkey_index = netkey_index;
961     // setup header
962     network_pdu->data[0] = (mesh_get_iv_index_for_tx() << 7) |  nid;
963     uint8_t ctl_ttl = (ctl << 7) | (ttl & 0x7f);
964     network_pdu->data[1] = ctl_ttl;
965     big_endian_store_24(network_pdu->data, 2, seq);
966     big_endian_store_16(network_pdu->data, 5, src);
967     big_endian_store_16(network_pdu->data, 7, dest);
968 }
969 
970 // Network PDU Getter
971 uint8_t  mesh_network_nid(mesh_network_pdu_t * network_pdu){
972     return network_pdu->data[0] & 0x7f;
973 }
974 uint16_t mesh_network_control(mesh_network_pdu_t * network_pdu){
975     return network_pdu->data[1] & 0x80;
976 }
977 uint8_t mesh_network_ttl(mesh_network_pdu_t * network_pdu){
978     return network_pdu->data[1] & 0x7f;
979 }
980 uint32_t mesh_network_seq(mesh_network_pdu_t * network_pdu){
981     return big_endian_read_24(network_pdu->data, 2);
982 }
983 uint16_t mesh_network_src(mesh_network_pdu_t * network_pdu){
984     return big_endian_read_16(network_pdu->data, 5);
985 }
986 uint16_t mesh_network_dst(mesh_network_pdu_t * network_pdu){
987     return big_endian_read_16(network_pdu->data, 7);
988 }
989 int mesh_network_segmented(mesh_network_pdu_t * network_pdu){
990     return network_pdu->data[9] & 0x80;
991 }
992 uint8_t * mesh_network_pdu_data(mesh_network_pdu_t * network_pdu){
993     return &network_pdu->data[9];
994 }
995 uint8_t   mesh_network_pdu_len(mesh_network_pdu_t * network_pdu){
996     return network_pdu->len - 9;
997 }
998 
999 static void mesh_network_dump_network_pdu(mesh_network_pdu_t * network_pdu){
1000     if (network_pdu){
1001         printf("- %p: ", network_pdu); printf_hexdump(network_pdu->data, network_pdu->len);
1002     }
1003 }
1004 static void mesh_network_dump_network_pdus(const char * name, btstack_linked_list_t * list){
1005     printf("List: %s:\n", name);
1006     btstack_linked_list_iterator_t it;
1007     btstack_linked_list_iterator_init(&it, list);
1008     while (btstack_linked_list_iterator_has_next(&it)){
1009         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t*) btstack_linked_list_iterator_next(&it);
1010         mesh_network_dump_network_pdu(network_pdu);
1011     }
1012 }
1013 static void mesh_network_reset_network_pdus(btstack_linked_list_t * list){
1014     while (!btstack_linked_list_empty(list)){
1015         mesh_network_pdu_t * pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(list);
1016         btstack_memory_mesh_network_pdu_free(pdu);
1017     }
1018 }
1019 void mesh_network_dump(void){
1020     mesh_network_dump_network_pdus("network_pdus_received", &network_pdus_received);
1021     mesh_network_dump_network_pdus("network_pdus_queued", &network_pdus_queued);
1022     mesh_network_dump_network_pdus("network_pdus_outgoing", &network_pdus_outgoing);
1023     printf("network_pdu_in_validation: \n");
1024     mesh_network_dump_network_pdu(network_pdu_in_validation);
1025 }
1026 void mesh_network_reset(void){
1027     mesh_network_reset_network_pdus(&network_pdus_received);
1028     mesh_network_reset_network_pdus(&network_pdus_queued);
1029     mesh_network_reset_network_pdus(&network_pdus_outgoing);
1030 }
1031 
1032 // buffer pool
1033 mesh_network_pdu_t * mesh_network_pdu_get(void){
1034     mesh_network_pdu_t * network_pdu = btstack_memory_mesh_network_pdu_get();
1035     if (network_pdu) {
1036         memset(network_pdu, 0, sizeof(mesh_network_pdu_t));
1037         network_pdu->pdu_header.pdu_type = MESH_PDU_TYPE_NETWORK;
1038     }
1039     return network_pdu;
1040 }
1041 
1042 void mesh_network_pdu_free(mesh_network_pdu_t * network_pdu){
1043     btstack_memory_mesh_network_pdu_free(network_pdu);
1044 }
1045 
1046 // Mesh Subnet Management
1047 
1048 void mesh_subnet_add(mesh_subnet_t * subnet){
1049     btstack_linked_list_add_tail(&subnets, (btstack_linked_item_t *) subnet);
1050 }
1051 
1052 void mesh_subnet_remove(mesh_subnet_t * subnet){
1053     btstack_linked_list_remove(&subnets, (btstack_linked_item_t *) subnet);
1054 }
1055 
1056 mesh_subnet_t * mesh_subnet_get_by_netkey_index(uint16_t netkey_index){
1057     btstack_linked_list_iterator_t it;
1058     btstack_linked_list_iterator_init(&it, &subnets);
1059     while (btstack_linked_list_iterator_has_next(&it)){
1060         mesh_subnet_t * item = (mesh_subnet_t *) btstack_linked_list_iterator_next(&it);
1061         if (item->netkey_index == netkey_index) return item;
1062     }
1063     return NULL;
1064 }
1065 
1066 int mesh_subnet_list_count(void){
1067     return btstack_linked_list_count(&subnets);
1068 }
1069 
1070 // mesh network key iterator over all keys
1071 void mesh_subnet_iterator_init(mesh_subnet_iterator_t *it){
1072     btstack_linked_list_iterator_init(&it->it, &subnets);
1073 }
1074 
1075 int mesh_subnet_iterator_has_more(mesh_subnet_iterator_t *it){
1076     return btstack_linked_list_iterator_has_next(&it->it);
1077 }
1078 
1079 mesh_subnet_t * mesh_subnet_iterator_get_next(mesh_subnet_iterator_t *it){
1080     return (mesh_subnet_t *) btstack_linked_list_iterator_next(&it->it);
1081 }
1082 
1083 mesh_network_key_t * mesh_subnet_get_outgoing_network_key(mesh_subnet_t * subnet){
1084     switch (subnet->key_refresh){
1085         case MESH_KEY_REFRESH_SECOND_PHASE:
1086             return subnet->new_key;
1087         case MESH_KEY_REFRESH_NOT_ACTIVE:
1088         case MESH_KEY_REFRESH_FIRST_PHASE:
1089         default:
1090             return subnet->old_key;
1091     }
1092 }
1093 
1094 /**
1095  * @brief Setup subnet for given netkey index
1096  */
1097 void mesh_subnet_setup_for_netkey_index(uint16_t netkey_index){
1098     mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(netkey_index);
1099     if (subnet != NULL) return;
1100 
1101     // find old / new keys
1102     mesh_network_key_t * old_key = NULL;
1103     mesh_network_key_t * new_key = NULL;
1104     mesh_network_key_iterator_t it;
1105     mesh_network_key_iterator_init(&it);
1106     while (mesh_network_key_iterator_has_more(&it)){
1107         mesh_network_key_t * network_key = mesh_network_key_iterator_get_next(&it);
1108         if (network_key->netkey_index != netkey_index) continue;
1109         if (old_key == NULL){
1110             old_key = network_key;
1111             continue;
1112         }
1113         // assign current key depending on key version
1114         if (((int8_t) (network_key->version - new_key->version)) > 0) {
1115             new_key = network_key;
1116         } else {
1117             new_key = old_key;
1118             old_key = network_key;
1119         }
1120     }
1121 
1122     // create subnet for netkey index
1123     subnet = btstack_memory_mesh_subnet_get();
1124     if (subnet == NULL) return;
1125     subnet->netkey_index = netkey_index;
1126     mesh_subnet_add(subnet);
1127 
1128     // set keys
1129     subnet->old_key = old_key;
1130     subnet->new_key = new_key;
1131 
1132     // key refresh
1133     if (new_key == NULL){
1134         // single key -> key refresh not active
1135         subnet->key_refresh = MESH_KEY_REFRESH_NOT_ACTIVE;
1136     }
1137     else {
1138         // two keys -> at least phase 1
1139         subnet->key_refresh = MESH_KEY_REFRESH_FIRST_PHASE;
1140     }
1141 }
1142