Skip to content

Add mbed TLS Authcrypt example #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 20, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 23 additions & 93 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,121 +1,51 @@
# HTTPS File Download Example for TLS Client on mbed OS
# mbed TLS Examples on mbedOS

This application downloads a file from an HTTPS server (developer.mbed.org) and looks for a specific string in that file.
This repository contains a collection of mbed TLS example applications based on mbed OS. Each subdirectory contains a separate example meant for building as an executable.

## Required hardware
# Getting started

## Required hardware
* An [FRDM-K64F](http://developer.mbed.org/platforms/FRDM-K64F/) development board.
* A micro-USB cable.
* An Ethernet cable and connection to the internet.

## Required software
* [mbed CLI](https://github.com/ARMmbed/mbed-cli) - to build the example program. To learn how to build mbed OS applications with mbed CLI, see the [user guide](https://github.com/ARMmbed/mbed-cli/blob/master/README.md)
* [Serial port monitor](https://developer.mbed.org/handbook/SerialPC#host-interface-and-terminal-applications).

## Getting started

1. Clone [this](https://github.com/ARMmbed/mbed-tls-sample) repository.
## Building and running the examples

2. Open a command line tool and navigate to the project’s directory.
1. Clone the repository containing the collection of examples:
```
$ git clone https://github.com/ARMmbed/mbed-os-example-tls
```

3. Update `mbed-os` sources using the `mbed update` command.
1. Open a command line tool and navigate to one of the project’s subdirectories.

4. Build the application by selecting the board and build toolchain using the command `mbed compile -m K64F -t GCC_ARM -c -j0`. mbed-cli builds a binary file under the project’s `.build` directory.
1. Update `mbed-os` sources using the `mbed deploy` command.

5. Connect the FRDM-K64F to the internet using the Ethernet cable.
1. Build the application by selecting the board and build toolchain using the command `mbed compile -m K64F -t GCC_ARM`. mbed-cli builds a binary file under the project’s `.build` directory.

6. Connect the FRDM-K64F to the computer with the micro-USB cable, being careful to use the **OpenSDA** connector on the target board. The board is listed as a mass-storage device.
1. Connect the FRDM-K64F to the computer with the micro-USB cable, being careful to use the **OpenSDA** connector on the target board. The board is listed as a mass-storage device.

7. Drag the binary `.build/K64F/GCC_ARM/mbed-tls-sample.bin` to the board to flash the application.
1. Drag the binary `.build/K64F/GCC_ARM/<EXAMPLE>.bin` to the board to flash the application.

8. The board is automatically programmed with the new binary. A flashing LED on it indicates that it is still working. When the LED stops blinking, the board is ready to work.
1. The board is automatically programmed with the new binary. A flashing LED on it indicates that it is still working. When the LED stops blinking, the board is ready to work.

9. Press the **RESET** button on the board to run the program.
1. Press the **RESET** button on the board to run the program.

## Monitoring the application

Please browse the subdirectories for specific documentation.
* [Benchmark](./benchmark/README.md)

The application prints debug messages over the serial port, so you can monitor its activity with a serial terminal emulator. Start the [serial terminal emulator](https://developer.mbed.org/handbook/Terminals) and connect to the [virtual serial port](https://developer.mbed.org/handbook/SerialPC#host-interface-and-terminal-applications) presented by FRDM-K64F. Use the following settings:

* 115200 baud (not 9600).
* 8N1.
* No flow control.

After pressing the **RESET** button on the board, the output in the terminal window should be similar to this:

{{timeout;120}}
{{host_test_name;default}}
{{description;mbed TLS example HTTPS client}}
{{test_id;MBEDTLS_EX_HTTPS_CLIENT}}
{{start}}

Client IP Address is 192.168.0.2
Starting DNS lookup for developer.mbed.org
DNS Response Received:
developer.mbed.org: 217.140.101.30
Connecting to 217.140.101.30:443
Connected to 217.140.101.30:443
Starting the TLS handshake...
TLS connection to developer.mbed.org established
Server certificate:
cert. version : 3
serial number : 11:21:4E:4B:13:27:F0:89:21:FB:70:EC:3B:B5:73:5C:FF:B9
issuer name : C=BE, O=GlobalSign nv-sa, CN=GlobalSign Organization Validation CA - SHA256 - G2
subject name : C=GB, ST=Cambridgeshire, L=Cambridge, O=ARM Ltd, CN=*.mbed.com
issued on : 2015-03-05 10:31:02
expires on : 2016-03-05 10:31:02
signed using : RSA with SHA-256
RSA key size : 2048 bits
basic constraints : CA=false
subject alt name : *.mbed.com, *.mbed.org, mbed.org, mbed.com
key usage : Digital Signature, Key Encipherment
ext key usage : TLS Web Server Authentication, TLS Web Client Authentication
Certificate verification passed

HTTPS: Received 473 chars from server
HTTPS: Received 200 OK status ... [OK]
HTTPS: Received 'Hello world!' status ... [OK]
HTTPS: Received message:

HTTP/1.1 200 OK
Server: nginx/1.7.10
Date: Tue, 18 Aug 2015 18:34:04 GMT
Content-Type: text/plain
Content-Length: 14
Connection: keep-alive
Last-Modified: Fri, 27 Jul 2012 13:30:34 GMT
Accept-Ranges: bytes
Cache-Control: max-age=36000
Expires: Wed, 19 Aug 2015 04:34:04 GMT
X-Upstream-L3: 172.17.42.1:8080
X-Upstream-L2: developer-sjc-indigo-2-nginx
X-Upstream-L1-next-hop: 217.140.101.86:8001
X-Upstream-L1: developer-sjc-indigo-border-nginx

Hello world!
{{success}}
{{end}}

## Debugging the TLS connection

To print out more debug information about the TLS connection, edit the file `source/main.cpp` and change the definition of `DEBUG_LEVEL` (near the top of the file) from 0 to a positive number:

* Level 1 only prints non-zero return codes from SSL functions and information about the full certificate chain being verified.

* Level 2 prints more information about internal state updates.

* Level 3 is intermediate.

* Level 4 (the maximum) includes full binary dumps of the packets.


The TLS connection can fail with an error similar to:

mbedtls_ssl_write() failed: -0x2700 (-9984): X509 - Certificate verification failed, e.g. CRL, CA or signature check failed
Failed to fetch /media/uploads/mbed_official/hello.txt from developer.mbed.org:443

This probably means you need to update the contents of the `SSL_CA_PEM` constant (this can happen if you modify `HTTPS_SERVER_NAME`, or when `developer.mbed.org` switches to a new CA when updating its certificate).

Another possible reason for this error is a proxy providing a different certificate. Proxies can be used in some network configurations or for performing man-in-the-middle attacks. If you choose to ignore this error and proceed with the connection anyway, you can change the definition of `UNSAFE` near the top of the file from 0 to 1.

**Warning:** this removes all security against a possible active attacker, so use at your own risk or for debugging only!
After pressing the **RESET** button on the board, you should be able to observe the application's output.

## Debugging mbed TLS

To optionally print out more debug information, edit the `main.cpp` for the sample and change the definition of `DEBUG_LEVEL` (near the top of the file) from 0 to a positive number between 1 and 4.
19 changes: 19 additions & 0 deletions authcrypt/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# mbed TLS Benchmark example on mbed OS

This application performs authenticated encryption and authenticated decryption of a buffer. It serves as a tutorial for the basic authenticated encryption functions of mbed TLS.

# Getting started

Set up your environment if you have not done so already. For instructions, refer to the [main readme](../README.md).

## Monitoring the application

The output in the terminal window should be similar to this:

```
plaintext message: 536f6d65207468696e67732061726520626574746572206c65667420756e7265616400
ciphertext: c57f7afb94f14c7977d785d08682a2596bd62ee9dcf216b8cccd997afee9b402f5de1739e8e6467aa363749ef39392e5c66622b01c7203ec0a3d14
decrypted: 536f6d65207468696e67732061726520626574746572206c65667420756e7265616400

DONE
```
180 changes: 180 additions & 0 deletions authcrypt/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
/*
* Hello world example of using the authenticated encryption with mbed TLS
*
* Copyright (C) 2016, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "mbed.h"

#include "mbedtls/cipher.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#if DEBUG_LEVEL > 0
#include "mbedtls/debug.h"
#endif

#include "mbedtls/platform.h"

#include <string.h>

static void print_hex(const char *title, const unsigned char buf[], size_t len)
{
mbedtls_printf("%s: ", title);

for (size_t i = 0; i < len; i++)
mbedtls_printf("%02x", buf[i]);

mbedtls_printf("\r\n");
}

/*
* The pre-shared key. Should be generated randomly and be unique to the
* device/channel/etc. Just used a fixed on here for simplicity.
*/
static const unsigned char secret_key[16] = {
0xf4, 0x82, 0xc6, 0x70, 0x3c, 0xc7, 0x61, 0x0a,
0xb9, 0xa0, 0xb8, 0xe9, 0x87, 0xb8, 0xc1, 0x72,
};

static int example(void)
{
/* message that should be protected */
const char message[] = "Some things are better left unread";
/* metadata transmitted in the clear but authenticated */
const char metadata[] = "eg sequence number, routing info";
/* ciphertext buffer large enough to hold message + nonce + tag */
unsigned char ciphertext[128] = { 0 };
int ret;

mbedtls_printf("\r\n\r\n");
print_hex("plaintext message", (unsigned char *) message, sizeof message);

/*
* Setup random number generator
* (Note: later this might be done automatically.)
*/
mbedtls_entropy_context entropy; /* entropy pool for seeding PRNG */
mbedtls_ctr_drbg_context drbg; /* pseudo-random generator */

mbedtls_entropy_init(&entropy);
mbedtls_ctr_drbg_init(&drbg);

/* Seed the PRNG using the entropy pool, and throw in our secret key as an
* additional source of randomness. */
ret = mbedtls_ctr_drbg_seed(&drbg, mbedtls_entropy_func, &entropy,
secret_key, sizeof secret_key);
if (ret != 0) {
return 1;
}

/*
* Setup AES-CCM contex
*/
mbedtls_cipher_context_t ctx;

mbedtls_cipher_init(&ctx);

ret = mbedtls_cipher_setup(&ctx, mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_CCM));
if (ret != 0) {
mbedtls_printf("mbedtls_cipher_setup() returned -0x%04X\r\n", -ret);
return 1;
}

ret = mbedtls_cipher_setkey(&ctx, secret_key, 8 * sizeof secret_key, MBEDTLS_ENCRYPT);
if (ret != 0) {
mbedtls_printf("mbedtls_cipher_setkey() returned -0x%04X\r\n", -ret);
return 1;
}

/*
* Encrypt-authenticate the message and authenticate additional data
*
* First generate a random 8-byte nonce.
* Put it directly in the output buffer as the recipient will need it.
*
* Warning: you must never re-use the same (key, nonce) pair. One of the
* best ways to ensure this to use a counter for the nonce. However this
* means you should save the counter accross rebots, if the key is a
* long-term one. The alternative we choose here is to generate the nonce
* randomly. However it only works if you have a good source of
* randomness.
*/
const size_t nonce_len = 8;
mbedtls_ctr_drbg_random(&drbg, ciphertext, nonce_len);

size_t ciphertext_len = 0;
/* Go for a conservative 16-byte (128-bit) tag
* and append it to the ciphertext */
const size_t tag_len = 16;
ret = mbedtls_cipher_auth_encrypt(&ctx, ciphertext, nonce_len,
(const unsigned char *) metadata, sizeof metadata,
(const unsigned char *) message, sizeof message,
ciphertext + nonce_len, &ciphertext_len,
ciphertext + nonce_len + sizeof message, tag_len );
if (ret != 0) {
mbedtls_printf("mbedtls_cipher_auth_encrypt() returned -0x%04X\r\n", -ret);
return 1;
}
ciphertext_len += nonce_len + tag_len;

/*
* The following information should now be transmitted:
* - first ciphertext_len bytes of ciphertext buffer
* - metadata if not already transmitted elsewhere
*/
print_hex("ciphertext", ciphertext, ciphertext_len);

/*
* Decrypt-authenticate
*/
unsigned char decrypted[128] = { 0 };
size_t decrypted_len = 0;

ret = mbedtls_cipher_setkey(&ctx, secret_key, 8 * sizeof secret_key, MBEDTLS_DECRYPT);
if (ret != 0) {
mbedtls_printf("mbedtls_cipher_setkey() returned -0x%04X\r\n", -ret);
return 1;
}

ret = mbedtls_cipher_auth_decrypt(&ctx,
ciphertext, nonce_len,
(const unsigned char *) metadata, sizeof metadata,
ciphertext + nonce_len, ciphertext_len - nonce_len - tag_len,
decrypted, &decrypted_len,
ciphertext + ciphertext_len - tag_len, tag_len );
/* Checking the return code is CRITICAL for security here */
if (ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED) {
mbedtls_printf("Something bad is happening! Data is not authentic!\r\n");
return 1;
}
if (ret != 0) {
mbedtls_printf("mbedtls_cipher_authdecrypt() returned -0x%04X\r\n", -ret);
return 1;
}

print_hex("decrypted", decrypted, decrypted_len);

mbedtls_printf("\r\nDONE\r\n");

return 0;
}

int main() {
int ret = example();
if (ret != 0) {
mbedtls_printf("Example failed with error %d\r\n", ret);
}
}
1 change: 1 addition & 0 deletions authcrypt/mbed-os.lib
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
https://github.com/ARMmbed/mbed-os/#b7b6dd2c8769251c66d68911f116ec899c7054f7
45 changes: 45 additions & 0 deletions benchmark/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# mbed TLS Benchmark example on mbed OS

This application benchmarks the various cryptographic primitives offered by mbed TLS.

# Getting started

Set up your environment if you have not done so already. For instructions, refer to the [main readme](../README.md).

## Monitoring the application

The output in the terminal window should be similar to this:

```
SHA-256 : 1673 Kb/s, 70 cycles/byte
SHA-512 : 546 Kb/s, 215 cycles/byte
AES-CBC-128 : 1428 Kb/s, 82 cycles/byte
AES-CBC-192 : 1260 Kb/s, 93 cycles/byte
AES-CBC-256 : 1127 Kb/s, 104 cycles/byte
AES-GCM-128 : 486 Kb/s, 242 cycles/byte
AES-GCM-192 : 464 Kb/s, 253 cycles/byte
AES-GCM-256 : 445 Kb/s, 264 cycles/byte
AES-CCM-128 : 610 Kb/s, 192 cycles/byte
AES-CCM-192 : 547 Kb/s, 214 cycles/byte
AES-CCM-256 : 496 Kb/s, 237 cycles/byte
CTR_DRBG (NOPR) : 1139 Kb/s, 102 cycles/byte
CTR_DRBG (PR) : 826 Kb/s, 142 cycles/byte
HMAC_DRBG SHA-256 (NOPR) : 193 Kb/s, 611 cycles/byte
HMAC_DRBG SHA-256 (PR) : 170 Kb/s, 695 cycles/byte
RSA-2048 : 28 ms/ public
RSA-2048 : 953 ms/private
RSA-4096 : 93 ms/ public
RSA-4096 : 5327 ms/private
ECDSA-secp384r1 : 451 ms/sign
ECDSA-secp256r1 : 304 ms/sign
ECDSA-secp384r1 : 863 ms/verify
ECDSA-secp256r1 : 594 ms/verify
ECDHE-secp384r1 : 829 ms/handshake
ECDHE-secp256r1 : 566 ms/handshake
ECDHE-Curve25519 : 533 ms/handshake
ECDH-secp384r1 : 407 ms/handshake
ECDH-secp256r1 : 281 ms/handshake
ECDH-Curve25519 : 268 ms/handshake

DONE
```
Loading