Android Bluetooth Connection Secure Insecure - android

I have been playing around with the bluetooth API for Android 2.2 (API level 8, HTC Desire) and had an app connecting to an embedded Bluetooth device using:
device.createRfcommSocketToServiceRecord(DEV_UUID);
This generated a pairing request as expected, however to streamline the connection process I wanted to avoid the user interaction when pairing so moved to API level 10 (HTC Desire with CyanogenMod 7) so I could use:
device.createInsecureRfcommSocketToServiceRecord(DEV_UUID);
When testing this also works as expected (connecting without prompting the user to pair), however when I try to create the secure RfcommSocket under API level 10 as before with 2.2 I get a connection refused exception...
java.io.IOException: Connection refused
at android.bluetooth.BluetoothSocket.connectNative(Native Method)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:204)
As far as I can tell this should still work in the same way, prompting the user to pair?
EDIT:
Just tried again using the following code and the outcome is the same (working for insecure but not for secure), I will try and get my hands on a stock 2.3 device to test on.
try {
Method m = dev.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class } );
BluetoothSocket bs = (BluetoothSocket)m.invoke(dev, devUUID);
Log.d("TEST", "Method Invoked");
bs.connect();
Log.d("TEST", "Connected to socket");
bs.close();
Log.d("TEST", "Closed Socket");
}

While looking for the solution of similar problem in my app, I have found this blog from code.google.com
It will help all those who are still looking for this problem solution on SO
http://mobisocial.stanford.edu/news/2011/03/bluetooth-reflection-and-legacy-nfc/ (link not working anymore)
The solution has become very simple now. Just include InsecureBluetooth.java in your project and change 2 lines in BluetoothChatService.java.
tmp = InsecureBluetooth.listenUsingRfcommWithServiceRecord(mAdapter, NAME, MY_UUID, true);
and
tmp = InsecureBluetooth.createRfcommSocketToServiceRecord(device, MY_UUID, true);
Thats it !

Related

How to make Android connect after the Bluetooth Adapter has been disabled & reenabled?

I have written an app that connects to a BLE device. The app works OK on most devices; but some devices (most noticeably Huawei P8 Lite and Nexus 6P) refuse to connect after the Bluetooth adapter has been disabled.
This is the test sequence:
Make sure the app is NOT running.
Slide down from the top, disable BT for a couple of seconds, then re-enable bluetooth.
Start the app. The app automatically connects to a bluetooth address stored in the preferences.
Wait for connect. This is where nothing happens on Huawei phones, but other phones, such as Samsung, works like a charm.
Verify from another phone the device is advertising and you can
connect to it.
This is the code I use to connect:
private final Runnable mBeginConnectRunnable = new Runnable() {
#Override
public void run() {
synchronized (GattConnection.this) {
if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
try {
mBluetoothAdapter.cancelDiscovery();
mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mAddress);
mGatt = mBluetoothDevice.connectGatt(mContext, mBackgroundConnect, mGattCallback);
final boolean connectSuccess = mGatt.connect();
Log.d(TAG, String.format(Locale.ENGLISH, "mGatt.connect(%s, %s) %s",
mAddress,
mBackgroundConnect ? "background[slow]" : "foreground[fast]",
connectSuccess ? "success" : "failed"));
refreshDeviceCache(mGatt);
} catch (Exception ex) {
Log.e(TAG, "Create connection failed: " + ex.getMessage());
setState(State.Closed);
}
} else {
Log.d(TAG, "Can't create connection. Adapter is disabled");
setState(State.Closed);
}
}
}
};
All calls are posted via a Handler to the main thread. I can see it waits for a connect, gives up after 30 seconds at which I call BluetoothGatt.close() on the object and nulls it. It's like nothing is out there.
After some time, later in the day, it works again.
Help is highly appreciated :-)
Update September 14, 2018: After great explanation from Emil I've updated our app and as such don't have this problem on the Nexus. I've noticed the Huawei P8 Lite continues to scan in the background and it seems there is nothing you can do to stop it.
To demonstrate the problems I've made a very simple and clean app that exercise the Bluetooth LE functionality on a phone and used it to demonstrate this problem and also the P8 is broken. The app is available here: https://play.google.com/store/apps/details?id=eu.millibit.bluetootherror
Source is available here: https://bitbucket.org/millibit/eu.millibit.bluetootherror/src/master/
I hope I over time can extend this app to make it a test vehicle for Android documenting all the stange behavior from Android and collect it in a database. In case you are interested in contributing, don't hesitate to drop me a mail on bt.error#millibit.dk
The Android Bluetooth stack has a design flaw in its API. When you connect to a specific device by Bluetooth Device Address, there is no way to tell if you mean a Public address or Random address.
If you start to connect to a device with autoConnect=false which is not bonded and has not recently been seen in a Scan, it will assume you mean a Public address. So if you try to connect to a device having a static random address, it will fail.
To be sure you connect with the correct address type if the device is not bonded, you MUST perform a scan first, find the device and THEN start the connection attempt.

Android Bluetooth PIN pairing without user interface on Android 4.2+

