This is a fork of the mbed port of axTLS

Dependents:   TLS_axTLS-Example HTTPSClientExample

Overview

This library is a fork from the mbed port of axTLS. It attempts to :

  • reduce the usage of dynamic memory
  • verify certificates with key size up to 2048 bits
  • provide a simple interface

Encryption

This library uses either RC4 or AES for encryption.

Memory usage

During the establishment of a connection, about 10KB of memory is allocated dynamically (it depends on certificates). Once the connection is established, the memory consumption is relatively low. This means that your program must not use too much static memory or allocate memory before you establish a TLS connection.

Certificates

Certificates are the major source of problem and will often be the reason why your program will crash. Due to memory constraint, there are some limitations on certificates :

  • Each certificate must not be bigger than 2KB
  • TLS client can only handle a chain of up to three certificates (excluding the root certificate). This means that the server must not send more than three certificates.

Also, this library can only load certificates following these specifications :

  • encoded in binary DER format (PKCS1)
  • The public key must use RSA only

Once the connection is established, you should free all loaded certificates by calling CertificateManager::clear(). This will free a few kilobytes (it depends on your certificates). In addition, to enable certificate verification during the connection, this library has a "precomputed mode". This mode uses much less memory than a normal certificate verification.

Normal mode

You need to copy the root certificate in binary-DER format on the mbed. Then in your code, let's say that your root certificate is saved on the mbed as "root.der", assuming that you include CertificateManager.h and that you created a LocalFileSystem, you can load this certificate as this ;

Load root certificate

CertificateManager::add("/local/root.der");
CertificateManager::load();

Do not forget that this mode takes quite a lot of memory ( the memory peak is high while verifying certificates) and will only work if the key size is not bigger than 1024 bits (otherwise it will crash while verifying certificates).

Precomputed mode

In this mode, you need to save the entire chain of certificates (in binary-DER format) including the root certificate on the mbed. In practice, this means that you must first retrieve all certificates that the server sends during a connection and then find the right root certificate. In your code, you must call CertificateManager::add for each certificate and in the right order : from the server certificate to the root certificate. Here is how you shoud load certificates in this mode :

Loadcertificates in precomputed mode

CertificateManager::add("/local/server1.der");
CertificateManager::add("/local/server2.der");
CertificateManager::add("/local/server3.der");
CertificateManager::add("/local/root.der");
CertificateManager::load(true);

Using this mode, you should be able to verify certificates with key size up to 2048 bits.

How do I find these certificates ?

I posted an entry in my notebook detailing how to get certificates from a server. You should be able to get all certificates you need except the root certificate. Here is a way how to get the root certificate on windows :

  1. Open (double-click) the last certificate sent by the server
  2. Go to details panel and click on the entry called Issuer. The first line gives you the name of this certificate and the second line indicates the company who created this certificate
  3. Open firefox
  4. Go to options, advanced panel and click on View Certificates
  5. Go to Authorities panel
  6. Choose the certificate whose name match the issuer of the last certificate sent by the server
  7. Export this certificate to binary-DER format.

Connect to mbed.org !

Import programTLS_axTLS-Example

Establishing a connection to mbed.org using TLS

