sachineswar
Posts: 4
Joined: Mon Apr 17, 2017 8:20 pm

Bluetooth pairing using fixed PIN on bluez 5.

Tue Oct 10, 2017 7:16 pm

Hi All,

I am trying to connect 2 or more Raspberry Pi 3 boards over bluetooth. I am looking for options to set security while pairing. I am using Raspian-stretch(Latest one available). Bluez version available on RPI-3 is 5.23(as shown from bluetoothd -v command).

I am using headless version. I want the pairing to be secured(meaing there should be some kind of authentication i can set like PIN(4 digits) or Passkey(6 digits)) without the user logged into it. So if i have to connect my phone to the RPI, i dont have to login to RPI inorder to enter the PIN/Passkey.
Then i would like to set up bluetooth PAN network so that i can communicate to between devices connected to PAN network.

I want pair the device/s using a PIN which is available in a file in the system or somewhere i can point it to. Say for example, pin.txt file in /temp/ directory or by running an agent to set the PIN. I read from other posts that bluez5.x got rid of the bluetooth-agent which was used in earlier version of bluez to do the things i could acomplish.

Agents in bluetoothctl such as DisplayOnly, KeyboardDisplay,NoInputNoOutput, DisplayYesNo,KeyboardOnly,on either sets a dynamic passkey which has to be entered manually or confirmation the passkey or just lets any device to pair and connect without any authntication in case of NoInputNoOutput.

Here is the link which i found of this forum stating that the agent is no longer available:
viewtopic.php?t=133961
I also refers to some examples that shows pairing of devices but doesnt address what i am looking for.

There is no info available on manpage too.
https://manpages.debian.org/stretch/blu ... .1.en.html

Here is something i found about the commands but still not what i am looking for.
https://wiki.archlinux.org/index.php/Bluetooth

Any help or suggestion to get around this or links to documnets i could refer to is appreciated.

Thanks in advance.

User avatar
Douglas6
Posts: 4710
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: Bluetooth pairing using fixed PIN on bluez 5.

Tue Oct 10, 2017 7:45 pm

sachineswar wrote:
Tue Oct 10, 2017 7:16 pm

Here is the link which i found of this forum stating that the agent is no longer available:
viewtopic.php?t=133961
You seem to have misinterpreted that thread. In it, I stated that:
Bluez-simple-agent is renamed, to simple-agent
I even provided a link: https://github.com/pauloborges/bluez/bl ... mple-agent

sachineswar
Posts: 4
Joined: Mon Apr 17, 2017 8:20 pm

Re: Bluetooth pairing using fixed PIN on bluez 5.

Tue Oct 10, 2017 10:33 pm

Thanks for pointing it out and clarifying. I think i mis-interpreted the comment "Bluez-utils has been removed in the Bluez 5 package. Bluez-simple-agent is renamed, to simple-agent (I think) but bluetoothctl has been added for managing devices."

simple agent is not available by default. It had to be downloaded manually.

I came across another link while looking for the same. Below link provides steps to use it and the first steps is to get the source files.
https://unix.stackexchange.com/question ... r-security

This uses simple-agent you mentioned but this was not a part of bluez5 package.

User avatar
Douglas6
Posts: 4710
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: Bluetooth pairing using fixed PIN on bluez 5.

Tue Oct 10, 2017 11:11 pm

You can download all of the BlueZ 5 test scripts with

Code: Select all

sudo apt-get install bluez-test-scripts

sachineswar
Posts: 4
Joined: Mon Apr 17, 2017 8:20 pm

Re: Bluetooth pairing using fixed PIN on bluez 5.

Wed Oct 11, 2017 1:31 pm

Douglas6 wrote: You can download all of the BlueZ 5 test scripts with

Code: Select all

sudo apt-get install bluez-test-scripts
Thanks a lot Douglas. This is what i was looking for. Now i can look into configuring Bluetooth PAN with all the paired devices.

mbezerril
Posts: 11
Joined: Fri Jul 26, 2019 8:22 pm

Re: Bluetooth pairing using fixed PIN on bluez 5.

