Home | pfodApps/pfodDevices | WebStringTemplates | Java/J2EE | Unix | Torches | Superannuation | | About Us

Forward Logo (image)      

HMAC Secure Challenge and Response
for micro-devices (AVR / Arduino)

by Matthew Ford 7st June 2013 (original 12th January 2013) – Moved to HMAC security, added per msg authentication, EEPROM considerations, password transfer-revised
© Forward Computing and Control Pty. Ltd. NSW Australia, All rights reserved.

Challenge and Response Security for Internet connected pfodDevices™
A CHAP design for a microprocessor (Atmel AVR / Arduino) based secure challenge and response

NOTE: This design has been replaced by one based on SipHash

This page outlines the original design and software for a Challenge Handshake Authentication Protocol (CHAP) to securely access to a micro-device based on Atmel AVR / Arduino hardware. This design has been replaced by a simpler/faster implementation using sipHash. Should sipHash prove to be flawed then wrapping it in HMAC to form HMAC-SihHash will be used.

CHAP has been modified to use Keyed-Hash based message authentication code (HMAC) instead of just hashing with MD5. This implementation of HMAC uses SHA256 as the underlying hash. Keys in the range of 64 to 256 bits are supported depending of the level of security required.


The pfod Specification provides a simple way to control a micro-device (pfodDevice). The pfodApp is an implementation of the specification for Android mobiles and it completely removes the need to do any Android programming. The present implementation of pfodApp connects to the pfodDevice via Bluetooth. However the means of connection or its security is not specified by the pfod Specification. So the establishment of the connection and any authentication are 'out-of-band' with respect to the pfod spec. A connection via wifi/internet is also permissible and available in the latest version of pfodApp.

Once you allow connections to your pfodDevice via the internet, security becomes a major consideration. With short range bluetooth, a non-discoverable and pin protected pfodDevice (using some other pin instead of 0000 or 1234) is reasonably secure. However when the connection is via the internet, there is a significant risk from port scanners finding the open pfodDevice port and so gaining control of the device.

To protect against this threat, I am proposing a 'secure' Challenge Handshake Authentication Protocol (CHAP) to access the pfodDevice and a per-message data-integrity and authentication check.

The verification that the pfodApp has authority to control the pfodDevice is based on a shared secret password.
a) After the completion of the link establishment phase (opening a TCP/IP connection), the pfodDevice (authenticator) sends a "challenge" message to the pfodApp (peer).
b) The pfodApp (peer) responds with a value calculated using a one-way hash function on the challenge and the secret password.
c) The pfodDevice (authenticator) checks the response against its own calculation of the expected hash value. If the values match, the pfodDevice (authenticator) acknowledges the authentication and starts accepting pfodApp messages, otherwise (if the response is incorrect) the pfodDevice terminates the connection.
d) Then for each message send between the pfodApp and the pfodDevice, a secure hash of the message+secretKey+msgCount +challenge is appended to ensure data-integrity and authentication.

For the one-way hash function, MD5 was used previously. MD5 has now been superseded by SHA256 (and others hashes). In 1997 rfc 2104 defined keyed-hash message authentication code (HMAC). This uses a double hashing to further obscure the input value. While many hashing functions can be used with HMAC, SHA256 is one of the better ones.

The cryptographic strength of the HMAC depends upon the size of the secret key that is used.” (HMAC wiki entry) 64 bit keys provide protection against the most common type of attack, opportunistic attacks by port scanners. To protect against concerted attacks using powerful computers, longer keys should be used. Key of lengths of 256bit (64 hex digits) are unlikely to be broken (see the brute force wiki entry).

The response is 64 bits, but because the challenge is never repeated, an attacker only gets one chance at guessing the correct response. That chance is vanishing small at 1 in 1e19. The challenge is 64bits. What is important about the challenge is that it never be repeated. (See below for how the challenge is generated).

For each pfod message sent between the pfodApp and pfodDevice, a 32bit hash (8 hex digits) is added to verify the message comes from the pfodApp / pfodDevice and that the message has not been changed.

The 'secret' key is supplied with each pfodDevice and should be random (see below for an easy way to generate 'random' keys). The minimum of 64 bits or 16 Hex digits was chosen to providing practical security against opportunistic attack, while not being too difficult to enter correctly into the pfodApp. If more security is required longer keys can be used, up to 256 bits or 64 Hex digits.

What Threats are being protected against

