xref: /btstack/src/mesh/provisioning_device.c (revision f4854a5efbe174cdf16fcaf3de7491781eef80ab)
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 #include "classic/rfcomm.h" // for crc8
48 
49 #include "mesh/mesh_crypto.h"
50 #include "mesh/pb_adv.h"
51 #include "mesh/pb_gatt.h"
52 #include "mesh/provisioning.h"
53 
54 static void provisioning_attention_timer_set(void);
55 static void prov_key_generated(void * arg);
56 
57 // remote ecc
58 static uint8_t remote_ec_q[64];
59 static uint8_t dhkey[32];
60 
61 static btstack_packet_handler_t prov_packet_handler;
62 
63 static uint8_t  prov_buffer_out[MESH_PROV_MAX_PROXY_PDU];
64 // ConfirmationInputs = ProvisioningInvitePDUValue || ProvisioningCapabilitiesPDUValue || ProvisioningStartPDUValue || PublicKeyProvisioner || PublicKeyDevice
65 static uint8_t  prov_confirmation_inputs[1 + 11 + 5 + 64 + 64];
66 static uint8_t  prov_authentication_method;
67 static uint8_t  prov_public_key_oob_used;
68 static uint8_t  prov_emit_public_key_oob_active;
69 static uint8_t  prov_emit_output_oob_active;
70 static uint8_t  prov_ec_q[64];
71 
72 static const uint8_t * prov_public_key_oob_q;
73 static const uint8_t * prov_public_key_oob_d;
74 
75 // num elements
76 static uint8_t  prov_num_elements = 1;
77 
78 // capabilites
79 static const uint8_t * prov_static_oob_data;
80 
81 static uint16_t  prov_static_oob_len;
82 static uint16_t  prov_output_oob_actions;
83 static uint16_t  prov_input_oob_actions;
84 static uint8_t   prov_public_key_oob_available;
85 static uint8_t   prov_static_oob_available;
86 static uint8_t   prov_output_oob_size;
87 static uint8_t   prov_input_oob_size;
88 static uint8_t   prov_error_code;
89 static uint8_t   prov_waiting_for_outgoing_complete;
90 
91 static uint8_t                      prov_attention_timer_timeout;
92 static btstack_timer_source_t       prov_attention_timer;
93 
94 static btstack_timer_source_t       prov_protocol_timer;
95 
96 static btstack_crypto_aes128_cmac_t prov_cmac_request;
97 static btstack_crypto_random_t      prov_random_request;
98 static btstack_crypto_ecc_p256_t    prov_ecc_p256_request;
99 static btstack_crypto_ccm_t         prov_ccm_request;
100 
101 // ConfirmationDevice
102 static uint8_t confirmation_device[16];
103 // ConfirmationSalt
104 static uint8_t confirmation_salt[16];
105 // ConfirmationKey
106 static uint8_t confirmation_key[16];
107 // RandomDevice
108 static uint8_t random_device[16];
109 // ProvisioningSalt
110 static uint8_t provisioning_salt[16];
111 // AuthValue
112 static uint8_t auth_value[16];
113 // SessionKey
114 static uint8_t session_key[16];
115 // SessionNonce
116 static uint8_t session_nonce[16];
117 // EncProvisioningData
118 static uint8_t enc_provisioning_data[25];
119 // ProvisioningData
120 static uint8_t provisioning_data[25];
121 
122 // received network_key
123 static mesh_network_key_t * network_key;
124 
125 // DeviceKey
126 static uint8_t device_key[16];
127 
128 static uint8_t  flags;
129 
130 static uint32_t iv_index;
131 static uint16_t unicast_address;
132 
133 typedef enum {
134     DEVICE_W4_INVITE,
135     DEVICE_SEND_CAPABILITIES,
136     DEVICE_W4_START,
137     DEVICE_W4_INPUT_OOK,
138     DEVICE_SEND_INPUT_COMPLETE,
139     DEVICE_W4_PUB_KEY,
140     DEVICE_SEND_PUB_KEY,
141     DEVICE_W4_CONFIRM,
142     DEVICE_SEND_CONFIRM,
143     DEVICE_W4_RANDOM,
144     DEVICE_SEND_RANDOM,
145     DEVICE_W4_DATA,
146     DEVICE_SEND_COMPLETE,
147     DEVICE_SEND_ERROR,
148 } device_state_t;
149 
150 static device_state_t device_state;
151 static uint16_t pb_transport_cid;
152 static pb_type_t pb_type;
153 
154 static void pb_send_pdu(uint16_t transport_cid, const uint8_t * buffer, uint16_t buffer_size){
155     switch (pb_type){
156         case PB_TYPE_ADV:
157             pb_adv_send_pdu(transport_cid, buffer, buffer_size);
158             break;
159         case PB_TYPE_GATT:
160             pb_gatt_send_pdu(transport_cid, buffer, buffer_size);
161             break;
162     }
163 }
164 
165 static void pb_close_link(uint16_t transport_cid, uint8_t reason){
166     switch (pb_type){
167         case PB_TYPE_ADV:
168             pb_adv_close_link(transport_cid, reason);
169             break;
170         case PB_TYPE_GATT:
171             pb_gatt_close_link(transport_cid, reason);
172             break;
173     }
174 }
175 
176 static void provisioning_emit_event(uint16_t pb_adv_cid, uint8_t mesh_subevent){
177     if (!prov_packet_handler) return;
178     uint8_t event[5] = { HCI_EVENT_MESH_META, 3, mesh_subevent};
179     little_endian_store_16(event, 3, pb_adv_cid);
180     prov_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
181 }
182 
183 static void provisioning_emit_output_oob_event(uint16_t pb_adv_cid, uint32_t number){
184     if (!prov_packet_handler) return;
185     uint8_t event[9] = { HCI_EVENT_MESH_META, 7, MESH_SUBEVENT_PB_PROV_START_EMIT_OUTPUT_OOB};
186     little_endian_store_16(event, 3, pb_adv_cid);
187     little_endian_store_16(event, 5, number);
188     prov_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
189 }
190 
191 static void provisioning_emit_attention_timer_event(uint16_t pb_adv_cid, uint8_t timer_s){
192     if (!prov_packet_handler) return;
193     uint8_t event[4] = { HCI_EVENT_MESH_META, 7, MESH_SUBEVENT_PB_PROV_ATTENTION_TIMER};
194     event[3] = timer_s;
195     prov_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
196 }
197 
198 static void provisiong_timer_handler(btstack_timer_source_t * ts){
199     UNUSED(ts);
200     printf("Provisioning Protocol Timeout -> Close Link!\n");
201     pb_close_link(1, 1);
202 }
203 
204 // The provisioning protocol shall have a minimum timeout of 60 seconds that is reset
205 // each time a provisioning protocol PDU is sent or received
206 static void provisioning_timer_start(void){
207     btstack_run_loop_remove_timer(&prov_protocol_timer);
208     btstack_run_loop_set_timer_handler(&prov_protocol_timer, &provisiong_timer_handler);
209     btstack_run_loop_set_timer(&prov_protocol_timer, PROVISIONING_PROTOCOL_TIMEOUT_MS);
210     btstack_run_loop_add_timer(&prov_protocol_timer);
211 }
212 
213 static void provisioning_timer_stop(void){
214     btstack_run_loop_remove_timer(&prov_protocol_timer);
215 }
216 
217 static void provisioning_attention_timer_timeout(btstack_timer_source_t * ts){
218     UNUSED(ts);
219     if (prov_attention_timer_timeout == 0) return;
220     prov_attention_timer_timeout--;
221     provisioning_attention_timer_set();
222 }
223 
224 static void provisioning_attention_timer_set(void){
225     provisioning_emit_attention_timer_event(1, prov_attention_timer_timeout);
226     if (prov_attention_timer_timeout){
227         btstack_run_loop_set_timer_handler(&prov_attention_timer, &provisioning_attention_timer_timeout);
228         btstack_run_loop_set_timer(&prov_attention_timer, 1000);
229         btstack_run_loop_add_timer(&prov_attention_timer);
230     }
231 }
232 
233 // Outgoing Provisioning PDUs
234 static void provisioning_send_provisioning_error(void){
235     // setup response
236     prov_buffer_out[0] = MESH_PROV_FAILED;
237     prov_buffer_out[1] = prov_error_code;
238     pb_send_pdu(pb_transport_cid, prov_buffer_out, 2);
239 }
240 
241 static void provisioning_send_capabilites(void){
242     // setup response
243     prov_buffer_out[0] = MESH_PROV_CAPABILITIES;
244 
245     /* Number of Elements supported */
246     prov_buffer_out[1] = prov_num_elements;
247 
248     /* Supported algorithms - FIPS P-256 Eliptic Curve */
249     big_endian_store_16(prov_buffer_out, 2, 1);
250 
251     /* Public Key Type - Public Key OOB information available */
252     prov_buffer_out[4] = prov_public_key_oob_available;
253 
254     /* Static OOB Type - Static OOB information available */
255     prov_buffer_out[5] = prov_static_oob_available;
256 
257     /* Output OOB Size - max of 8 */
258     prov_buffer_out[6] = prov_output_oob_size;
259 
260     /* Output OOB Action */
261     big_endian_store_16(prov_buffer_out, 7, prov_output_oob_actions);
262 
263     /* Input OOB Size - max of 8*/
264     prov_buffer_out[9] = prov_input_oob_size;
265 
266     /* Input OOB Action */
267     big_endian_store_16(prov_buffer_out, 10, prov_input_oob_actions);
268 
269     // store for confirmation inputs: len 11
270     memcpy(&prov_confirmation_inputs[1], &prov_buffer_out[1], 11);
271 
272     // send
273 
274     pb_send_pdu(pb_transport_cid, prov_buffer_out, 12);
275 }
276 
277 static void provisioning_send_public_key(void){
278     // setup response
279     prov_buffer_out[0] = MESH_PROV_PUB_KEY;
280     memcpy(&prov_buffer_out[1], prov_ec_q, 64);
281 
282     // store for confirmation inputs: len 64
283     memcpy(&prov_confirmation_inputs[81], &prov_buffer_out[1], 64);
284 
285     // send
286     pb_send_pdu(pb_transport_cid, prov_buffer_out, 65);
287 }
288 
289 static void provisioning_send_input_complete(void){
290     // setup response
291     prov_buffer_out[0] = MESH_PROV_INPUT_COMPLETE;
292 
293     // send
294     pb_send_pdu(pb_transport_cid, prov_buffer_out, 17);
295 }
296 static void provisioning_send_confirm(void){
297     // setup response
298     prov_buffer_out[0] = MESH_PROV_CONFIRM;
299     memcpy(&prov_buffer_out[1], confirmation_device, 16);
300 
301     // send
302     pb_send_pdu(pb_transport_cid, prov_buffer_out, 17);
303 }
304 
305 static void provisioning_send_random(void){
306     // setup response
307     prov_buffer_out[0] = MESH_PROV_RANDOM;
308     memcpy(&prov_buffer_out[1],  random_device, 16);
309 
310     // send pdu
311     pb_send_pdu(pb_transport_cid, prov_buffer_out, 17);
312 }
313 
314 static void provisioning_send_complete(void){
315     // setup response
316     prov_buffer_out[0] = MESH_PROV_COMPLETE;
317 
318     // send pdu
319     pb_send_pdu(pb_transport_cid, prov_buffer_out, 1);
320 }
321 
322 static void provisioning_done(void){
323     if (prov_emit_public_key_oob_active){
324         prov_emit_public_key_oob_active = 0;
325         provisioning_emit_event(1, MESH_SUBEVENT_PB_PROV_STOP_EMIT_PUBLIC_KEY_OOB);
326     }
327     if (prov_emit_output_oob_active){
328         prov_emit_output_oob_active = 0;
329         provisioning_emit_event(1, MESH_SUBEVENT_PB_PROV_STOP_EMIT_OUTPUT_OOB);
330     }
331     if (prov_attention_timer_timeout){
332         prov_attention_timer_timeout = 0;
333         provisioning_emit_attention_timer_event(1, 0);
334     }
335     device_state = DEVICE_W4_INVITE;
336 
337     // generate new public key
338     printf("Generate new public key\n");
339     btstack_crypto_ecc_p256_generate_key(&prov_ecc_p256_request, prov_ec_q, &prov_key_generated, NULL);
340 }
341 
342 static void provisioning_handle_auth_value_output_oob(void * 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 
569     UNUSED(arg);
570 
571     printf("ConfirmationDevice: ");
572     printf_hexdump(confirmation_device, sizeof(confirmation_device));
573 
574     device_state = DEVICE_SEND_CONFIRM;
575     provisioning_run();
576 }
577 
578 static void provisioning_handle_confirmation_random_device(void * arg){
579     // re-use prov_confirmation_inputs buffer
580     memcpy(&prov_confirmation_inputs[0],  random_device, 16);
581     memcpy(&prov_confirmation_inputs[16], auth_value, 16);
582 
583     // calc confirmation device
584     btstack_crypto_aes128_cmac_message(&prov_cmac_request, confirmation_key, 32, prov_confirmation_inputs, confirmation_device, &provisioning_handle_confirmation_device_calculated, NULL);
585 }
586 
587 static void provisioning_handle_confirmation_k1_calculated(void * arg){
588     printf("ConfirmationKey:   ");
589     printf_hexdump(confirmation_key, sizeof(confirmation_key));
590 
591     printf("AuthValue: ");
592     printf_hexdump(auth_value, 16);
593 
594     // generate random_device
595     btstack_crypto_random_generate(&prov_random_request,random_device, 16, &provisioning_handle_confirmation_random_device, NULL);
596 }
597 
598 static void provisioning_handle_confirmation_s1_calculated(void * arg){
599     UNUSED(arg);
600 
601     // ConfirmationSalt
602     printf("ConfirmationSalt:   ");
603     printf_hexdump(confirmation_salt, sizeof(confirmation_salt));
604 
605     // ConfirmationKey
606     mesh_k1(&prov_cmac_request, dhkey, sizeof(dhkey), confirmation_salt, (const uint8_t*) "prck", 4, confirmation_key, &provisioning_handle_confirmation_k1_calculated, NULL);
607 }
608 
609 static void provisioning_handle_confirmation(uint8_t *packet, uint16_t size){
610 
611     UNUSED(size);
612     UNUSED(packet);
613 
614     //
615     if (prov_emit_output_oob_active){
616         prov_emit_output_oob_active = 0;
617         provisioning_emit_event(1, MESH_SUBEVENT_PB_PROV_STOP_EMIT_OUTPUT_OOB);
618     }
619 
620     // CalculationInputs
621     printf("ConfirmationInputs: ");
622     printf_hexdump(prov_confirmation_inputs, sizeof(prov_confirmation_inputs));
623 
624     // calculate s1
625     btstack_crypto_aes128_cmac_zero(&prov_cmac_request, sizeof(prov_confirmation_inputs), prov_confirmation_inputs, confirmation_salt, &provisioning_handle_confirmation_s1_calculated, NULL);
626 }
627 
628 // PROV_RANDOM
629 static void provisioning_handle_random_session_nonce_calculated(void * arg){
630     UNUSED(arg);
631 
632     // The nonce shall be the 13 least significant octets == zero most significant octets
633     uint8_t temp[13];
634     memcpy(temp, &session_nonce[3], 13);
635     memcpy(session_nonce, temp, 13);
636 
637     // SessionNonce
638     printf("SessionNonce:   ");
639     printf_hexdump(session_nonce, 13);
640 
641     device_state = DEVICE_SEND_RANDOM;
642     provisioning_run();
643 }
644 
645 static void provisioning_handle_random_session_key_calculated(void * arg){
646     UNUSED(arg);
647 
648     // SessionKey
649     printf("SessionKey:   ");
650     printf_hexdump(session_key, sizeof(session_key));
651 
652     // SessionNonce
653     mesh_k1(&prov_cmac_request, dhkey, sizeof(dhkey), provisioning_salt, (const uint8_t*) "prsn", 4, session_nonce, &provisioning_handle_random_session_nonce_calculated, NULL);
654 }
655 
656 static void provisioning_handle_random_s1_calculated(void * arg){
657 
658     UNUSED(arg);
659 
660     // ProvisioningSalt
661     printf("ProvisioningSalt:   ");
662     printf_hexdump(provisioning_salt, sizeof(provisioning_salt));
663 
664     // SessionKey
665     mesh_k1(&prov_cmac_request, dhkey, sizeof(dhkey), provisioning_salt, (const uint8_t*) "prsk", 4, session_key, &provisioning_handle_random_session_key_calculated, NULL);
666 }
667 
668 static void provisioning_handle_random(uint8_t *packet, uint16_t size){
669 
670     UNUSED(size);
671     UNUSED(packet);
672 
673     // TODO: validate Confirmation
674 
675     // calc ProvisioningSalt = s1(ConfirmationSalt || RandomProvisioner || RandomDevice)
676     memcpy(&prov_confirmation_inputs[0], confirmation_salt, 16);
677     memcpy(&prov_confirmation_inputs[16], packet, 16);
678     memcpy(&prov_confirmation_inputs[32], random_device, 16);
679     btstack_crypto_aes128_cmac_zero(&prov_cmac_request, 48, prov_confirmation_inputs, provisioning_salt, &provisioning_handle_random_s1_calculated, NULL);
680 }
681 
682 // PROV_DATA
683 static void provisioning_handle_network_dervived(void * arg){
684     provisioning_timer_stop();
685 
686     // notify client
687     provisioning_emit_event(1, MESH_SUBEVENT_PB_PROV_COMPLETE);
688 
689     device_state = DEVICE_SEND_COMPLETE;
690     provisioning_run();
691 
692 }
693 
694 static void provisioning_handle_data_device_key(void * arg){
695     // derive full network key
696     mesh_network_key_derive(&prov_cmac_request, network_key, &provisioning_handle_network_dervived, NULL);
697 }
698 
699 static void provisioning_handle_data_ccm(void * arg){
700 
701     UNUSED(arg);
702 
703     // TODO: validate MIC?
704     uint8_t mic[8];
705     btstack_crypto_ccm_get_authentication_value(&prov_ccm_request, mic);
706     printf("MIC: ");
707     printf_hexdump(mic, 8);
708 
709     // allocate network key
710     network_key = btstack_memory_mesh_network_key_get();
711 
712     // sort provisoning data
713     memcpy(network_key->net_key, provisioning_data, 16);
714     network_key->netkey_index = big_endian_read_16(provisioning_data, 16);
715     network_key->internal_index = 0;
716     flags = provisioning_data[18];
717     iv_index = big_endian_read_32(provisioning_data, 19);
718     unicast_address = big_endian_read_16(provisioning_data, 23);
719 
720     // DeviceKey
721     mesh_k1(&prov_cmac_request, dhkey, sizeof(dhkey), provisioning_salt, (const uint8_t*) "prdk", 4, device_key, &provisioning_handle_data_device_key, NULL);
722 }
723 
724 static void provisioning_handle_data(uint8_t *packet, uint16_t size){
725 
726     UNUSED(size);
727 
728     memcpy(enc_provisioning_data, packet, 25);
729 
730     // decode response
731     btstack_crypto_ccm_init(&prov_ccm_request, session_key, session_nonce, 25, 0, 8);
732     btstack_crypto_ccm_decrypt_block(&prov_ccm_request, 25, enc_provisioning_data, provisioning_data, &provisioning_handle_data_ccm, NULL);
733 }
734 
735 static void provisioning_handle_unexpected_pdu(uint8_t *packet, uint16_t size){
736     printf("Unexpected PDU #%u in state #%u\n", packet[0], (int) device_state);
737     provisioning_handle_provisioning_error(0x03);
738 }
739 
740 static void provisioning_handle_pdu(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
741 
742     if (size < 1) return;
743 
744     switch (packet_type){
745         case HCI_EVENT_PACKET:
746             if (packet[0] != HCI_EVENT_MESH_META)  break;
747             switch (packet[2]){
748                 case MESH_SUBEVENT_PB_TRANSPORT_LINK_OPEN:
749                     pb_transport_cid = mesh_subevent_pb_transport_link_open_get_pb_transport_cid(packet);
750                     pb_type = mesh_subevent_pb_transport_link_open_get_pb_type(packet);
751                     printf("Link opened, reset state, transport cid 0x%02x, PB type %d\n", pb_transport_cid, pb_type);
752                     provisioning_done();
753                     break;
754                 case MESH_SUBEVENT_PB_TRANSPORT_PDU_SENT:
755                     printf("Outgoing packet acked\n");
756                     prov_waiting_for_outgoing_complete = 0;
757                     break;
758                 case MESH_SUBEVENT_PB_TRANSPORT_LINK_CLOSED:
759                     printf("Link close, reset state\n");
760                     pb_transport_cid = MESH_PB_TRANSPORT_INVALID_CID;
761                     provisioning_done();
762                     break;
763             }
764             break;
765         case PROVISIONING_DATA_PACKET:
766             // check state
767             switch (device_state){
768                 case DEVICE_W4_INVITE:
769                     if (packet[0] != MESH_PROV_INVITE) provisioning_handle_unexpected_pdu(packet, size);
770                     printf("MESH_PROV_INVITE: ");
771                     printf_hexdump(&packet[1], size-1);
772                     provisioning_handle_invite(&packet[1], size-1);
773                     break;
774                 case DEVICE_W4_START:
775                     if (packet[0] != MESH_PROV_START) provisioning_handle_unexpected_pdu(packet, size);
776                     printf("MESH_PROV_START:  ");
777                     printf_hexdump(&packet[1], size-1);
778                     provisioning_handle_start(&packet[1], size-1);
779                     break;
780                 case DEVICE_W4_PUB_KEY:
781                     if (packet[0] != MESH_PROV_PUB_KEY) provisioning_handle_unexpected_pdu(packet, size);
782                     printf("MESH_PROV_PUB_KEY: ");
783                     printf_hexdump(&packet[1], size-1);
784                     provisioning_handle_public_key(&packet[1], size-1);
785                     break;
786                 case DEVICE_W4_CONFIRM:
787                     if (packet[0] != MESH_PROV_CONFIRM) provisioning_handle_unexpected_pdu(packet, size);
788                     printf("MESH_PROV_CONFIRM: ");
789                     printf_hexdump(&packet[1], size-1);
790                     provisioning_handle_confirmation(&packet[1], size-1);
791                     break;
792                 case DEVICE_W4_RANDOM:
793                     if (packet[0] != MESH_PROV_RANDOM) provisioning_handle_unexpected_pdu(packet, size);
794                     printf("MESH_PROV_RANDOM:  ");
795                     printf_hexdump(&packet[1], size-1);
796                     provisioning_handle_random(&packet[1], size-1);
797                     break;
798                 case DEVICE_W4_DATA:
799                     if (packet[0] != MESH_PROV_DATA) provisioning_handle_unexpected_pdu(packet, size);
800                     printf("MESH_PROV_DATA:  ");
801                     provisioning_handle_data(&packet[1], size-1);
802                     break;
803                 default:
804                     break;
805             }
806             break;
807         default:
808             break;
809     }
810     provisioning_run();
811 }
812 
813 static void prov_key_generated(void * arg){
814     UNUSED(arg);
815     printf("ECC-P256: ");
816     printf_hexdump(prov_ec_q, sizeof(prov_ec_q));
817     // allow override
818     if (prov_public_key_oob_available){
819         printf("Replace generated ECC with Public Key OOB:");
820         memcpy(prov_ec_q, prov_public_key_oob_q, 64);
821         printf_hexdump(prov_ec_q, sizeof(prov_ec_q));
822         btstack_crypto_ecc_p256_set_key(prov_public_key_oob_q, prov_public_key_oob_d);
823     }
824 }
825 
826 void provisioning_device_init(void){
827     // setup PB ADV
828     pb_adv_init();
829     pb_adv_register_packet_handler(&provisioning_handle_pdu);
830     // setup PB GATT
831     pb_gatt_init();
832     pb_gatt_register_packet_handler(&provisioning_handle_pdu);
833 
834     pb_transport_cid = MESH_PB_TRANSPORT_INVALID_CID;
835 
836     // init provisioning state
837     provisioning_done();
838 
839     // generate public key
840     btstack_crypto_ecc_p256_generate_key(&prov_ecc_p256_request, prov_ec_q, &prov_key_generated, NULL);
841 }
842 
843 void provisioning_device_register_packet_handler(btstack_packet_handler_t packet_handler){
844     prov_packet_handler = packet_handler;
845 }
846 
847 void provisioning_device_set_public_key_oob(const uint8_t * public_key, const uint8_t * private_key){
848     prov_public_key_oob_q = public_key;
849     prov_public_key_oob_d = private_key;
850     prov_public_key_oob_available = 1;
851     btstack_crypto_ecc_p256_set_key(prov_public_key_oob_q, prov_public_key_oob_d);
852 }
853 
854 void provisioning_device_set_static_oob(uint16_t static_oob_len, const uint8_t * static_oob_data){
855     prov_static_oob_available = 1;
856     prov_static_oob_data = static_oob_data;
857     prov_static_oob_len  = btstack_min(static_oob_len, 16);
858 }
859 
860 void provisioning_device_set_output_oob_actions(uint16_t supported_output_oob_action_types, uint8_t max_oob_output_size){
861     prov_output_oob_actions = supported_output_oob_action_types;
862     prov_output_oob_size    = max_oob_output_size;
863 }
864 
865 void provisioning_device_set_input_oob_actions(uint16_t supported_input_oob_action_types, uint8_t max_oob_input_size){
866     prov_input_oob_actions = supported_input_oob_action_types;
867     prov_input_oob_size    = max_oob_input_size;
868 }
869 
870 void provisioning_device_input_oob_complete_numeric(uint16_t pb_adv_cid, uint32_t input_oob){
871     UNUSED(pb_adv_cid);
872     if (device_state != DEVICE_W4_INPUT_OOK) return;
873 
874     // store input_oob as auth value
875     big_endian_store_32(auth_value, 12, input_oob);
876     device_state = DEVICE_SEND_INPUT_COMPLETE;
877     provisioning_run();
878 }
879 
880 void provisioning_device_input_oob_complete_alphanumeric(uint16_t pb_adv_cid, const uint8_t * input_oob_data, uint16_t input_oob_len){
881     UNUSED(pb_adv_cid);
882     if (device_state != DEVICE_W4_INPUT_OOK) return;
883 
884     // store input_oob and fillup with zeros
885     input_oob_len = btstack_min(input_oob_len, 16);
886     memset(auth_value, 0, 16);
887     memcpy(auth_value, input_oob_data, input_oob_len);
888     device_state = DEVICE_SEND_INPUT_COMPLETE;
889     provisioning_run();
890 }
891 
892 
893 uint8_t provisioning_device_data_get_flags(void){
894     return flags;
895 }
896 uint16_t provisioning_device_data_get_unicast_address(void){
897     return unicast_address;
898 }
899 const uint8_t * provisioning_device_data_get_device_key(void){
900     return device_key;
901 }
902 uint32_t provisioning_device_data_get_iv_index(void){
903     return iv_index;
904 }
905 mesh_network_key_t * provisioning_device_data_get_network_key(void){
906     return network_key;
907 }
908 
909 void provisioning_device_data_get(mesh_provisioning_data_t * provisioning_data){
910     provisioning_data->unicast_address = unicast_address;
911     provisioning_data->iv_index = iv_index;
912     provisioning_data->flags = flags;
913     memcpy(provisioning_data->device_key, device_key, 16);
914     provisioning_data->network_key = network_key;
915 }
916