#! /usr/bin/python from __future__ import print_function # import print from python3: end="" import time import re import pexpect # sudo apt-get install python-pexpect import subprocess import random import binascii import struct import sys, os, time import bluepy.btle as btle ''' Service <uuid=Generic Access handleStart=20 handleEnd=28> 22 0x16 READ FLAG_7 24 0x18 READ 26 0x1A READ Service <uuid=Heart Rate handleStart=40 handleEnd=65535> 42 0x2A READ Pair with me a16ee1a4001c66c3a670 ''' # !!! make sure bluetoothd runs in --compat mode before executing this script !!! def pair_with_pin(start_time, time_limit=60): # int(time.time()), time_limit - approximate pairing window time in seconds, it might take up to 2x (nested timeout conditions) "exectutes pairing on bluetooth adapter side" try: ''' Start actual pair stuff ''' subprocess.call(['hciconfig','hci0','sspmode', '0']) print("[sp] starting bluetoothctl") # bluetoothctl child = pexpect.spawn('bluetoothctl') child.logfile = open("/tmp/mylog", "w") child.expect("#") child.sendline('agent off') # might be unnecessary child.expect("unregistered") child.sendline('scan on') # might be unnecessary child.sendline('agent KeyboardDisplay ') child.expect("Agent registered") child.sendline('pairable on') child.expect("pairable on succeeded") child.sendline('discoverable on') child.expect("discoverable on succeeded") child.sendline('default-agent') child.sendline('remove 3c:71:bf:f1:ef:c6') child.sendline('scan on') child.expect("Device 3C:71:BF:F1:EF:C6 FLAG_3") child.sendline('pair 3c:71:bf:f1:ef:c6') i = child.expect('Paired: yes', timeout = time_limit) if i == 0: # found 'Paired: yes' == successful pairing trust_mac = 'trust ' + re.search(r'(?:[0-9a-fA-F]:?){12}.+$', child.before).group(0) # extract MAC from last line, one with 'Paired: Yes' child.sendline(trust_mac) # optionally add device to trusted child.expect('trust succeeded', timeout = 10) else: # i == 1 print('[sp] Retrying if time will allow') except pexpect.EOF: print ('[sp] EOF') except pexpect.TIMEOUT: print ('[sp] Timeout') return True #main program body PAIRING_TIME_LIMIT = 60 subprocess.call(['hciconfig','hci0','down']) subprocess.call(['hciconfig','hci0','up']) deviceMAC = open('ctf_mac.txt').read() p = btle.Peripheral(deviceMAC) print ("[bp] Attached to peripheral") print("[++] Loading level 07") hex1 = binascii.unhexlify(str('%0*x' % (4,7))) p.writeCharacteristic(0x30, hex1, withResponse=False) p.disconnect() status = pair_with_pin(int(time.time()), PAIRING_TIME_LIMIT) if status == True: print('[sp] Pairing successful') ''' Start bluepy stuff ''' time.sleep(2) deviceMAC = open('ctf_mac.txt').read() p = btle.Peripheral(deviceMAC) svc=p.getServiceByUUID("0000180d-0000-1000-8000-00805f9b34fb") print ("[bp] Attached to peripheral") hex1 = p.readCharacteristic(0x2C) hex2 = binascii.b2a_hex(hex1) hexlif2 = str(binascii.unhexlify(hex2)) print("[==] Flag: "+hexlif2) p.disconnect() exit()