SticknFind update

So StickNFind, despite saying they’ll deal with the issues on Facebook, aren’t responding to email. I’ve now found over 30 people who are finding the tags don’t work or are very unreliable, and it seems none of us are getting a response.

I have played with them some more, and have found the following.

  • Battery contacts seem unreliable – squeezing one of the tags gently causes it to work.
  • Range is at most 20ft line of sight in a room. This only seems to work if I start next to the tag and move further away. If I start the app 20ft from the tag though, it rarely works, and when it does, the dot on the radar doesn’t turn blue, so I can’t make it beep or flash.
  • If I run a single tag, the radar distance can be fairly constant. With 2 other tags, they dance around.
  • If I start downloading a large file on my laptop near the tags, the distance increases rapidly or they stop working entirely. There is some form of interference.
  • They seem much more reliable outside of buildings.

What’s wrong with the alarm industry today?

Wilco Baan Hofman made a talk last week at the Hack in the Box conference, where he detailed some of his work in reverse engineering the proprietary SIA-HS protocol, which is now becoming more and more common in alarm reporting systems.

As usual, the security industry prefers secrecy over openness, so most of these alarm reporting protocols, and importantly all of their implementations are closed. Time and time again this has been proven to be a sure-fire way of building systems with gaping security holes.

He states 10 assumptions that Alphatronics, the designer of SIA-HS, made. All of these assumptions lead to fatal mistakes being made in the implementation of a secure protocol.

A lot of these assumptions are technical – I can attribute them to ignorance or incompetence.

But not assumption 5. This has to be a conscious, management level decision.

If my product is certified, it is secure

This couldn’t be any more wrong, and points to a worrying, widespread, archaic and persistent attitude problem that many alarm manufacturers have. He backs his statement up with a quote:

“Alphatronics emphasizes that the uncovered vulnerabilities do not influence
the product certification.”

Now, some quotes I have from my correspondence with three alarm manufacturers:

 “The fact remains that this is a Grade 2 security panel and meets all the security requirements for that grade.”

“We consistently strive to ensure that all our products meet the relevant standards and we generate a continual program of product testing and quality control. The product has not been designed to compete with professionally installed commercial products.”

“We have been selling wireless alarms since 1990 and code issues have never been a problem. Potential burglars would need extensive knowledge and equipment to overcome any alarm system.”

All of these are in response to the disclosure of easily exploitable vulnerabilities. The next one is in response to simply discussing vulnerabilities:

“If you have managed to reverse engineer our protocol i would be:

1. Suprised

2. Glad to see you in court”

I honestly find this attitude offensive and I can’t understand it.

Why is it a problem that alarm manufacturers only want to meet the standards and not exceed them?

  • The environment alarms are deployed in is continually changing. What seemed secure 10 years ago may now be stunningly insecure today. Standards take years to draw up, and are normally out of date by the time they are published, and are then used for long periods.
  • A standard cannot and does not cover all known angles of attack. If there is a valid and demonstrable vulnerability but it is not encompassed by the standard, that does not stop it being a vulnerability.
  • Very few alarm systems have any mechanism to update anything but the alarm panel firmware. Most panels don’t allow updates to be carried out automatically or by end users. This massively constrains the ability to patch security holes. The attitude that “it was once certified secure, it is secure now” just causes this practice to continue.
  • Most of the vulnerabilities raised with the manufacturers I would consider a direct result of bad software design and could be fixed with firmware updates. Continuing to sell these systems without altering them is lazy.
  • Electronic and software security systems differ to physical security systems. It would take me 2 hours each and every time to drill the door on a high end safe. However, if I invest a few days in analysing an alarm system and find a vulnerability, I can usually use the vulnerability in seconds time and time again. Importantly, I can package the vulnerability in a way that any idiot can use it.

Maintaining this position directly results in insecure, un-patchable alarm systems being deployed. It doesn’t look like this is going to change.

User comments from StickNFind – some posts are being deleted

