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 uint16_t att_request_size = 0; 86 static uint8_t att_request_buffer[ATT_REQUEST_BUFFER_SIZE]; 87 88 static int att_ir_le_device_db_index = -1; 89 static int att_ir_lookup_active = 0; 90 91 static int att_handle_value_indication_handle = 0; 92 static btstack_timer_source_t att_handle_value_indication_timer; 93 static btstack_packet_callback_registration_t hci_event_callback_registration; 94 static btstack_packet_callback_registration_t sm_event_callback_registration; 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_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 115 if (!att_client_packet_handler) return; 116 117 uint8_t event[6]; 118 int pos = 0; 119 event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE; 120 event[pos++] = sizeof(event) - 2; 121 little_endian_store_16(event, pos, con_handle); 122 pos += 2; 123 little_endian_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(btstack_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 (hci_event_packet_get_type(packet)) { 140 141 case L2CAP_EVENT_CAN_SEND_NOW: 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 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 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_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_run(); 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_run(); 236 } 237 238 static void att_run(void){ 239 switch (att_server_state){ 240 case ATT_SERVER_IDLE: 241 case ATT_SERVER_W4_SIGNED_WRITE_VALIDATION: 242 return; 243 case ATT_SERVER_REQUEST_RECEIVED: 244 if (att_request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){ 245 log_info("ATT Signed Write!"); 246 if (!sm_cmac_ready()) { 247 log_info("ATT Signed Write, sm_cmac engine not ready. Abort"); 248 att_server_state = ATT_SERVER_IDLE; 249 return; 250 } 251 if (att_request_size < (3 + 12)) { 252 log_info("ATT Signed Write, request to short. Abort."); 253 att_server_state = ATT_SERVER_IDLE; 254 return; 255 } 256 if (att_ir_lookup_active){ 257 return; 258 } 259 if (att_ir_le_device_db_index < 0){ 260 log_info("ATT Signed Write, CSRK not available"); 261 att_server_state = ATT_SERVER_IDLE; 262 return; 263 } 264 265 // check counter 266 uint32_t counter_packet = little_endian_read_32(att_request_buffer, att_request_size-12); 267 uint32_t counter_db = le_device_db_remote_counter_get(att_ir_le_device_db_index); 268 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet); 269 if (counter_packet < counter_db){ 270 log_info("ATT Signed Write, db reports higher counter, abort"); 271 att_server_state = ATT_SERVER_IDLE; 272 return; 273 } 274 275 // signature is { sequence counter, secure hash } 276 sm_key_t csrk; 277 le_device_db_remote_csrk_get(att_ir_le_device_db_index, csrk); 278 att_server_state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION; 279 log_info("Orig Signature: "); 280 log_info_hexdump( &att_request_buffer[att_request_size-8], 8); 281 uint16_t attribute_handle = little_endian_read_16(att_request_buffer, 1); 282 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); 283 return; 284 } 285 // NOTE: fall through for regular commands 286 287 case ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED: 288 if (!att_dispatch_server_can_send_now(att_connection.con_handle)) return; 289 290 l2cap_reserve_packet_buffer(); 291 uint8_t * att_response_buffer = l2cap_get_outgoing_buffer(); 292 uint16_t att_response_size = att_handle_request(&att_connection, att_request_buffer, att_request_size, att_response_buffer); 293 294 // intercept "insufficient authorization" for authenticated connections to allow for user authorization 295 if ((att_response_size >= 4) 296 && (att_response_buffer[0] == ATT_ERROR_RESPONSE) 297 && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION) 298 && (att_connection.authenticated)){ 299 300 switch (sm_authorization_state(att_connection.con_handle)){ 301 case AUTHORIZATION_UNKNOWN: 302 l2cap_release_packet_buffer(); 303 sm_request_pairing(att_connection.con_handle); 304 return; 305 case AUTHORIZATION_PENDING: 306 l2cap_release_packet_buffer(); 307 return; 308 default: 309 break; 310 } 311 } 312 313 att_server_state = ATT_SERVER_IDLE; 314 if (att_response_size == 0) { 315 l2cap_release_packet_buffer(); 316 return; 317 } 318 319 l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, att_response_size); 320 321 // notify client about MTU exchange result 322 if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){ 323 att_emit_mtu_event(att_connection.con_handle, att_connection.mtu); 324 } 325 326 break; 327 } 328 } 329 330 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){ 331 switch (packet_type){ 332 case HCI_EVENT_PACKET: 333 if (packet[0] != L2CAP_EVENT_CAN_SEND_NOW) break; 334 att_run(); 335 break; 336 337 case ATT_DATA_PACKET: 338 // handle value indication confirms 339 if (packet[0] == ATT_HANDLE_VALUE_CONFIRMATION && att_handle_value_indication_handle){ 340 btstack_run_loop_remove_timer(&att_handle_value_indication_timer); 341 uint16_t att_handle = att_handle_value_indication_handle; 342 att_handle_value_indication_handle = 0; 343 att_handle_value_indication_notify_client(0, att_connection.con_handle, att_handle); 344 return; 345 } 346 347 // directly process command 348 // note: signed write cannot be handled directly as authentication needs to be verified 349 if (packet[0] == ATT_WRITE_COMMAND){ 350 att_handle_request(&att_connection, packet, size, 0); 351 return; 352 } 353 354 // check size 355 if (size > sizeof(att_request_buffer)) { 356 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)); 357 return; 358 } 359 360 // last request still in processing? 361 if (att_server_state != ATT_SERVER_IDLE){ 362 log_info("att_packet_handler: skipping att pdu 0x%02x as server not idle (state %u)", packet[0], att_server_state); 363 return; 364 } 365 366 // store request 367 att_server_state = ATT_SERVER_REQUEST_RECEIVED; 368 att_request_size = size; 369 memcpy(att_request_buffer, packet, size); 370 371 att_run(); 372 break; 373 } 374 } 375 376 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){ 377 378 // register for HCI Events 379 hci_event_callback_registration.callback = &att_event_packet_handler; 380 hci_add_event_handler(&hci_event_callback_registration); 381 382 // register for SM events 383 sm_event_callback_registration.callback = &att_event_packet_handler; 384 sm_add_event_handler(&sm_event_callback_registration); 385 386 // and L2CAP ATT Server PDUs 387 att_dispatch_register_server(att_packet_handler); 388 389 att_server_state = ATT_SERVER_IDLE; 390 att_set_db(db); 391 att_set_read_callback(read_callback); 392 att_set_write_callback(write_callback); 393 394 } 395 396 void att_server_register_packet_handler(btstack_packet_handler_t handler){ 397 att_client_packet_handler = handler; 398 } 399 400 int att_server_can_send_packet_now(void){ 401 if (att_connection.con_handle == 0) return 0; 402 return att_dispatch_server_can_send_now(att_connection.con_handle); 403 } 404 405 int att_server_notify(uint16_t attribute_handle, uint8_t *value, uint16_t value_len){ 406 if (!att_dispatch_server_can_send_now(att_connection.con_handle)) return BTSTACK_ACL_BUFFERS_FULL; 407 408 l2cap_reserve_packet_buffer(); 409 uint8_t * packet_buffer = l2cap_get_outgoing_buffer(); 410 uint16_t size = att_prepare_handle_value_notification(&att_connection, attribute_handle, value, value_len, packet_buffer); 411 return l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size); 412 } 413 414 int att_server_indicate(uint16_t attribute_handle, uint8_t *value, uint16_t value_len){ 415 if (att_handle_value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PORGRESS; 416 if (!att_dispatch_server_can_send_now(att_connection.con_handle)) return BTSTACK_ACL_BUFFERS_FULL; 417 418 // track indication 419 att_handle_value_indication_handle = attribute_handle; 420 btstack_run_loop_set_timer_handler(&att_handle_value_indication_timer, att_handle_value_indication_timeout); 421 btstack_run_loop_set_timer(&att_handle_value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS); 422 btstack_run_loop_add_timer(&att_handle_value_indication_timer); 423 424 l2cap_reserve_packet_buffer(); 425 uint8_t * packet_buffer = l2cap_get_outgoing_buffer(); 426 uint16_t size = att_prepare_handle_value_indication(&att_connection, attribute_handle, value, value_len, packet_buffer); 427 l2cap_send_prepared_connectionless(att_connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size); 428 return 0; 429 } 430