There are two main threat that this proposal is designed to guard against:-
1) to prevent a remote hacker finding the open pfodDevice ip and port, connecting to it to control its functions,
2) to protect against a hacker with access to the network from taking over control of the pfodDevice from you once the CHAP handshake is complete.

What Threats are not being protected against.

This design does not protect against taking control of, or denying access to, the pfodDevice in the following cases
i) Where the attacker has physical access to the pfodDevice which would normally have the 'secret' password attached to it. (forcing a power cycle is protected against.)
ii) Where the attacker has physical access to the Android mobile where the 'secret' password has been entered. If you loose you mobile you must change the pfodDevice password.
iii) Denial of Service attacks, where the attacker prevents you from accessing the pfodDevice by the attacker continually trying to connect to the pfodDevice and failing to gain access.

Outline of the Challenge and Response sequence (CHAP).

  1. pfodDevice listens on an ip:port for a connection.

  2. On receiving a connection the pfodDevice remains silent

  3. If the pfodDevice does not receive a request for a challenge within short time, it closes the connection and listens for another one.

  4. The pfodApp sends a connection prompt. For example {=}. Any other msg causes the pfodDevice to close the connection.

  5. The pfodDevice responds with a 64 bit number encoded as 16 Hex chars, the challenge plus a one byte (2 hex chars) hash identifier. e.g. {=|FFFFFFFE00000CBC01} (see below for how this unique non-repeating challenge is calculated). The pfodDevice also calculates the valid response using HMAC and SHA256 and the “secret key”

  6. The pfodApp calculates the valid response via HMAC and SHA256, using the 'secret' key and this challenge and sends the first 64bits (8 bytes) of the result, Hex encoded, back to the pfodDevice, e.g. {=|BA7816BF8F01CFEA}.

  7. The pfodDevice compares the response with its own calculation. If it is not equal, the pfodDevice drops (force closes) the connection. If it is equal, the pfodDevice keeps the connection open and replies with {=} and then awaits the normal pfod first message, in plain text (usually {.} requesting the pfodDevice's main menu).

  8. At the end of the connection, when a challenge was sent, the pfodDevice calculates the next challenge and valid response before accepting another connection.

  9. For each plain text control message and response, the pfodApp and pfodDevice append 8 hex digits which are the first four bytes of the HMAC-SHA256 of the message+msgCounter+challenge and the secret key. The receiver of the message looks for these extra chars after the message } and checks that they are the correct hash. If not the the connection is closed.

How the Security is maintained on an open clear text link

Point ii) above, where the pfodDevice is silent, reduces the chance of a random port scanner from being given any information about what has just been connected to. However the following analysis assumes the attacker knows that a pfodDevice is on a particular ip:port and has been monitoring the previous traffic on that port.

At point v) the pfodDevice sends a challenge of a 64bit (8 byte) number (one of 2e19 possible numbers). The security depends on the pfodDevice never sending the same number twice so that even if the attacker has listened to ALL the previous traffic, they will not know what the correct response is to this new/different number without knowing the secret key.

At point vi) the pfodApp calculates the valid response. Using an 64 bit return, there is less then 1 chance in 1e19 that a attacker will guess the correct result by chance.

At point ix) each message has a secure 32 bit hash added to it. Because a message counter is included, repeated commands have different hashes. Because the non-repeating challenge is include, the same message sequence in different connections has different hashes. A hacker has on average a one in 2e9 chance of spoofing the correct hash by chance. Before a hacker can attempt to spoof a message, he must first wait for you to complete a successful CHAP logon and then take control of the session. Any incorrect hash closes the connection. See below for how you can increase this level of security.

Protection Against “Man in the Middle” Attacks

This design provides protection against Man in the Middle attacks. In these attacks, the attacker inserts themselves between you and the pfodDevice and intercepts all your messages and relays them to the pfodDevice, or replaces them his own messages. However because each message has its own hash which depends on the shared “secret key” that the attacker does not know, if the attacker modifies the message being sent to the pfodDevice or inserts his one of his own, he will not know what correct hash to add to the message and the connection will be closed by the receiver.

Also because the pfodDevice also adds a secure hash to its responses, the attacker cannot modify the menus presented to the pfodApp and so cannot induce the user to send a particular command.

How the Challenge Bytes are Calculated

The security of this method depends on never sending the same challenge twice, so the attacker cannot know the valid response just by listening to all the previous traffic.