Fri Jul 26, 2019 8:26 pm

Did you get the Simple-agent working with the bluez5? I can't do this in the Raspberry pi zero W

User avatar
Douglas6
Posts: 4710
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: Bluetooth pairing using fixed PIN on bluez 5.

Fri Jul 26, 2019 8:33 pm

What seems to be the problem?

mbezerril
Posts: 11
Joined: Fri Jul 26, 2019 8:22 pm

Re: Bluetooth pairing using fixed PIN on bluez 5.

Fri Jul 26, 2019 10:47 pm

I put the simple-agent to run, and when I try to pair, the phone asks for the pin, I put the exact same pin that I've hard coded and my phone says that the pin is incorrect.

This is my simple-agent:

Code: Select all

#!/usr/bin/python

from __future__ import absolute_import, print_function, unicode_literals

from optparse import OptionParser
import sys
import dbus
import dbus.service
import dbus.mainloop.glib
try:
  from gi.repository import GObject
except ImportError:
  import gobject as GObject
import bluezutils

BUS_NAME = 'org.bluez'
AGENT_INTERFACE = 'org.bluez.Agent1'
AGENT_PATH = "/test/agent"

bus = None
device_obj = None
dev_path = None

def ask(prompt):
	try:
		result = raw_input(prompt)
		print(result)
		return result
	except:
		result = input(prompt)
		print(result)
		return result

def set_trusted(path):
	print("SET_THURSTED")
	props = dbus.Interface(bus.get_object("org.bluez", path), "org.freedesktop.DBus.Properties")
	props.Set("org.bluez.Device1", "Trusted", True)

def dev_connect(path):
	print("DEV_CONNECT")
	dev = dbus.Interface(bus.get_object("org.bluez", path), "org.bluez.Device1")
	dev.Connect()

class Rejected(dbus.DBusException):
	_dbus_error_name = "org.bluez.Error.Rejected"

class Agent(dbus.service.Object):
	exit_on_release = True

	def set_exit_on_release(self, exit_on_release):
		self.exit_on_release = exit_on_release

	@dbus.service.method(AGENT_INTERFACE, in_signature="", out_signature="")
	def Release(self):
		print("Release")
		if self.exit_on_release:
			mainloop.quit()

	@dbus.service.method(AGENT_INTERFACE, in_signature="os", out_signature="")
	def AuthorizeService(self, device, uuid):
		print("AuthorizeService (%s, %s)" % (device, uuid))
		authorize = ask("Authorize connection (yes/no): ")
		if (authorize == "yes"):
			return
		raise Rejected("Connection rejected by user")

	@dbus.service.method(AGENT_INTERFACE, in_signature="o", out_signature="s")
	def RequestPinCode(self, device):
		print("RequestPinCode (%s)" % (device))
		set_trusted(device)
		return "3211"

	@dbus.service.method(AGENT_INTERFACE, in_signature="o", out_signature="u")
	def RequestPasskey(self, device):
		print("RequestPasskey (%s)" % (device))
		set_trusted(device)
		#passkey = ask("Enter passkey: ")
		#print(passkey)
		#print(type(passkey))
		#return dbus.UInt32(passkey)
		return dbus.UInt32("3211")

	@dbus.service.method(AGENT_INTERFACE, in_signature="ouq", out_signature="")
	def DisplayPasskey(self, device, passkey, entered):
		print("DisplayPasskey (%s, %06u entered %u)" %
						(device, passkey, entered))

	@dbus.service.method(AGENT_INTERFACE, in_signature="os", out_signature="")
	def DisplayPinCode(self, device, pincode):
		print("DisplayPinCode (%s, %s)" % (device, pincode))

	@dbus.service.method(AGENT_INTERFACE, in_signature="ou", out_signature="")
	def RequestConfirmation(self, device, passkey):
		print("RequestConfirmation (%s, %06d)" % (device, passkey))
		#confirm = ask("Confirm passkey (yes/no): ")
		#if (confirm == "yes"):
		set_trusted(device)
		return
		#raise Rejected("Passkey doesn't match")

	@dbus.service.method(AGENT_INTERFACE, in_signature="o", out_signature="")
	def RequestAuthorization(self, device):
		print("RequestAuthorization (%s)" % (device))
		#auth = ask("Authorize? (yes/no): ")
		#if (auth == "yes"):
		return
		#raise Rejected("Pairing rejected")

	@dbus.service.method(AGENT_INTERFACE, in_signature="", out_signature="")
	def Cancel(self):
		print("Cancel")

