Raspberry PI bluetooth backdoor/serial access

Aka: install a safe-mode-access.

I was programming my RasPI 3 to be a Wi-Fi AP. I don't have an HDMI monitor, only an HDMI converter and I'm not happy to use it. So, I was trying to setup my RPI by SSH. Of course, I was locked out by a wrong command in a script.

So, I was looking for an off-road access. RPI has an embedded WiFi and Bluetooth chipset. I'm using an USB WiFi dongle (because RPI chip doesn't support multiple SSID), so I can use both.
I prefer Bluetooth over embedded Wi-Fi for one reason: if I broke some other things (like routing),
I still have a way in (using a Serial bluetooth connection).

I'm using the latest (2017-07-05) Raspbian Lite image. Based on stretch I presume, because there is SystemD that is really annoying.

To initialize bluetooth connection, we need to add this unit to systemd:

[Unit]
Description=Bluetooth Backdoor

[Service] ExecStart=/opt/backdoor.sh

[Install] WantedBy=multi-user.target

(yes, the script is named "backdoor" for a reason)
Now we need the script itself:

#!/bin/bash
expect -f /opt/bluetooth.exp
sdptool add SP
/usr/bin/rfcomm watch rfcomm0 1 /sbin/agetty --noclear rfcomm0 38400 linux

Then, we need the expect file for bluetoothctl:

spawn bluetoothctl
send "power on\r"
expect "\[bluetooth]# "
send "agent on\r"
expect "\[bluetooth]# "
send "discoverable on\r"
expect "\[bluetooth]# "
send "default-agent\r"
expect "\[bluetooth]# "
send "quit\r"

Save these three files. Then, launch bluetoothctl and pair/trust your device. Then:

# systemctl enable backdoor.service

That's it. You can connect to it using (on another PC):

$ sudo rfcomm connect rfcomm0 AA:BB:CC:DD:EE:FF 1

And then using some terminal emulator (minicom) on

/dev/rfcomm0

(speed 38400).

You may need to add "--compat" to "ExecStart" for unit "bluetooth.service" in order to enable SDP (you can check by launching "sdptool browse local": if you see an error, you need to edit that systemd unit and then restart the daemon)