xref: /btstack/src/ble/att_server.c (revision 16ece13520cb8efcf94cb63eab58a3eda87f40a2)
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 "run_loop.h"
52 #include "btstack_debug.h"
53 #include "btstack_memory.h"
54 #include "hci.h"
55 #include "hci_dump.h"
56 
57 #include "l2cap.h"
58 
59 #include "ble/sm.h"
60 #include "ble/att.h"
61 #include "att_dispatch.h"
62 #include "gap.h"
63 #include "ble/le_device_db.h"
64 
65 #include "ble/att_server.h"
66 
67 static void att_run(void);
68 
69 // max ATT request matches L2CAP PDU -- allow to use smaller buffer
70 #ifndef ATT_REQUEST_BUFFER_SIZE
71 #define ATT_REQUEST_BUFFER_SIZE HCI_ACL_PAYLOAD_SIZE
72 #endif
73 
74 typedef enum {
75     ATT_SERVER_IDLE,
76     ATT_SERVER_REQUEST_RECEIVED,
77     ATT_SERVER_W4_SIGNED_WRITE_VALIDATION,
78     ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED,
79 } att_server_state_t;
80 
81 static att_connection_t att_connection;
82 static att_server_state_t att_server_state;
83 
84 static uint8_t   att_client_addr_type;
85 static bd_addr_t att_client_address;
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 timer_source_t att_handle_value_indication_timer;
94 
95 static btstack_packet_handler_t att_client_packet_handler = NULL;
96 
97 static void att_handle_value_indication_notify_client(uint8_t status, uint16_t client_handle, uint16_t attribute_handle){
98 
99     if (!att_client_packet_handler) return;
100 
101     uint8_t event[7];
102     int pos = 0;
103     event[pos++] = ATT_HANDLE_VALUE_INDICATION_COMPLETE;
104     event[pos++] = sizeof(event) - 2;
105     event[pos++] = status;
106     bt_store_16(event, pos, client_handle);
107     pos += 2;
108     bt_store_16(event, pos, attribute_handle);
109     pos += 2;
110     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
111 }
112 
113 static void att_emit_mtu_event(uint16_t handle, uint16_t mtu){
114 
115     if (!att_client_packet_handler) return;
116 
117     uint8_t event[6];
118     int pos = 0;
119     event[pos++] = ATT_MTU_EXCHANGE_COMPLETE;
120     event[pos++] = sizeof(event) - 2;
121     bt_store_16(event, pos, handle);
122     pos += 2;
123     bt_store_16(event, pos, mtu);
124     pos += 2;
125     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
126 }
127 
128 static void att_handle_value_indication_timeout(timer_source_t *ts){
129     uint16_t att_handle = att_handle_value_indication_handle;
130     att_handle_value_indication_notify_client(ATT_HANDLE_VALUE_INDICATION_TIMEOUT, att_connection.con_handle, att_handle);
131 }
132 
133 static void att_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
134 
135     bd_addr_t event_address;
136     switch (packet_type) {
137 
138         case HCI_EVENT_PACKET:
139             switch (packet[0]) {
140 
141                 case DAEMON_EVENT_HCI_PACKET_SENT:
142                     att_run();
143                     break;
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                             bt_flip_addr(att_client_address, &packet[8]);
151                             // reset connection properties
152                             att_connection.con_handle = READ_BT_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 != READ_BT_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                     att_clear_transaction_queue(&att_connection);
178                     att_connection.con_handle = 0;
179                     att_handle_value_indication_handle = 0; // reset error state
180                     // restart advertising if we have been connected before
181                     // -> avoid sending advertise enable a second time before command complete was received
182                     att_server_state = ATT_SERVER_IDLE;
183                     break;
184 
185                 case SM_IDENTITY_RESOLVING_STARTED:
186                     log_info("SM_IDENTITY_RESOLVING_STARTED");
187                     att_ir_lookup_active = 1;
188                     break;
189                 case SM_IDENTITY_RESOLVING_SUCCEEDED:
190                     att_ir_lookup_active = 0;
191                     att_ir_le_device_db_index = READ_BT_16(packet, 11);
192                     log_info("SM_IDENTITY_RESOLVING_SUCCEEDED id %u", att_ir_le_device_db_index);
193                     att_run();
194                     break;
195                 case SM_IDENTITY_RESOLVING_FAILED:
196                     log_info("SM_IDENTITY_RESOLVING_FAILED");
197                     att_ir_lookup_active = 0;
198                     att_ir_le_device_db_index = -1;
199                     att_run();
200                     break;
201 
202                 case SM_AUTHORIZATION_RESULT: {
203                     if (packet[4] != att_client_addr_type) break;
204                     bt_flip_addr(event_address, &packet[5]);
205                     if (memcmp(event_address, att_client_address, 6) != 0) break;
206                     att_connection.authorized = packet[11];
207                     att_run();
208                 	break;
209                 }
210 
211                 default:
212                     break;
213             }
214     }
215     if (att_client_packet_handler){
216         att_client_packet_handler(packet_type, channel, packet, size);
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     swap64(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 = READ_BT_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_run();
238 }
239 
240 static void att_run(void){
241     switch (att_server_state){
242         case ATT_SERVER_IDLE:
243         case ATT_SERVER_W4_SIGNED_WRITE_VALIDATION:
244             return;
245         case ATT_SERVER_REQUEST_RECEIVED:
246             if (att_request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){
247                 log_info("ATT Signed Write!");
248                 if (!sm_cmac_ready()) {
249                     log_info("ATT Signed Write, sm_cmac engine not ready. Abort");
250                     att_server_state = ATT_SERVER_IDLE;
251                      return;
252                 }
253                 if (att_request_size < (3 + 12)) {
254                     log_info("ATT Signed Write, request to short. Abort.");
255                     att_server_state = ATT_SERVER_IDLE;
256                     return;
257                 }
258                 if (att_ir_lookup_active){
259                     return;
260                 }
261                 if (att_ir_le_device_db_index < 0){
262                     log_info("ATT Signed Write, CSRK not available");
263                     att_server_state = ATT_SERVER_IDLE;
264                     return;
265                 }
266 
267                 // check counter
268                 uint32_t counter_packet = READ_BT_32(att_request_buffer, att_request_size-12);
269                 uint32_t counter_db     = le_device_db_remote_counter_get(att_ir_le_device_db_index);
270                 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet);
271                 if (counter_packet < counter_db){
272                     log_info("ATT Signed Write, db reports higher counter, abort");
273                     att_server_state = ATT_SERVER_IDLE;
274                     return;
275                 }
276 
277                 // signature is { sequence counter, secure hash }
278                 sm_key_t csrk;
279                 le_device_db_remote_csrk_get(att_ir_le_device_db_index, csrk);
280                 att_server_state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION;
281                 log_info("Orig Signature: ");
282                 hexdump( &att_request_buffer[att_request_size-8], 8);
283                 uint16_t attribute_handle = READ_BT_16(att_request_buffer, 1);
284                 sm_cmac_start(csrk, att_request_buffer[0], attribute_handle, att_request_size - 15, &att_request_buffer[3], counter_packet, att_signed_write_handle_cmac_result);
285                 return;
286             }
287             // NOTE: fall through for regular commands
288 
289         case ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED:
290             if (!l2cap_can_send_fixed_channel_packet_now(att_connection.con_handle)) return;
291 
292             l2cap_reserve_packet_buffer();
293             uint8_t * att_response_buffer = l2cap_get_outgoing_buffer();
294             uint16_t  att_response_size   = att_handle_request(&att_connection, att_request_buffer, att_request_size, att_response_buffer);
295 
296             // intercept "insufficient authorization" for authenticated connections to allow for user authorization
297             if ((att_response_size     >= 4)
298             && (att_response_buffer[0] == ATT_ERROR_RESPONSE)
299             && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION)
300             && (att_connection.authenticated)){
301 
302             	switch (sm_authorization_state(att_connection.con_handle)){
303             		case AUTHORIZATION_UNKNOWN:
304                         l2cap_release_packet_buffer();
305 		             	sm_request_pairing(att_connection.con_handle);
306 	    		        return;
307 	    		    case AUTHORIZATION_PENDING:
308                         l2cap_release_packet_buffer();
309 	    		    	return;
310 	    		    default:
311 	    		    	break;
312             	}
313             }
314 
315             att_server_state = ATT_SERVER_IDLE;
316             if (att_response_size == 0) {
317                 l2cap_release_packet_buffer();
318                 return;
319             }
320 
321             l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, att_response_size);
322 
323             // notify client about MTU exchange result
324             if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){
325                 att_emit_mtu_event(att_connection.con_handle, att_connection.mtu);
326             }
327 
328             break;
329     }
330 }
331 
332 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
333     if (packet_type != ATT_DATA_PACKET) return;
334 
335     // handle value indication confirms
336     if (packet[0] == ATT_HANDLE_VALUE_CONFIRMATION && att_handle_value_indication_handle){
337         run_loop_remove_timer(&att_handle_value_indication_timer);
338         uint16_t att_handle = att_handle_value_indication_handle;
339         att_handle_value_indication_handle = 0;
340         att_handle_value_indication_notify_client(0, att_connection.con_handle, att_handle);
341         return;
342     }
343 
344     // check size
345     if (size > sizeof(att_request_buffer)) return;
346 
347     // last request still in processing?
348     if (att_server_state != ATT_SERVER_IDLE) return;
349 
350     // store request
351     att_server_state = ATT_SERVER_REQUEST_RECEIVED;
352     att_request_size = size;
353     memcpy(att_request_buffer, packet, size);
354 
355     att_run();
356 }
357 
358 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){
359 
360     sm_register_packet_handler(att_event_packet_handler);
361 
362     att_dispatch_register_server(att_packet_handler);
363 
364     att_server_state = ATT_SERVER_IDLE;
365     att_set_db(db);
366     att_set_read_callback(read_callback);
367     att_set_write_callback(write_callback);
368 
369 }
370 
371 void att_server_register_packet_handler(btstack_packet_handler_t handler){
372     att_client_packet_handler = handler;
373 }
374 
375 int  att_server_can_send(void){
376 	if (att_connection.con_handle == 0) return 0;
377 	return l2cap_can_send_fixed_channel_packet_now(att_connection.con_handle);
378 }
379 
380 int att_server_notify(uint16_t handle, uint8_t *value, uint16_t value_len){
381     if (!l2cap_can_send_fixed_channel_packet_now(att_connection.con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
382 
383     l2cap_reserve_packet_buffer();
384     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
385     uint16_t size = att_prepare_handle_value_notification(&att_connection, handle, value, value_len, packet_buffer);
386 	return l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
387 }
388 
389 int att_server_indicate(uint16_t handle, uint8_t *value, uint16_t value_len){
390     if (att_handle_value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PORGRESS;
391     if (!l2cap_can_send_fixed_channel_packet_now(att_connection.con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
392 
393     // track indication
394     att_handle_value_indication_handle = handle;
395     run_loop_set_timer_handler(&att_handle_value_indication_timer, att_handle_value_indication_timeout);
396     run_loop_set_timer(&att_handle_value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS);
397     run_loop_add_timer(&att_handle_value_indication_timer);
398 
399     l2cap_reserve_packet_buffer();
400     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
401     uint16_t size = att_prepare_handle_value_indication(&att_connection, handle, value, value_len, packet_buffer);
402 	l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
403     return 0;
404 }
405