The proposal here is the break the 8 byte (64 bits) challenge into 3 parts. Each part is sent in Big Endian format.
a) EEPROM - 16 bits read from EEPROM on each power up, starting from 0xFFFF, decremented and stored back in the EEPROM on power up.
b) Counter - 16 bits from a RAM counter starting at 0 on each power up and incrementing each time a challenge is sent.
c) Time since last connection and status - 32 bits, 31bits for time since last connection, 1bit for status of last connnection.

Finally one byte (2 hex digits) are added to identify the type of hash to uses. 01 indicates HMAC-SHA256, 02 indicates SipHash, 03 indicates HMAC-SipHash. Currently pfodApp only supports type 02 - SipHash

a) The endurance of the EEPROM is guaranteed to 100,000, after this many power cycles the EEPROM may not work correctly. 16 bits gives about 65535 numbers which is less then the EEPROM endurance of 100,000 write/erase cycles . When this number reaches 0x0000 the pfodDevice will refuse connections

To protect against an attacker denying valid user access by using up all the allowable power cycles by interrupting the uC mains power, a 15sec power up delay will be introduced. This means an attacker would have to cycle the power every 15secs for 11 days (i.e. 65500 power cycles) in order to consume the available power cycle counts. They would then deny valid user access to the pfodDevice, as the pfodDevice will refuse connections. A small battery back up would extend this to an impractically long time.

b) The 16 bits from the uC RAM counter will count from 0 to 65535. With a minimum of 50mS per connection during which a challenge is requested, sent and an invalid response returned, it will take longer then about 1hr for this number to repeat if connections are continuously made by an attacker and invalid responses sent. When this number does return to 0, the EEPROM number will be decremented and stored so that the challenge will stay unique. Using this method of attack it would take about 7 years to use up all the EEPROM power cycle numbers after which the pfodDevice would refuse valid users as well.

c) The 32 bits are divided into 1 bit for the status (the leading bit) and 31 bits from the uC mS counter/timer for the time since the last connection attempt. It can count up to ~25 days. With the vagaries of wireless connections (the tcp connection takes between 22mS (local) and 225mS(transcontinental) or longer to set up) this number will be mostly unpredictable. However it does tell the pfodApp how long since the last connection attempt was made (if it was made in the last 25 days). If the timer stops counting when it reaches maximum count (2e9 mS). The status bit is set, if the last connection failed any of the hash checks, either the challenge or message hashes. If the connection times out waiting for the for connection challenge response to complete, or waiting for the next message, the status flag is NOT set. Only a failed hash check sets the status flag. If this flag is set then it is most likely some tried to break into the pfodDevice. Taking the flag as the sign of the time since the last connection, i.e. flag bit + 31 time bits == 4 bytes, then if the time since the last connection is a negative number, some one tried to break into the pfodDevice.

a) and b) together ensure the challenge is always unique and never repeating. The security of the challenge/response depends on never sending the same challenge twice which is guaranteed by the EEPROM power cycle counter and connection counter and on the difficultly in determining the 'secret' password from the response generated by the HMAC-SHA256 hash.

The pfodApp does not need to know how this challenge is generated, so the developer coding the microprocessor can vary the distribution of bits between these three part to suit their particular processor and situation.

How the Individual Message Hashes are Calculated

The message hashes are calculated by taking the message to be sent and appending the message count as an unsigned long, starting from 0 for the first message after the CHAP handshake is completed and appending the challenge sent by the pfodDevice. This is then passed to the HMAC-SHA256 together with the “secret key” to calculate the hash. The first 4 bytes of the resulting hash are send (as 8 hex digits) immediately following the closing } of the message. Note: no white space is allowed between the closing } and the hash bytes. Only the characters from (and including) the opening { to the closing } of the message are including when calculating the hash. White space is allowed inside the message (i.e. between the { and } )

The unsigned long message counter allows for 4e9 messages per connection without any possibility of repeating. At 20mS per message that is 3 years of messages in a single continuous connection.

How to increase the security for an important command

Each message to the pfodDevice is protected by a secure hash of 4 bytes. This means an attacker has a 1e9 chance of guessing the correct hash for this command.

If you want to make it even less likely that an attacker can guess the correct hash for that “special” command then bury the special command in a sub-menu and code the pfodDevice so that the user has to first request the sub-menu before the command becomes active. This means an attacker has to now send two correct commands with the correct hashes one after another. This decreases the odds to 1 in 10e18 that an attacker can guess these two message hashes correctly. If this is not enough add another level of menu etc..