Received 2 tags yesterday. Initially both worked fine, now one stopped. The broken one beeps/lights up when you insert the battery but I cannot pair it anymore. Also using other bluetooth low energy apps like “SensorTag” I can only pair to one of the two.
How do I get a refund? 1st sticker just stopped working and cannot be re-paired, second sticker seemed to be working solidly but is now lost and no amount of scanning and walking around can find it (was attached to cats collar, cat is back minus collar) I suggest you fix your technology before you sell any more.
Got my stickers and use it with iPhone App… Have to say that it needs some improvement as sometimes it works sometimes it don’t so in this stage its very unreliable. Sometimes it alerts if its just side by side sometimes it does not even fare away… Might be an issue of ios… My pepple watch does much better stick to the Bluetooth as sNf does… It often completely
looses connection to the phone… Still some work to do
Sad to say these are not very good 🙁 really want them to be but they just don’t work very well, for example they keep loosing pairing so when you try to find item, even if on my lap, it can’t find it. The app doesn’t work well and is quite confusing for example what is zooming and why does it show direction if its only distance? Every time you open it you have to agree to the terms. I appreciate its an early product but I think should have kept it for a bit longer to make it fully work prior to release. Like I said I love the concept just wish it worked!

Thomas Krømke

Ordered 2. None of them can be find with the app or bluethooth on my iphone or ipod  hope the company will fix this somehow.

Ian Anderson

Works fine here so far on note 2. Only played a little bit though. Had to reseat the battery to wake up and pair the first tag which had been on my keys for a couple of weeks.

Tom Grant

Has anyone had any luck getting these things to work iOS or Android? Been waiting on this android app to find out if mine did. And now I find that I cant even pair them. One beeps sometimes when tapped, other does nothing. Swapped batteries to rule that out. One beeped and held the tone till I pulled the battery out.

Greetings,

Received the 10 pieces I ordered a few days ago. Have been playing around with one for the past few days. Works rather erratically. Anyone else out there have issues? Would love to read real user comments. Thank you & have a great day.

My stickers didn’t ship on time. After several emails and comments, I demanded my money back, and about 6 hours later I received a message that they had shipped from Hong Kong. They shipped via registered mail, so I had to drive to the post office to get them. I tried every method I could find to pair them, but only one sticker beeps and will not pair, and the other does nothing. So, I have to go buy new batteries? I’ve never seen a brand new product ship with dead batteries!

My stickers are going haywire, they all interfere with each other and 2.4ghz sources in the house (wifi, other Bluetooth devices). Basically if I pair my iPhone 5 to a sticker in my wallet and set the leash to “out of range”, it will beep constantly as I walk past RF noise sources. 2 stickers push the range of both back dozens of feet and they take turn being connected. Useless.

@StickNFind Why does one of my stickers have a logo on it and not work, and the other has no logo and does beep and light up?

Finally got my #SticknFind bluetooth item fining stickers. Very underwhelming. They still don’t have the promised App.

@cybergibbons @hansolo_ distance reading is really flaky! Pic was shot while ALL stickers were <1cm away #sticknfind pic.twitter.com/uz9JWgRbzP

@StickNFind some of my SnFs were DoA. solder bubble touching batt too small, wouldn’t make contact. added paper to fill the gap, works now

@cybergibbons @StickNFind Me too. Range about 20 feet. HOW much did I pay for these things?

@cybergibbons @StickNFind Managed to get one to work with a pen. The other one doesn’t seem to react even after reseating the battery

I received 2 of the 12 stickers I expect. They can be a little temperamental, but they work when paired to an iPad 3 at home. In my crowded tech work environment, it barely works at all.

Luckily though we have an iPad, idk which model but it’s one of the newer ones. I managed to connect a sticker without disconnect problems like others had, instead I have an accuracy problem. 0-3 feet it works fine, but after that the distance fluctuates even when both the iPad and sticker (and everything else in the room) are completely still and have line of sight. 6ft shows 4-12ft, 15ft shows 32-64ft, etc. Temp actually showed 72F down to 68F in a 78F room

Sigh :/

@StickNFind help! I leashed my keys and once out of range the iOS app keeps triggering alarm. No way to get out of it without force quitting

Why XOR alone is an incredibly bad “encryption” technique

From HITB presentation

From HITB presentation

In Wilco Bann Hoffman’s presentation at HITB, he showed some slides with screenshots from Wireshark, a packet capture utility.

Down at the bottom, you can see a hex representation of the data in the packet on the left. On the right is an ASCII representation of the same hex data. “.” means “Yeah, that hex doesn’t mean anything to me”. When you see this, it means you are looking at something that is likely binary data or encrypted text.

