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