Revision:
0:85fceccc1a7c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/axTLS/ssl/os_port.c	Thu Sep 12 15:18:04 2013 +0000
@@ -0,0 +1,281 @@
+/*
+ * Copyright (c) 2007, Cameron Rich
+ * 
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, 
+ *   this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice, 
+ *   this list of conditions and the following disclaimer in the documentation 
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the axTLS project nor the names of its contributors 
+ *   may be used to endorse or promote products derived from this software 
+ *   without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @file os_port.c
+ *
+ * OS specific functions.
+ */
+#include <time.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <stdarg.h>
+#include "os_port.h"
+#include <stdio.h>
+#include "sockets.h"
+
+static int memory_buf[400];
+static char enable = 0;
+static int nb_entries = 0;
+
+void disable_memory_buf(void)
+{
+    enable = 0;
+}
+void enable_memory_buf(void)
+{
+    enable = 1;
+}
+void init_memory_buf(void)
+{
+    for(int i = 0; i < 400; i += 2)
+    {
+        memory_buf[i] = -1;
+        memory_buf[i+1] = 0;
+    }
+}   
+void print_buf_stats(void)
+{
+    if(enable)
+    {
+        int used = 0;
+        for(int i = 1; i < 400; i += 2)
+            used += memory_buf[i];
+        printf("%d\n", used);
+    }
+}
+
+void print_all_buf_stats(void)
+{       
+    int used = 0;
+    for(int i = 1; i < 400; i += 2)
+        used += memory_buf[i];
+    printf("used: %d bytes\n", used);
+    
+    for(int i = 0; i < 400; i += 2)
+        if(memory_buf[i] != -1)
+            printf("ptr:%X, size:%d\n", memory_buf[i], memory_buf[i+1]);
+}
+
+static void add_entry(void *x, size_t s, const char* f, const int l)
+{
+    nb_entries++;
+    for(int i = 0; i < 400; i += 2)
+    {
+        if(memory_buf[i] == -1)
+        {
+            if(enable)
+                printf("new ptr:%X, size:%d at %s:%d\n", x, s, f, l); 
+            memory_buf[i] = (int)(x);
+            memory_buf[i+1] = s;
+            return;
+        }
+    }
+    if(enable)
+        printf("No space left in buffer\n"); 
+}
+
+static void remove_entry(void *x, const char* f, const int l)
+{
+    nb_entries--;
+    for(int i = 0; i < 400; i += 2)
+    {
+        if(memory_buf[i] == (int)(x))
+        {
+            if(enable)
+                printf("free ptr:%X, size:%d at %s:%d\n", memory_buf[i], memory_buf[i+1], f, l); 
+            memory_buf[i] = -1;
+            memory_buf[i+1] = 0;
+            return;
+        }
+    }
+    if(enable)
+        printf("not found\n");
+}
+
+#ifdef MBED
+/**
+ * gettimeofday() not in mbed 
+ */
+EXP_FUNC void STDCALL gettimeofday(struct timeval* t, void* timezone)
+{       
+    t->tv_sec = time(NULL);
+    t->tv_usec = 0;                         /* 1sec precision only */ 
+}
+
+#endif
+
+#ifdef WIN32
+/**
+ * gettimeofday() not in Win32 
+ */
+EXP_FUNC void STDCALL gettimeofday(struct timeval* t, void* timezone)
+{       
+#if defined(_WIN32_WCE)
+    t->tv_sec = time(NULL);
+    t->tv_usec = 0;                         /* 1sec precision only */ 
+#else
+    struct _timeb timebuffer;
+    _ftime(&timebuffer);
+    t->tv_sec = (long)timebuffer.time;
+    t->tv_usec = 1000 * timebuffer.millitm; /* 1ms precision */
+#endif
+}
+
+
+/**
+ * strcasecmp() not in Win32
+ */
+EXP_FUNC int STDCALL strcasecmp(const char *s1, const char *s2)
+{
+    while (tolower(*s1) == tolower(*s2++))
+    {
+        if (*s1++ == '\0')
+        {
+            return 0;
+        }
+    }
+
+    return *(unsigned char *)s1 - *(unsigned char *)(s2 - 1);
+}
+
+
+EXP_FUNC int STDCALL getdomainname(char *buf, int buf_size)
+{
+    HKEY hKey;
+    unsigned long datatype;
+    unsigned long bufferlength = buf_size;
+
+    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
+            TEXT("SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters"),
+                        0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS)
+        return -1;
+
+    RegQueryValueEx(hKey, "Domain", NULL, &datatype, buf, &bufferlength);
+    RegCloseKey(hKey);
+    return 0; 
+}
+#endif
+
+#undef malloc
+#undef realloc
+#undef calloc
+#undef free
+
+static const char * out_of_mem_str = "out of memory";
+//static const char * file_open_str = "Could not open file \"%s\"";
+
+/* 
+ * Some functions that call display some error trace and then call abort().
+ * This just makes life much easier on embedded systems, since we're 
+ * suffering major trauma...
+ */
+EXP_FUNC void * STDCALL ax_malloc(size_t s, const char* f, const int l)
+{
+    if(enable)  
+        printf("malloc\t");
+
+    void *x;
+
+    if ((x = malloc(s)) == NULL)
+        exit_now(out_of_mem_str);
+    add_entry(x,s, f, l);
+    print_buf_stats();
+
+    return x;
+}
+
+EXP_FUNC void * STDCALL ax_realloc(void *y, size_t s, const char* f, const int l)
+{
+    if(enable)  
+        printf("realloc\t");
+
+    void *x;
+
+    if ((x = realloc(y, s)) == NULL)
+        exit_now(out_of_mem_str);
+    remove_entry(y, f, l);
+    add_entry(x,s, f, l);
+    print_buf_stats();
+    return x;
+}
+
+EXP_FUNC void * STDCALL ax_calloc(size_t n, size_t s, const char* f, const int l)
+{
+    if(enable)  
+        printf("calloc\t");
+    void *x;
+  
+    if ((x = calloc(n, s)) == NULL) {
+        exit_now(out_of_mem_str);
+    }
+
+    add_entry(x,n*s, f, l);
+    print_buf_stats();
+    return x;
+}
+
+EXP_FUNC void STDCALL ax_free(void *y, const char* f, const int l)
+{
+    if(enable)  
+        printf("free\t");
+        
+    remove_entry(y, f, l);
+    print_buf_stats();
+    free(y);
+}
+/*
+EXP_FUNC int STDCALL ax_open(const char *pathname, int flags)
+{
+    int x;
+
+    if ((x = open(pathname, flags)) < 0)
+        exit_now(file_open_str, pathname);
+
+    return x;
+}
+*/
+
+/**
+ * This is a call which will deliberately exit an application, but will
+ * display some information before dying.
+ */
+void exit_now(const char *format, ...)
+{
+    va_list argp;
+
+    va_start(argp, format);
+    vfprintf(stderr, format, argp);
+    va_end(argp);
+    abort();
+}
+
+
+