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