This is a security protocol, so we might assume it is encrypted in some manner. It can be a royal pain to work out how something is encrypted, especially with such a small amount of data. But because the designer of this protocol has made a schoolboy error, anyone with any experience will immediately see how it is encrypted and what they key is. I am not exaggerating here – I saw it in seconds and knew others would to.

Look at the hex data. What do you see? There are an awful lot of 0xB6 values there, aren’t there?

Why would that be?

A really common building block in encryption is to XOR (eXclusive OR) the data with some key material. It’s a clever and fundamental tool used in nearly every single encryption algorithm.

Let’s look at a really quick example:

11010010
10101010 ⊕
--------
01111000

We bitwise XOR the values of the data (0xD2) with the key (0xAA) to get the “encrypted” data (0x78).

To unencrypt, we just do the same thing:

01111000
10101010 ⊕
--------
11010010

Very clever, very clean, and also very easy to do quickly on most processors.

If the key is not constant, this can be an excellent way of encrypting. But if the key (0xAA) stays the same, we have a big problem.

Why? What happens when we encrypt 0x00:

00000000
10101010 ⊕
--------
10101010

The cipher text is the same as the key! Oh no. We’ve just leaked our key.

An awful lot of protocols end up with a lot of 0x00 in them. It’s a common padding value and a common string termination value. We just need to look at the packet in Wireshark, see all of those 0xB6, and we can be pretty certain that XOR is being used with a key of 0xB6.

A very simple python script

A very simple python script

And this is the case. A quick Python script later, and mostly ASCII comes out.

Now we have some plaintext

Now we have some plaintext

Even if 0x00 wasn’t used so frequently, XOR with a fixed key does nothing to increase the entropy of the data. If we used frequency analysis, we would get meaningful results. It’s also pretty easy to bruteforce a single byte key – you can even automate the detection of valid ASCII characters.

Very worrying that this was used over the open internet for security purposes.

First impressions of my StickNFind Bluetooth location stickers

Ever since reading Cory Doctorow’sMakers“, I was excited about the idea of being able to tag my belongings with small electronic devices that would flash and beep to enable me to locate them.

There were some devices already available, like the Loc8tor range of products. However, battery life was poor (2-5 months typical), feature set was limited, and they were still quite large.

So when I saw the StickNFind project on IndieGoGo (a crowd funding site, similar to KickStarter), I was really excited. Ultra-small (probably the size of some arbitrary US denominated coin I am wholly unfamiliar with), long battery life (1 year typical), 100 ft range, and uses an iPhone or Android phone to locate them. Perfect! I signed up for 4 of them.

They turned up yesterday, and it appears I am one of the first people to get hold of them. Unfortunately, it appears that not all is well in StickNFind land.

They came well packaged in a cardboard box, with the four tags stuck onto a piece of cardboard. The instructions noted that I may need to “tap it 4 times with your finger or with a pen” to wake it up. I tried gently tapping the first one I peeled off, and nothing happened. Then I tried harder. Still nothing. I checked for one of those small plastic tabs that you need to pull out to activate a battery. Nothing.

An open and closed StickNFind

An open and closed StickNFind

I peeled a second one off. This one responded after a few taps with a flash and a beep. So did the third, and fourth. Looks like the first one is dead.

I then downloaded the app onto my iPhone 5. This is the latest v1.1 app.

The three tags paired fairly quickly with my phone with the default text tags of “sNf – 0”, “sNf – 1”, “sNf – 3”. They kind of showed up on the radar view, but the range was showing big numbers in the range of 100 (feet? inches? cm? m? the axis is not labelled).

When they are showing on the radar screen, you can make them beep, flash or do both. For some reason, only tag 0 and 1 would do this. 3 was showing on the screen, and the beep/flash buttons were present, but it wouldn’t respond.

I found out the app makes you accept the EULA each time you start it, and crashes very frequently.

I then tried the “Find It” feature. I turned this on for tag 0. It immediately said that the tag had been found. I turned it on for tag 1. The tag beeped and flashed a few times, and told me it had been found. Operation seemed intermittent with all three tags.

Back to the radar, and I found that the three tags, despite being adjacent to each other, were showing at ranges varying from a couple of units to a hundred or more. They kept on moving around, despite the tags and phone being stationary.

Not working so well - none show up despite being next to the phone

Not working so well – none show up despite being next to the phone