def pair_reply():
	print("Device paired")
	set_trusted(dev_path)
	dev_connect(dev_path)
	mainloop.quit()

def pair_error(error):
	err_name = error.get_dbus_name()
	if err_name == "org.freedesktop.DBus.Error.NoReply" and device_obj:
		print("Timed out. Cancelling pairing")
		device_obj.CancelPairing()
	else:
		print("Creating device failed: %s" % (error))


	mainloop.quit()

if __name__ == '__main__':
	dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

	bus = dbus.SystemBus()

	capability = "NoInputNoOutput"

	parser = OptionParser()
	parser.add_option("-i", "--adapter", action="store",
					type="string",
					dest="adapter_pattern",
					default=None)
	parser.add_option("-c", "--capability", action="store",
					type="string", dest="capability")
	parser.add_option("-t", "--timeout", action="store",
					type="int", dest="timeout",
					default=60000)
	(options, args) = parser.parse_args()
	if options.capability:
		capability  = options.capability

	path = "/test/agent"
	agent = Agent(bus, path)

	mainloop = GObject.MainLoop()

	obj = bus.get_object(BUS_NAME, "/org/bluez");
	manager = dbus.Interface(obj, "org.bluez.AgentManager1")
	manager.RegisterAgent(path, capability)

	print("Agent registered")

	# Fix-up old style invocation (BlueZ 4)
	if len(args) > 0 and args[0].startswith("hci"):
		options.adapter_pattern = args[0]
		del args[:1]

	if len(args) > 0:
		device = bluezutils.find_device(args[0], options.adapter_pattern)
		dev_path = device.object_path
		agent.set_exit_on_release(False)
		device.Pair(reply_handler=pair_reply, error_handler=pair_error, timeout=60000)
		device_obj = device
	else:
		manager.RequestDefaultAgent(path)

	mainloop.run()

	#adapter.UnregisterAgent(path)
	#print("Agent unregistered")
I know that simple-agent was disabled in bluez5, but I found some people that put this to work, but they didn'n explain how.

My bluez is 5.50.

The only thing that I didn't try is ask about.

User avatar
Douglas6
Posts: 4710
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: Bluetooth pairing using fixed PIN on bluez 5.

Sat Jul 27, 2019 2:06 am

Ok, I finally got around to running Buster (which includes BlueZ 5.50). I installed bluez-test-scripts, and gunzipped and ran simple-agent. It seems to perform as expected. I didn't try your code, which seems to be a modified version of something.

I'd be interested in knowing why you think simple-agent has been 'disabled'. And I'd suggest you contact the author of your script to find out why it's not working with BlueZ 5.50.

mbezerril
Posts: 11
Joined: Fri Jul 26, 2019 8:22 pm

Re: Bluetooth pairing using fixed PIN on bluez 5.

Sat Jul 27, 2019 9:56 pm

First... thank you for your efforts to help me!
Second...
I made the script modifications. I'm trying to put the fixed pin on the bluez5.50 in a raspberry pi 0 W. I made all like the tutorials and others did, but when I put the pin code, my phone says that is wrong and the raspberry don't pair.

My phone is a Moto G6 play with Android 9.
My raspberry is a Raspberry pi 0 W with Raspbian Buster and Bluez5.50.

User avatar
Douglas6
Posts: 4710
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: Bluetooth pairing using fixed PIN on bluez 5.

Sun Jul 28, 2019 2:49 am

Ah. Ok. You have no problem with simple-agent being 'disabled' or not working, regardless of the BlueZ version, you simply can't modify it to do what you want. I'll spend a little time on it tomorrow, although your specification leaves something to be desired.

