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