I opened the fourth tag and reseated the battery. This time it showed up on the iPhone, but as a “StickNFind – 0” – why is this name different to the others?

Why is the name different for one tag?

Why is the name different for one tag?

All the while, on the radar page, the tags were dancing back and forth like a loon on speed. I couldn’t see how the leash functionality (where you are warned that the tag has moved away from you) would work.

I looked at the temperature screen. One was showing 11degC, another 22degC. It does say you may need to wait. So I waited until morning.

Next morning, tag “sNf – 3” had completely stopped responding. The others were intermittent – I couldn’t seem to wake them. The temperatures were still wildly different, despite being in a centrally heated space next to each other.

I thought I would test the range. Even across our small open downstairs space, they would all drop out now and then. I went upstairs and none of them would work, and it is only a wooden floor.

I attached one tag to my keys. I took them to work and back again, and found that it didn’t work for most of the day. It briefly worked in my office, but the range was less than 30ft.

Once home, I found that I couldn’t get any of the tags working at all. One of them beeped and flashed a significant time after it was asked to. I reseated several of the batteries and checked they were dead, but still no luck.

I thought maybe my phone was at fault (although it works with other Bluetooth devices), so I tried my “new iPad”. I managed to pair it with one of the tags, but could get the tag to do nothing useful.

I checked the batteries using a multimeter, and all are showing 3V as expected.

Detail of inside the tag

Detail of inside the tag

So – my first impressions:

  • Tags don’t seem to work most of the time
  • Range isn’t reliable
  • Leash functionality is unusable as a result
  • Temperature readings are way off and vary from device to device
  • App crashes frequently and has many quirks

Really not good. I approached @StickNFind on twitter and found they suggested I call them in the US. I requested email, as a call would cost me a fair amount. No response. Website just has a contact form, no email address.

Since then, a few others have posted comments on IndieGoGo suggesting similar problems:

My stickers are going haywire, they all interfere with each other and 2.4ghz sources in the house (wifi, other Bluetooth devices). Basically if I pair my iPhone 5 to a sticker in my wallet and set the leash to “out of range”, it will beep constantly as I walk past RF noise sources. 2 stickers push the range of both back dozens of feet and they take turn being connected. Useless.
Sad to say these are not very good :( really want them to be but they just don't work very well, for example they keep loosing pairing so when you try to find item, even if on my lap, it can't find it. The app doesn't work well and is quite confusing for example what is zooming and why does it show direction if its only distance? Every time you open it you have to agree to the terms. I appreciate its an early product but I think should have kept it for a bit longer to make it fully work prior to release. Like I said I love the concept just wish it worked!
just received my two stickers and they both will not activate upon multiple tries at tapping. Needs to be replaced

So far, I am really not impressed. Unfortunately, I also backed the BluTracker project by the same guys. I don’t know if this is a problem with my specific devices, or the product as a whole. I hope they respond.

Note – please don’t bitch about crowd funding being a risk etc. They have delivered a product that doesn’t seem to work and it is being sold to people not on IndieGoGo now.

Inside a high security electronic combination lock

 

ObliqueView posts an interesting series of images of the inside of a Kaba Mas X-09 electronic combination lock (link to manufacturer page and full set). These locks are expensive, but very highly regarded by many locksmiths. At the same time, many old-school locksmiths seem to distrust anything electronic. This seems to have hindered the security analysis of these locks.

I’ve not seen one of these away from a secure filing cabinet. They are very expensive, so this is a nice little insight into their workings. Some quick notes on what I can observe:

  • The top of the large (ultra?) cap has been blanked out. I can’t imagine what you would need to hide.
  • The pink/orange dots look like UV sensitive ink. This might be for post-intrusion forensics.
  • The board has a conformal coating or lacquer. I’m surprised it isn’t fully potted – it would be better for security.
  • It looks like a simple two-layer PCB.
  • Something odd is going on with the vias. There are a lot of normal small circular vias covered by green solder mask. But a lot are large square, and not covered by solder mask. They might be test points, but that is a lot of them. (edit – I asked on Electronics Stackexchange, without seeding anyone’s mind, what they were – and got test points back. I can only assume because this has to be so reliable, they are into heavy testing)
  • Looks like markings on the chips have been removed. This is token. You can identify nearly all processors and chips without markings.
  • One of U1 looks like a serial EEPROM, from one side being common and the proximity to the larger chips. It looks like the footprint is designed to take two different sized ICs.
  • PCB design is messy, not pleasing to the eye. I can’t work out if this is because it was autorouted, routed by someone inexperienced, or if it is just meant to be confusing to make probing hard.

If anyone has a broken one of these, I’d take it off your hands…

Reverse engineering a wireless burglar alarm, part 8

Last time we worked out that we could drive the CC1150 daughterboard using the Seeeduino Mega Arduino board easily.

The Seeeduino Mega uses a ATmega2560 microcontroller, which has a number of features which will help us do this:

  • Hardware SPI interface – this makes high speed SPI connections almost effortless. No nasty bit-banging here.
  • Pin change interrupts – this means we can quickly and efficiently respond to the clock signal coming into the microcontroller. 6.25kHz isn’t so fast that it precludes the use of a polling technique, but polling is wasteful and limits what we can do with the rest of our time.
  • Lots of memory – we don’t need to care about creating wasteful buffers. The 8KB in the 2560 is far more flexible that 2KB in the 328.

Connecting the hardware is easy – we need to use PB0 (CS), PB1 (CLK), PB2 (MOSI) and PB3 (MISO). These map through to pins 53, 52, 51 and 50. We are going to use the adjacent PL0 port (pin 49) to clock out the data to GDO0. VCC is supplied from the 3.3V supply on the Seeeduino Mega (it is switchable from 3.3 to 5V operation – a valuable addition).

It was at this time I found out that if you connect the CC1150 incorrectly it gets very hot and starts letting out the magic smoke. It also still works after this..

Now, as for the software – I’m not really sure where to begin. It’s quite hard to explain bit-by-bit. I hope it is self-explanatory, to a large extent.

The code is available on github. There isn’t really much fancy going on here – I am using some CC11xx headers from previous projects to help identify the settings registers. All this aims to do is take the 48 bit (6 bytes) of data we have sniffed from a door contact, and replay this signal. It configures the CC1150 exactly as per the sniffed traffic, and then we use a pin change interrupt to clock the data out.

Oooo 2-FSK!

Oooo 2-FSK!

Once all of this is wired up, I can immediately see that my spectrum analyser is showing bursts of 2-FSK. That must mean things are approximately correct. I used to hate working with RF – I could never tell if it was the transmitter, receiver or just idiocy that was preventing things from working. A spectrum analyser gives you reassurance that you are doing at least something right.

So now I need to see if the bell box can learn the door contact from this signal. I connect up the bellbox, press and hold learn, and… nothing. I try the door contact, and it is learnt immediately. I must be doing something wrong.

(when working with alarm sirens, you need to be careful. If you leave the siren connected, they can be loud enough to actually damage your hearing. I never trust the soft setting to turn off the siren for testing, so always disconnect it physically. This then presents another danger – siren drivers can produce large voltages when the siren is open circuit – sometimes hundreds of volts, enough to give you a fair belt.)

The trusty Saleae Logic Analyser comes out again, and I connect it up to my cloned alarm sensor. It’s apparent that the signal isn’t quite right – a few extra bits here and there. A really quick and easy debug method is to use extra IO ports – PL1 and PL2 in this case – to  observe timing and code flow. Serial is just too slow for this kind of stuff – it might help me, but normally it slows down execution enough to cause problems. ATmega chips do have on-chip debug, but it is always more trouble than it is worth – these are very simple microcontrollers!

He's learning, we're learning.

He’s learning, we’re learning.

It turns out it is a simple bug – I’d used an incorrect comparison to signify the end of a packet. The code is fixed, and I try again. This time the panel learns the remote!

So where to from here? I need to start experimenting with the data in the packet, and seeing what the panel will and won’t accept. Next time.

Arduino misconceptions 7: boolean variables are a native C/AVR type

A lot of Arduino sketches make fairly heavy use of the “boolean” type – after all, digitalRead() and digitalWrite() use TRUE/FALSE or HIGH/LOW don’t they? Why not use boolean? It seems intuitive, after all.

One of the silliest lines in Arduino

One of the silliest lines in Arduino

Well, there are many, many reasons not to use boolean. I think it is one of the biggest mistakes in the Arduino environment.

Everything on the AVR is at least 8 bits wide. If I write to a memory location, register, or port, I need to write all 8 bits. If I read, I need to read all 8 bits. A boolean is just a single bit. We can infer from this that we are going to need to do some work to represent a boolean.

The next thing we need to realise is how C evaluates true and false on various  types. This is really simple. If every bit in an integer is set to 0, evaluate this as false. Otherwise, true. This stems from the way that processors work internally, using the Z (zero) flag to determine if a branch should be taken or not.

This means that 0xA6 is as true as 0x01 is as true as 0xFF. The only thing that evaluates to false is 0x00.

These two things – the smallest native memory location being 8 bits wide, and the evaluation of 0x00 as false – make it really easy to implement a boolean. We just use an 8-bit unsigned integer and call it boolean. We then assigned 0x00 to FALSE and something non-zero to TRUE.

typedef uint8_t boolean;
#define FALSE 0
#define TRUE 1

This is almost exactly how Arduino implements booleans. It works, but it hides some of the fundamental concepts you need to understand to efficiently write code for AVR microcontrollers.

What are the problems with this?

  • You are wasting 7 bits of a 8 bit memory location or register. This is fine on a modern PC, but on an AVR microcontroller, you only have 32 registers and limited RAM.
  • This is hugely exacerbated when you have build arrays of boolean. Having an array of bits is very common (for example, in serial transmission). “boolean arr_of_bool[32]” uses 32 bytes to store 32 bits. Use “uint8_t arr_of_uint8[4]” instead, and learn how to set bits.
  • It hides the concept that the only thing that evaluates to false is 0. You often see “if (variable == true)” in Arduino code. It just isn’t required. Even worse is “if (variable ? TRUE : FALSE)”. Ouch – I’ve even seen this tenary operator inside a comparison in a library before.
  • It hides the concept of setting individual bits in a byte. You really cannot go very far in embedded systems without knowing about this.
  • It is not a native C type. Move to another platform or compiler and you will need to re-implement it. Should it be bool or boolean? true or TRUE? HIGH or LOW?

I’d be really keen to see Arduino move towards native data types, but I can’t see it happening.

Bitwise operations or how I learned to stop worrying and love my compiler

Whilst writing up some of the forthcoming posts on the alarm system, I found myself trying to write a simple method of setting, clearing, and getting bits in a byte buffer. I wanted this to be as transparent as possible so that the code was easy to understand.

The AVR microcontrollers are 8-bit. This means that registers, memory, and addresses are all 8-bits wide. It surprises many Arduino users when they find out that the type “boolean” is simply an entire unsigned, 8-bit integer (uint8_t). Boolean is just not a native concept to C and embedded systems. It’s incredibly wasteful to use a whole 8 bits to represent a single boolean value.

Bitwise operations

This isn’t to say that you don’t need to set individual bits in a byte though – this is actually a very common operation. Normally to do this, you use a couple of simple constructs.

To set the 6th bit in a register (0 is the first bit):

REGISTER |= 1 << 5;

This means "Shift 0b00000001 along 5 to 0b00010000, and perform a logical OR with whatever is in the register already". This has the effect of setting bit 5 to 1, and leaving all the other bits as are.

To clear the 5th bit in a register:

REGISTER &= ~(1 << 4);

This means "Shift 0b00000001 along 4 to 0b00001000, invert it to 0b11110111, and perform a logical AND with whatever is in the register already". This has the effect of clearing bit 4, and leaving all the other bits as are.

Bytewise operations

The above is all fine if you just want to look at a single bit in a byte. What happens if I want to deal with more than 8-bits? I need more bytes!

By far the easiest way to do this is to use an array:

uint8_t array_of_bytes[32];

Which just means "create an array of 32 unsigned 8-bit integers".

I can access the first byte using:

array_of_bytes[0];

And the tenth by using:

array_of_bytes[9];

Really simple! I can combine this with the bitwise operations:

array_of_bytes[13] |= 1 << 3;
array_of_bytes[4] &= ~(1 << 6);

Now I have an easy way of accessing any bit in an array of bytes.

Bringing it together

The problem comes if I decide I want to set the bit 27 in the array. How do I work out which byte this is in?

This is just some simple maths. To work out the byte, integer divide 27 by 8 - we get 3. This means it will be in the 4th byte i.e.

array_of_bytes[3]; // indexing starts at 0!

Then take the remainder of 27 by 8 (the modulus) - we get 3 again. We need to set the 4th bit.

array_of_bytes[3] |= (1 << 3);

So now we have a method to set an individual bit in an array of bytes.

Making it easier

Rather than remember all of this maths and shifting each time I want to set a bit, why not use a macro?

#define bit_set(array,i)   array[i/8] |=  1 << (i % 8)

This is just want we have said above. % is the modulus operator in C. This looks very clean and efficient.

That is until I use it in a project and find it is incredibly slow to set each bit in a buffer one by one. Why could this be? (I'll go into benchmarking code another time)

If you look through the ATmega328P or ATmega2560 datasheets, you can see two key things:

  1. There is no hardware division unit on the microcontroller - division is expensive!
  2. There is only a single bit shift in either direction. Shifts of more than one need to be made up of multiple single bit shifts.

There's something clever we could try here though. Division by 8 is exactly the same as shifting right by 3 bits:

0b00011011 (dec 27)
shift 3 bits right
0b00000011 (dec 3)

So now we can change our macro a bit:

#define bit_set(array,i)   array[i >> 3] |=  1  (i % 8)

We can take this further though... modulus 8 is the same as only keeping the first 3 bits of a number i.e. masking.

0b00011011 (dec 27)
mask with 0b00000111
0b00000011 (dec 3)

So the macro can be changed even further:

#define bit_set(array,i)   array[i >> 3] |=  1 << (i & 0x07)

And now we recompile and try again...

And get exactly the same result as before.

It turns out avrgcc is clever enough to spot that the divide by 8 and modulus 8 can be implemented by simple shifts and masks.

What is the moral of this story? Generally these days you will not make many gains in micro-optimisation. The compiler handles all of this, and normally much better than you can. Think about the big picture to make gains!

Reverse engineering a wireless burglar alarm, part 7

So, where were we? We’ve worked out how several components of the alarm use the CC1150 to send out signals, and now I want to emulate the signal and then play with it.

By far the easiest way to do this is to use the same CC1150 chip as in the authentic transmitters. I can be absolutely sure the 2-FSK modulation with ~50kHz deviation will be reproduced exactly. There are many other RF transmitter chips out there that can do this, but we know that these work and we already have the correct settings.

So, the first challenge is – where do I get a board with a CC1150 on it? Well, we have plenty of alarm sensors with neat little CC1150 daughterboards on them!

Door contact RF board

Door contact RF board

I chose a door contact as my victim – they are the cheapest and simplest sensors.

The daughterboard has an 8-pin interface, with a 0.1″ pitch pin header connecting the two. I need to desolder the board to use it. Desoldering pin headers is always a pain – you can’t desolder all 8 pins at a time. My technique now is:

  1. Chop the pin header along it’s length, separating the two boards. I have a nice pair of snips for this, but a Dremel with cut-off wheel can do it if they don’t fit.
  2. Chop the plastic spacer away from the pins, leaving you with just half the pins stuck in the board.
  3. Desolder the pins one at a time.
DSCF7845

The daughterboard

Now I have a small CC1150 board. I soldered a new pin header onto it, and a pin socket onto the rest of the door contact. This allows me to easily reconnect it to the door contact if I need to.

You’ll notice in the picture above that there is a small bridge wire. I desoldered and resoldered the CC1150 QLP package (just to see if I could) and burned a track in the process.

DSCF7846

Testing testing 1-2

Now we need to drive this board using something. There are a plethora of options available to me:

  • An Arduino board
  • A mbed board
  • A Bus Pirate
  • A GoodFET
  • A CC1110 development board (this would skip using the CC1150 board, as it has a built-in transceiver)
  • One of the Ciseco CC11xx boards (again, this would skip the CC1150 board)
  • Any of the other development boards I have lying around…

I decided I would use an Arduino board – specifically the Seeeduino Mega.

Why the Arduino? In reality, I’ve stopped using the Arduino environment and now use AVRGCC, so this is really just a nice little AVR development platform.

It won out over the mbed as I have had SPI issues with the mbed before.

The Bus Pirate and GoodFET are very similar, but require a host PC. I would like this standalone.

It seemed silly to implement this on a CC1110 chip, and I have had problems in implementing proprietary encoding schemes on it before.

Why the Mega? I find myself often using the extra pins and RAM as compared to the ATmega328p used in the Uno

So, now I have a RF board and something to control it. Next, I need to connect the two and write some code!