User avatar
Douglas6
Posts: 4710
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: Bluetooth pairing using fixed PIN on bluez 5.

Sun Jul 28, 2019 6:59 pm

Ok, here's what I did. Since I'm running Buster, I started out with BlueZ 5.50. Then I installed the bluez-test-scripts and gunzipped simple-agent. I made the following change:

Code: Select all

        def RequestPinCode(self, device):
                print("RequestPinCode (%s)" % (device))
                set_trusted(device)
#               return ask("Enter PIN Code: ")
                return "3211"
I then made my Pi discoverable, and ran simple-agent (no flags). On my phone (also a Moto G6 running Pie), I selected to pair a new device and chose 'raspberrypi' The phone asked me for a PIN code, so I entered "3221". After a couple of seconds I was paired and connected. I tried some invalid PINs and the phone just kept asking for a new PIN.

Is that what you're looking to do?

mbezerril
Posts: 11
Joined: Fri Jul 26, 2019 8:22 pm

Re: Bluetooth pairing using fixed PIN on bluez 5.

Sun Jul 28, 2019 7:03 pm

I'm trying to make the exact same thing you did now!
But I'm using a raspberry pi 0 W.
Did you install using the

Code: Select all

sudo apt-get install bluez-test-scripts
command?
Where did you got the simple-agent scripts?

There is some hardware differences that break the communication?

User avatar
Douglas6
Posts: 4710
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: Bluetooth pairing using fixed PIN on bluez 5.

Sun Jul 28, 2019 7:15 pm

Yes, that is how I installed the simple-agent script. Remember if are running Stretch and upgraded to BlueZ 5.50, the scripts may no longer match.

I should have pointed out that I'm running on a Pi3B, although I can't think what difference that may make.

mbezerril
Posts: 11
Joined: Fri Jul 26, 2019 8:22 pm

Re: Bluetooth pairing using fixed PIN on bluez 5.

Sun Jul 28, 2019 7:17 pm

I'm going to make some tests and follow the exact same step you did. Let's see what happens.

Thank you so much for help me! :D

I'll return later to say the result of my tests

mbezerril
Posts: 11
Joined: Fri Jul 26, 2019 8:22 pm

Re: Bluetooth pairing using fixed PIN on bluez 5.

Mon Jul 29, 2019 3:00 pm

I made a new test and it's not working yet...
What I did...

I flashed a new Raspbian Buster in the SD card.
  1. I configured the static IP and SSH and the Wi-Fi settings.
  2. Then I run

    Code: Select all

    sudo apt-get -y update && sudo apt-get -y upgrade && sudo apt-get -y dist-upgrade
  3. Then I run

    Code: Select all

    sudo apt-get install bluez-test-scripts
    but I can't find any downloaded script on /usr folder.
  4. So I went to the Documents folder and run

    Code: Select all

    git clone https://git.kernel.org/pub/scm/bluetooth/bluez.git
  5. after finished the download, I went to the /etc/bluetooth/main.conf to set the pairing and discoverable timeout to 0 and after I run the

    Code: Select all

    sudo hciconfig hci0 sspmode 0 
    command.
  6. I entered back in the /home/pi/Documents/bluez/tests and run the simple-agent without any modifications.
  7. I went to my phone and put to pair and put the "0000" code, and in the raspberry ( zero W) the prompt asked for some pin and I putted the pincode "0000" and...
The phone sad that the pin is wrong....
I don't what I did wrong now. :cry:

User avatar
Douglas6
Posts: 4710
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: Bluetooth pairing using fixed PIN on bluez 5.

Mon Jul 29, 2019 4:09 pm

After installing bluez-test-scripts, the simple-agent script should be found in /usr/share/doc/bluez-test-scripts/examples/. You'll need to gunzip it. Could you try running that script, with Python and not Python3?

mbezerril
Posts: 11
Joined: Fri Jul 26, 2019 8:22 pm

Re: Bluetooth pairing using fixed PIN on bluez 5.

Mon Jul 29, 2019 5:43 pm

