xref: /btstack/src/mesh/mesh_upper_transport.c (revision b6fc147f78a37f3479b846963ca40c9b931f6e2f)
1 /*
2  * Copyright (C) 2014 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_upper_transport.c"
39 
40 #include "mesh/mesh_upper_transport.h"
41 
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 
46 #include "btstack_util.h"
47 #include "btstack_memory.h"
48 
49 #include "mesh/beacon.h"
50 #include "mesh/mesh_iv_index_seq_number.h"
51 #include "mesh/mesh_keys.h"
52 #include "mesh/mesh_lower_transport.h"
53 #include "mesh/mesh_peer.h"
54 #include "mesh/mesh_virtual_addresses.h"
55 
56 static void (*higher_layer_handler)( mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu);
57 
58 static void mesh_print_hex(const char * name, const uint8_t * data, uint16_t len){
59     printf("%-20s ", name);
60     printf_hexdump(data, len);
61 }
62 // static void mesh_print_x(const char * name, uint32_t value){
63 //     printf("%20s: 0x%x", name, (int) value);
64 // }
65 
66 
67 // combined key x address iterator for upper transport decryption
68 
69 typedef struct {
70     // state
71     mesh_transport_key_iterator_t  key_it;
72     mesh_virtual_address_iterator_t address_it;
73     // elements
74     const mesh_transport_key_t *   key;
75     const mesh_virtual_address_t * address;
76     // address - might be virtual
77     uint16_t dst;
78     // key info
79 } mesh_transport_key_and_virtual_address_iterator_t;
80 
81 static void mesh_transport_key_and_virtual_address_iterator_init(mesh_transport_key_and_virtual_address_iterator_t *it,
82                                                                  uint16_t dst, uint16_t netkey_index, uint8_t akf,
83                                                                  uint8_t aid) {
84     printf("KEY_INIT: dst %04x, akf %x, aid %x\n", dst, akf, aid);
85     // config
86     it->dst   = dst;
87     // init elements
88     it->key     = NULL;
89     it->address = NULL;
90     // init element iterators
91     mesh_transport_key_aid_iterator_init(&it->key_it, netkey_index, akf, aid);
92     // init address iterator
93     if (mesh_network_address_virtual(it->dst)){
94         mesh_virtual_address_iterator_init(&it->address_it, dst);
95         // get first key
96         if (mesh_transport_key_aid_iterator_has_more(&it->key_it)) {
97             it->key = mesh_transport_key_aid_iterator_get_next(&it->key_it);
98         }
99     }
100 }
101 
102 // cartesian product: keys x addressses
103 static int mesh_transport_key_and_virtual_address_iterator_has_more(mesh_transport_key_and_virtual_address_iterator_t * it){
104     if (mesh_network_address_virtual(it->dst)) {
105         // find next valid entry
106         while (1){
107             if (mesh_virtual_address_iterator_has_more(&it->address_it)) return 1;
108             if (!mesh_transport_key_aid_iterator_has_more(&it->key_it)) return 0;
109             // get next key
110             it->key = mesh_transport_key_aid_iterator_get_next(&it->key_it);
111             mesh_virtual_address_iterator_init(&it->address_it, it->dst);
112         }
113     } else {
114         return mesh_transport_key_aid_iterator_has_more(&it->key_it);
115     }
116 }
117 
118 static void mesh_transport_key_and_virtual_address_iterator_next(mesh_transport_key_and_virtual_address_iterator_t * it){
119     if (mesh_network_address_virtual(it->dst)) {
120         it->address = mesh_virtual_address_iterator_get_next(&it->address_it);
121     } else {
122         it->key = mesh_transport_key_aid_iterator_get_next(&it->key_it);
123     }
124 }
125 
126 // UPPER TRANSPORT
127 
128 // stub lower transport
129 
130 static void mesh_upper_transport_validate_unsegmented_message(mesh_network_pdu_t * network_pdu);
131 static void mesh_upper_transport_validate_segmented_message(mesh_transport_pdu_t * transport_pdu);
132 
133 static void mesh_transport_run(void);
134 
135 static int crypto_active;
136 static mesh_network_pdu_t   * network_pdu_in_validation;
137 static mesh_transport_pdu_t * transport_pdu_in_validation;
138 static uint8_t application_nonce[13];
139 static btstack_crypto_ccm_t ccm;
140 static mesh_transport_key_and_virtual_address_iterator_t mesh_transport_key_it;
141 
142 // upper transport callbacks - in access layer
143 static void (*mesh_access_message_handler)(mesh_pdu_t * pdu);
144 static void (*mesh_control_message_handler)(mesh_pdu_t * pdu);
145 
146 // unsegmented (network) and segmented (transport) control and access messages
147 static btstack_linked_list_t upper_transport_incoming;
148 
149 
150 static void mesh_upper_unsegmented_control_message_received(mesh_network_pdu_t * network_pdu){
151     uint8_t * lower_transport_pdu     = mesh_network_pdu_data(network_pdu);
152     uint8_t  opcode = lower_transport_pdu[0];
153     if (mesh_control_message_handler){
154         mesh_control_message_handler((mesh_pdu_t*) network_pdu);
155     } else {
156         printf("[!] Unhandled Control message with opcode %02x\n", opcode);
157         // done
158         mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *) network_pdu);
159     }
160 }
161 
162 static void mesh_upper_transport_process_unsegmented_message_done(mesh_network_pdu_t *network_pdu){
163     crypto_active = 0;
164     if (mesh_network_control(network_pdu)) {
165         mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *) network_pdu);
166     } else {
167         mesh_network_pdu_free(network_pdu);
168         mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *) network_pdu_in_validation);
169         network_pdu_in_validation = NULL;
170     }
171     mesh_transport_run();
172 }
173 
174 static void mesh_upper_transport_process_segmented_message_done(mesh_transport_pdu_t *transport_pdu){
175     crypto_active = 0;
176     if (mesh_transport_ctl(transport_pdu)) {
177         mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *)transport_pdu);
178     } else {
179         mesh_transport_pdu_free(transport_pdu);
180         mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *)transport_pdu_in_validation);
181         transport_pdu_in_validation = NULL;
182     }
183     mesh_transport_run();
184 }
185 
186 static uint32_t iv_index_for_ivi_nid(uint8_t ivi_nid){
187     // get IV Index and IVI
188     uint32_t iv_index = mesh_get_iv_index();
189     int ivi = ivi_nid >> 7;
190 
191     // if least significant bit differs, use previous IV Index
192     if ((iv_index & 1 ) ^ ivi){
193         iv_index--;
194     }
195     return iv_index;
196 }
197 
198 static void transport_unsegmented_setup_nonce(uint8_t * nonce, const mesh_network_pdu_t * network_pdu){
199     nonce[1] = 0x00;    // SZMIC if a Segmented Access message or 0 for all other message formats
200     memcpy(&nonce[2], &network_pdu->data[2], 7);
201     big_endian_store_32(nonce, 9, iv_index_for_ivi_nid(network_pdu->data[0]));
202 }
203 
204 static void transport_segmented_setup_nonce(uint8_t * nonce, const mesh_transport_pdu_t * transport_pdu){
205     nonce[1] = transport_pdu->transmic_len == 8 ? 0x80 : 0x00;
206     memcpy(&nonce[2], &transport_pdu->network_header[2], 7);
207     big_endian_store_32(nonce, 9, iv_index_for_ivi_nid(transport_pdu->network_header[0]));
208 }
209 
210 static void transport_unsegmented_setup_application_nonce(uint8_t * nonce, const mesh_network_pdu_t * network_pdu){
211     nonce[0] = 0x01;
212     transport_unsegmented_setup_nonce(nonce, network_pdu);
213     mesh_print_hex("AppNonce", nonce, 13);
214 }
215 
216 static void transport_unsegmented_setup_device_nonce(uint8_t * nonce, const mesh_network_pdu_t * network_pdu){
217     nonce[0] = 0x02;
218     transport_unsegmented_setup_nonce(nonce, network_pdu);
219     mesh_print_hex("DeviceNonce", nonce, 13);
220 }
221 
222 static void transport_segmented_setup_application_nonce(uint8_t * nonce, const mesh_transport_pdu_t * transport_pdu){
223     nonce[0] = 0x01;
224     transport_segmented_setup_nonce(nonce, transport_pdu);
225     mesh_print_hex("AppNonce", nonce, 13);
226 }
227 
228 static void transport_segmented_setup_device_nonce(uint8_t * nonce, const mesh_transport_pdu_t * transport_pdu){
229     nonce[0] = 0x02;
230     transport_segmented_setup_nonce(nonce, transport_pdu);
231     mesh_print_hex("DeviceNonce", nonce, 13);
232 }
233 
234 static void mesh_upper_transport_validate_unsegmented_message_ccm(void * arg){
235     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) arg;
236 
237     uint8_t * lower_transport_pdu     = mesh_network_pdu_data(network_pdu);
238     uint8_t trans_mic_len = 4;
239 
240     // store TransMIC
241     uint8_t trans_mic[8];
242     btstack_crypto_ccm_get_authentication_value(&ccm, trans_mic);
243     mesh_print_hex("TransMIC", trans_mic, trans_mic_len);
244 
245     uint8_t * upper_transport_pdu     = mesh_network_pdu_data(network_pdu) + 1;
246     uint8_t   upper_transport_pdu_len = mesh_network_pdu_len(network_pdu)  - 1;
247 
248     mesh_print_hex("Decryted PDU", upper_transport_pdu, upper_transport_pdu_len - trans_mic_len);
249 
250     if (memcmp(trans_mic, &upper_transport_pdu[upper_transport_pdu_len - trans_mic_len], trans_mic_len) == 0){
251         printf("TransMIC matches\n");
252 
253         // remove TransMIC from payload
254         network_pdu->len -= trans_mic_len;
255 
256         // if virtual address, update dst to pseudo_dst
257         if (mesh_network_address_virtual(mesh_network_dst(network_pdu))){
258             big_endian_store_16(network_pdu->data, 7, mesh_transport_key_it.address->pseudo_dst);
259         }
260 
261         // pass to upper layer
262         if (mesh_access_message_handler){
263             mesh_access_message_handler((mesh_pdu_t*) network_pdu);
264         } else {
265             printf("[!] Unhandled Unsegmented Access message\n");
266             // done
267             mesh_upper_transport_process_unsegmented_message_done(network_pdu);
268         }
269 
270         printf("\n");
271     } else {
272         uint8_t afk = lower_transport_pdu[0] & 0x40;
273         if (afk){
274             printf("TransMIC does not match, try next key\n");
275             mesh_upper_transport_validate_unsegmented_message(network_pdu);
276         } else {
277             printf("TransMIC does not match device key, done\n");
278             // done
279             mesh_upper_transport_process_unsegmented_message_done(network_pdu);
280         }
281     }
282 }
283 
284 static void mesh_upper_transport_validate_segmented_message_ccm(void * arg){
285     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) arg;
286 
287     uint8_t * upper_transport_pdu     =  transport_pdu->data;
288     uint8_t   upper_transport_pdu_len =  transport_pdu->len - transport_pdu->transmic_len;
289 
290     mesh_print_hex("Decrypted PDU", upper_transport_pdu, upper_transport_pdu_len);
291 
292     // store TransMIC
293     uint8_t trans_mic[8];
294     btstack_crypto_ccm_get_authentication_value(&ccm, trans_mic);
295     mesh_print_hex("TransMIC", trans_mic, transport_pdu->transmic_len);
296 
297     if (memcmp(trans_mic, &upper_transport_pdu[upper_transport_pdu_len], transport_pdu->transmic_len) == 0){
298         printf("TransMIC matches\n");
299 
300         // remove TransMIC from payload
301         transport_pdu->len -= transport_pdu->transmic_len;
302 
303         // if virtual address, update dst to pseudo_dst
304         if (mesh_network_address_virtual(mesh_transport_dst(transport_pdu))){
305             big_endian_store_16(transport_pdu->network_header, 7, mesh_transport_key_it.address->pseudo_dst);
306         }
307 
308         // pass to upper layer
309         if (mesh_access_message_handler){
310             mesh_access_message_handler((mesh_pdu_t*) transport_pdu);
311         } else {
312             printf("[!] Unhandled Segmented Access/Control message\n");
313             // done
314             mesh_upper_transport_process_segmented_message_done(transport_pdu);
315         }
316 
317         printf("\n");
318 
319     } else {
320         uint8_t akf = transport_pdu->akf_aid & 0x40;
321         if (akf){
322             printf("TransMIC does not match, try next key\n");
323             mesh_upper_transport_validate_segmented_message(transport_pdu);
324         } else {
325             printf("TransMIC does not match device key, done\n");
326             // done
327             mesh_upper_transport_process_segmented_message_done(transport_pdu);
328         }
329     }
330 }
331 
332 void mesh_upper_transport_message_processed_by_higher_layer(mesh_pdu_t * pdu){
333     crypto_active = 0;
334     switch (pdu->pdu_type){
335         case MESH_PDU_TYPE_NETWORK:
336             mesh_upper_transport_process_unsegmented_message_done((mesh_network_pdu_t *) pdu);
337             break;
338         case MESH_PDU_TYPE_TRANSPORT:
339             mesh_upper_transport_process_segmented_message_done((mesh_transport_pdu_t *) pdu);
340             break;
341         default:
342             break;
343     }
344 }
345 
346 static void mesh_upper_transport_validate_segmented_message_digest(void * arg){
347     mesh_transport_pdu_t * transport_pdu   = (mesh_transport_pdu_t*) arg;
348     uint8_t   upper_transport_pdu_len      = transport_pdu_in_validation->len - transport_pdu_in_validation->transmic_len;
349     uint8_t * upper_transport_pdu_data_in  = transport_pdu_in_validation->data;
350     uint8_t * upper_transport_pdu_data_out = transport_pdu->data;
351     btstack_crypto_ccm_decrypt_block(&ccm, upper_transport_pdu_len, upper_transport_pdu_data_in, upper_transport_pdu_data_out, &mesh_upper_transport_validate_segmented_message_ccm, transport_pdu);
352 }
353 
354 static void mesh_upper_transport_validate_unsegmented_message_digest(void * arg){
355     mesh_network_pdu_t * network_pdu       = (mesh_network_pdu_t *) arg;
356     uint8_t   trans_mic_len = 4;
357     uint8_t   lower_transport_pdu_len      = network_pdu_in_validation->len - 9;
358     uint8_t * upper_transport_pdu_data_in  = &network_pdu_in_validation->data[10];
359     uint8_t * upper_transport_pdu_data_out = &network_pdu->data[10];
360     uint8_t   upper_transport_pdu_len      = lower_transport_pdu_len - 1 - trans_mic_len;
361     btstack_crypto_ccm_decrypt_block(&ccm, upper_transport_pdu_len, upper_transport_pdu_data_in, upper_transport_pdu_data_out, &mesh_upper_transport_validate_unsegmented_message_ccm, network_pdu);
362 }
363 
364 static void mesh_upper_transport_validate_unsegmented_message(mesh_network_pdu_t * network_pdu){
365 
366     if (!mesh_transport_key_and_virtual_address_iterator_has_more(&mesh_transport_key_it)){
367         printf("No valid transport key found\n");
368         mesh_upper_transport_process_unsegmented_message_done(network_pdu);
369         return;
370     }
371     mesh_transport_key_and_virtual_address_iterator_next(&mesh_transport_key_it);
372     const mesh_transport_key_t * message_key = mesh_transport_key_it.key;
373 
374     if (message_key->akf){
375         transport_unsegmented_setup_application_nonce(application_nonce, network_pdu_in_validation);
376     } else {
377         transport_unsegmented_setup_device_nonce(application_nonce, network_pdu_in_validation);
378     }
379 
380     // store application / device key index
381     mesh_print_hex("AppOrDevKey", message_key->key, 16);
382     network_pdu->appkey_index = message_key->appkey_index;
383 
384     // unsegmented message have TransMIC of 32 bit
385     uint8_t trans_mic_len = 4;
386     printf("Unsegmented Access message with TransMIC len 4\n");
387 
388     uint8_t   lower_transport_pdu_len = network_pdu_in_validation->len - 9;
389     uint8_t * upper_transport_pdu_data = &network_pdu_in_validation->data[10];
390     uint8_t   upper_transport_pdu_len  = lower_transport_pdu_len - 1 - trans_mic_len;
391 
392     mesh_print_hex("EncAccessPayload", upper_transport_pdu_data, upper_transport_pdu_len);
393 
394     // decrypt ccm
395     crypto_active = 1;
396     uint16_t aad_len  = 0;
397     if (mesh_network_address_virtual(mesh_network_dst(network_pdu))){
398         aad_len  = 16;
399     }
400     btstack_crypto_ccm_init(&ccm, message_key->key, application_nonce, upper_transport_pdu_len, aad_len, trans_mic_len);
401     if (aad_len){
402         btstack_crypto_ccm_digest(&ccm, (uint8_t*) mesh_transport_key_it.address->label_uuid, aad_len, &mesh_upper_transport_validate_unsegmented_message_digest, network_pdu);
403     } else {
404         mesh_upper_transport_validate_unsegmented_message_digest(network_pdu);
405     }
406 }
407 
408 static void mesh_upper_transport_validate_segmented_message(mesh_transport_pdu_t * transport_pdu){
409     uint8_t * upper_transport_pdu_data =  transport_pdu->data;
410     uint8_t   upper_transport_pdu_len  =  transport_pdu->len - transport_pdu->transmic_len;
411 
412     if (!mesh_transport_key_and_virtual_address_iterator_has_more(&mesh_transport_key_it)){
413         printf("No valid transport key found\n");
414         mesh_upper_transport_process_segmented_message_done(transport_pdu);
415         return;
416     }
417     mesh_transport_key_and_virtual_address_iterator_next(&mesh_transport_key_it);
418     const mesh_transport_key_t * message_key = mesh_transport_key_it.key;
419 
420     if (message_key->akf){
421         transport_segmented_setup_application_nonce(application_nonce, transport_pdu_in_validation);
422     } else {
423         transport_segmented_setup_device_nonce(application_nonce, transport_pdu_in_validation);
424     }
425 
426     // store application / device key index
427     mesh_print_hex("AppOrDevKey", message_key->key, 16);
428     transport_pdu->appkey_index = message_key->appkey_index;
429 
430     mesh_print_hex("EncAccessPayload", upper_transport_pdu_data, upper_transport_pdu_len);
431 
432     // decrypt ccm
433     crypto_active = 1;
434     uint16_t aad_len  = 0;
435     if (mesh_network_address_virtual(mesh_transport_dst(transport_pdu))){
436         aad_len  = 16;
437     }
438     btstack_crypto_ccm_init(&ccm, message_key->key, application_nonce, upper_transport_pdu_len, aad_len, transport_pdu->transmic_len);
439 
440     if (aad_len){
441         btstack_crypto_ccm_digest(&ccm, (uint8_t *) mesh_transport_key_it.address->label_uuid, aad_len, &mesh_upper_transport_validate_segmented_message_digest, transport_pdu);
442     } else {
443         mesh_upper_transport_validate_segmented_message_digest(transport_pdu);
444     }
445 }
446 
447 static void mesh_upper_transport_process_unsegmented_access_message(mesh_network_pdu_t *network_pdu){
448     // copy original pdu
449     network_pdu->len = network_pdu_in_validation->len;
450     memcpy(network_pdu->data, network_pdu_in_validation->data, network_pdu->len);
451 
452     //
453     uint8_t * lower_transport_pdu     = &network_pdu_in_validation->data[9];
454     uint8_t   lower_transport_pdu_len = network_pdu_in_validation->len - 9;
455 
456     mesh_print_hex("Lower Transport network pdu", &network_pdu_in_validation->data[9], lower_transport_pdu_len);
457 
458     uint8_t aid =  lower_transport_pdu[0] & 0x3f;
459     uint8_t akf = (lower_transport_pdu[0] & 0x40) >> 6;
460     printf("AKF: %u\n",   akf);
461     printf("AID: %02x\n", aid);
462 
463     mesh_transport_key_and_virtual_address_iterator_init(&mesh_transport_key_it, mesh_network_dst(network_pdu),
464             network_pdu->netkey_index, akf, aid);
465     mesh_upper_transport_validate_unsegmented_message(network_pdu);
466 }
467 
468 static void mesh_upper_transport_process_message(mesh_transport_pdu_t * transport_pdu){
469     // copy original pdu
470     transport_pdu->len = transport_pdu_in_validation->len;
471     memcpy(transport_pdu, transport_pdu_in_validation, sizeof(mesh_transport_pdu_t));
472 
473     //
474     uint8_t * upper_transport_pdu     =  transport_pdu->data;
475     uint8_t   upper_transport_pdu_len =  transport_pdu->len - transport_pdu->transmic_len;
476     mesh_print_hex("Upper Transport pdu", upper_transport_pdu, upper_transport_pdu_len);
477 
478     uint8_t aid =  transport_pdu->akf_aid & 0x3f;
479     uint8_t akf = (transport_pdu->akf_aid & 0x40) >> 6;
480 
481     printf("AKF: %u\n",   akf);
482     printf("AID: %02x\n", aid);
483 
484     mesh_transport_key_and_virtual_address_iterator_init(&mesh_transport_key_it, mesh_transport_dst(transport_pdu),
485             transport_pdu->netkey_index, akf, aid);
486     mesh_upper_transport_validate_segmented_message(transport_pdu);
487 }
488 
489 static void mesh_upper_transport_message_received(mesh_pdu_t * pdu){
490     btstack_linked_list_add_tail(&upper_transport_incoming, (btstack_linked_item_t*) pdu);
491     mesh_transport_run();
492 }
493 
494 void mesh_upper_transport_pdu_free(mesh_pdu_t * pdu){
495     mesh_network_pdu_t * network_pdu;
496     mesh_transport_pdu_t * transport_pdu;
497     switch (pdu->pdu_type) {
498         case MESH_PDU_TYPE_NETWORK:
499             network_pdu = (mesh_network_pdu_t *) pdu;
500             mesh_network_pdu_free(network_pdu);
501             break;
502         case MESH_PDU_TYPE_TRANSPORT:
503             transport_pdu = (mesh_transport_pdu_t *) pdu;
504             mesh_transport_pdu_free(transport_pdu);
505             break;
506         default:
507             break;
508     }
509 }
510 
511 static void mesh_upper_transport_pdu_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu){
512     switch (callback_type){
513         case MESH_TRANSPORT_PDU_RECEIVED:
514             mesh_upper_transport_message_received(pdu);
515             break;
516         case MESH_TRANSPORT_PDU_SENT:
517             // notify upper layer (or just free pdu)
518             if (higher_layer_handler){
519                 higher_layer_handler(callback_type, status, pdu);
520             } else {
521                 mesh_upper_transport_pdu_free(pdu);
522             }
523             break;
524         default:
525             break;
526     }
527 }
528 static void mesh_upper_transport_send_unsegmented_access_pdu_ccm(void * arg){
529     crypto_active = 0;
530 
531     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) arg;
532     uint8_t * upper_transport_pdu     = mesh_network_pdu_data(network_pdu) + 1;
533     uint8_t   upper_transport_pdu_len = mesh_network_pdu_len(network_pdu)  - 1;
534     mesh_print_hex("EncAccessPayload", upper_transport_pdu, upper_transport_pdu_len);
535     // store TransMIC
536     btstack_crypto_ccm_get_authentication_value(&ccm, &upper_transport_pdu[upper_transport_pdu_len]);
537     mesh_print_hex("TransMIC", &upper_transport_pdu[upper_transport_pdu_len], 4);
538     network_pdu->len += 4;
539     // send network pdu
540     mesh_lower_transport_send_pdu((mesh_pdu_t*) network_pdu);
541 }
542 
543 static void mesh_upper_transport_send_segmented_access_pdu_ccm(void * arg){
544     crypto_active = 0;
545 
546     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) arg;
547     mesh_print_hex("EncAccessPayload", transport_pdu->data, transport_pdu->len);
548     // store TransMIC
549     btstack_crypto_ccm_get_authentication_value(&ccm, &transport_pdu->data[transport_pdu->len]);
550     mesh_print_hex("TransMIC", &transport_pdu->data[transport_pdu->len], transport_pdu->transmic_len);
551     transport_pdu->len += transport_pdu->transmic_len;
552     mesh_lower_transport_send_pdu((mesh_pdu_t*) transport_pdu);
553 }
554 
555 static uint8_t mesh_upper_transport_setup_unsegmented_control_pdu(mesh_network_pdu_t * network_pdu, uint16_t netkey_index, uint8_t ttl, uint16_t src, uint16_t dest, uint8_t opcode,
556                           const uint8_t * control_pdu_data, uint16_t control_pdu_len){
557 
558     printf("[+] Upper transport, setup unsegmented Control PDU (opcode %02x): \n", opcode);
559     printf_hexdump(control_pdu_data, control_pdu_len);
560 
561     if (control_pdu_len > 11) return 1;
562 
563     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
564     if (!network_key) return 1;
565 
566     uint8_t transport_pdu_data[12];
567     transport_pdu_data[0] = opcode;
568     memcpy(&transport_pdu_data[1], control_pdu_data, control_pdu_len);
569     uint16_t transport_pdu_len = control_pdu_len + 1;
570 
571     mesh_print_hex("LowerTransportPDU", transport_pdu_data, transport_pdu_len);
572     // setup network_pdu
573     mesh_network_setup_pdu(network_pdu, netkey_index, network_key->nid, 1, ttl, mesh_sequence_number_next(), src, dest, transport_pdu_data, transport_pdu_len);
574 
575     return 0;
576 }
577 
578 static uint8_t mesh_upper_transport_setup_segmented_control_pdu(mesh_transport_pdu_t * transport_pdu, uint16_t netkey_index, uint8_t ttl, uint16_t src, uint16_t dest, uint8_t opcode,
579                           const uint8_t * control_pdu_data, uint16_t control_pdu_len){
580 
581     printf("[+] Upper transport, setup segmented Control PDU (opcode %02x): \n", opcode);
582     printf_hexdump(control_pdu_data, control_pdu_len);
583 
584     if (control_pdu_len > 256) return 1;
585 
586     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
587     if (!network_key) return 1;
588 
589     uint32_t seq = mesh_sequence_number_peek();
590 
591     memcpy(transport_pdu->data, control_pdu_data, control_pdu_len);
592     transport_pdu->len = control_pdu_len;
593     transport_pdu->netkey_index = netkey_index;
594     transport_pdu->akf_aid = opcode;
595     transport_pdu->transmic_len = 0;    // no TransMIC for control
596     mesh_transport_set_nid_ivi(transport_pdu, network_key->nid);
597     mesh_transport_set_seq(transport_pdu, seq);
598     mesh_transport_set_src(transport_pdu, src);
599     mesh_transport_set_dest(transport_pdu, dest);
600     mesh_transport_set_ctl_ttl(transport_pdu, 0x80 | ttl);
601 
602     return 0;
603 }
604 
605 uint8_t mesh_upper_transport_setup_control_pdu(mesh_pdu_t * pdu, uint16_t netkey_index,
606                                                uint8_t ttl, uint16_t src, uint16_t dest, uint8_t opcode, const uint8_t * control_pdu_data, uint16_t control_pdu_len){
607     switch (pdu->pdu_type){
608         case MESH_PDU_TYPE_NETWORK:
609             return mesh_upper_transport_setup_unsegmented_control_pdu((mesh_network_pdu_t *) pdu, netkey_index, ttl, src, dest, opcode, control_pdu_data, control_pdu_len);
610         case MESH_PDU_TYPE_TRANSPORT:
611             return mesh_upper_transport_setup_segmented_control_pdu((mesh_transport_pdu_t *) pdu, netkey_index, ttl, src, dest, opcode, control_pdu_data, control_pdu_len);
612         default:
613             return 1;
614     }
615 }
616 
617 static uint8_t mesh_upper_transport_setup_unsegmented_access_pdu_header(mesh_network_pdu_t * network_pdu, uint16_t netkey_index,
618         uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest){
619 
620     // get app or device key
621     const mesh_transport_key_t * appkey;
622     appkey = mesh_transport_key_get(appkey_index);
623     if (appkey == NULL){
624         printf("appkey_index %x unknown\n", appkey_index);
625         return 1;
626     }
627     uint8_t akf_aid = (appkey->akf << 6) | appkey->aid;
628 
629     // lookup network by netkey_index
630     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
631     if (!network_key) return 1;
632 
633     network_pdu->data[9] = akf_aid;
634     // setup network_pdu
635     mesh_network_setup_pdu_header(network_pdu, netkey_index, network_key->nid, 0, ttl, mesh_sequence_number_next(), src, dest);
636     network_pdu->appkey_index = appkey_index;
637     return 0;
638 }
639 
640 static uint8_t mesh_upper_transport_setup_unsegmented_access_pdu(mesh_network_pdu_t * network_pdu, uint16_t netkey_index, uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest,
641                                                        const uint8_t * access_pdu_data, uint8_t access_pdu_len){
642 
643     int status = mesh_upper_transport_setup_unsegmented_access_pdu_header(network_pdu, netkey_index, appkey_index, ttl, src, dest);
644     if (status) return status;
645 
646     printf("[+] Upper transport, setup unsegmented Access PDU - seq %06x\n", mesh_network_seq(network_pdu));
647     mesh_print_hex("Access Payload", access_pdu_data, access_pdu_len);
648 
649     // store in transport pdu
650     memcpy(&network_pdu->data[10], access_pdu_data, access_pdu_len);
651     network_pdu->len = 10 + access_pdu_len;
652     return 0;
653 }
654 
655 static uint8_t mesh_upper_transport_setup_segmented_access_pdu_header(mesh_transport_pdu_t * transport_pdu, uint16_t netkey_index, uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest,
656                                                         uint8_t szmic){
657     uint32_t seq = mesh_sequence_number_peek();
658 
659     printf("[+] Upper transport, setup segmented Access PDU - seq %06x, szmic %u, iv_index %08x\n", seq, szmic,
660            mesh_get_iv_index_for_tx());
661     mesh_print_hex("Access Payload", transport_pdu->data, transport_pdu->len);
662 
663     // get app or device key
664     const mesh_transport_key_t *appkey;
665     appkey = mesh_transport_key_get(appkey_index);
666     if (appkey == NULL) {
667         printf("appkey_index %x unknown\n", appkey_index);
668         return 1;
669     }
670     uint8_t akf_aid = (appkey->akf << 6) | appkey->aid;
671 
672     // lookup network by netkey_index
673     const mesh_network_key_t *network_key = mesh_network_key_list_get(netkey_index);
674     if (!network_key) return 1;
675 
676     const uint8_t trans_mic_len = szmic ? 8 : 4;
677 
678     // store in transport pdu
679     transport_pdu->transmic_len = trans_mic_len;
680     transport_pdu->netkey_index = netkey_index;
681     transport_pdu->appkey_index = appkey_index;
682     transport_pdu->akf_aid = akf_aid;
683     mesh_transport_set_nid_ivi(transport_pdu, network_key->nid | ((mesh_get_iv_index_for_tx() & 1) << 7));
684     mesh_transport_set_seq(transport_pdu, seq);
685     mesh_transport_set_src(transport_pdu, src);
686     mesh_transport_set_dest(transport_pdu, dest);
687     mesh_transport_set_ctl_ttl(transport_pdu, ttl);
688     return 0;
689 }
690 
691 
692 static uint8_t mesh_upper_transport_setup_segmented_access_pdu(mesh_transport_pdu_t * transport_pdu, uint16_t netkey_index, uint16_t appkey_index, uint8_t ttl, uint16_t src, uint16_t dest,
693                           uint8_t szmic, const uint8_t * access_pdu_data, uint8_t access_pdu_len){
694     int status = mesh_upper_transport_setup_segmented_access_pdu_header(transport_pdu, netkey_index, appkey_index, ttl, src, dest, szmic);
695     if (status) return status;
696 
697     // store in transport pdu
698     memcpy(transport_pdu->data, access_pdu_data, access_pdu_len);
699     transport_pdu->len = access_pdu_len;
700     return 0;
701 }
702 uint8_t mesh_upper_transport_setup_access_pdu_header(mesh_pdu_t * pdu, uint16_t netkey_index, uint16_t appkey_index,
703                                               uint8_t ttl, uint16_t src, uint16_t dest, uint8_t szmic){
704     switch (pdu->pdu_type){
705         case MESH_PDU_TYPE_NETWORK:
706             return mesh_upper_transport_setup_unsegmented_access_pdu_header((mesh_network_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest);
707         case MESH_PDU_TYPE_TRANSPORT:
708             return mesh_upper_transport_setup_segmented_access_pdu_header((mesh_transport_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest, szmic);
709         default:
710             return 1;
711     }
712 }
713 
714 uint8_t mesh_upper_transport_setup_access_pdu(mesh_pdu_t * pdu, uint16_t netkey_index, uint16_t appkey_index,
715                                               uint8_t ttl, uint16_t src, uint16_t dest, uint8_t szmic,
716                                               const uint8_t * access_pdu_data, uint8_t access_pdu_len){
717     switch (pdu->pdu_type){
718         case MESH_PDU_TYPE_NETWORK:
719             return mesh_upper_transport_setup_unsegmented_access_pdu((mesh_network_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest, access_pdu_data, access_pdu_len);
720         case MESH_PDU_TYPE_TRANSPORT:
721             return mesh_upper_transport_setup_segmented_access_pdu((mesh_transport_pdu_t *) pdu, netkey_index, appkey_index, ttl, src, dest, szmic, access_pdu_data, access_pdu_len);
722         default:
723             return 1;
724     }
725 }
726 
727 void mesh_upper_transport_send_control_pdu(mesh_pdu_t * pdu){
728     mesh_lower_transport_send_pdu((mesh_pdu_t*) pdu);
729 }
730 
731 static void mesh_upper_transport_send_unsegmented_access_pdu_digest(void * arg){
732     mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) arg;
733     uint8_t * access_pdu_data = mesh_network_pdu_data(network_pdu) + 1;
734     uint16_t  access_pdu_len  = mesh_network_pdu_len(network_pdu)  - 1;
735     btstack_crypto_ccm_encrypt_block(&ccm, access_pdu_len, access_pdu_data, access_pdu_data, &mesh_upper_transport_send_unsegmented_access_pdu_ccm, network_pdu);
736 }
737 
738 static mesh_transport_key_t * mesh_upper_transport_get_outgoing_appkey(uint16_t netkey_index, uint16_t appkey_index){
739     // Device Key is fixed
740     if (appkey_index == MESH_DEVICE_KEY_INDEX) {
741         return mesh_transport_key_get(appkey_index);
742     }
743 
744     // Get key refresh state from subnet
745     mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(netkey_index);
746     if (subnet == NULL) return NULL;
747 
748     // identify old and new app keys for given appkey_index
749     mesh_transport_key_t * old_key = NULL;
750     mesh_transport_key_t * new_key = NULL;
751     mesh_transport_key_iterator_t it;
752     mesh_transport_key_iterator_init(&it, netkey_index);
753     while (mesh_transport_key_iterator_has_more(&it)){
754         mesh_transport_key_t * transport_key = mesh_transport_key_iterator_get_next(&it);
755         if (transport_key->appkey_index != appkey_index) continue;
756         if (transport_key->old_key == 0) {
757             new_key = transport_key;
758         } else {
759             old_key = transport_key;
760         }
761     }
762 
763     // if no key is marked as old, just use the current one
764     if (old_key == NULL) return new_key;
765 
766     // use new key if it exists in phase two
767     if ((subnet->key_refresh == MESH_KEY_REFRESH_SECOND_PHASE) && (new_key != NULL)){
768         return new_key;
769     } else {
770         return old_key;
771     }
772 }
773 
774 static void mesh_upper_transport_send_unsegmented_access_pdu(mesh_network_pdu_t * network_pdu){
775 
776     // if dst is virtual address, lookup label uuid and hash
777     uint16_t aad_len = 0;
778     mesh_virtual_address_t * virtual_address = NULL;
779     uint16_t dst = mesh_network_dst(network_pdu);
780     if (mesh_network_address_virtual(dst)){
781         virtual_address = mesh_virtual_address_for_pseudo_dst(dst);
782         if (!virtual_address){
783             printf("No virtual address register for pseudo dst %4x\n", dst);
784             btstack_memory_mesh_network_pdu_free(network_pdu);
785             return;
786         }
787         aad_len = 16;
788         big_endian_store_16(network_pdu->data, 7, virtual_address->hash);
789     }
790 
791     // setup nonce
792     uint16_t appkey_index = network_pdu->appkey_index;
793     if (appkey_index == MESH_DEVICE_KEY_INDEX){
794         transport_unsegmented_setup_device_nonce(application_nonce, network_pdu);
795     } else {
796         transport_unsegmented_setup_application_nonce(application_nonce, network_pdu);
797     }
798 
799     // get app or device key
800     const mesh_transport_key_t * appkey = mesh_upper_transport_get_outgoing_appkey(network_pdu->netkey_index, appkey_index);
801     mesh_print_hex("AppOrDevKey", appkey->key, 16);
802 
803     // encrypt ccm
804     uint8_t   trans_mic_len = 4;
805     uint16_t  access_pdu_len  = mesh_network_pdu_len(network_pdu)  - 1;
806     crypto_active = 1;
807 
808     btstack_crypto_ccm_init(&ccm, appkey->key, application_nonce, access_pdu_len, aad_len, trans_mic_len);
809     if (virtual_address){
810         mesh_print_hex("LabelUUID", virtual_address->label_uuid, 16);
811         btstack_crypto_ccm_digest(&ccm, virtual_address->label_uuid, 16, &mesh_upper_transport_send_unsegmented_access_pdu_digest, network_pdu);
812     } else {
813         mesh_upper_transport_send_unsegmented_access_pdu_digest(network_pdu);
814     }
815 }
816 
817 static void mesh_upper_transport_send_segmented_access_pdu_digest(void *arg){
818     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) arg;
819     uint16_t  access_pdu_len  = transport_pdu->len;
820     uint8_t * access_pdu_data = transport_pdu->data;
821     btstack_crypto_ccm_encrypt_block(&ccm, access_pdu_len,access_pdu_data, access_pdu_data, &mesh_upper_transport_send_segmented_access_pdu_ccm, transport_pdu);
822 }
823 
824 static void mesh_upper_transport_send_segmented_access_pdu(mesh_transport_pdu_t * transport_pdu){
825 
826     // if dst is virtual address, lookup label uuid and hash
827     uint16_t aad_len = 0;
828     mesh_virtual_address_t * virtual_address = NULL;
829     uint16_t dst = mesh_transport_dst(transport_pdu);
830     if (mesh_network_address_virtual(dst)){
831         virtual_address = mesh_virtual_address_for_pseudo_dst(dst);
832         if (!virtual_address){
833             printf("No virtual address register for pseudo dst %4x\n", dst);
834             btstack_memory_mesh_transport_pdu_free(transport_pdu);
835             return;
836         }
837         // printf("Using hash %4x with LabelUUID: ", virtual_address->hash);
838         // printf_hexdump(virtual_address->label_uuid, 16);
839         aad_len = 16;
840         big_endian_store_16(transport_pdu->network_header, 7, virtual_address->hash);
841     }
842 
843     // setup nonce - uses dst, so after pseudo address translation
844     uint16_t appkey_index = transport_pdu->appkey_index;
845     if (appkey_index == MESH_DEVICE_KEY_INDEX){
846         transport_segmented_setup_device_nonce(application_nonce, transport_pdu);
847     } else {
848         transport_segmented_setup_application_nonce(application_nonce, transport_pdu);
849     }
850 
851     // get app or device key
852     const mesh_transport_key_t * appkey = mesh_upper_transport_get_outgoing_appkey(transport_pdu->netkey_index, appkey_index);
853     mesh_print_hex("AppOrDevKey", appkey->key, 16);
854 
855     // encrypt ccm
856     uint8_t   transmic_len    = transport_pdu->transmic_len;
857     uint16_t  access_pdu_len  = transport_pdu->len;
858     crypto_active = 1;
859     btstack_crypto_ccm_init(&ccm, appkey->key, application_nonce, access_pdu_len, aad_len, transmic_len);
860     if (virtual_address){
861         mesh_print_hex("LabelUUID", virtual_address->label_uuid, 16);
862         btstack_crypto_ccm_digest(&ccm, virtual_address->label_uuid, 16, &mesh_upper_transport_send_segmented_access_pdu_digest, transport_pdu);
863     } else {
864         mesh_upper_transport_send_segmented_access_pdu_digest(transport_pdu);
865     }
866 }
867 
868 void mesh_upper_transport_send_access_pdu(mesh_pdu_t * pdu){
869     switch (pdu->pdu_type){
870         case MESH_PDU_TYPE_NETWORK:
871             mesh_upper_transport_send_unsegmented_access_pdu((mesh_network_pdu_t *) pdu);
872             break;
873         case MESH_PDU_TYPE_TRANSPORT:
874             mesh_upper_transport_send_segmented_access_pdu((mesh_transport_pdu_t *) pdu);
875             break;
876         default:
877             break;
878     }
879 }
880 
881 void mesh_upper_transport_register_access_message_handler(void (*callback)(mesh_pdu_t *pdu)){
882     mesh_access_message_handler = callback;
883 }
884 
885 void mesh_upper_transport_register_control_message_handler(void (*callback)(mesh_pdu_t *pdu)){
886     mesh_control_message_handler = callback;
887 }
888 
889 void mesh_upper_transport_set_higher_layer_handler(void (*pdu_handler)( mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu)){
890     higher_layer_handler = pdu_handler;
891 }
892 
893 void mesh_upper_transport_init(){
894     mesh_lower_transport_init();
895     mesh_lower_transport_set_higher_layer_handler(&mesh_upper_transport_pdu_handler);
896 }
897 
898 static void mesh_transport_run(void){
899     while(!btstack_linked_list_empty(&upper_transport_incoming)){
900 
901         if (crypto_active) return;
902 
903         // peek at next message
904         mesh_pdu_t * pdu =  (mesh_pdu_t *) btstack_linked_list_get_first_item(&upper_transport_incoming);
905         mesh_transport_pdu_t * transport_pdu;
906         mesh_network_pdu_t   * network_pdu;
907         switch (pdu->pdu_type){
908             case MESH_PDU_TYPE_NETWORK:
909                 network_pdu = (mesh_network_pdu_t *) pdu;
910                 // control?
911                 if (mesh_network_control(network_pdu)) {
912                     (void) btstack_linked_list_pop(&upper_transport_incoming);
913                     mesh_upper_unsegmented_control_message_received(network_pdu);
914                 } else {
915                     mesh_network_pdu_t * decode_pdu = mesh_network_pdu_get();
916                     if (!decode_pdu) return;
917                     // get encoded network pdu and start processing
918                     network_pdu_in_validation = network_pdu;
919                     (void) btstack_linked_list_pop(&upper_transport_incoming);
920                     mesh_upper_transport_process_unsegmented_access_message(decode_pdu);
921                 }
922                 break;
923             case MESH_PDU_TYPE_TRANSPORT:
924                 transport_pdu = (mesh_transport_pdu_t *) pdu;
925                 uint8_t ctl = mesh_transport_ctl(transport_pdu);
926                 if (ctl){
927                     printf("Ignoring Segmented Control Message\n");
928                     (void) btstack_linked_list_pop(&upper_transport_incoming);
929                     mesh_lower_transport_message_processed_by_higher_layer((mesh_pdu_t *) transport_pdu);
930                 } else {
931                     mesh_transport_pdu_t * decode_pdu = mesh_transport_pdu_get();
932                     if (!decode_pdu) return;
933                     // get encoded transport pdu and start processing
934                     transport_pdu_in_validation = transport_pdu;
935                     (void) btstack_linked_list_pop(&upper_transport_incoming);
936                     mesh_upper_transport_process_message(decode_pdu);
937                 }
938                 break;
939             default:
940                 break;
941         }
942     }
943 }
944