There are similar questions to this here already, but the answers and suggestions relate to older versions of Android. I understand that the bluetooth stack has been completely revised from 4.2 onwards and older solutions do not work anymore.
I have tried all the older solutions to no avail. the use of the private APIs no longer works because they have changed. I dont mind using private APIs but it must work on the newest versions and later (ie API 17+)
I am trying to do the following:
set up a bluetooth pairing between an Android device and an embedded device using legacy PIN pairing without the embedded device being discoverable nor the user having to manually enter the PIN. In fact I want no PIN entry dialog box at all.
The plan is that the two devices have a predefined shared secret PIN, so that I can perform the pairing programmatically and then open an RFCOMM connection between them. All of this without UI. The hardware address of the embedded device is known to the Android program.
There is no security issue here. the project involves just talking to a nearyby, small embedded device through BT as simple as possible.
Ideas that might work on Android 4.2 (Jelly Bean) most welcome, thanks.
turns out some of the problem was inside the embedded device. on the Android side, the following works:
BluetoothSocket s = null;
try
{
s = device.createInsecureRfcommSocketToServiceRecord(SerialPortServiceClass_UUID);
}
catch (IOException e)
{
Log.e(TAG, "BT connect failed", e);
return false;
}
where
private static final UUID SerialPortServiceClass_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

Android zebra print not working on newer versions

We are using DiscoveredPrinterBluetooth to keep discovered printer, ZebraPrinterConnection and ZebraPrinter to send data to printer. Everything is working ok on older android versions, but on let say 4.0 is not working, finds printer but keeps showing insert pin screen. Get error in log:
V/BluetoothSocket.cpp(5371): ...connect(96, RFCOMM) = 111 (errno 111)
As I see there is problem with newer versions, looking at
Bluetooth pairing without user confirmation
but I don't know how to solve it in my case? Any ideas? Thanks
The 2.0 version of the Zebra SDK has an implementation of insecure bluetooth connections.
Check out BluetoothConnectionInsecure in the new SDK. This could be used instead of BluetoothConnection if you want insecure BT connections...

socket.connect causes "read failed socket might closed" only on Android 4.2.1 on Nexus [duplicate]