I went to /usr/share/doc/bluez-test-scripts/examples/ , runned gunzip simple-agent.gz.
Then I tried

Code: Select all

./simple-agent
sudo ./simple-agent
python simple-agent
sudo python simple-agent 
And in all tries happend the same thing. My phone keeps saying that the pin is incorrect, and I'm putting the same number when the script ask me.
I didn't make any change in the code.
There is some secutiry settings that in missed?

Note: On the first line of the script has a comment that says to the terminal wich kind of interpreter use, and there is only python, wich means that are the python2.7 the default interpreter.

User avatar
Douglas6
Posts: 4710
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: Bluetooth pairing using fixed PIN on bluez 5.

Mon Jul 29, 2019 5:46 pm

Ok. It sounds like the only difference is the Pi0W vs. the Pi3B. I'll try and dig up my Zero and test on that.

User avatar
Douglas6
Posts: 4710
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: Bluetooth pairing using fixed PIN on bluez 5.

Mon Jul 29, 2019 9:24 pm

Um, I guess I don't own a Pi0W (just a Pi0). I've put one on order, and I'll give it a run-thru when it arrives, by the weekend.

mbezerril
Posts: 11
Joined: Fri Jul 26, 2019 8:22 pm

Re: Bluetooth pairing using fixed PIN on bluez 5.

Mon Jul 29, 2019 9:34 pm

:shock: You are really helping me!

I searched about the hardware differences between the two boards and the only difference I found was the processor.
Maybe the bluez is having some bug on rpi0w processor?

I found this table, and something that called my attention was the 32-bits processor instead of the 64-bits like the rpi3
Image

User avatar
Douglas6
Posts: 4710
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: Bluetooth pairing using fixed PIN on bluez 5.

Mon Jul 29, 2019 9:46 pm

I can't see how the processor would make a difference. I frankly expect the Zero to give me the same results as the 3B, but there's only one way to know.

User avatar
davidcoton
Posts: 3922
Joined: Mon Sep 01, 2014 2:37 pm
Location: Cambridge, UK

Re: Bluetooth pairing using fixed PIN on bluez 5.

Mon Jul 29, 2019 9:49 pm

mbezerril wrote:
Mon Jul 29, 2019 9:34 pm
I found this table
I wouldn't put too much emphasis on that conclusion. The Pi3B under Raspbian works in 32bit mode, so the difference is not so great (though still a possibility).

BTW, the last line of the table is comparing apples and pears.
Signature retired

User avatar
Douglas6
Posts: 4710
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: Bluetooth pairing using fixed PIN on bluez 5.

Mon Jul 29, 2019 10:34 pm

I just noticed something odd. I've never changed the sspmode, as you did. In fact, when I tried, i couldn't:

Code: Select all

[s][email protected]:~ $ sudo hciconfig hci0 sspmode 0
Can't set Simple Pairing mode on hci0: Input/output error (5)[/s]
So, there's another odd difference.

Could you try setting sspmode back to '1', and retest?

Sorry, my mistake. Still investigating, but I believe sspmode is making the difference.

mbezerril
Posts: 11
Joined: Fri Jul 26, 2019 8:22 pm

Re: Bluetooth pairing using fixed PIN on bluez 5.

Mon Jul 29, 2019 11:02 pm

I made as you ask, and here are some results using the sspmode 1 with differents capabilities...

sudo ./simple-agent -c NoInputNoOutput :
Only show on my phone "pair" and "cancel" and automatically accept after touch on pair.

sudo ./simple-agent -c DisplayOnly and sudo ./simple-agent -c DisplayOnly:
Only show me a number and asks to confirm with yes or no in the raspberry terminal and phone

sudo ./simple-agent -c KeyboardOnly:
Show me a number on the phone and I need to type this number on raspberry

sudo ./simple-agent -c DisplayYesNo:
Very weird... The phone just wait showing me nothing and on the raspberry I need to type yes or no.

In none of the cases, my phone asked me to type some pin.
Last edited by mbezerril on Tue Jul 30, 2019 2:46 pm, edited 1 time in total.

Return to “Advanced users”