xref: /btstack/src/ble/att_server.c (revision bb38f0573479840fea287bac2a8c2ae6b5a83aea)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 
39 //
40 // ATT Server Globals
41 //
42 
43 #include <stdint.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <inttypes.h>
48 
49 #include "btstack_config.h"
50 
51 #include "att_dispatch.h"
52 #include "ble/att_db.h"
53 #include "ble/att_server.h"
54 #include "ble/core.h"
55 #include "ble/le_device_db.h"
56 #include "ble/sm.h"
57 #include "btstack_debug.h"
58 #include "btstack_event.h"
59 #include "btstack_memory.h"
60 #include "btstack_run_loop.h"
61 #include "gap.h"
62 #include "hci.h"
63 #include "hci_dump.h"
64 #include "l2cap.h"
65 
66 static void att_run(void);
67 
68 // max ATT request matches L2CAP PDU -- allow to use smaller buffer
69 #ifndef ATT_REQUEST_BUFFER_SIZE
70 #define ATT_REQUEST_BUFFER_SIZE HCI_ACL_PAYLOAD_SIZE
71 #endif
72 
73 typedef enum {
74     ATT_SERVER_IDLE,
75     ATT_SERVER_REQUEST_RECEIVED,
76     ATT_SERVER_W4_SIGNED_WRITE_VALIDATION,
77     ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED,
78 } att_server_state_t;
79 
80 static att_connection_t att_connection;
81 static att_server_state_t att_server_state;
82 
83 static uint8_t   att_client_addr_type;
84 static bd_addr_t att_client_address;
85 static uint8_t   att_client_waiting_for_can_send;
86 static uint16_t  att_request_size   = 0;
87 static uint8_t   att_request_buffer[ATT_REQUEST_BUFFER_SIZE];
88 
89 static int       att_ir_le_device_db_index = -1;
90 static int       att_ir_lookup_active = 0;
91 
92 static int       att_handle_value_indication_handle = 0;
93 static btstack_timer_source_t att_handle_value_indication_timer;
94 static btstack_packet_callback_registration_t hci_event_callback_registration;
95 static btstack_packet_callback_registration_t sm_event_callback_registration;
96 static btstack_packet_handler_t att_client_packet_handler = NULL;
97 
98 static btstack_linked_list_t can_send_now_clients;
99 
100 static void att_handle_value_indication_notify_client(uint8_t status, uint16_t client_handle, uint16_t attribute_handle){
101     if (!att_client_packet_handler) return;
102 
103     uint8_t event[7];
104     int pos = 0;
105     event[pos++] = ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE;
106     event[pos++] = sizeof(event) - 2;
107     event[pos++] = status;
108     little_endian_store_16(event, pos, client_handle);
109     pos += 2;
110     little_endian_store_16(event, pos, attribute_handle);
111     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
112 }
113 
114 static void att_emit_mtu_event(hci_con_handle_t con_handle, uint16_t mtu){
115     if (!att_client_packet_handler) return;
116 
117     uint8_t event[6];
118     int pos = 0;
119     event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE;
120     event[pos++] = sizeof(event) - 2;
121     little_endian_store_16(event, pos, con_handle);
122     pos += 2;
123     little_endian_store_16(event, pos, mtu);
124     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
125 }
126 
127 static void att_emit_can_send_now_event(void){
128     if (!att_client_packet_handler) return;
129 
130     uint8_t event[] = { ATT_EVENT_CAN_SEND_NOW, 0};
131     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
132 }
133 
134 static void att_handle_value_indication_timeout(btstack_timer_source_t *ts){
135     uint16_t att_handle = att_handle_value_indication_handle;
136     att_handle_value_indication_notify_client(ATT_HANDLE_VALUE_INDICATION_TIMEOUT, att_connection.con_handle, att_handle);
137 }
138 
139 static void att_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
140 
141     bd_addr_t event_address;
142     switch (packet_type) {
143 
144         case HCI_EVENT_PACKET:
145             switch (hci_event_packet_get_type(packet)) {
146 
147                 case HCI_EVENT_LE_META:
148                     switch (packet[2]) {
149                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
150                         	// store connection info
151                         	att_client_addr_type = packet[7];
152                             reverse_bd_addr(&packet[8], att_client_address);
153                             // reset connection properties
154                             att_connection.con_handle = little_endian_read_16(packet, 4);
155                             att_connection.mtu = ATT_DEFAULT_MTU;
156                             att_connection.max_mtu = l2cap_max_le_mtu();
157                             if (att_connection.max_mtu > ATT_REQUEST_BUFFER_SIZE){
158                                 att_connection.max_mtu = ATT_REQUEST_BUFFER_SIZE;
159                             }
160                             att_connection.encryption_key_size = 0;
161                             att_connection.authenticated = 0;
162 		                	att_connection.authorized = 0;
163                             break;
164 
165                         default:
166                             break;
167                     }
168                     break;
169 
170                 case HCI_EVENT_ENCRYPTION_CHANGE:
171                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
172                 	// check handle
173                 	if (att_connection.con_handle != little_endian_read_16(packet, 3)) break;
174                 	att_connection.encryption_key_size = sm_encryption_key_size(att_connection.con_handle);
175                 	att_connection.authenticated = sm_authenticated(att_connection.con_handle);
176                 	break;
177 
178                 case HCI_EVENT_DISCONNECTION_COMPLETE:
179                     // check handle
180                     if (att_connection.con_handle != hci_event_disconnection_complete_get_connection_handle(packet)) break;
181                     att_clear_transaction_queue(&att_connection);
182                     att_connection.con_handle = 0;
183                     att_handle_value_indication_handle = 0; // reset error state
184                     att_server_state = ATT_SERVER_IDLE;
185                     break;
186 
187                 case SM_EVENT_IDENTITY_RESOLVING_STARTED:
188                     log_info("SM_EVENT_IDENTITY_RESOLVING_STARTED");
189                     att_ir_lookup_active = 1;
190                     break;
191                 case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
192                     att_ir_lookup_active = 0;
193                     att_ir_le_device_db_index = little_endian_read_16(packet, 11);
194                     log_info("SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED id %u", att_ir_le_device_db_index);
195                     att_run();
196                     break;
197                 case SM_EVENT_IDENTITY_RESOLVING_FAILED:
198                     log_info("SM_EVENT_IDENTITY_RESOLVING_FAILED");
199                     att_ir_lookup_active = 0;
200                     att_ir_le_device_db_index = -1;
201                     att_run();
202                     break;
203                 case SM_EVENT_AUTHORIZATION_RESULT: {
204                     if (packet[4] != att_client_addr_type) break;
205                     reverse_bd_addr(&packet[5], event_address);
206                     if (memcmp(event_address, att_client_address, 6) != 0) break;
207                     att_connection.authorized = packet[11];
208                     att_dispatch_server_request_can_send_now_event(att_connection.con_handle);
209                 	break;
210                 }
211                 default:
212                     break;
213             }
214             break;
215         default:
216             break;
217     }
218 }
219 
220 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
221 
222     if (att_server_state != ATT_SERVER_W4_SIGNED_WRITE_VALIDATION) return;
223 
224     uint8_t hash_flipped[8];
225     reverse_64(hash, hash_flipped);
226     if (memcmp(hash_flipped, &att_request_buffer[att_request_size-8], 8)){
227         log_info("ATT Signed Write, invalid signature");
228         att_server_state = ATT_SERVER_IDLE;
229         return;
230     }
231     log_info("ATT Signed Write, valid signature");
232 
233     // update sequence number
234     uint32_t counter_packet = little_endian_read_32(att_request_buffer, att_request_size-12);
235     le_device_db_remote_counter_set(att_ir_le_device_db_index, counter_packet+1);
236     att_server_state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
237     att_dispatch_server_request_can_send_now_event(att_connection.con_handle);
238 }
239 
240 #if 0
241 static int att_server_ready_to_send(att_connection_t * connection){
242 }
243 #endif
244 
245 // pre: att_server_state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED
246 // pre: can send now
247 // returns: 1 if packet was sent
248 static int att_server_process_validated_request(hci_con_handle_t con_handle){
249 
250     l2cap_reserve_packet_buffer();
251     uint8_t * att_response_buffer = l2cap_get_outgoing_buffer();
252     uint16_t  att_response_size   = att_handle_request(&att_connection, att_request_buffer, att_request_size, att_response_buffer);
253 
254     // intercept "insufficient authorization" for authenticated connections to allow for user authorization
255     if ((att_response_size     >= 4)
256     && (att_response_buffer[0] == ATT_ERROR_RESPONSE)
257     && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION)
258     && (att_connection.authenticated)){
259 
260         switch (sm_authorization_state(att_connection.con_handle)){
261             case AUTHORIZATION_UNKNOWN:
262                 l2cap_release_packet_buffer();
263                 sm_request_pairing(att_connection.con_handle);
264                 return 0;
265             case AUTHORIZATION_PENDING:
266                 l2cap_release_packet_buffer();
267                 return 0;
268             default:
269                 break;
270         }
271     }
272 
273     att_server_state = ATT_SERVER_IDLE;
274     if (att_response_size == 0) {
275         l2cap_release_packet_buffer();
276         return 0;
277     }
278 
279     l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, att_response_size);
280 
281     // notify client about MTU exchange result
282     if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){
283         att_emit_mtu_event(att_connection.con_handle, att_connection.mtu);
284     }
285     return 1;
286 }
287 
288 static void att_run(void){
289     switch (att_server_state){
290         case ATT_SERVER_REQUEST_RECEIVED:
291             if (att_request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){
292                 log_info("ATT Signed Write!");
293                 if (!sm_cmac_ready()) {
294                     log_info("ATT Signed Write, sm_cmac engine not ready. Abort");
295                     att_server_state = ATT_SERVER_IDLE;
296                     return;
297                 }
298                 if (att_request_size < (3 + 12)) {
299                     log_info("ATT Signed Write, request to short. Abort.");
300                     att_server_state = ATT_SERVER_IDLE;
301                     return;
302                 }
303                 if (att_ir_lookup_active){
304                     return;
305                 }
306                 if (att_ir_le_device_db_index < 0){
307                     log_info("ATT Signed Write, CSRK not available");
308                     att_server_state = ATT_SERVER_IDLE;
309                     return;
310                 }
311 
312                 // check counter
313                 uint32_t counter_packet = little_endian_read_32(att_request_buffer, att_request_size-12);
314                 uint32_t counter_db     = le_device_db_remote_counter_get(att_ir_le_device_db_index);
315                 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet);
316                 if (counter_packet < counter_db){
317                     log_info("ATT Signed Write, db reports higher counter, abort");
318                     att_server_state = ATT_SERVER_IDLE;
319                     return;
320                 }
321 
322                 // signature is { sequence counter, secure hash }
323                 sm_key_t csrk;
324                 le_device_db_remote_csrk_get(att_ir_le_device_db_index, csrk);
325                 att_server_state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION;
326                 log_info("Orig Signature: ");
327                 log_info_hexdump( &att_request_buffer[att_request_size-8], 8);
328                 uint16_t attribute_handle = little_endian_read_16(att_request_buffer, 1);
329                 sm_cmac_signed_write_start(csrk, att_request_buffer[0], attribute_handle, att_request_size - 15, &att_request_buffer[3], counter_packet, att_signed_write_handle_cmac_result);
330                 return;
331             }
332 
333             // move on
334             att_server_state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
335             att_dispatch_server_request_can_send_now_event(att_connection.con_handle);
336             break;
337 
338         default:
339             break;
340     }
341 }
342 
343 static void att_server_handle_can_send_now(void){
344 
345     // NOTE: we get l2cap fixed channel instead of con_handle
346     // TODO: get con_handle
347 
348     if (att_server_state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED){
349         int sent = att_server_process_validated_request(att_connection.con_handle);
350         if (sent && (att_client_waiting_for_can_send || !btstack_linked_list_empty(&can_send_now_clients))){
351             att_dispatch_server_request_can_send_now_event(att_connection.con_handle);
352             return;
353         }
354     }
355 
356     while (!btstack_linked_list_empty(&can_send_now_clients)){
357         // handle first client
358         btstack_context_callback_registration_t * client = (btstack_context_callback_registration_t*) can_send_now_clients;
359         btstack_linked_list_remove(&can_send_now_clients, (btstack_linked_item_t *) client);
360         client->callback(client->context);
361 
362         // request again if needed
363         if (!att_dispatch_server_can_send_now(att_connection.con_handle)){
364             if (!btstack_linked_list_empty(&can_send_now_clients) || att_client_waiting_for_can_send){
365                 att_dispatch_server_request_can_send_now_event(att_connection.con_handle);
366             }
367             return;
368         }
369     }
370 
371     if (att_client_waiting_for_can_send){
372         att_client_waiting_for_can_send = 0;
373         att_emit_can_send_now_event();
374     }
375 }
376 
377 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
378     switch (packet_type){
379 
380         case HCI_EVENT_PACKET:
381             if (packet[0] != L2CAP_EVENT_CAN_SEND_NOW) break;
382             att_server_handle_can_send_now();
383             break;
384 
385         case ATT_DATA_PACKET:
386             // handle value indication confirms
387             if (packet[0] == ATT_HANDLE_VALUE_CONFIRMATION && att_handle_value_indication_handle){
388                 btstack_run_loop_remove_timer(&att_handle_value_indication_timer);
389                 uint16_t att_handle = att_handle_value_indication_handle;
390                 att_handle_value_indication_handle = 0;
391                 att_handle_value_indication_notify_client(0, att_connection.con_handle, att_handle);
392                 return;
393             }
394 
395             // directly process command
396             // note: signed write cannot be handled directly as authentication needs to be verified
397             if (packet[0] == ATT_WRITE_COMMAND){
398                 att_handle_request(&att_connection, packet, size, 0);
399                 return;
400             }
401 
402             // check size
403             if (size > sizeof(att_request_buffer)) {
404                 log_info("att_packet_handler: dropping att pdu 0x%02x as size %u > att_request_buffer %u", packet[0], size, (int) sizeof(att_request_buffer));
405                 return;
406             }
407 
408             // last request still in processing?
409             if (att_server_state != ATT_SERVER_IDLE){
410                 log_info("att_packet_handler: skipping att pdu 0x%02x as server not idle (state %u)", packet[0], att_server_state);
411                 return;
412             }
413 
414             // store request
415             att_server_state = ATT_SERVER_REQUEST_RECEIVED;
416             att_request_size = size;
417             memcpy(att_request_buffer, packet, size);
418 
419             att_run();
420             break;
421     }
422 }
423 
424 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){
425 
426     // register for HCI Events
427     hci_event_callback_registration.callback = &att_event_packet_handler;
428     hci_add_event_handler(&hci_event_callback_registration);
429 
430     // register for SM events
431     sm_event_callback_registration.callback = &att_event_packet_handler;
432     sm_add_event_handler(&sm_event_callback_registration);
433 
434     // and L2CAP ATT Server PDUs
435     att_dispatch_register_server(att_packet_handler);
436 
437     att_server_state = ATT_SERVER_IDLE;
438     att_set_db(db);
439     att_set_read_callback(read_callback);
440     att_set_write_callback(write_callback);
441 
442 }
443 
444 void att_server_register_packet_handler(btstack_packet_handler_t handler){
445     att_client_packet_handler = handler;
446 }
447 
448 // NOTE: con_handle is ignored for now as only a single connection is supported
449 // TODO: support multiple connections
450 
451 int  att_server_can_send_packet_now(hci_con_handle_t con_handle){
452 	if (att_connection.con_handle == 0) return 0;
453 	return att_dispatch_server_can_send_now(att_connection.con_handle);
454 }
455 
456 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){
457     att_client_waiting_for_can_send = 1;
458     att_dispatch_server_request_can_send_now_event(att_connection.con_handle);
459 }
460 
461 void att_server_register_can_send_now_callback(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
462     // check if can send already
463     if (att_dispatch_server_can_send_now(con_handle)){
464         callback_registration->callback(callback_registration->context);
465         return;
466     }
467     btstack_linked_list_add_tail(&can_send_now_clients, (btstack_linked_item_t*) callback_registration);
468     att_dispatch_server_request_can_send_now_event(con_handle);
469 }
470 
471 int att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
472     if (!att_dispatch_server_can_send_now(att_connection.con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
473 
474     l2cap_reserve_packet_buffer();
475     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
476     uint16_t size = att_prepare_handle_value_notification(&att_connection, attribute_handle, value, value_len, packet_buffer);
477 	return l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
478 }
479 
480 int att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
481     if (att_handle_value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PORGRESS;
482     if (!att_dispatch_server_can_send_now(att_connection.con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
483 
484     // track indication
485     att_handle_value_indication_handle = attribute_handle;
486     btstack_run_loop_set_timer_handler(&att_handle_value_indication_timer, att_handle_value_indication_timeout);
487     btstack_run_loop_set_timer(&att_handle_value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS);
488     btstack_run_loop_add_timer(&att_handle_value_indication_timer);
489 
490     l2cap_reserve_packet_buffer();
491     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
492     uint16_t size = att_prepare_handle_value_indication(&att_connection, attribute_handle, value, value_len, packet_buffer);
493 	l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
494     return 0;
495 }
496