The implementation of this design consists of two parts, the pfodApp support in the Android mobile and the pfodDevice support code on an Atmel AVR / Arduino device.

The AVR / Arduino programming is straight forward, except for the SHA256 hash. Fortunately cryptosuite provides an SHA256 based HMAC implementation for Arduino. A small correction to the code is need to get this to compile on Arduino 1.0.3 and higher.

For an assembler implementation ECRYPT II provides AVR assembler source code for the SHA256 hash and AVR_Crypto_Lib provides an AVR C code version of SHA256 and an assembler version. HMAC would need to be implemented but this straight forward. (see the HMAC wiki entry or cryptosuite for the coding details)

For the pfodApp, the GNU Crypto project provides the java source code for gnu/java/security/hash/Sha256.java and also for HMAC.

Generating the Password

The secret key should not be anything an attacker can guess. That is it should be completely random. See Anatomy of a hack for how easy it is to “brute force” short text passwords.

In this implementation the password is itself generated by taking the first n bytes (n=8 to 32) of the HMAC-SHA256 hash of some text entered by the user and using the output of Java getNano() time as the 64 bit key. The text can be anything. Because getNano() is used as the key each time a password is produced you will get a different one, even using the same text. The input text can be discarded once the key has been generated. These n bytes would then be programmed into the pfodDevice's EEPROM and also attached to the pfodDevice (as 16 to 64 Hex digits).

This approach produces an essentially random password. Anatomy of a hack indicates you that even with a 'random' password, 8 bytes is the minimum you should use and for reliable protection you need to use 128 bit (32 hex digits) or more to be protect against brute force attacks. Remember, once an attacher sniffs one of your connections, they can spend as much time as they like trying to recover the password. Using QR code image to transfer of password, as described below, there is no reason not to use 128 bit (32 hex digit) or longer passwords.

Transferring the Password to the pfodApp

If the password is only 64bits (8 bytes - 16 hex digits), then it is not too difficult for the user to enter these hex digits manually into the pfodApp. However if a longer, more secure, password is used, say 256bits (64 hex digits) then it becomes very difficult for the user to enter it correctly.

For longer passwords the preferred method is to attach the password as an QR coded image to the pfodDevice which the mobile can scan and copy and paste to the connections password field. To generate the QR code image you can use this java program available from here. There are numerous apps available to scan QR codes such as QR Droid Private .


This page details the design and software of a Challenge Response security for an internet connected micro-processor based, pfodDevice, which will provide protection against unauthorised access and control.

The minimum 64 bits or 16 Hex digits was chosen to providing practical security against opportunistic attack, while not being too difficult to enter correctly into the pfodApp. By using QR code passwords there is no reason not to use longer keys, up to 256 bits or 64 Hex digits which provide much more protection against brute force attacks.

As described above the chances of an attacker gaining access by sending a valid response to the challenge are vanishing small (<1e19) and “man in the middle” attacks are guarded against by adding a secure hash to each message sent which allows the receiver to check the message has not been changed and that the message comes from the same device that took part in the CHAP authentication.

The biggest risk is a denial of service attack.

There are two main denial of service attacks. In the first one the attacker continually connects, denying access for a period of time before the pfodDevice closes that connection. This is the easiest form of internet denial of service attack. The second type of attack is to consume all the available EEPROM stored power cycle counts. Using up the EEPROM power cycles via an internet attack would take more than 7 years of continuous attacks, each one requesting a challenge from the pfodDevice. In either case the attacker does not gain access to the control the pfodDevice, but only succeeds in denying valid uses access.

In order to gain access to and to control to the pfodDevice, an attacker would need to discover the secret key, either by a monitoring the traffic and trying all the possible keys (i.e. brute force attack) or by gaining physical access to either the mobile phone or the pfodDevice itself. The brute force attack is not possible for longer keys (128/256 bits).

This design has been superseded by one based on SipHash.

AndroidTM is a trademark of Google Inc, For use of the Arduino name see http://arduino.cc/en/Main/FAQ

pfodDevice™ and pfodApp™ are trade marks of Forward Computing and Control Pty. Ltd.

Forward home page link (image)

Contact Forward Computing and Control by
©Copyright 1996-2015 Forward Computing and Control Pty. Ltd. ACN 003 669 994