I have a project that connects to a device over Bluetooth. It used to work fairly reliably, but now it fails the BluetoothSocket.connect() call every time. (Well, I got it to connect once during the thousands of attempts over a 4 hour period.) Most of the code has been taken from the standard sample chat code in the API, with the exception of the common modification in getting the BluetoothSocket device itself:
Method m = device.getClass().getMethod(
"createRfcommSocket", new Class[] { int.class });
tmp = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));
Here's the method of interest, which gets run once a BluetoothSocket is obtained:
public void run() {
setName("ConnectThread" + mSocketType);
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
mmSocket.connect();
} catch (Exception e) {
Log.e(TAG, "Connection to " + mmDevice.getName() + " at "
+ mmDevice.getAddress() + " failed:" + e.getMessage());
// Close the socket
try {
mmSocket.close();
} catch (Exception e2) {
Log.e(TAG, "unable to close() " + mSocketType
+ " socket during connection failure", e2);
}
connectionFailed(e.getMessage());
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
}
The relevant log entry (printed when the exception is caught while calling connect()) is this:
11-30 10:23:51.685: E/BluetoothChatService(2870): Connection to
ZYNO-700091 at 00:06:66:42:8E:01 failed:read failed, socket might
closed, read ret: -1
This error used to come up once in a while. I have an aggressive reconnect system - it basically hammers the connection over and over until it connects, and if it were ever to disconnect, it starts hammering it again. So, it kills the connection thread and starts from scratch constantly. I had considered that there might be an issue there - maybe a multithreading one, or maybe in handling the socket cleanup/initialization. However, if that were the case, I'd still expect the first connection attempt to succeed, since that system doesn't kick in until there's a failed connection attempt.
I looked into the source code throwing the exception. The issue seems to be that the underlying InputStream has no data. Of course, that's not really an answer, just a step towards it. Why would the stream have no data?
I'm trying to keep an open mind about the potential issue. Am I getting the BluetoothSocket properly? The fact that it was once an intermittent issue and is now nearly constant makes me suspect multithreading, but that's a relatively simple topic in Java compared to C++ - hard to screw up if you know what you're doing. Plus, the majority of this code (in particular, the parts dealing with synchronizing the threads) is straight out of the sample code.
The device on the other end is an embedded Bluetooth device, so there's not much hope of debugging the problem from that end.
UPDATE ===========================
It occurred to me that it might be due to an OS upgrade (I'm running on Galaxy Nexus phones - I have several to test with). So I unpacked a new phone with 4.0.4 and it worked! So then went back and tested on the two original test phones, both running 4.2, expecting the failure I've been seeing all this time. Strangely, now it works on those phones too. I'd like to say I did something to make this work again, but I didn't. I'm still mystified, and now also suspicious that this thing is going to work when I really need it to.
I wonder if there's a possibility that somehow connecting using 4.0.4 could have properly set the state of the server module, making it receptive to the 4.2 devices? Just a shot in the dark, I suppose...
UPDATE 2 ===========================
I've found that unpairing and re-pairing will allow the devices to connect. It's a workaround, but it's better than nothing.
Jellybean has a completely different Bluetooth stack, so version differences could certainly be triggering something, but that in itself wouldn't explain why it stays working or not-working after connecting with an older device. Could it be to do with pairing? If it happens again, try unpairing from the device and pairing again.
I know this is kind of an old question. But as I was not able to find any solution on the web, here is a workaround I recently have created: IOException: read failed, socket might closed - Bluetooth on Android 4.3
In my case it was due to bad UUID in createRfcommSocketToServiceRecord() function.
I want to connect to SPP serial profile in raspberry pi 3 and I used this UUID:
private static final UUID MY_UUID_SECURE =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
I found somewhere in android documents' page for SPP.
I had the same problem while connecting to the arduino via bluetooth module.The problem only arised while connecting with arduino as it connected smoothly with another android phone bluetooth.
What worked for me was changing the UUID string..

BluetoothSocket.connect() throwing exception "read failed"

I have a project that connects to a device over Bluetooth. It used to work fairly reliably, but now it fails the BluetoothSocket.connect() call every time. (Well, I got it to connect once during the thousands of attempts over a 4 hour period.) Most of the code has been taken from the standard sample chat code in the API, with the exception of the common modification in getting the BluetoothSocket device itself:
Method m = device.getClass().getMethod(
"createRfcommSocket", new Class[] { int.class });
tmp = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));
Here's the method of interest, which gets run once a BluetoothSocket is obtained:
public void run() {
setName("ConnectThread" + mSocketType);
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
mmSocket.connect();
} catch (Exception e) {
Log.e(TAG, "Connection to " + mmDevice.getName() + " at "
+ mmDevice.getAddress() + " failed:" + e.getMessage());
// Close the socket
try {
mmSocket.close();
} catch (Exception e2) {
Log.e(TAG, "unable to close() " + mSocketType
+ " socket during connection failure", e2);
}
connectionFailed(e.getMessage());
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
}
The relevant log entry (printed when the exception is caught while calling connect()) is this:
11-30 10:23:51.685: E/BluetoothChatService(2870): Connection to
ZYNO-700091 at 00:06:66:42:8E:01 failed:read failed, socket might
closed, read ret: -1
This error used to come up once in a while. I have an aggressive reconnect system - it basically hammers the connection over and over until it connects, and if it were ever to disconnect, it starts hammering it again. So, it kills the connection thread and starts from scratch constantly. I had considered that there might be an issue there - maybe a multithreading one, or maybe in handling the socket cleanup/initialization. However, if that were the case, I'd still expect the first connection attempt to succeed, since that system doesn't kick in until there's a failed connection attempt.
I looked into the source code throwing the exception. The issue seems to be that the underlying InputStream has no data. Of course, that's not really an answer, just a step towards it. Why would the stream have no data?
I'm trying to keep an open mind about the potential issue. Am I getting the BluetoothSocket properly? The fact that it was once an intermittent issue and is now nearly constant makes me suspect multithreading, but that's a relatively simple topic in Java compared to C++ - hard to screw up if you know what you're doing. Plus, the majority of this code (in particular, the parts dealing with synchronizing the threads) is straight out of the sample code.
The device on the other end is an embedded Bluetooth device, so there's not much hope of debugging the problem from that end.
UPDATE ===========================
It occurred to me that it might be due to an OS upgrade (I'm running on Galaxy Nexus phones - I have several to test with). So I unpacked a new phone with 4.0.4 and it worked! So then went back and tested on the two original test phones, both running 4.2, expecting the failure I've been seeing all this time. Strangely, now it works on those phones too. I'd like to say I did something to make this work again, but I didn't. I'm still mystified, and now also suspicious that this thing is going to work when I really need it to.
I wonder if there's a possibility that somehow connecting using 4.0.4 could have properly set the state of the server module, making it receptive to the 4.2 devices? Just a shot in the dark, I suppose...
UPDATE 2 ===========================
I've found that unpairing and re-pairing will allow the devices to connect. It's a workaround, but it's better than nothing.
Jellybean has a completely different Bluetooth stack, so version differences could certainly be triggering something, but that in itself wouldn't explain why it stays working or not-working after connecting with an older device. Could it be to do with pairing? If it happens again, try unpairing from the device and pairing again.
I know this is kind of an old question. But as I was not able to find any solution on the web, here is a workaround I recently have created: IOException: read failed, socket might closed - Bluetooth on Android 4.3
In my case it was due to bad UUID in createRfcommSocketToServiceRecord() function.
I want to connect to SPP serial profile in raspberry pi 3 and I used this UUID:
private static final UUID MY_UUID_SECURE =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
I found somewhere in android documents' page for SPP.
I had the same problem while connecting to the arduino via bluetooth module.The problem only arised while connecting with arduino as it connected smoothly with another android phone bluetooth.
What worked for me was changing the UUID string..

Categories

Resources