def gatt_writes(dev, addr, addrType, rows, mtu=23, wait=False): '''Set up the BLE connection and write data''' with BLEConnectionManager(dev, 'central') as connection_manager: conn = connection_manager.init_connection(addr, addrType) connection_manager.connect(conn) if mtu is not None: connection_manager.exchange_mtu(conn, mtu) for row in rows: handle, message, fuzz_positions, num_iterations = row handle_base10 = binascii.unhexlify(handle) gatt_write(connection_manager, conn, handle_base10, message, fuzz_positions, num_iterations) if wait: print "Replay finished. Will continue to wait until user force's exit (ctrl+c)" while True: gevent.sleep(1)
from blesuite.connection_manager import BLEConnectionManager import gevent import time adapter = 0 role = 'central' timeout_seconds = 10 target_device_name = "BLEBoy" with BLEConnectionManager(adapter, role) as connection_manager: # enable scanning connection_manager.start_scan() # Take start time start_time = time.time() # initialize dictionary of discovered devices, readable format. readable_discovered_devices = {} device_found = False while True: # timeout condition current_time = time.time() if current_time - start_time >= timeout_seconds: break # get devices discovered_devices = connection_manager.get_discovered_devices() # Decode GAP data into readable values for i in discovered_devices.keys(): if i not in readable_discovered_devices.keys():
"ATT Read Security Mode: %d ATT Read Security Level: %d " "Connection Security Mode: %d Connection Security Level: %d" % (att_authentication_check_result, att_opcode, uuid, att_property, att_read_permission.security_mode, att_read_permission.security_level, att_write_permission.security_mode, att_write_permission.security_level, connection_permission.get_security_mode_mode(), connection_permission.get_security_mode_level())) # always throw an authentication error to see how the peer device responds return False ''' # initialize event handler event_handler = MyCustomATTSecurityHandler() with BLEConnectionManager( adapter, role, att_security_event_hook=event_handler) as connection_manager: # Generate BLEDevice ble_device = BLEDevice() # Add Services and Characteristics to BLEDevice service1 = ble_device.add_service(0x01, 0x06, "2124") #Add characteristic with open permissions, but requires authorization, thus triggering our event handler characteristic1 = service1.add_characteristic( 0x03, 0x02, "2124", Permissions.READ | Permissions.WRITE, "testValue1", characteristic_value_attribute_read_permission=att_utils.
from blesuite.connection_manager import BLEConnectionManager import blesuite.utils.gap_utils as gap_utils import bdaddr adapter = 0 target_device_name = "TargetDevice" target_address = "AA:BB:CC:DD:EE:FF" target_address_type = "random" target_device_bledevice = None with BLEConnectionManager(adapter, 'central') as connection_manager: print "Smart scanning device for clone" connection = connection_manager.init_connection(target_address, target_address_type) connection_manager.connect(connection) target_device_bledevice = connection_manager.smart_scan(connection) print "Done smart scanning" with BLEConnectionManager(adapter, "peripheral") as connection_manager: # spoofing address ret = bdaddr.bdaddr(("hci" + str(adapter)), target_address) if ret == -1: raise ValueError('Spoofing failed. Your device may not be supported.') else: print "Address spoofed" # Using distinguishable name for demonstration purposes local_name = "TargetDevice" complete_name = "TargetDevice" # generate integer representation of advertisement data flags using helper function flag_int = gap_utils.generate_ad_flag_value(le_general_discoverable=True, bredr_not_supported=True) # generate advertisement data entry using helper function flag_entry = gap_utils.advertisement_data_entry_builder("Flags", chr(flag_int))
send_packet = True log.debug("ATT response hook triggered. Received packet: %s Send packet: %s packet: %s" % (received_packet, send_packet, our_response_packet)) # If we receive an ATT Write Request and that results in some error, instead of sending the error packet, # send a valid ATT Write Response to trick the peer device. if ATT_Read_Request in received_packet and ATT_Error_Response in our_response_packet: our_response_packet = ATT_Read_Response("Intercepted!") return (send_packet, our_response_packet) ''' # initialize event handler event_handler = MyCustomATTEventHandler() with BLEConnectionManager(adapter, role, att_operation_event_hook=event_handler) as connection_manager: # Generate BLEDevice ble_device = BLEDevice() # Add Services and Characteristics to BLEDevice service1 = ble_device.add_service(0x01, 0x06, "2124") characteristic1 = service1.add_characteristic(0x03, 0x02, "2124", Permissions.READ | Permissions.WRITE, "testValue1", characteristic_value_attribute_read_permission=att_utils.ATT_SECURITY_MODE_NO_ACCESS, characteristic_value_attribute_write_permission=att_utils.ATT_SECURITY_MODE_OPEN ) characteristic1.add_user_description_descriptor(0x04, "Characteristic 1") # Generate GATT server on host using BLEDevice information.
def process_args(args): """ Process command line tool arguments parsed by argparse and call appropriate bleSuite functions. :param args: parser.parse_args() :return: """ command = args.command[0] if args.debug: logging.basicConfig(level=logging.DEBUG) timeout = args.timeout[0] * 1000 # convert seconds to ms if command == 'spoof': import bdaddr if args.address[0] == "": print "Please specify an address to spoof." else: logger.debug("About to spoof to address %s for adapter %s" % (args.address[0], args.adapter[0])) ret = bdaddr.bdaddr(("hci"+str(args.adapter[0])), args.address[0]) if ret == -1: raise ValueError('Spoofing failed. Your device may not be supported.') if command == 'scan': print "BTLE Scan beginning" with BLEConnectionManager(args.adapter[0], 'central') as connection_manager: discovered = connection_manager.scan(timeout) print "Discovered:" for i in discovered.keys(): print "\t", i, "(public)" if discovered[i][0] == 0 else "(random)" for h, j in enumerate(discovered[i][1]): gap = connection_manager.decode_gap_data(str(discovered[i][1][h])) info = connection_manager.generate_gap_data_dict(gap) for k in info.keys(): print "\t\t", k + ":" print "\t\t\t", info[k] if command == 'smartscan': print "BTLE Smart Scan beginning" device = ble_run_smart_scan(args.address[0], args.adapter[0], args.address_type[0], skip_device_info_query=args.skip_device_info_query, attempt_read=args.smart_read, timeout=timeout) if command == 'servicescan': print "BTLE Scanning Services" ble_service_scan(args.address[0], args.adapter[0], args.address_type[0]) if command == 'read': if len(args.handles) <= 0 and len(args.uuids) <= 0: print "ERROR: No handles or UUIDs supplied for read operation." return print "Reading value from handle or UUID" if args.async: uuidData, handleData = ble_service_read_async(args.address[0], args.adapter[0], args.address_type[0], args.handles, args.uuids, timeout=timeout) for dataTuple in handleData: print "\nHandle:", "0x" + dataTuple[0] print_data_and_hex(dataTuple[1], False) ''' if isinstance(dataTuple[1][0], str): utils.print_helper.print_data_and_hex(dataTuple[1], False) else: utils.print_helper.print_data_and_hex(dataTuple[1][1], False)''' for dataTuple in uuidData: print "\nUUID:", dataTuple[0] print_data_and_hex(dataTuple[1], False) ''' if isinstance(dataTuple[1][0], str): utils.print_helper.print_data_and_hex(dataTuple[1], False) else: utils.print_helper.print_data_and_hex(dataTuple[1][1].received(), True)''' else: uuidData, handleData = ble_service_read(args.address[0], args.adapter[0], args.address_type[0], args.handles, args.uuids, timeout=timeout) for dataTuple in handleData: print "\nHandle:", "0x" + dataTuple[0] print_data_and_hex(dataTuple[1], False) for dataTuple in uuidData: print "\nUUID:", dataTuple[0] print_data_and_hex(dataTuple[1], False) if command == 'write': if len(args.handles) <= 0: print "ERROR: No handles supplied for write operation. Note: Write operation does not support use of UUIDs." return print "Writing value to handle" if args.async: logger.debug("Async Write") if len(args.data) > 0: handleData = ble_service_write_async(args.address[0], args.adapter[0], args.address_type[0], args.handles, args.data, timeout=timeout) elif args.payload_delimiter[0] == 'EOF': logger.debug("Payload Delimiter: EOF") dataSet = [] for dataFile in args.files: if dataFile is None: continue logger.debug("Reading file: %s", dataFile) f = open(dataFile, 'r') dataSet.append(f.read()) f.close() logger.debug("Sending data set: %s" % dataSet) handleData = ble_service_write_async(args.addr[0], args.adapter[0], args.address_type[0], args.handles, dataSet, timeout=timeout) logger.debug("Received data: %s" % handleData) '''for dataTuple in handleData: print "\nHandle:", "0x" + dataTuple[0] utils.print_helper.print_data_and_hex(dataTuple[1], False)''' else: logger.debug("Payload Delimiter: %s", args.payload_delimiter[0]) dataSet = [] for dataFile in args.files: if dataFile is None: continue f = open(dataFile, 'r') data = f.read() f.close() data = data.split(args.payload_delimiter[0]) dataSet.extend(data) logger.debug("Sending dataSet: %s" % dataSet) handleData = ble_service_write_async(args.address[0], args.adapter[0], args.address_type[0], args.handles, dataSet, timeout=timeout) for dataTuple in handleData: print "\nHandle:", "0x" + dataTuple[0] print "Input:" utils.print_helper.print_data_and_hex(dataTuple[2], False, prefix="\t") print "Output:" #if tuple[1][0] is a string, it means our cmdLineToolWrapper removed the GattResponse object #due to a timeout, else we grab the GattResponse and its response data if isinstance(dataTuple[1][0], str): utils.print_helper.print_data_and_hex(dataTuple[1], False, prefix="\t") else: utils.print_helper.print_data_and_hex(dataTuple[1][1].received(), False, prefix="\t") else: logger.debug("Sync Write") print args.data if len(args.data) > 0: handleData = ble_service_write(args.address[0], args.adapter[0], args.address_type[0], args.handles, args.data, timeout=timeout) '''for dataTuple in handleData: print "\nHandle:", "0x" + dataTuple[0] utils.print_helper.print_data_and_hex(dataTuple[1], False)''' elif args.payload_delimiter[0] == 'EOF': logger.debug("Payload Delimiter: EOF") dataSet = [] for dataFile in args.files: if dataFile is None: continue logger.debug("Reading file: %s", dataFile) f = open(dataFile, 'r') dataSet.append(f.read()) f.close() logger.debug("Sending data set: %s" % dataSet) handleData = ble_service_write(args.address[0], args.adapter[0], args.address_type[0], args.handles, dataSet, timeout=timeout) logger.debug("Received data: %s" % handleData) '''for dataTuple in handleData: print "\nHandle:", "0x" + dataTuple[0] utils.print_helper.print_data_and_hex(dataTuple[1], False)''' else: logger.debug("Payload Delimiter: %s", args.payload_delimiter[0]) dataSet = [] for dataFile in args.files: if dataFile is None: continue f = open(dataFile, 'r') data = f.read() f.close() data = data.split(args.payload_delimiter[0]) dataSet.extend(data) logger.debug("Sending dataSet: %s" % dataSet) handleData = ble_service_write(args.address[0], args.adapter[0], args.address_type[0], args.handles, dataSet, timeout=timeout) for dataTuple in handleData: print "\nHandle:", "0x" + dataTuple[0] print "Input:" print_data_and_hex([dataTuple[2]], False, prefix="\t") print "Output:" print_data_and_hex(dataTuple[1], False, prefix="\t") if command == 'subscribe': print "Subscribing to device" if args.subscribe_timeout[0] is not None: timeout = args.subscribe_timeout[0] * 1000 else: timeout = None ble_handle_subscribe(args.address[0], args.handles, args.adapter[0], args.address_type[0], args.mode[0], timeout) return
from blesuite.connection_manager import BLEConnectionManager import blesuite.utils.gap_utils as gap_utils import gevent import time with BLEConnectionManager(0, "peripheral") as connection_manager: local_name = "Name Foo2" complete_name = "Foo4" # generate integer representation of advertisement data flags using helper function flag_int = gap_utils.generate_ad_flag_value(le_general_discoverable=True, bredr_not_supported=True) # generate advertisement data entry using helper function flag_entry = gap_utils.advertisement_data_entry_builder("Flags", chr(flag_int)) # generate advertisement data entry for shortened local name using helper function short_local_name_entry = gap_utils.advertisement_data_entry_builder("Shortened Local Name", complete_name) # generate advertisement data entry for complete local name using helper function complete_local_name_entry = gap_utils.advertisement_data_entry_builder("Complete Local Name", local_name) # build advertisement data list ad_entries_list = [flag_entry, short_local_name_entry, complete_local_name_entry] # build finalized advertisement data from list ad_entries = gap_utils.advertisement_data_complete_builder(ad_entries_list) # Set advertising data sent in advertising packets connection_manager.set_advertising_data(ad_entries)