xref: /btstack/src/mesh/provisioning_device.c (revision a8d51f092f1b660d0f6921369ad2bc3f9368296c)
1 /*
2  * Copyright (C) 2017 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__ "provisioning_device.c"
39 
40 #include <stdint.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 
45 #include "btstack.h"
46 #include "btstack_memory.h"
47 
48 #include "mesh/mesh_crypto.h"
49 #ifdef ENABLE_MESH_ADV_BEARER
50 #include "mesh/pb_adv.h"
51 #endif
52 #ifdef ENABLE_MESH_GATT_BEARER
53 #include "mesh/pb_gatt.h"
54 #endif
55 #include "mesh/provisioning.h"
56 
57 static void prov_key_generated(void * arg);
58 
59 // remote ecc
60 static uint8_t remote_ec_q[64];
61 static uint8_t dhkey[32];
62 
63 static btstack_packet_handler_t prov_packet_handler;
64 
65 static uint8_t  prov_buffer_out[MESH_PROV_MAX_PROXY_PDU];
66 // ConfirmationInputs = ProvisioningInvitePDUValue || ProvisioningCapabilitiesPDUValue || ProvisioningStartPDUValue || PublicKeyProvisioner || PublicKeyDevice
67 static uint8_t  prov_confirmation_inputs[1 + 11 + 5 + 64 + 64];
68 static uint8_t  prov_authentication_method;
69 static uint8_t  prov_public_key_oob_used;
70 static uint8_t  prov_emit_public_key_oob_active;
71 static uint8_t  prov_emit_output_oob_active;
72 static uint8_t  prov_ec_q[64];
73 
74 static const uint8_t * prov_public_key_oob_q;
75 static const uint8_t * prov_public_key_oob_d;
76 
77 // num elements
78 static uint8_t  prov_num_elements = 1;
79 
80 // capabilites
81 static const uint8_t * prov_static_oob_data;
82 
83 static uint16_t  prov_static_oob_len;
84 static uint16_t  prov_output_oob_actions;
85 static uint16_t  prov_input_oob_actions;
86 static uint8_t   prov_public_key_oob_available;
87 static uint8_t   prov_static_oob_available;
88 static uint8_t   prov_output_oob_size;
89 static uint8_t   prov_input_oob_size;
90 static uint8_t   prov_error_code;
91 static uint8_t   prov_waiting_for_outgoing_complete;
92 
93 static uint8_t                      prov_attention_timer_timeout;
94 
95 static btstack_timer_source_t       prov_protocol_timer;
96 
97 static btstack_crypto_aes128_cmac_t prov_cmac_request;
98 static btstack_crypto_random_t      prov_random_request;
99 static btstack_crypto_ecc_p256_t    prov_ecc_p256_request;
100 static btstack_crypto_ccm_t         prov_ccm_request;
101 
102 // ConfirmationDevice
103 static uint8_t confirmation_device[16];
104 // ConfirmationSalt
105 static uint8_t confirmation_salt[16];
106 // ConfirmationKey
107 static uint8_t confirmation_key[16];
108 // RandomDevice
109 static uint8_t random_device[16];
110 // ProvisioningSalt
111 static uint8_t provisioning_salt[16];
112 // AuthValue
113 static uint8_t auth_value[16];
114 // SessionKey
115 static uint8_t session_key[16];
116 // SessionNonce
117 static uint8_t session_nonce[16];
118 // EncProvisioningData
119 static uint8_t enc_provisioning_data[25];
120 // ProvisioningData
121 static uint8_t provisioning_data[25];
122 
123 // received network_key
124 static mesh_network_key_t * network_key;
125 
126 // DeviceKey
127 static uint8_t device_key[16];
128 
129 static uint8_t  flags;
130 
131 static uint32_t iv_index;
132 static uint16_t unicast_address;
133 
134 typedef enum {
135     DEVICE_W4_INVITE,
136     DEVICE_SEND_CAPABILITIES,
137     DEVICE_W4_START,
138     DEVICE_W4_INPUT_OOK,
139     DEVICE_SEND_INPUT_COMPLETE,
140     DEVICE_W4_PUB_KEY,
141     DEVICE_SEND_PUB_KEY,
142     DEVICE_PUB_KEY_SENT,
143     DEVICE_W4_CONFIRM,
144     DEVICE_SEND_CONFIRM,
145     DEVICE_W4_RANDOM,
146     DEVICE_SEND_RANDOM,
147     DEVICE_W4_DATA,
148     DEVICE_SEND_COMPLETE,
149     DEVICE_SEND_ERROR,
150     DEVICE_W4_DONE,
151 } device_state_t;
152 
153 static device_state_t device_state;
154 static uint16_t pb_transport_cid;
155 static mesh_pb_type_t pb_type;
156 
157 static void pb_send_pdu(uint16_t transport_cid, const uint8_t * buffer, uint16_t buffer_size){
158     switch (pb_type){
159 #ifdef ENABLE_MESH_ADV_BEARER
160         case MESH_PB_TYPE_ADV:
161             pb_adv_send_pdu(transport_cid, buffer, buffer_size);
162             break;
163 #endif
164 #ifdef ENABLE_MESH_GATT_BEARER
165         case MESH_PB_TYPE_GATT:
166             pb_gatt_send_pdu(transport_cid, buffer, buffer_size);
167             break;
168 #endif
169         default:
170             break;
171      }
172 }
173 
174 static void pb_close_link(uint16_t transport_cid, uint8_t reason){
175     switch (pb_type){
176 #ifdef ENABLE_MESH_ADV_BEARER
177         case MESH_PB_TYPE_ADV:
178             pb_adv_close_link(transport_cid, reason);
179             break;
180 #endif
181 #ifdef ENABLE_MESH_GATT_BEARER
182         case MESH_PB_TYPE_GATT:
183             pb_gatt_close_link(transport_cid, reason);
184             break;
185 #endif
186         default:
187             break;
188     }
189 }
190 
191 static void provisioning_emit_event(uint16_t pb_adv_cid, uint8_t mesh_subevent){
192     if (!prov_packet_handler) return;
193     uint8_t event[5] = { HCI_EVENT_MESH_META, 3, mesh_subevent};
194     little_endian_store_16(event, 3, pb_adv_cid);
195     prov_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
196 }
197 
198 static void provisioning_emit_output_oob_event(uint16_t pb_adv_cid, uint32_t number){
199     if (!prov_packet_handler) return;
200     uint8_t event[9] = { HCI_EVENT_MESH_META, 7, MESH_SUBEVENT_PB_PROV_START_EMIT_OUTPUT_OOB};
201     little_endian_store_16(event, 3, pb_adv_cid);
202     little_endian_store_32(event, 5, number);
203     prov_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
204 }
205 
206 static void provisioning_emit_attention_timer_event(uint16_t pb_adv_cid, uint8_t timer_s){
207     if (!prov_packet_handler) return;
208     uint8_t event[6] = { HCI_EVENT_MESH_META, 4, MESH_SUBEVENT_PB_PROV_ATTENTION_TIMER};
209     little_endian_store_16(event, 3, pb_adv_cid);
210     event[5] = timer_s;
211     prov_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
212 }
213 
214 static void provisiong_timer_handler(btstack_timer_source_t * ts){
215     UNUSED(ts);
216     printf("Provisioning Protocol Timeout -> Close Link!\n");
217     pb_close_link(1, 1);
218 }
219 
220 // The provisioning protocol shall have a minimum timeout of 60 seconds that is reset
221 // each time a provisioning protocol PDU is sent or received
222 static void provisioning_timer_start(void){
223     btstack_run_loop_remove_timer(&prov_protocol_timer);
224     btstack_run_loop_set_timer_handler(&prov_protocol_timer, &provisiong_timer_handler);
225     btstack_run_loop_set_timer(&prov_protocol_timer, PROVISIONING_PROTOCOL_TIMEOUT_MS);
226     btstack_run_loop_add_timer(&prov_protocol_timer);
227 }
228 
229 static void provisioning_timer_stop(void){
230     btstack_run_loop_remove_timer(&prov_protocol_timer);
231 }
232 
233 
234 // Outgoing Provisioning PDUs
235 static void provisioning_send_provisioning_error(void){
236     // setup response
237     prov_buffer_out[0] = MESH_PROV_FAILED;
238     prov_buffer_out[1] = prov_error_code;
239     pb_send_pdu(pb_transport_cid, prov_buffer_out, 2);
240 }
241 
242 static void provisioning_send_capabilites(void){
243     // setup response
244     prov_buffer_out[0] = MESH_PROV_CAPABILITIES;
245 
246     /* Number of Elements supported */
247     prov_buffer_out[1] = prov_num_elements;
248 
249     /* Supported algorithms - FIPS P-256 Eliptic Curve */
250     big_endian_store_16(prov_buffer_out, 2, 1);
251 
252     /* Public Key Type - Public Key OOB information available */
253     prov_buffer_out[4] = prov_public_key_oob_available;
254 
255     /* Static OOB Type - Static OOB information available */
256     prov_buffer_out[5] = prov_static_oob_available;
257 
258     /* Output OOB Size - max of 8 */
259     prov_buffer_out[6] = prov_output_oob_size;
260 
261     /* Output OOB Action */
262     big_endian_store_16(prov_buffer_out, 7, prov_output_oob_actions);
263 
264     /* Input OOB Size - max of 8*/
265     prov_buffer_out[9] = prov_input_oob_size;
266 
267     /* Input OOB Action */
268     big_endian_store_16(prov_buffer_out, 10, prov_input_oob_actions);
269 
270     // store for confirmation inputs: len 11
271     (void)memcpy(&prov_confirmation_inputs[1], &prov_buffer_out[1], 11);
272 
273     // send
274 
275     pb_send_pdu(pb_transport_cid, prov_buffer_out, 12);
276 }
277 
278 static void provisioning_send_public_key(void){
279     // setup response
280     prov_buffer_out[0] = MESH_PROV_PUB_KEY;
281     (void)memcpy(&prov_buffer_out[1], prov_ec_q, 64);
282 
283     // store for confirmation inputs: len 64
284     (void)memcpy(&prov_confirmation_inputs[81], &prov_buffer_out[1], 64);
285 
286     // send
287     pb_send_pdu(pb_transport_cid, prov_buffer_out, 65);
288 }
289 
290 static void provisioning_send_input_complete(void){
291     // setup response
292     prov_buffer_out[0] = MESH_PROV_INPUT_COMPLETE;
293 
294     // send
295     pb_send_pdu(pb_transport_cid, prov_buffer_out, 17);
296 }
297 static void provisioning_send_confirm(void){
298     // setup response
299     prov_buffer_out[0] = MESH_PROV_CONFIRM;
300     (void)memcpy(&prov_buffer_out[1], confirmation_device, 16);
301 
302     // send
303     pb_send_pdu(pb_transport_cid, prov_buffer_out, 17);
304 }
305 
306 static void provisioning_send_random(void){
307     // setup response
308     prov_buffer_out[0] = MESH_PROV_RANDOM;
309     (void)memcpy(&prov_buffer_out[1], random_device, 16);
310 
311     // send pdu
312     pb_send_pdu(pb_transport_cid, prov_buffer_out, 17);
313 }
314 
315 static void provisioning_send_complete(void){
316     // setup response
317     prov_buffer_out[0] = MESH_PROV_COMPLETE;
318 
319     // send pdu
320     pb_send_pdu(pb_transport_cid, prov_buffer_out, 1);
321 }
322 
323 static void provisioning_done(void){
324     if (prov_emit_public_key_oob_active){
325         prov_emit_public_key_oob_active = 0;
326         provisioning_emit_event(1, MESH_SUBEVENT_PB_PROV_STOP_EMIT_PUBLIC_KEY_OOB);
327     }
328     if (prov_emit_output_oob_active){
329         prov_emit_output_oob_active = 0;
330         provisioning_emit_event(1, MESH_SUBEVENT_PB_PROV_STOP_EMIT_OUTPUT_OOB);
331     }
332     if (prov_attention_timer_timeout){
333         prov_attention_timer_timeout = 0;
334         provisioning_emit_attention_timer_event(1, 0);
335     }
336     device_state = DEVICE_W4_INVITE;
337 
338     // generate new public key
339     printf("Generate new public key\n");
340     btstack_crypto_ecc_p256_generate_key(&prov_ecc_p256_request, prov_ec_q, &prov_key_generated, NULL);
341 }
342 
343 static void provisioning_handle_auth_value_output_oob(void * arg){
344     UNUSED(arg);
345     // limit auth value to single digit
346     auth_value[15] = auth_value[15] % 9 + 1;
347 
348     printf("Output OOB: %u\n", auth_value[15]);
349 
350     // emit output oob value
351     provisioning_emit_output_oob_event(1, auth_value[15]);
352     prov_emit_output_oob_active = 1;
353 }
354 
355 static void provisioning_public_key_exchange_complete(void){
356 
357     // reset auth_value
358     memset(auth_value, 0, sizeof(auth_value));
359 
360     // handle authentication method
361     switch (prov_authentication_method){
362         case 0x00:
363             device_state = DEVICE_W4_CONFIRM;
364             break;
365         case 0x01:
366             (void)memcpy(&auth_value[16 - prov_static_oob_len],
367                          prov_static_oob_data, prov_static_oob_len);
368             device_state = DEVICE_W4_CONFIRM;
369             break;
370         case 0x02:
371             device_state = DEVICE_W4_CONFIRM;
372             printf("Generate random for auth_value\n");
373             // generate single byte of random data to use for authentication
374             btstack_crypto_random_generate(&prov_random_request, &auth_value[15], 1, &provisioning_handle_auth_value_output_oob, NULL);
375             break;
376         case 0x03:
377             // Input OOB
378             printf("Input OOB requested\n");
379             provisioning_emit_event(1, MESH_SUBEVENT_PB_PROV_INPUT_OOB_REQUEST);
380             device_state = DEVICE_W4_INPUT_OOK;
381             break;
382         default:
383             break;
384     }
385 }
386 
387 static void provisioning_run(void){
388     printf("provisioning_run: state %x, wait for outgoing complete %u\n", device_state, prov_waiting_for_outgoing_complete);
389     if (prov_waiting_for_outgoing_complete) return;
390     int start_timer = 1;
391     switch (device_state){
392         case DEVICE_SEND_ERROR:
393             start_timer = 0;    // game over
394             device_state = DEVICE_W4_DONE;
395             prov_waiting_for_outgoing_complete = 1;
396             provisioning_send_provisioning_error();
397             break;
398         case DEVICE_SEND_CAPABILITIES:
399             device_state = DEVICE_W4_START;
400             prov_waiting_for_outgoing_complete = 1;
401             provisioning_send_capabilites();
402             break;
403         case DEVICE_SEND_INPUT_COMPLETE:
404             device_state = DEVICE_W4_CONFIRM;
405             prov_waiting_for_outgoing_complete = 1;
406             provisioning_send_input_complete();
407             break;
408         case DEVICE_SEND_PUB_KEY:
409             device_state = DEVICE_PUB_KEY_SENT;
410             prov_waiting_for_outgoing_complete = 1;
411             provisioning_send_public_key();
412             provisioning_public_key_exchange_complete();
413             break;
414         case DEVICE_SEND_CONFIRM:
415             device_state = DEVICE_W4_RANDOM;
416             prov_waiting_for_outgoing_complete = 1;
417             provisioning_send_confirm();
418             break;
419         case DEVICE_SEND_RANDOM:
420             device_state = DEVICE_W4_DATA;
421             prov_waiting_for_outgoing_complete = 1;
422             provisioning_send_random();
423             break;
424         case DEVICE_SEND_COMPLETE:
425             start_timer = 0;    // last message
426             device_state = DEVICE_W4_DONE;
427             prov_waiting_for_outgoing_complete = 1;
428             provisioning_send_complete();
429             break;
430         default:
431             return;
432     }
433     if (start_timer){
434         provisioning_timer_start();
435     }
436 }
437 
438 static void provisioning_handle_provisioning_error(uint8_t error_code){
439     printf("PROVISIONING ERROR\n");
440     provisioning_timer_stop();
441     prov_error_code = error_code;
442     device_state = DEVICE_SEND_ERROR;
443     provisioning_run();
444 }
445 
446 static void provisioning_handle_invite(uint8_t *packet, uint16_t size){
447 
448     if (size != 1) return;
449 
450     // store for confirmation inputs: len 1
451     (void)memcpy(&prov_confirmation_inputs[0], packet, 1);
452 
453     // handle invite message
454     prov_attention_timer_timeout = packet[0];
455     if (prov_attention_timer_timeout){
456         provisioning_emit_attention_timer_event(pb_transport_cid, prov_attention_timer_timeout);
457     }
458 
459     device_state = DEVICE_SEND_CAPABILITIES;
460     provisioning_run();
461 }
462 
463 static void provisioning_handle_start(uint8_t * packet, uint16_t size){
464 
465     if (size != 5) return;
466 
467     // validate Algorithm
468     int ok = 1;
469     if (packet[0] > 0x00){
470         ok = 0;
471     }
472     // validate Publik Key
473     if (packet[1] > 0x01){
474         ok = 0;
475     }
476     // validate Authentication Method
477     switch (packet[2]){
478         case 0:
479         case 1:
480             if (packet[3] != 0 || packet[4] != 0){
481                 ok = 0;
482                 break;
483             }
484             break;
485         case 2:
486             if (packet[3] > 0x04 || packet[4] == 0 || packet[4] > 0x08){
487                 ok = 0;
488                 break;
489             }
490             break;
491         case 3:
492             if (packet[3] > 0x03 || packet[4] == 0 || packet[4] > 0x08){
493                 ok = 0;
494                 break;
495             }
496             break;
497         default:
498             // TODO check
499             break;
500     }
501     if (!ok){
502         printf("PROV_START arguments incorrect\n");
503         provisioning_handle_provisioning_error(0x02);
504         return;
505     }
506 
507     // store for confirmation inputs: len 5
508     (void)memcpy(&prov_confirmation_inputs[12], packet, 5);
509 
510     // public key oob
511     prov_public_key_oob_used = packet[1];
512 
513     // authentication method
514     prov_authentication_method = packet[2];
515 
516     // start emit public OOK if specified
517     if (prov_public_key_oob_available && prov_public_key_oob_used){
518         provisioning_emit_event(1, MESH_SUBEVENT_PB_PROV_START_EMIT_PUBLIC_KEY_OOB);
519     }
520 
521     printf("PublicKey:  %02x\n", prov_public_key_oob_used);
522     printf("AuthMethod: %02x\n", prov_authentication_method);
523 
524     device_state = DEVICE_W4_PUB_KEY;
525     provisioning_run();
526 }
527 
528 static void provisioning_handle_public_key_dhkey(void * arg){
529     UNUSED(arg);
530 
531     printf("DHKEY: ");
532     printf_hexdump(dhkey, sizeof(dhkey));
533 
534     // skip sending own public key when public key oob is used
535     if (prov_public_key_oob_available && prov_public_key_oob_used){
536         // just copy key for confirmation inputs
537         (void)memcpy(&prov_confirmation_inputs[81], prov_ec_q, 64);
538         provisioning_public_key_exchange_complete();
539     } else {
540         // queue public key pdu
541         printf("DEVICE_SEND_PUB_KEY\n");
542         device_state = DEVICE_SEND_PUB_KEY;
543     }
544     provisioning_run();
545 }
546 
547 static void provisioning_handle_public_key(uint8_t *packet, uint16_t size){
548 
549     // validate public key
550     if (size != sizeof(remote_ec_q) || btstack_crypto_ecc_p256_validate_public_key(packet) != 0){
551         printf("Public Key invalid, abort provisioning\n");
552         provisioning_handle_provisioning_error(0x07);   // Unexpected Error
553         return;
554     }
555 
556     // stop emit public OOK if specified and send to crypto module
557     if (prov_public_key_oob_available && prov_public_key_oob_used){
558         provisioning_emit_event(1, MESH_SUBEVENT_PB_PROV_STOP_EMIT_PUBLIC_KEY_OOB);
559 
560         printf("Replace generated ECC with Public Key OOB:");
561         (void)memcpy(prov_ec_q, prov_public_key_oob_q, 64);
562         printf_hexdump(prov_ec_q, sizeof(prov_ec_q));
563         btstack_crypto_ecc_p256_set_key(prov_public_key_oob_q, prov_public_key_oob_d);
564     }
565 
566     // store for confirmation inputs: len 64
567     (void)memcpy(&prov_confirmation_inputs[17], packet, 64);
568 
569     // store remote q
570     (void)memcpy(remote_ec_q, packet, sizeof(remote_ec_q));
571 
572     // calculate DHKey
573     btstack_crypto_ecc_p256_calculate_dhkey(&prov_ecc_p256_request, remote_ec_q, dhkey, provisioning_handle_public_key_dhkey, NULL);
574 }
575 
576 static void provisioning_handle_confirmation_device_calculated(void * arg){
577     UNUSED(arg);
578 
579     printf("ConfirmationDevice: ");
580     printf_hexdump(confirmation_device, sizeof(confirmation_device));
581 
582     device_state = DEVICE_SEND_CONFIRM;
583     provisioning_run();
584 }
585 
586 static void provisioning_handle_confirmation_random_device(void * arg){
587     UNUSED(arg);
588 
589     // re-use prov_confirmation_inputs buffer
590     (void)memcpy(&prov_confirmation_inputs[0], random_device, 16);
591     (void)memcpy(&prov_confirmation_inputs[16], auth_value, 16);
592 
593     // calc confirmation device
594     btstack_crypto_aes128_cmac_message(&prov_cmac_request, confirmation_key, 32, prov_confirmation_inputs, confirmation_device, &provisioning_handle_confirmation_device_calculated, NULL);
595 }
596 
597 static void provisioning_handle_confirmation_k1_calculated(void * arg){
598     UNUSED(arg);
599 
600     printf("ConfirmationKey:   ");
601     printf_hexdump(confirmation_key, sizeof(confirmation_key));
602 
603     printf("AuthValue: ");
604     printf_hexdump(auth_value, 16);
605 
606     // generate random_device
607     btstack_crypto_random_generate(&prov_random_request,random_device, 16, &provisioning_handle_confirmation_random_device, NULL);
608 }
609 
610 static void provisioning_handle_confirmation_s1_calculated(void * arg){
611     UNUSED(arg);
612 
613     // ConfirmationSalt
614     printf("ConfirmationSalt:   ");
615     printf_hexdump(confirmation_salt, sizeof(confirmation_salt));
616 
617     // ConfirmationKey
618     mesh_k1(&prov_cmac_request, dhkey, sizeof(dhkey), confirmation_salt, (const uint8_t*) "prck", 4, confirmation_key, &provisioning_handle_confirmation_k1_calculated, NULL);
619 }
620 
621 static void provisioning_handle_confirmation(uint8_t *packet, uint16_t size){
622     UNUSED(size);
623     UNUSED(packet);
624 
625     //
626     if (prov_emit_output_oob_active){
627         prov_emit_output_oob_active = 0;
628         provisioning_emit_event(1, MESH_SUBEVENT_PB_PROV_STOP_EMIT_OUTPUT_OOB);
629     }
630 
631     // CalculationInputs
632     printf("ConfirmationInputs: ");
633     printf_hexdump(prov_confirmation_inputs, sizeof(prov_confirmation_inputs));
634 
635     // calculate s1
636     btstack_crypto_aes128_cmac_zero(&prov_cmac_request, sizeof(prov_confirmation_inputs), prov_confirmation_inputs, confirmation_salt, &provisioning_handle_confirmation_s1_calculated, NULL);
637 }
638 
639 // PROV_RANDOM
640 static void provisioning_handle_random_session_nonce_calculated(void * arg){
641     UNUSED(arg);
642 
643     // The nonce shall be the 13 least significant octets == zero most significant octets
644     uint8_t temp[13];
645     (void)memcpy(temp, &session_nonce[3], 13);
646     (void)memcpy(session_nonce, temp, 13);
647 
648     // SessionNonce
649     printf("SessionNonce:   ");
650     printf_hexdump(session_nonce, 13);
651 
652     device_state = DEVICE_SEND_RANDOM;
653     provisioning_run();
654 }
655 
656 static void provisioning_handle_random_session_key_calculated(void * arg){
657     UNUSED(arg);
658 
659     // SessionKey
660     printf("SessionKey:   ");
661     printf_hexdump(session_key, sizeof(session_key));
662 
663     // SessionNonce
664     mesh_k1(&prov_cmac_request, dhkey, sizeof(dhkey), provisioning_salt, (const uint8_t*) "prsn", 4, session_nonce, &provisioning_handle_random_session_nonce_calculated, NULL);
665 }
666 
667 static void provisioning_handle_random_s1_calculated(void * arg){
668 
669     UNUSED(arg);
670 
671     // ProvisioningSalt
672     printf("ProvisioningSalt:   ");
673     printf_hexdump(provisioning_salt, sizeof(provisioning_salt));
674 
675     // SessionKey
676     mesh_k1(&prov_cmac_request, dhkey, sizeof(dhkey), provisioning_salt, (const uint8_t*) "prsk", 4, session_key, &provisioning_handle_random_session_key_calculated, NULL);
677 }
678 
679 static void provisioning_handle_random(uint8_t *packet, uint16_t size){
680 
681     UNUSED(size);
682     UNUSED(packet);
683 
684     // TODO: validate Confirmation
685 
686     // calc ProvisioningSalt = s1(ConfirmationSalt || RandomProvisioner || RandomDevice)
687     (void)memcpy(&prov_confirmation_inputs[0], confirmation_salt, 16);
688     (void)memcpy(&prov_confirmation_inputs[16], packet, 16);
689     (void)memcpy(&prov_confirmation_inputs[32], random_device, 16);
690     btstack_crypto_aes128_cmac_zero(&prov_cmac_request, 48, prov_confirmation_inputs, provisioning_salt, &provisioning_handle_random_s1_calculated, NULL);
691 }
692 
693 // PROV_DATA
694 static void provisioning_handle_network_dervived(void * arg){
695     UNUSED(arg);
696 
697     provisioning_timer_stop();
698 
699     // notify client
700     provisioning_emit_event(1, MESH_SUBEVENT_PB_PROV_COMPLETE);
701 
702     device_state = DEVICE_SEND_COMPLETE;
703     provisioning_run();
704 
705 }
706 
707 static void provisioning_handle_data_device_key(void * arg){
708     UNUSED(arg);
709 
710     // derive full network key
711     mesh_network_key_derive(&prov_cmac_request, network_key, &provisioning_handle_network_dervived, NULL);
712 }
713 
714 static void provisioning_handle_data_ccm(void * arg){
715 
716     UNUSED(arg);
717 
718     // TODO: validate MIC?
719     uint8_t mic[8];
720     btstack_crypto_ccm_get_authentication_value(&prov_ccm_request, mic);
721     printf("MIC: ");
722     printf_hexdump(mic, 8);
723 
724     // allocate network key
725     network_key = btstack_memory_mesh_network_key_get();
726 
727     // sort provisoning data
728     (void)memcpy(network_key->net_key, provisioning_data, 16);
729     network_key->netkey_index = big_endian_read_16(provisioning_data, 16);
730     // assume free index available for very first network key
731     network_key->internal_index = mesh_network_key_get_free_index();
732     flags = provisioning_data[18];
733     iv_index = big_endian_read_32(provisioning_data, 19);
734     unicast_address = big_endian_read_16(provisioning_data, 23);
735 
736     // DeviceKey
737     mesh_k1(&prov_cmac_request, dhkey, sizeof(dhkey), provisioning_salt, (const uint8_t*) "prdk", 4, device_key, &provisioning_handle_data_device_key, NULL);
738 }
739 
740 static void provisioning_handle_data(uint8_t *packet, uint16_t size){
741 
742     UNUSED(size);
743 
744     (void)memcpy(enc_provisioning_data, packet, 25);
745 
746     // decode response
747     btstack_crypto_ccm_init(&prov_ccm_request, session_key, session_nonce, 25, 0, 8);
748     btstack_crypto_ccm_decrypt_block(&prov_ccm_request, 25, enc_provisioning_data, provisioning_data, &provisioning_handle_data_ccm, NULL);
749 }
750 
751 static void provisioning_handle_unexpected_pdu(uint8_t *packet, uint16_t size){
752     UNUSED(size);
753     printf("Unexpected PDU #%u in state #%u\n", packet[0], (int) device_state);
754     provisioning_handle_provisioning_error(0x03);
755 }
756 
757 static void provisioning_handle_pdu(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
758     UNUSED(channel);
759 
760     if (size < 1) return;
761 
762     switch (packet_type){
763         case HCI_EVENT_PACKET:
764 
765             if (hci_event_packet_get_type(packet) != HCI_EVENT_MESH_META)  break;
766 
767             switch (hci_event_mesh_meta_get_subevent_code(packet)){
768                 case MESH_SUBEVENT_PB_TRANSPORT_LINK_OPEN:
769                     pb_transport_cid = mesh_subevent_pb_transport_link_open_get_pb_transport_cid(packet);
770                     pb_type = mesh_subevent_pb_transport_link_open_get_pb_type(packet);
771                     printf("Link opened, reset state, transport cid 0x%02x, PB type %d\n", pb_transport_cid, pb_type);
772                     provisioning_done();
773                     break;
774                 case MESH_SUBEVENT_PB_TRANSPORT_PDU_SENT:
775                     printf("Outgoing packet acked\n");
776                     prov_waiting_for_outgoing_complete = 0;
777                     if (device_state == DEVICE_W4_DONE){
778                         pb_close_link(1, 0);
779                         provisioning_done();
780                     }
781                     break;
782                 case MESH_SUBEVENT_PB_TRANSPORT_LINK_CLOSED:
783                     printf("Link close, reset state\n");
784                     pb_transport_cid = MESH_PB_TRANSPORT_INVALID_CID;
785                     provisioning_done();
786                     break;
787                 default:
788                     break;
789             }
790             break;
791         case PROVISIONING_DATA_PACKET:
792             // check state
793             switch (device_state){
794                 case DEVICE_W4_INVITE:
795                     if (packet[0] != MESH_PROV_INVITE) provisioning_handle_unexpected_pdu(packet, size);
796                     printf("MESH_PROV_INVITE: ");
797                     printf_hexdump(&packet[1], size-1);
798                     provisioning_handle_invite(&packet[1], size-1);
799                     break;
800                 case DEVICE_W4_START:
801                     if (packet[0] != MESH_PROV_START) provisioning_handle_unexpected_pdu(packet, size);
802                     printf("MESH_PROV_START:  ");
803                     printf_hexdump(&packet[1], size-1);
804                     provisioning_handle_start(&packet[1], size-1);
805                     break;
806                 case DEVICE_W4_PUB_KEY:
807                     if (packet[0] != MESH_PROV_PUB_KEY) provisioning_handle_unexpected_pdu(packet, size);
808                     printf("MESH_PROV_PUB_KEY: ");
809                     printf_hexdump(&packet[1], size-1);
810                     provisioning_handle_public_key(&packet[1], size-1);
811                     break;
812                 case DEVICE_W4_CONFIRM:
813                     if (packet[0] != MESH_PROV_CONFIRM) provisioning_handle_unexpected_pdu(packet, size);
814                     printf("MESH_PROV_CONFIRM: ");
815                     printf_hexdump(&packet[1], size-1);
816                     provisioning_handle_confirmation(&packet[1], size-1);
817                     break;
818                 case DEVICE_W4_RANDOM:
819                     if (packet[0] != MESH_PROV_RANDOM) provisioning_handle_unexpected_pdu(packet, size);
820                     printf("MESH_PROV_RANDOM:  ");
821                     printf_hexdump(&packet[1], size-1);
822                     provisioning_handle_random(&packet[1], size-1);
823                     break;
824                 case DEVICE_W4_DATA:
825                     if (packet[0] != MESH_PROV_DATA) provisioning_handle_unexpected_pdu(packet, size);
826                     printf("MESH_PROV_DATA:  ");
827                     provisioning_handle_data(&packet[1], size-1);
828                     break;
829                 default:
830                     break;
831             }
832             break;
833         default:
834             break;
835     }
836     provisioning_run();
837 }
838 
839 static void prov_key_generated(void * arg){
840     UNUSED(arg);
841     printf("ECC-P256: ");
842     printf_hexdump(prov_ec_q, sizeof(prov_ec_q));
843     // allow override
844     if (prov_public_key_oob_available){
845         printf("Replace generated ECC with Public Key OOB:");
846         (void)memcpy(prov_ec_q, prov_public_key_oob_q, 64);
847         printf_hexdump(prov_ec_q, sizeof(prov_ec_q));
848         btstack_crypto_ecc_p256_set_key(prov_public_key_oob_q, prov_public_key_oob_d);
849     }
850 }
851 
852 void provisioning_device_init(void){
853 #ifdef ENABLE_MESH_ADV_BEARER
854     // setup PB ADV
855     pb_adv_init();
856     pb_adv_register_device_packet_handler(&provisioning_handle_pdu);
857 #endif
858 #ifdef ENABLE_MESH_GATT_BEARER
859     // setup PB GATT
860     pb_gatt_init();
861     pb_gatt_register_packet_handler(&provisioning_handle_pdu);
862 #endif
863 
864     pb_transport_cid = MESH_PB_TRANSPORT_INVALID_CID;
865 
866     // init provisioning state and generate ecc key
867     provisioning_done();
868 }
869 
870 void provisioning_device_register_packet_handler(btstack_packet_handler_t packet_handler){
871     prov_packet_handler = packet_handler;
872 }
873 
874 void provisioning_device_set_public_key_oob(const uint8_t * public_key, const uint8_t * private_key){
875     prov_public_key_oob_q = public_key;
876     prov_public_key_oob_d = private_key;
877     prov_public_key_oob_available = 1;
878     btstack_crypto_ecc_p256_set_key(prov_public_key_oob_q, prov_public_key_oob_d);
879 }
880 
881 void provisioning_device_set_static_oob(uint16_t static_oob_len, const uint8_t * static_oob_data){
882     prov_static_oob_available = 1;
883     prov_static_oob_data = static_oob_data;
884     prov_static_oob_len  = btstack_min(static_oob_len, 16);
885 }
886 
887 void provisioning_device_set_output_oob_actions(uint16_t supported_output_oob_action_types, uint8_t max_oob_output_size){
888     prov_output_oob_actions = supported_output_oob_action_types;
889     prov_output_oob_size    = max_oob_output_size;
890 }
891 
892 void provisioning_device_set_input_oob_actions(uint16_t supported_input_oob_action_types, uint8_t max_oob_input_size){
893     prov_input_oob_actions = supported_input_oob_action_types;
894     prov_input_oob_size    = max_oob_input_size;
895 }
896 
897 void provisioning_device_input_oob_complete_numeric(uint16_t pb_adv_cid, uint32_t input_oob){
898     UNUSED(pb_adv_cid);
899     if (device_state != DEVICE_W4_INPUT_OOK) return;
900 
901     // store input_oob as auth value
902     big_endian_store_32(auth_value, 12, input_oob);
903     device_state = DEVICE_SEND_INPUT_COMPLETE;
904     provisioning_run();
905 }
906 
907 void provisioning_device_input_oob_complete_alphanumeric(uint16_t pb_adv_cid, const uint8_t * input_oob_data, uint16_t input_oob_len){
908     UNUSED(pb_adv_cid);
909     if (device_state != DEVICE_W4_INPUT_OOK) return;
910 
911     // store input_oob and fillup with zeros
912     input_oob_len = btstack_min(input_oob_len, 16);
913     memset(auth_value, 0, 16);
914     (void)memcpy(auth_value, input_oob_data, input_oob_len);
915     device_state = DEVICE_SEND_INPUT_COMPLETE;
916     provisioning_run();
917 }
918 
919 void provisioning_device_data_get(mesh_provisioning_data_t * the_provisioning_data){
920     the_provisioning_data->unicast_address = unicast_address;
921     the_provisioning_data->iv_index = iv_index;
922     the_provisioning_data->flags = flags;
923     (void)memcpy(the_provisioning_data->device_key, device_key, 16);
924     the_provisioning_data->network_key = network_key;
925 }
926