xref: /btstack/src/ble/att_server.c (revision ddaf35c7579ab4463891f4e60cea40b4398b142c)
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 void att_handle_value_indication_notify_client(uint8_t status, uint16_t client_handle, uint16_t attribute_handle){
99     if (!att_client_packet_handler) return;
100 
101     uint8_t event[7];
102     int pos = 0;
103     event[pos++] = ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE;
104     event[pos++] = sizeof(event) - 2;
105     event[pos++] = status;
106     little_endian_store_16(event, pos, client_handle);
107     pos += 2;
108     little_endian_store_16(event, pos, attribute_handle);
109     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
110 }
111 
112 static void att_emit_mtu_event(hci_con_handle_t con_handle, uint16_t mtu){
113     if (!att_client_packet_handler) return;
114 
115     uint8_t event[6];
116     int pos = 0;
117     event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE;
118     event[pos++] = sizeof(event) - 2;
119     little_endian_store_16(event, pos, con_handle);
120     pos += 2;
121     little_endian_store_16(event, pos, mtu);
122     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
123 }
124 
125 static void att_emit_can_send_now_event(void){
126     if (!att_client_packet_handler) return;
127 
128     uint8_t event[] = { ATT_EVENT_CAN_SEND_NOW, 0};
129     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
130 }
131 
132 static void att_handle_value_indication_timeout(btstack_timer_source_t *ts){
133     uint16_t att_handle = att_handle_value_indication_handle;
134     att_handle_value_indication_notify_client(ATT_HANDLE_VALUE_INDICATION_TIMEOUT, att_connection.con_handle, att_handle);
135 }
136 
137 static void att_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
138 
139     bd_addr_t event_address;
140     switch (packet_type) {
141 
142         case HCI_EVENT_PACKET:
143             switch (hci_event_packet_get_type(packet)) {
144 
145                 case HCI_EVENT_LE_META:
146                     switch (packet[2]) {
147                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
148                         	// store connection info
149                         	att_client_addr_type = packet[7];
150                             reverse_bd_addr(&packet[8], att_client_address);
151                             // reset connection properties
152                             att_connection.con_handle = little_endian_read_16(packet, 4);
153                             att_connection.mtu = ATT_DEFAULT_MTU;
154                             att_connection.max_mtu = l2cap_max_le_mtu();
155                             if (att_connection.max_mtu > ATT_REQUEST_BUFFER_SIZE){
156                                 att_connection.max_mtu = ATT_REQUEST_BUFFER_SIZE;
157                             }
158                             att_connection.encryption_key_size = 0;
159                             att_connection.authenticated = 0;
160 		                	att_connection.authorized = 0;
161                             break;
162 
163                         default:
164                             break;
165                     }
166                     break;
167 
168                 case HCI_EVENT_ENCRYPTION_CHANGE:
169                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
170                 	// check handle
171                 	if (att_connection.con_handle != little_endian_read_16(packet, 3)) break;
172                 	att_connection.encryption_key_size = sm_encryption_key_size(att_connection.con_handle);
173                 	att_connection.authenticated = sm_authenticated(att_connection.con_handle);
174                 	break;
175 
176                 case HCI_EVENT_DISCONNECTION_COMPLETE:
177                     // check handle
178                     if (att_connection.con_handle != hci_event_disconnection_complete_get_connection_handle(packet)) break;
179                     att_clear_transaction_queue(&att_connection);
180                     att_connection.con_handle = 0;
181                     att_handle_value_indication_handle = 0; // reset error state
182                     att_server_state = ATT_SERVER_IDLE;
183                     break;
184 
185                 case SM_EVENT_IDENTITY_RESOLVING_STARTED:
186                     log_info("SM_EVENT_IDENTITY_RESOLVING_STARTED");
187                     att_ir_lookup_active = 1;
188                     break;
189                 case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
190                     att_ir_lookup_active = 0;
191                     att_ir_le_device_db_index = little_endian_read_16(packet, 11);
192                     log_info("SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED id %u", att_ir_le_device_db_index);
193                     att_run();
194                     break;
195                 case SM_EVENT_IDENTITY_RESOLVING_FAILED:
196                     log_info("SM_EVENT_IDENTITY_RESOLVING_FAILED");
197                     att_ir_lookup_active = 0;
198                     att_ir_le_device_db_index = -1;
199                     att_run();
200                     break;
201                 case SM_EVENT_AUTHORIZATION_RESULT: {
202                     if (packet[4] != att_client_addr_type) break;
203                     reverse_bd_addr(&packet[5], event_address);
204                     if (memcmp(event_address, att_client_address, 6) != 0) break;
205                     att_connection.authorized = packet[11];
206                     att_dispatch_server_request_can_send_now_event(att_connection.con_handle);
207                 	break;
208                 }
209                 default:
210                     break;
211             }
212             break;
213         default:
214             break;
215     }
216 }
217 
218 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
219 
220     if (att_server_state != ATT_SERVER_W4_SIGNED_WRITE_VALIDATION) return;
221 
222     uint8_t hash_flipped[8];
223     reverse_64(hash, hash_flipped);
224     if (memcmp(hash_flipped, &att_request_buffer[att_request_size-8], 8)){
225         log_info("ATT Signed Write, invalid signature");
226         att_server_state = ATT_SERVER_IDLE;
227         return;
228     }
229     log_info("ATT Signed Write, valid signature");
230 
231     // update sequence number
232     uint32_t counter_packet = little_endian_read_32(att_request_buffer, att_request_size-12);
233     le_device_db_remote_counter_set(att_ir_le_device_db_index, counter_packet+1);
234     att_server_state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
235     att_dispatch_server_request_can_send_now_event(att_connection.con_handle);
236 }
237 
238 #if 0
239 static int att_server_ready_to_send(att_connection_t * connection){
240 }
241 #endif
242 
243 // pre: att_server_state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED
244 // pre: can send now
245 // returns: 1 if packet was sent
246 static int att_server_process_validated_request(hci_con_handle_t con_handle){
247 
248     l2cap_reserve_packet_buffer();
249     uint8_t * att_response_buffer = l2cap_get_outgoing_buffer();
250     uint16_t  att_response_size   = att_handle_request(&att_connection, att_request_buffer, att_request_size, att_response_buffer);
251 
252     // intercept "insufficient authorization" for authenticated connections to allow for user authorization
253     if ((att_response_size     >= 4)
254     && (att_response_buffer[0] == ATT_ERROR_RESPONSE)
255     && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION)
256     && (att_connection.authenticated)){
257 
258         switch (sm_authorization_state(att_connection.con_handle)){
259             case AUTHORIZATION_UNKNOWN:
260                 l2cap_release_packet_buffer();
261                 sm_request_pairing(att_connection.con_handle);
262                 return 0;
263             case AUTHORIZATION_PENDING:
264                 l2cap_release_packet_buffer();
265                 return 0;
266             default:
267                 break;
268         }
269     }
270 
271     att_server_state = ATT_SERVER_IDLE;
272     if (att_response_size == 0) {
273         l2cap_release_packet_buffer();
274         return 0;
275     }
276 
277     l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, att_response_size);
278 
279     // notify client about MTU exchange result
280     if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){
281         att_emit_mtu_event(att_connection.con_handle, att_connection.mtu);
282     }
283     return 1;
284 }
285 
286 static void att_run(void){
287     switch (att_server_state){
288         case ATT_SERVER_REQUEST_RECEIVED:
289             if (att_request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){
290                 log_info("ATT Signed Write!");
291                 if (!sm_cmac_ready()) {
292                     log_info("ATT Signed Write, sm_cmac engine not ready. Abort");
293                     att_server_state = ATT_SERVER_IDLE;
294                     return;
295                 }
296                 if (att_request_size < (3 + 12)) {
297                     log_info("ATT Signed Write, request to short. Abort.");
298                     att_server_state = ATT_SERVER_IDLE;
299                     return;
300                 }
301                 if (att_ir_lookup_active){
302                     return;
303                 }
304                 if (att_ir_le_device_db_index < 0){
305                     log_info("ATT Signed Write, CSRK not available");
306                     att_server_state = ATT_SERVER_IDLE;
307                     return;
308                 }
309 
310                 // check counter
311                 uint32_t counter_packet = little_endian_read_32(att_request_buffer, att_request_size-12);
312                 uint32_t counter_db     = le_device_db_remote_counter_get(att_ir_le_device_db_index);
313                 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet);
314                 if (counter_packet < counter_db){
315                     log_info("ATT Signed Write, db reports higher counter, abort");
316                     att_server_state = ATT_SERVER_IDLE;
317                     return;
318                 }
319 
320                 // signature is { sequence counter, secure hash }
321                 sm_key_t csrk;
322                 le_device_db_remote_csrk_get(att_ir_le_device_db_index, csrk);
323                 att_server_state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION;
324                 log_info("Orig Signature: ");
325                 log_info_hexdump( &att_request_buffer[att_request_size-8], 8);
326                 uint16_t attribute_handle = little_endian_read_16(att_request_buffer, 1);
327                 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);
328                 return;
329             }
330 
331             // move on
332             att_server_state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
333             att_dispatch_server_request_can_send_now_event(att_connection.con_handle);
334             break;
335 
336         default:
337             break;
338     }
339 }
340 
341 static void att_server_handle_can_send_now(void){
342 
343     // NOTE: we get l2cap fixed channel instead of con_handle
344     // TODO: get con_handle
345 
346     if (att_server_state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED){
347         int sent = att_server_process_validated_request(att_connection.con_handle);
348         if (sent && att_client_waiting_for_can_send){
349             att_dispatch_server_request_can_send_now_event(att_connection.con_handle);
350             return;
351         }
352     }
353 
354     if (att_client_waiting_for_can_send){
355         att_client_waiting_for_can_send = 0;
356         att_emit_can_send_now_event();
357     }
358 }
359 
360 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
361     switch (packet_type){
362 
363         case HCI_EVENT_PACKET:
364             if (packet[0] != L2CAP_EVENT_CAN_SEND_NOW) break;
365             att_server_handle_can_send_now();
366             break;
367 
368         case ATT_DATA_PACKET:
369             // handle value indication confirms
370             if (packet[0] == ATT_HANDLE_VALUE_CONFIRMATION && att_handle_value_indication_handle){
371                 btstack_run_loop_remove_timer(&att_handle_value_indication_timer);
372                 uint16_t att_handle = att_handle_value_indication_handle;
373                 att_handle_value_indication_handle = 0;
374                 att_handle_value_indication_notify_client(0, att_connection.con_handle, att_handle);
375                 return;
376             }
377 
378             // directly process command
379             // note: signed write cannot be handled directly as authentication needs to be verified
380             if (packet[0] == ATT_WRITE_COMMAND){
381                 att_handle_request(&att_connection, packet, size, 0);
382                 return;
383             }
384 
385             // check size
386             if (size > sizeof(att_request_buffer)) {
387                 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));
388                 return;
389             }
390 
391             // last request still in processing?
392             if (att_server_state != ATT_SERVER_IDLE){
393                 log_info("att_packet_handler: skipping att pdu 0x%02x as server not idle (state %u)", packet[0], att_server_state);
394                 return;
395             }
396 
397             // store request
398             att_server_state = ATT_SERVER_REQUEST_RECEIVED;
399             att_request_size = size;
400             memcpy(att_request_buffer, packet, size);
401 
402             att_run();
403             break;
404     }
405 }
406 
407 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){
408 
409     // register for HCI Events
410     hci_event_callback_registration.callback = &att_event_packet_handler;
411     hci_add_event_handler(&hci_event_callback_registration);
412 
413     // register for SM events
414     sm_event_callback_registration.callback = &att_event_packet_handler;
415     sm_add_event_handler(&sm_event_callback_registration);
416 
417     // and L2CAP ATT Server PDUs
418     att_dispatch_register_server(att_packet_handler);
419 
420     att_server_state = ATT_SERVER_IDLE;
421     att_set_db(db);
422     att_set_read_callback(read_callback);
423     att_set_write_callback(write_callback);
424 
425 }
426 
427 void att_server_register_packet_handler(btstack_packet_handler_t handler){
428     att_client_packet_handler = handler;
429 }
430 
431 // NOTE: con_handle is ignored for now as only a single connection is supported
432 // TODO: support multiple connections
433 
434 int  att_server_can_send_packet_now(hci_con_handle_t con_handle){
435 	if (att_connection.con_handle == 0) return 0;
436 	return att_dispatch_server_can_send_now(att_connection.con_handle);
437 }
438 
439 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){
440     att_client_waiting_for_can_send = 1;
441     att_dispatch_server_request_can_send_now_event(att_connection.con_handle);
442 }
443 
444 int att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
445     if (!att_dispatch_server_can_send_now(att_connection.con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
446 
447     l2cap_reserve_packet_buffer();
448     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
449     uint16_t size = att_prepare_handle_value_notification(&att_connection, attribute_handle, value, value_len, packet_buffer);
450 	return l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
451 }
452 
453 int att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
454     if (att_handle_value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PORGRESS;
455     if (!att_dispatch_server_can_send_now(att_connection.con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
456 
457     // track indication
458     att_handle_value_indication_handle = attribute_handle;
459     btstack_run_loop_set_timer_handler(&att_handle_value_indication_timer, att_handle_value_indication_timeout);
460     btstack_run_loop_set_timer(&att_handle_value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS);
461     btstack_run_loop_add_timer(&att_handle_value_indication_timer);
462 
463     l2cap_reserve_packet_buffer();
464     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
465     uint16_t size = att_prepare_handle_value_indication(&att_connection, attribute_handle, value, value_len, packet_buffer);
466 	l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
467     return 0;
468 }
469