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 pos += 2; 110 (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event)); 111 } 112 113 static void att_emit_mtu_event(hci_con_handle_t con_handle, uint16_t mtu){ 114 if (!att_client_packet_handler) return; 115 116 uint8_t event[6]; 117 int pos = 0; 118 event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE; 119 event[pos++] = sizeof(event) - 2; 120 little_endian_store_16(event, pos, con_handle); 121 pos += 2; 122 little_endian_store_16(event, pos, mtu); 123 pos += 2; 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 att_clear_transaction_queue(&att_connection); 180 att_connection.con_handle = 0; 181 att_handle_value_indication_handle = 0; // reset error state 182 // restart advertising if we have been connected before 183 // -> avoid sending advertise enable a second time before command complete was received 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_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){ 351 att_dispatch_server_request_can_send_now_event(att_connection.con_handle); 352 return; 353 } 354 } 355 356 if (att_client_waiting_for_can_send){ 357 att_client_waiting_for_can_send = 0; 358 att_emit_can_send_now_event(); 359 } 360 } 361 362 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){ 363 switch (packet_type){ 364 365 case HCI_EVENT_PACKET: 366 if (packet[0] != L2CAP_EVENT_CAN_SEND_NOW) break; 367 att_server_handle_can_send_now(); 368 break; 369 370 case ATT_DATA_PACKET: 371 // handle value indication confirms 372 if (packet[0] == ATT_HANDLE_VALUE_CONFIRMATION && att_handle_value_indication_handle){ 373 btstack_run_loop_remove_timer(&att_handle_value_indication_timer); 374 uint16_t att_handle = att_handle_value_indication_handle; 375 att_handle_value_indication_handle = 0; 376 att_handle_value_indication_notify_client(0, att_connection.con_handle, att_handle); 377 return; 378 } 379 380 // directly process command 381 // note: signed write cannot be handled directly as authentication needs to be verified 382 if (packet[0] == ATT_WRITE_COMMAND){ 383 att_handle_request(&att_connection, packet, size, 0); 384 return; 385 } 386 387 // check size 388 if (size > sizeof(att_request_buffer)) { 389 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)); 390 return; 391 } 392 393 // last request still in processing? 394 if (att_server_state != ATT_SERVER_IDLE){ 395 log_info("att_packet_handler: skipping att pdu 0x%02x as server not idle (state %u)", packet[0], att_server_state); 396 return; 397 } 398 399 // store request 400 att_server_state = ATT_SERVER_REQUEST_RECEIVED; 401 att_request_size = size; 402 memcpy(att_request_buffer, packet, size); 403 404 att_run(); 405 break; 406 } 407 } 408 409 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){ 410 411 // register for HCI Events 412 hci_event_callback_registration.callback = &att_event_packet_handler; 413 hci_add_event_handler(&hci_event_callback_registration); 414 415 // register for SM events 416 sm_event_callback_registration.callback = &att_event_packet_handler; 417 sm_add_event_handler(&sm_event_callback_registration); 418 419 // and L2CAP ATT Server PDUs 420 att_dispatch_register_server(att_packet_handler); 421 422 att_server_state = ATT_SERVER_IDLE; 423 att_set_db(db); 424 att_set_read_callback(read_callback); 425 att_set_write_callback(write_callback); 426 427 } 428 429 void att_server_register_packet_handler(btstack_packet_handler_t handler){ 430 att_client_packet_handler = handler; 431 } 432 433 // NOTE: con_handle is ignored for now as only a single connection is supported 434 // TODO: support multiple connections 435 436 int att_server_can_send_packet_now(hci_con_handle_t con_handle){ 437 if (att_connection.con_handle == 0) return 0; 438 return att_dispatch_server_can_send_now(att_connection.con_handle); 439 } 440 441 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){ 442 att_client_waiting_for_can_send = 1; 443 att_dispatch_server_request_can_send_now_event(att_connection.con_handle); 444 } 445 446 int att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){ 447 if (!att_dispatch_server_can_send_now(att_connection.con_handle)) return BTSTACK_ACL_BUFFERS_FULL; 448 449 l2cap_reserve_packet_buffer(); 450 uint8_t * packet_buffer = l2cap_get_outgoing_buffer(); 451 uint16_t size = att_prepare_handle_value_notification(&att_connection, attribute_handle, value, value_len, packet_buffer); 452 return l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size); 453 } 454 455 int att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){ 456 if (att_handle_value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PORGRESS; 457 if (!att_dispatch_server_can_send_now(att_connection.con_handle)) return BTSTACK_ACL_BUFFERS_FULL; 458 459 // track indication 460 att_handle_value_indication_handle = attribute_handle; 461 btstack_run_loop_set_timer_handler(&att_handle_value_indication_timer, att_handle_value_indication_timeout); 462 btstack_run_loop_set_timer(&att_handle_value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS); 463 btstack_run_loop_add_timer(&att_handle_value_indication_timer); 464 465 l2cap_reserve_packet_buffer(); 466 uint8_t * packet_buffer = l2cap_get_outgoing_buffer(); 467 uint16_t size = att_prepare_handle_value_indication(&att_connection, attribute_handle, value, value_len, packet_buffer); 468 l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size); 469 return 0; 470 } 471