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 "btstack_debug.h" 52 #include "btstack_event.h" 53 #include "btstack_memory.h" 54 #include "btstack_run_loop.h" 55 #include "hci.h" 56 #include "hci_dump.h" 57 #include "l2cap.h" 58 59 #include "ble/sm.h" 60 #include "ble/att_db.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 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 100 if (!att_client_packet_handler) return; 101 102 uint8_t event[7]; 103 int pos = 0; 104 event[pos++] = ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE; 105 event[pos++] = sizeof(event) - 2; 106 event[pos++] = status; 107 little_endian_store_16(event, pos, client_handle); 108 pos += 2; 109 little_endian_store_16(event, pos, attribute_handle); 110 pos += 2; 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 116 if (!att_client_packet_handler) return; 117 118 uint8_t event[6]; 119 int pos = 0; 120 event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE; 121 event[pos++] = sizeof(event) - 2; 122 little_endian_store_16(event, pos, con_handle); 123 pos += 2; 124 little_endian_store_16(event, pos, mtu); 125 pos += 2; 126 (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event)); 127 } 128 129 static void att_handle_value_indication_timeout(btstack_timer_source_t *ts){ 130 uint16_t att_handle = att_handle_value_indication_handle; 131 att_handle_value_indication_notify_client(ATT_HANDLE_VALUE_INDICATION_TIMEOUT, att_connection.con_handle, att_handle); 132 } 133 134 static void att_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 135 136 bd_addr_t event_address; 137 switch (packet_type) { 138 139 case HCI_EVENT_PACKET: 140 switch (hci_event_packet_get_type(packet)) { 141 142 case L2CAP_EVENT_CAN_SEND_NOW: 143 att_run(); 144 break; 145 146 case HCI_EVENT_LE_META: 147 switch (packet[2]) { 148 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE: 149 // store connection info 150 att_client_addr_type = packet[7]; 151 reverse_bd_addr(&packet[8], att_client_address); 152 // reset connection properties 153 att_connection.con_handle = little_endian_read_16(packet, 4); 154 att_connection.mtu = ATT_DEFAULT_MTU; 155 att_connection.max_mtu = l2cap_max_le_mtu(); 156 if (att_connection.max_mtu > ATT_REQUEST_BUFFER_SIZE){ 157 att_connection.max_mtu = ATT_REQUEST_BUFFER_SIZE; 158 } 159 att_connection.encryption_key_size = 0; 160 att_connection.authenticated = 0; 161 att_connection.authorized = 0; 162 break; 163 164 default: 165 break; 166 } 167 break; 168 169 case HCI_EVENT_ENCRYPTION_CHANGE: 170 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE: 171 // check handle 172 if (att_connection.con_handle != little_endian_read_16(packet, 3)) break; 173 att_connection.encryption_key_size = sm_encryption_key_size(att_connection.con_handle); 174 att_connection.authenticated = sm_authenticated(att_connection.con_handle); 175 break; 176 177 case HCI_EVENT_DISCONNECTION_COMPLETE: 178 att_clear_transaction_queue(&att_connection); 179 att_connection.con_handle = 0; 180 att_handle_value_indication_handle = 0; // reset error state 181 // restart advertising if we have been connected before 182 // -> avoid sending advertise enable a second time before command complete was received 183 att_server_state = ATT_SERVER_IDLE; 184 break; 185 186 case SM_EVENT_IDENTITY_RESOLVING_STARTED: 187 log_info("SM_EVENT_IDENTITY_RESOLVING_STARTED"); 188 att_ir_lookup_active = 1; 189 break; 190 case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED: 191 att_ir_lookup_active = 0; 192 att_ir_le_device_db_index = little_endian_read_16(packet, 11); 193 log_info("SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED id %u", att_ir_le_device_db_index); 194 att_run(); 195 break; 196 case SM_EVENT_IDENTITY_RESOLVING_FAILED: 197 log_info("SM_EVENT_IDENTITY_RESOLVING_FAILED"); 198 att_ir_lookup_active = 0; 199 att_ir_le_device_db_index = -1; 200 att_run(); 201 break; 202 case SM_EVENT_AUTHORIZATION_RESULT: { 203 if (packet[4] != att_client_addr_type) break; 204 reverse_bd_addr(&packet[5], event_address); 205 if (memcmp(event_address, att_client_address, 6) != 0) break; 206 att_connection.authorized = packet[11]; 207 att_run(); 208 break; 209 } 210 default: 211 break; 212 } 213 break; 214 default: 215 break; 216 } 217 } 218 219 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){ 220 221 if (att_server_state != ATT_SERVER_W4_SIGNED_WRITE_VALIDATION) return; 222 223 uint8_t hash_flipped[8]; 224 reverse_64(hash, hash_flipped); 225 if (memcmp(hash_flipped, &att_request_buffer[att_request_size-8], 8)){ 226 log_info("ATT Signed Write, invalid signature"); 227 att_server_state = ATT_SERVER_IDLE; 228 return; 229 } 230 log_info("ATT Signed Write, valid signature"); 231 232 // update sequence number 233 uint32_t counter_packet = little_endian_read_32(att_request_buffer, att_request_size-12); 234 le_device_db_remote_counter_set(att_ir_le_device_db_index, counter_packet+1); 235 att_server_state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED; 236 att_run(); 237 } 238 239 static void att_run(void){ 240 switch (att_server_state){ 241 case ATT_SERVER_IDLE: 242 case ATT_SERVER_W4_SIGNED_WRITE_VALIDATION: 243 return; 244 case ATT_SERVER_REQUEST_RECEIVED: 245 if (att_request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){ 246 log_info("ATT Signed Write!"); 247 if (!sm_cmac_ready()) { 248 log_info("ATT Signed Write, sm_cmac engine not ready. Abort"); 249 att_server_state = ATT_SERVER_IDLE; 250 return; 251 } 252 if (att_request_size < (3 + 12)) { 253 log_info("ATT Signed Write, request to short. Abort."); 254 att_server_state = ATT_SERVER_IDLE; 255 return; 256 } 257 if (att_ir_lookup_active){ 258 return; 259 } 260 if (att_ir_le_device_db_index < 0){ 261 log_info("ATT Signed Write, CSRK not available"); 262 att_server_state = ATT_SERVER_IDLE; 263 return; 264 } 265 266 // check counter 267 uint32_t counter_packet = little_endian_read_32(att_request_buffer, att_request_size-12); 268 uint32_t counter_db = le_device_db_remote_counter_get(att_ir_le_device_db_index); 269 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet); 270 if (counter_packet < counter_db){ 271 log_info("ATT Signed Write, db reports higher counter, abort"); 272 att_server_state = ATT_SERVER_IDLE; 273 return; 274 } 275 276 // signature is { sequence counter, secure hash } 277 sm_key_t csrk; 278 le_device_db_remote_csrk_get(att_ir_le_device_db_index, csrk); 279 att_server_state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION; 280 log_info("Orig Signature: "); 281 log_info_hexdump( &att_request_buffer[att_request_size-8], 8); 282 uint16_t attribute_handle = little_endian_read_16(att_request_buffer, 1); 283 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); 284 return; 285 } 286 // NOTE: fall through for regular commands 287 288 case ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED: 289 if (!att_dispatch_server_can_send_now(att_connection.con_handle)) return; 290 291 l2cap_reserve_packet_buffer(); 292 uint8_t * att_response_buffer = l2cap_get_outgoing_buffer(); 293 uint16_t att_response_size = att_handle_request(&att_connection, att_request_buffer, att_request_size, att_response_buffer); 294 295 // intercept "insufficient authorization" for authenticated connections to allow for user authorization 296 if ((att_response_size >= 4) 297 && (att_response_buffer[0] == ATT_ERROR_RESPONSE) 298 && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION) 299 && (att_connection.authenticated)){ 300 301 switch (sm_authorization_state(att_connection.con_handle)){ 302 case AUTHORIZATION_UNKNOWN: 303 l2cap_release_packet_buffer(); 304 sm_request_pairing(att_connection.con_handle); 305 return; 306 case AUTHORIZATION_PENDING: 307 l2cap_release_packet_buffer(); 308 return; 309 default: 310 break; 311 } 312 } 313 314 att_server_state = ATT_SERVER_IDLE; 315 if (att_response_size == 0) { 316 l2cap_release_packet_buffer(); 317 return; 318 } 319 320 l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, att_response_size); 321 322 // notify client about MTU exchange result 323 if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){ 324 att_emit_mtu_event(att_connection.con_handle, att_connection.mtu); 325 } 326 327 break; 328 } 329 } 330 331 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){ 332 if (packet_type != ATT_DATA_PACKET) return; 333 334 // handle value indication confirms 335 if (packet[0] == ATT_HANDLE_VALUE_CONFIRMATION && att_handle_value_indication_handle){ 336 btstack_run_loop_remove_timer(&att_handle_value_indication_timer); 337 uint16_t att_handle = att_handle_value_indication_handle; 338 att_handle_value_indication_handle = 0; 339 att_handle_value_indication_notify_client(0, att_connection.con_handle, att_handle); 340 return; 341 } 342 343 // check size 344 if (size > sizeof(att_request_buffer)) return; 345 346 // last request still in processing? 347 if (att_server_state != ATT_SERVER_IDLE) return; 348 349 // store request 350 att_server_state = ATT_SERVER_REQUEST_RECEIVED; 351 att_request_size = size; 352 memcpy(att_request_buffer, packet, size); 353 354 att_run(); 355 } 356 357 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){ 358 359 // register for HCI Events 360 hci_event_callback_registration.callback = &att_event_packet_handler; 361 hci_add_event_handler(&hci_event_callback_registration); 362 363 // register for SM events 364 sm_event_callback_registration.callback = &att_event_packet_handler; 365 sm_add_event_handler(&sm_event_callback_registration); 366 367 // and L2CAP ATT Server PDUs 368 att_dispatch_register_server(att_packet_handler); 369 370 att_server_state = ATT_SERVER_IDLE; 371 att_set_db(db); 372 att_set_read_callback(read_callback); 373 att_set_write_callback(write_callback); 374 375 } 376 377 void att_server_register_packet_handler(btstack_packet_handler_t handler){ 378 att_client_packet_handler = handler; 379 } 380 381 int att_server_can_send_packet_now(void){ 382 if (att_connection.con_handle == 0) return 0; 383 return att_dispatch_server_can_send_now(att_connection.con_handle); 384 } 385 386 int att_server_notify(uint16_t attribute_handle, uint8_t *value, uint16_t value_len){ 387 if (!att_dispatch_server_can_send_now(att_connection.con_handle)) return BTSTACK_ACL_BUFFERS_FULL; 388 389 l2cap_reserve_packet_buffer(); 390 uint8_t * packet_buffer = l2cap_get_outgoing_buffer(); 391 uint16_t size = att_prepare_handle_value_notification(&att_connection, attribute_handle, value, value_len, packet_buffer); 392 return l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size); 393 } 394 395 int att_server_indicate(uint16_t attribute_handle, uint8_t *value, uint16_t value_len){ 396 if (att_handle_value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PORGRESS; 397 if (!att_dispatch_server_can_send_now(att_connection.con_handle)) return BTSTACK_ACL_BUFFERS_FULL; 398 399 // track indication 400 att_handle_value_indication_handle = attribute_handle; 401 btstack_run_loop_set_timer_handler(&att_handle_value_indication_timer, att_handle_value_indication_timeout); 402 btstack_run_loop_set_timer(&att_handle_value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS); 403 btstack_run_loop_add_timer(&att_handle_value_indication_timer); 404 405 l2cap_reserve_packet_buffer(); 406 uint8_t * packet_buffer = l2cap_get_outgoing_buffer(); 407 uint16_t size = att_prepare_handle_value_indication(&att_connection, attribute_handle, value, value_len, packet_buffer); 408 l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size); 409 return 0; 410 } 411