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