diff --git a/libraries/ESP8266WiFi/src/WiFiClientSecure.h b/libraries/ESP8266WiFi/src/WiFiClientSecure.h index 4b5b9c9343..88aae7e4aa 100644 --- a/libraries/ESP8266WiFi/src/WiFiClientSecure.h +++ b/libraries/ESP8266WiFi/src/WiFiClientSecure.h @@ -23,7 +23,7 @@ #ifndef wificlientsecure_h #define wificlientsecure_h #include "WiFiClient.h" -#include "include/ssl.h" +#include class SSLContext; diff --git a/libraries/Hash/src/Hash.cpp b/libraries/Hash/src/Hash.cpp index 5a58c961d2..9021fca45c 100644 --- a/libraries/Hash/src/Hash.cpp +++ b/libraries/Hash/src/Hash.cpp @@ -27,7 +27,7 @@ #include "Hash.h" extern "C" { -#include "sha1/sha1.h" +#include } /** @@ -39,31 +39,9 @@ extern "C" { void sha1(uint8_t * data, uint32_t size, uint8_t hash[20]) { SHA1_CTX ctx; - -#ifdef DEBUG_SHA1 - os_printf("DATA:"); - for(uint16_t i = 0; i < size; i++) { - os_printf("%02X", data[i]); - } - os_printf("\n"); - os_printf("DATA:"); - for(uint16_t i = 0; i < size; i++) { - os_printf("%c", data[i]); - } - os_printf("\n"); -#endif - - SHA1Init(&ctx); - SHA1Update(&ctx, data, size); - SHA1Final(hash, &ctx); - -#ifdef DEBUG_SHA1 - os_printf("SHA1:"); - for(uint16_t i = 0; i < 20; i++) { - os_printf("%02X", hash[i]); - } - os_printf("\n\n"); -#endif + SHA1_Init(&ctx); + SHA1_Update(&ctx, data, size); + SHA1_Final(hash, &ctx); } void sha1(char * data, uint32_t size, uint8_t hash[20]) { diff --git a/libraries/Hash/src/sha1/sha1.c b/libraries/Hash/src/sha1/sha1.c deleted file mode 100644 index fae926462d..0000000000 --- a/libraries/Hash/src/sha1/sha1.c +++ /dev/null @@ -1,208 +0,0 @@ -/** - * @file sha1.c - * @date 20.05.2015 - * @author Steve Reid - * - * from: http://www.virtualbox.org/svn/vbox/trunk/src/recompiler/tests/sha1.c - */ - -/* from valgrind tests */ - -/* ================ sha1.c ================ */ -/* - SHA-1 in C - By Steve Reid - 100% Public Domain - - Test Vectors (from FIPS PUB 180-1) - "abc" - A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D - "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" - 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 - A million repetitions of "a" - 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F -*/ - -/* #define LITTLE_ENDIAN * This should be #define'd already, if true. */ -/* #define SHA1HANDSOFF * Copies data before messing with it. */ - -#define SHA1HANDSOFF - -#include -#include -#include -#include - -#include "sha1.h" - -//#include - -#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) - -/* blk0() and blk() perform the initial expand. */ -/* I got the idea of expanding during the round function from SSLeay */ -#if BYTE_ORDER == LITTLE_ENDIAN -#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \ - |(rol(block->l[i],8)&0x00FF00FF)) -#elif BYTE_ORDER == BIG_ENDIAN -#define blk0(i) block->l[i] -#else -#error "Endianness not defined!" -#endif -#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ - ^block->l[(i+2)&15]^block->l[i&15],1)) - -/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ -#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); -#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); -#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); -#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); -#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); - - -/* Hash a single 512-bit block. This is the core of the algorithm. */ - -void ICACHE_FLASH_ATTR SHA1Transform(uint32_t state[5], uint8_t buffer[64]) -{ -uint32_t a, b, c, d, e; -typedef union { - unsigned char c[64]; - uint32_t l[16]; -} CHAR64LONG16; -#ifdef SHA1HANDSOFF -CHAR64LONG16 block[1]; /* use array to appear as a pointer */ - memcpy(block, buffer, 64); -#else - /* The following had better never be used because it causes the - * pointer-to-const buffer to be cast into a pointer to non-const. - * And the result is written through. I threw a "const" in, hoping - * this will cause a diagnostic. - */ -CHAR64LONG16* block = (const CHAR64LONG16*)buffer; -#endif - /* Copy context->state[] to working vars */ - a = state[0]; - b = state[1]; - c = state[2]; - d = state[3]; - e = state[4]; - /* 4 rounds of 20 operations each. Loop unrolled. */ - R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3); - R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7); - R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11); - R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15); - R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19); - R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23); - R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27); - R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31); - R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35); - R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39); - R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43); - R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47); - R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51); - R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55); - R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59); - R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63); - R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67); - R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71); - R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75); - R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79); - /* Add the working vars back into context.state[] */ - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - state[4] += e; - /* Wipe variables */ - a = b = c = d = e = 0; -#ifdef SHA1HANDSOFF - memset(block, '\0', sizeof(block)); -#endif -} - - -/* SHA1Init - Initialize new context */ - -void ICACHE_FLASH_ATTR SHA1Init(SHA1_CTX* context) -{ - /* SHA1 initialization constants */ - context->state[0] = 0x67452301; - context->state[1] = 0xEFCDAB89; - context->state[2] = 0x98BADCFE; - context->state[3] = 0x10325476; - context->state[4] = 0xC3D2E1F0; - context->count[0] = context->count[1] = 0; -} - - -/* Run your data through this. */ - -void ICACHE_FLASH_ATTR SHA1Update(SHA1_CTX* context, uint8_t* data, uint32_t len) -{ - uint32_t i; - uint32_t j; - - j = context->count[0]; - if ((context->count[0] += len << 3) < j) - context->count[1]++; - context->count[1] += (len>>29); - j = (j >> 3) & 63; - if ((j + len) > 63) { - memcpy(&context->buffer[j], data, (i = 64-j)); - SHA1Transform(context->state, context->buffer); - for ( ; i + 63 < len; i += 64) { - SHA1Transform(context->state, &data[i]); - } - j = 0; - } - else i = 0; - memcpy(&context->buffer[j], &data[i], len - i); -} - - -/* Add padding and return the message digest. */ - -void ICACHE_FLASH_ATTR SHA1Final(unsigned char digest[20], SHA1_CTX* context) -{ -unsigned i; -unsigned char finalcount[8]; -unsigned char c; - -#if 0 /* untested "improvement" by DHR */ - /* Convert context->count to a sequence of bytes - * in finalcount. Second element first, but - * big-endian order within element. - * But we do it all backwards. - */ - unsigned char *fcp = &finalcount[8]; - - for (i = 0; i < 2; i++) - { - uint32_t t = context->count[i]; - int j; - - for (j = 0; j < 4; t >>= 8, j++) - *--fcp = (unsigned char) t; - } -#else - for (i = 0; i < 8; i++) { - finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] - >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */ - } -#endif - c = 0200; - SHA1Update(context, &c, 1); - while ((context->count[0] & 504) != 448) { - c = 0000; - SHA1Update(context, &c, 1); - } - SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */ - for (i = 0; i < 20; i++) { - digest[i] = (unsigned char) - ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); - } - /* Wipe variables */ - memset(context, '\0', sizeof(*context)); - memset(&finalcount, '\0', sizeof(finalcount)); -} -/* ================ end of sha1.c ================ */ diff --git a/libraries/Hash/src/sha1/sha1.h b/libraries/Hash/src/sha1/sha1.h deleted file mode 100644 index 158bd76b36..0000000000 --- a/libraries/Hash/src/sha1/sha1.h +++ /dev/null @@ -1,32 +0,0 @@ -/** - * @file sha1.h - * @date 20.05.2015 - * @author Steve Reid - * - * from: http://www.virtualbox.org/svn/vbox/trunk/src/recompiler/tests/sha1.c - */ - -/* ================ sha1.h ================ */ -/* - SHA-1 in C - By Steve Reid - 100% Public Domain -*/ - -#ifndef SHA1_H_ -#define SHA1_H_ - -typedef struct { - uint32_t state[5]; - uint32_t count[2]; - unsigned char buffer[64]; -} SHA1_CTX; - -void SHA1Transform(uint32_t state[5], uint8_t buffer[64]); -void SHA1Init(SHA1_CTX* context); -void SHA1Update(SHA1_CTX* context, uint8_t* data, uint32_t len); -void SHA1Final(unsigned char digest[20], SHA1_CTX* context); - -#endif /* SHA1_H_ */ - -/* ================ end of sha1.h ================ */ diff --git a/platform.txt b/platform.txt index 4c305a85dc..f2ef913a32 100644 --- a/platform.txt +++ b/platform.txt @@ -23,7 +23,7 @@ build.lwip_flags=-DLWIP_OPEN_SRC compiler.path={runtime.tools.xtensa-lx106-elf-gcc.path}/bin/ compiler.sdk.path={runtime.platform.path}/tools/sdk compiler.libc.path={runtime.platform.path}/tools/sdk/libc/xtensa-lx106-elf -compiler.cpreprocessor.flags=-D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-I{compiler.sdk.path}/include" "-I{compiler.sdk.path}/lwip/include" "-I{compiler.libc.path}/include" "-I{build.path}/core" +compiler.cpreprocessor.flags=-D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-I{compiler.sdk.path}/include" "-I{compiler.sdk.path}/lwip/include" "-I{compiler.libc.path}/include" "-I{build.path}/core" "-I{compiler.sdk.path}/axtls" compiler.c.cmd=xtensa-lx106-elf-gcc compiler.c.flags=-c {compiler.warning_flags} -Os -g -Wpointer-arith -Wno-implicit-function-declaration -Wl,-EL -fno-inline-functions -nostdlib -mlongcalls -mtext-section-literals -falign-functions=4 -MMD -std=gnu99 -ffunction-sections -fdata-sections diff --git a/tools/sdk/axtls/.gitignore b/tools/sdk/axtls/.gitignore new file mode 100644 index 0000000000..03ba8b58a6 --- /dev/null +++ b/tools/sdk/axtls/.gitignore @@ -0,0 +1,5 @@ +*.o +bin/ +Makefile.local +.DS_Store + diff --git a/tools/sdk/axtls/.gitmodules b/tools/sdk/axtls/.gitmodules new file mode 100644 index 0000000000..6816a4b760 --- /dev/null +++ b/tools/sdk/axtls/.gitmodules @@ -0,0 +1,3 @@ +[submodule "compat"] + path = compat + url = https://github.com/attachix/lwirax.git diff --git a/tools/sdk/axtls/.gitrepo b/tools/sdk/axtls/.gitrepo new file mode 100644 index 0000000000..1adebadafc --- /dev/null +++ b/tools/sdk/axtls/.gitrepo @@ -0,0 +1,11 @@ +; DO NOT EDIT (unless you know what you are doing) +; +; This subdirectory is a git "subrepo", and this file is maintained by the +; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme +; +[subrepo] + remote = https://github.com/igrr/axtls-8266 + branch = master + commit = 27f4a6caf69625a9e798b7a1c3b1406ec1ec1d85 + parent = b6958986d1fd1e020ae8794d91959c2e1030eacf + cmdver = 0.3.1 diff --git a/tools/sdk/axtls/.travis.yml b/tools/sdk/axtls/.travis.yml new file mode 100644 index 0000000000..5258cf5890 --- /dev/null +++ b/tools/sdk/axtls/.travis.yml @@ -0,0 +1,43 @@ +sudo: false +language: bash +os: + - linux + +script: + # Download Arduino IDE + - wget -O arduino.tar.xz https://www.arduino.cc/download.php?f=/arduino-nightly-linux64.tar.xz + - tar xf arduino.tar.xz + - mv arduino-nightly $HOME/arduino_ide + # Download ESP8266 Arduino core + - cd $HOME/arduino_ide/hardware + - mkdir esp8266com + - cd esp8266com + - git clone https://github.com/esp8266/Arduino.git esp8266 + - cd esp8266 + - export ESP8266_ARDUINO_DIR="$PWD" + # Download toolchain and esptool + - cd tools + - python get.py + - export PATH="$PATH:$PWD/xtensa-lx106-elf/bin" + # Build axTLS + - cd $TRAVIS_BUILD_DIR + - make + # Copy the library into Arduino core + - cp bin/libaxtls.a $ESP8266_ARDUINO_DIR/tools/sdk/lib/libaxtls.a + # Try building examples in ESP8266WiFi library from the ESP8266 Arduino core + - /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_1.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :1 -ac -screen 0 1280x1024x16 + - sleep 3 + - export DISPLAY=:1.0 + - export PATH="$HOME/arduino_ide:$PATH" + - which arduino + - cd $ESP8266_ARDUINO_DIR + - source tests/common.sh + - arduino --board esp8266com:esp8266:generic --save-prefs + - arduino --get-pref sketchbook.path + - build_sketches $HOME/arduino_ide $ESP8266_ARDUINO_DIR/libraries/ESP8266WiFi/examples/HTTPSRequest + # Feel free to add more test cases (for other environments) here + +notifications: + email: + on_success: change + on_failure: change diff --git a/tools/sdk/axtls/LICENSE b/tools/sdk/axtls/LICENSE new file mode 100644 index 0000000000..eed70a9a67 --- /dev/null +++ b/tools/sdk/axtls/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2008, 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 REGENTS 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. diff --git a/tools/sdk/axtls/Makefile b/tools/sdk/axtls/Makefile new file mode 100644 index 0000000000..e48e869f15 --- /dev/null +++ b/tools/sdk/axtls/Makefile @@ -0,0 +1,79 @@ +TOOLCHAIN_PREFIX := xtensa-lx106-elf- +CC := $(TOOLCHAIN_PREFIX)gcc +AR := $(TOOLCHAIN_PREFIX)ar +LD := $(TOOLCHAIN_PREFIX)gcc +OBJCOPY := $(TOOLCHAIN_PREFIX)objcopy + +XTENSA_LIBS ?= $(shell $(CC) -print-sysroot) + +TOOLCHAIN_DIR=$(shell cd $(XTENSA_LIBS)/../../; pwd) + +OBJ_FILES := \ + crypto/aes.o \ + crypto/bigint.o \ + crypto/hmac.o \ + crypto/md5.o \ + crypto/rc4.o \ + crypto/rsa.o \ + crypto/sha1.o \ + crypto/sha256.o \ + crypto/sha384.o \ + crypto/sha512.o \ + ssl/asn1.o \ + ssl/gen_cert.o \ + ssl/loader.o \ + ssl/os_port.o \ + ssl/p12.o \ + ssl/tls1.o \ + ssl/tls1_clnt.o \ + ssl/tls1_svr.o \ + ssl/x509.o \ + crypto/crypto_misc.o \ + + +CPPFLAGS += -I$(XTENSA_LIBS)/include \ + -Icrypto \ + -Issl \ + -I. + +LDFLAGS += -L$(XTENSA_LIBS)/lib \ + -L$(XTENSA_LIBS)/arch/lib \ + + +CFLAGS+=-std=c99 -DESP8266 + +CFLAGS += -Wall -Os -g -O2 -Wpointer-arith -Wl,-EL -nostdlib -mlongcalls -mno-text-section-literals -D__ets__ -DICACHE_FLASH + +CFLAGS += -ffunction-sections -fdata-sections + +CFLAGS += -fdebug-prefix-map=$(PWD)= -fdebug-prefix-map=$(TOOLCHAIN_DIR)=xtensa-lx106-elf -gno-record-gcc-switches + +MFORCE32 := $(shell $(CC) --help=target | grep mforce-l32) +ifneq ($(MFORCE32),) + # If the compiler supports the -mforce-l32 flag, the compiler will generate correct code for loading + # 16- and 8-bit constants from program memory. So in the code we can directly access the arrays + # placed into program memory. + CFLAGS += -mforce-l32 +else + # Otherwise we need to use a helper function to load 16- and 8-bit constants from program memory. + CFLAGS += -DWITH_PGM_READ_HELPER +endif + +BIN_DIR := bin +AXTLS_AR := $(BIN_DIR)/libaxtls.a + +all: $(AXTLS_AR) + +$(AXTLS_AR): | $(BIN_DIR) + +$(AXTLS_AR): $(OBJ_FILES) + $(AR) cru $@ $^ + +$(BIN_DIR): + mkdir -p $(BIN_DIR) + +clean: + rm -rf $(OBJ_FILES) $(AXTLS_AR) + + +.PHONY: all clean diff --git a/tools/sdk/axtls/README.md b/tools/sdk/axtls/README.md new file mode 100644 index 0000000000..8537ba13f9 --- /dev/null +++ b/tools/sdk/axtls/README.md @@ -0,0 +1,39 @@ +This is an ESP8266 port of [axTLS](http://axtls.sourceforge.net/) library, currently based on axTLS 2.1.2 (SVN version 274). + +This library supports TLS 1.2, and the following cipher suites: + +Cipher suite name (RFC) | OpenSSL name | Key exchange | Encryption | Hash +----------------------------------|---------------|--------------|------------|--------- +TLS_RSA_WITH_AES_128_CBC_SHA | AES128-SHA | RSA | AES-128 | SHA-1 +TLS_RSA_WITH_AES_256_CBC_SHA | AES256-SHA | RSA | AES-256 | SHA-1 +TLS_RSA_WITH_AES_128_CBC_SHA256 | AES128-SHA256 | RSA | AES-128 | SHA-256 +TLS_RSA_WITH_AES_256_CBC_SHA256 | AES256-SHA256 | RSA | AES-256 | SHA-256 + +## Using the library + +This is not a self-sufficient library. In addition to the standard C library functions, application has to provide the following functions: + +``` +ax_port_read +ax_port_write +ax_port_open +ax_port_close +ax_get_file +phy_get_rand (provided by the IoT SDK) +ets_printf (in ESP8266 ROM) +ets_putc (in ESP8266 ROM) +``` + +For use with LwIP raw TCP API, see [compat/README.md](https://github.com/attachix/lwirax/blob/master/README.md) + +## Building [![Build status](https://travis-ci.org/igrr/axtls-8266.svg)](https://travis-ci.org/igrr/axtls-8266) + +To build, add xtensa toolchain to your path, and run `make`. The library will be built in `bin/` directory. + +## Credits and license + +[axTLS](http://axtls.sourceforge.net/) is written and maintained by Cameron Rich. + +Other people have contributed to this port; see git logs for a full list. + +See [LICENSE](LICENSE) file for axTLS license. diff --git a/tools/sdk/axtls/VERSION b/tools/sdk/axtls/VERSION new file mode 100644 index 0000000000..4ea2b1f403 --- /dev/null +++ b/tools/sdk/axtls/VERSION @@ -0,0 +1 @@ +1.4.9 diff --git a/tools/sdk/axtls/bindings/Config.in b/tools/sdk/axtls/bindings/Config.in new file mode 100644 index 0000000000..443fc1a323 --- /dev/null +++ b/tools/sdk/axtls/bindings/Config.in @@ -0,0 +1,105 @@ +# +# For a description of the syntax of this configuration file, +# see scripts/config/Kconfig-language.txt +# +menu "Language Bindings" + +config CONFIG_BINDINGS + bool "Create language bindings" + default n + help + axTLS supports language bindings in C#, VB.NET, Java and Perl. + + Select Y here if you want to build the various language bindings. + +config CONFIG_CSHARP_BINDINGS + bool "Create C# bindings" + default n + depends on CONFIG_BINDINGS + help + Build C# bindings. + + This requires .NET to be installed on Win32 platforms and mono to be + installed on all other platforms. + +config CONFIG_VBNET_BINDINGS + bool "Create VB.NET bindings" + default n + depends on CONFIG_BINDINGS + help + Build VB.NET bindings. + + This requires the .NET to be installed and is only built under Win32 + platforms. + +menu ".Net Framework" +depends on CONFIG_CSHARP_BINDINGS || CONFIG_VBNET_BINDINGS +config CONFIG_DOT_NET_FRAMEWORK_BASE + string "Location of .NET Framework" + default "c:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727" +endmenu + +config CONFIG_JAVA_BINDINGS + bool "Create Java bindings" + default n + depends on CONFIG_BINDINGS + help + Build Java bindings. + + Current Issues (see README): + * Needs Java 1.4 or better. + * If building under Win32 it will use the Win32 JDK. + +menu "Java Home" +depends on CONFIG_JAVA_BINDINGS +config CONFIG_JAVA_HOME + string "Location of JDK" + default "c:\\Program Files\\Java\\jdk1.5.0_06" if CONFIG_PLATFORM_WIN32 || CONFIG_PLATFORM_CYGWIN + default "/usr/lib/jvm/java-7-openjdk-amd64" if !CONFIG_PLATFORM_WIN32 && !CONFIG_PLATFORM_CYGWIN + depends on CONFIG_JAVA_BINDINGS + help + The location of Sun's JDK. +endmenu + +config CONFIG_PERL_BINDINGS + bool "Create Perl bindings" + default n + depends on CONFIG_BINDINGS + help + Build Perl bindings. + + Current Issues (see README): + * 64 bit versions don't work at present. + * libperl.so needs to be in the shared library path. + +menu "Perl Home" +depends on CONFIG_PERL_BINDINGS && CONFIG_PLATFORM_WIN32 +config CONFIG_PERL_CORE + string "Location of Perl CORE" + default "c:\\perl\\lib\\CORE" + help: + works with ActiveState + "http://www.activestate.com/Products/ActivePerl" + +config CONFIG_PERL_LIB + string "Name of Perl Library" + default "perl58.lib" +endmenu + +config CONFIG_LUA_BINDINGS + bool "Create Lua bindings" + default n + depends on CONFIG_BINDINGS && !CONFIG_PLATFORM_WIN32 + help + Build Lua bindings (see www.lua.org). + +menu "Lua Home" +depends on CONFIG_LUA_BINDINGS +config CONFIG_LUA_CORE + string "Location of Lua CORE" + default "/usr/local" + help: + If the Lua exists on another directory then this needs to be changed +endmenu + +endmenu diff --git a/tools/sdk/axtls/bindings/csharp/axTLS.cs b/tools/sdk/axtls/bindings/csharp/axTLS.cs new file mode 100644 index 0000000000..6a2f6b0633 --- /dev/null +++ b/tools/sdk/axtls/bindings/csharp/axTLS.cs @@ -0,0 +1,491 @@ +/* + * Copyright (c) 2007-2016, 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. + */ + +/** + * A wrapper around the unmanaged interface to give a semi-decent C# API + */ + +using System; +using System.Runtime.InteropServices; +using System.Net.Sockets; + +/** + * @defgroup csharp_api C# API. + * + * Ensure that the appropriate Dispose() methods are called when finished with + * various objects - otherwise memory leaks will result. + * @{ + */ +namespace axTLS +{ + /** + * @class SSL + * @ingroup csharp_api + * @brief A representation of an SSL connection. + */ + public class SSL + { + public IntPtr m_ssl; /**< A pointer to the real SSL type */ + + /** + * @brief Store the reference to an SSL context. + * @param ip [in] A reference to an SSL object. + */ + public SSL(IntPtr ip) + { + m_ssl = ip; + } + + /** + * @brief Free any used resources on this connection. + * + * A "Close Notify" message is sent on this connection (if possible). + * It is up to the application to close the socket. + */ + public void Dispose() + { + axtls.ssl_free(m_ssl); + } + + /** + * @brief Return the result of a handshake. + * @return SSL_OK if the handshake is complete and ok. + * @see ssl.h for the error code list. + */ + public int HandshakeStatus() + { + return axtls.ssl_handshake_status(m_ssl); + } + + /** + * @brief Return the SSL cipher id. + * @return The cipher id which is one of: + * - SSL_AES128_SHA (0x2f) + * - SSL_AES256_SHA (0x35) + * - SSL_AES128_SHA256 (0x3c) + * - SSL_AES256_SHA256 (0x3d) + */ + public byte GetCipherId() + { + return axtls.ssl_get_cipher_id(m_ssl); + } + + /** + * @brief Get the session id for a handshake. + * + * This will be a 32 byte sequence and is available after the first + * handshaking messages are sent. + * @return The session id as a 32 byte sequence. + * @note A SSLv23 handshake may have only 16 valid bytes. + */ + public byte[] GetSessionId() + { + IntPtr ptr = axtls.ssl_get_session_id(m_ssl); + byte sess_id_size = axtls.ssl_get_session_id_size(m_ssl); + byte[] result = new byte[sess_id_size]; + Marshal.Copy(ptr, result, 0, sess_id_size); + return result; + } + + /** + * @brief Retrieve an X.509 distinguished name component. + * + * When a handshake is complete and a certificate has been exchanged, + * then the details of the remote certificate can be retrieved. + * + * This will usually be used by a client to check that the server's + * common name matches the URL. + * + * A full handshake needs to occur for this call to work. + * + * @param component [in] one of: + * - SSL_X509_CERT_COMMON_NAME + * - SSL_X509_CERT_ORGANIZATION + * - SSL_X509_CERT_ORGANIZATIONAL_NAME + * - SSL_X509_CA_CERT_COMMON_NAME + * - SSL_X509_CA_CERT_ORGANIZATION + * - SSL_X509_CA_CERT_ORGANIZATIONAL_NAME + * @return The appropriate string (or null if not defined) + */ + public string GetCertificateDN(int component) + { + return axtls.ssl_get_cert_dn(m_ssl, component); + } + } + + /** + * @class SSLUtil + * @ingroup csharp_api + * @brief Some global helper functions. + */ + public class SSLUtil + { + + /** + * @brief Return the build mode of the axTLS project. + * @return The build mode is one of: + * - SSL_BUILD_SERVER_ONLY + * - SSL_BUILD_ENABLE_VERIFICATION + * - SSL_BUILD_ENABLE_CLIENT + * - SSL_BUILD_FULL_MODE + */ + public static int BuildMode() + { + return axtls.ssl_get_config(axtls.SSL_BUILD_MODE); + } + + /** + * @brief Return the number of chained certificates that the + * client/server supports. + * @return The number of supported server certificates. + */ + public static int MaxCerts() + { + return axtls.ssl_get_config(axtls.SSL_MAX_CERT_CFG_OFFSET); + } + + /** + * @brief Return the number of CA certificates that the client/server + * supports. + * @return The number of supported CA certificates. + */ + public static int MaxCACerts() + { + return axtls.ssl_get_config(axtls.SSL_MAX_CA_CERT_CFG_OFFSET); + } + + /** + * @brief Indicate if PEM is supported. + * @return true if PEM supported. + */ + public static bool HasPEM() + { + return axtls.ssl_get_config(axtls.SSL_HAS_PEM) > 0 ? true : false; + } + + /** + * @brief Display the text string of the error. + * @param error_code [in] The integer error code. + */ + public static void DisplayError(int error_code) + { + axtls.ssl_display_error(error_code); + } + + /** + * @brief Return the version of the axTLS project. + */ + public static string Version() + { + return axtls.ssl_version(); + } + } + + /** + * @class SSLCTX + * @ingroup csharp_api + * @brief A base object for SSLServer/SSLClient. + */ + public class SSLCTX + { + /** + * @brief A reference to the real client/server context. + */ + protected IntPtr m_ctx; + + /** + * @brief Establish a new client/server context. + * + * This function is called before any client/server SSL connections are + * made. If multiple threads are used, then each thread will have its + * own SSLCTX context. Any number of connections may be made with a + * single context. + * + * Each new connection will use the this context's private key and + * certificate chain. If a different certificate chain is required, + * then a different context needs to be be used. + * + * @param options [in] Any particular options. At present the options + * supported are: + * - SSL_SERVER_VERIFY_LATER (client only): Don't stop a handshake if + * the server authentication fails. The certificate can be + * authenticated later with a call to VerifyCert(). + * - SSL_CLIENT_AUTHENTICATION (server only): Enforce client + * authentication i.e. each handshake will include a "certificate + * request" message from the server. + * - SSL_DISPLAY_BYTES (full mode build only): Display the byte + * sequences during the handshake. + * - SSL_DISPLAY_STATES (full mode build only): Display the state + * changes during the handshake. + * - SSL_DISPLAY_CERTS (full mode build only): Display the + * certificates that are passed during a handshake. + * - SSL_DISPLAY_RSA (full mode build only): Display the RSA key + * details that are passed during a handshake. + * @param num_sessions [in] The number of sessions to be used for + * session caching. If this value is 0, then there is no session + * caching. + * @return A client/server context. + */ + protected SSLCTX(uint options, int num_sessions) + { + m_ctx = axtls.ssl_ctx_new(options, num_sessions); + } + + /** + * @brief Remove a client/server context. + * + * Frees any used resources used by this context. Each connection will + * be sent a "Close Notify" alert (if possible). + */ + public void Dispose() + { + axtls.ssl_ctx_free(m_ctx); + } + + /** + * @brief Read the SSL data stream. + * @param ssl [in] An SSL object reference. + * @param in_data [out] After a successful read, the decrypted data + * will be here. It will be null otherwise. + * @return The number of decrypted bytes: + * - if > 0, then the handshaking is complete and we are returning the + * number of decrypted bytes. + * - SSL_OK if the handshaking stage is successful (but not yet + * complete). + * - < 0 if an error. + * @see ssl.h for the error code list. + * @note Use in_data before doing any successive ssl calls. + */ + public int Read(SSL ssl, out byte[] in_data) + { + IntPtr ptr = IntPtr.Zero; + int ret = axtls.ssl_read(ssl.m_ssl, ref ptr); + + if (ret > axtls.SSL_OK) + { + in_data = new byte[ret]; + Marshal.Copy(ptr, in_data, 0, ret); + } + else + { + in_data = null; + } + + return ret; + } + + /** + * @brief Write to the SSL data stream. + * @param ssl [in] An SSL obect reference. + * @param out_data [in] The data to be written + * @return The number of bytes sent, or if < 0 if an error. + * @see ssl.h for the error code list. + */ + public int Write(SSL ssl, byte[] out_data) + { + return axtls.ssl_write(ssl.m_ssl, out_data, out_data.Length); + } + + /** + * @brief Write to the SSL data stream. + * @param ssl [in] An SSL obect reference. + * @param out_data [in] The data to be written + * @param out_len [in] The number of bytes to be written + * @return The number of bytes sent, or if < 0 if an error. + * @see ssl.h for the error code list. + */ + public int Write(SSL ssl, byte[] out_data, int out_len) + { + return axtls.ssl_write(ssl.m_ssl, out_data, out_len); + } + + /** + * @brief Find an ssl object based on a Socket reference. + * + * Goes through the list of SSL objects maintained in a client/server + * context to look for a socket match. + * @param s [in] A reference to a Socket object. + * @return A reference to the SSL object. Returns null if the object + * could not be found. + */ + public SSL Find(Socket s) + { + int client_fd = s.Handle.ToInt32(); + return new SSL(axtls. ssl_find(m_ctx, client_fd)); + } + + /** + * @brief Authenticate a received certificate. + * + * This call is usually made by a client after a handshake is complete + * and the context is in SSL_SERVER_VERIFY_LATER mode. + * @param ssl [in] An SSL object reference. + * @return SSL_OK if the certificate is verified. + */ + public int VerifyCert(SSL ssl) + { + return axtls.ssl_verify_cert(ssl.m_ssl); + } + + /** + * @brief Force the client to perform its handshake again. + * + * For a client this involves sending another "client hello" message. + * For the server is means sending a "hello request" message. + * + * This is a blocking call on the client (until the handshake + * completes). + * @param ssl [in] An SSL object reference. + * @return SSL_OK if renegotiation instantiation was ok + */ + public int Renegotiate(SSL ssl) + { + return axtls.ssl_renegotiate(ssl.m_ssl); + } + + /** + * @brief Load a file into memory that is in binary DER or ASCII PEM + * format. + * + * These are temporary objects that are used to load private keys, + * certificates etc into memory. + * @param obj_type [in] The format of the file. Can be one of: + * - SSL_OBJ_X509_CERT (no password required) + * - SSL_OBJ_X509_CACERT (no password required) + * - SSL_OBJ_RSA_KEY (AES128/AES256 PEM encryption supported) + * - SSL_OBJ_P8 (RC4-128 encrypted data supported) + * - SSL_OBJ_P12 (RC4-128 encrypted data supported) + * + * PEM files are automatically detected (if supported). + * @param filename [in] The location of a file in DER/PEM format. + * @param password [in] The password used. Can be null if not required. + * @return SSL_OK if all ok + */ + public int ObjLoad(int obj_type, string filename, string password) + { + return axtls.ssl_obj_load(m_ctx, obj_type, filename, password); + } + + /** + * @brief Transfer binary data into the object loader. + * + * These are temporary objects that are used to load private keys, + * certificates etc into memory. + * @param obj_type [in] The format of the memory data. + * @param data [in] The binary data to be loaded. + * @param len [in] The amount of data to be loaded. + * @param password [in] The password used. Can be null if not required. + * @return SSL_OK if all ok + */ + public int ObjLoad(int obj_type, byte[] data, int len, string password) + { + return axtls.ssl_obj_memory_load(m_ctx, obj_type, + data, len, password); + } + } + + /** + * @class SSLServer + * @ingroup csharp_api + * @brief The server context. + * + * All server connections are started within a server context. + */ + public class SSLServer : SSLCTX + { + /** + * @brief Start a new server context. + * + * @see SSLCTX for details. + */ + public SSLServer(uint options, int num_sessions) : + base(options, num_sessions) {} + + /** + * @brief Establish a new SSL connection to an SSL client. + * + * It is up to the application to establish the initial socket + * connection. + * + * Call Dispose() when the connection is to be removed. + * @param s [in] A reference to a Socket object. + * @return An SSL object reference. + */ + public SSL Connect(Socket s) + { + int client_fd = s.Handle.ToInt32(); + return new SSL(axtls.ssl_server_new(m_ctx, client_fd)); + } + } + + /** + * @class SSLClient + * @ingroup csharp_api + * @brief The client context. + * + * All client connections are started within a client context. + */ + public class SSLClient : SSLCTX + { + /** + * @brief Start a new client context. + * + * @see SSLCTX for details. + */ + public SSLClient(uint options, int num_sessions) : + base(options, num_sessions) {} + + /** + * @brief Establish a new SSL connection to an SSL server. + * + * It is up to the application to establish the initial socket + * connection. + * + * This is a blocking call - it will finish when the handshake is + * complete (or has failed). + * + * Call Dispose() when the connection is to be removed. + * @param s [in] A reference to a Socket object. + * @param session_id [in] A 32 byte session id for session resumption. + * This can be null if no session resumption is not required. + * @return An SSL object reference. Use SSL.handshakeStatus() to check + * if a handshake succeeded. + */ + public SSL Connect(Socket s, byte[] session_id) + { + int client_fd = s.Handle.ToInt32(); + byte sess_id_size = (byte)(session_id != null ? + session_id.Length : 0); + return new SSL(axtls.ssl_client_new(m_ctx, client_fd, session_id, + sess_id_size)); + } + } +} +/** @} */ diff --git a/tools/sdk/axtls/bindings/generate_SWIG_interface.pl b/tools/sdk/axtls/bindings/generate_SWIG_interface.pl new file mode 100755 index 0000000000..90c4ba3bef --- /dev/null +++ b/tools/sdk/axtls/bindings/generate_SWIG_interface.pl @@ -0,0 +1,392 @@ +#!/usr/bin/perl + +# +# 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. +# + +#=============================================================== +# Transforms function signature into SWIG format +sub transformSignature +{ + foreach $item (@_) + { + $line =~ s/STDCALL //g; + $line =~ s/EXP_FUNC/extern/g; + + # make API Java more 'byte' friendly + $line =~ s/uint32_t/int/g; + $line =~ s/const uint8_t \* /const unsigned char \* /g; + $line =~ s/\(void\)/()/g; + if ($ARGV[0] eq "-java") + { + $line =~ s/.*ssl_read.*//g; + $line =~ s/const uint8_t \*(\w+)/const signed char $1\[\]/g; + $line =~ s/uint8_t/signed char/g; + } + elsif ($ARGV[0] eq "-perl") + { + $line =~ s/const uint8_t \*(\w+)/const unsigned char $1\[\]/g; + $line =~ s/uint8_t/unsigned char/g; + } + else # lua + { + $line =~ s/const uint8_t \*session_id/const unsigned char session_id\[\]/g; + $line =~ s/const uint8_t \*\w+/unsigned char *INPUT/g; + $line =~ s/uint8_t/unsigned char/g; + } + } + + return $line; +} + +# Parse input file +sub parseFile +{ + foreach $line (@_) + { + next if $line =~ /ssl_x509_create/; # ignore for now + + # test for a #define + if (!$skip && $line =~ m/^#define/) + { + $splitDefine = 1 if $line =~ m/\\$/; + print DATA_OUT $line; + + # check line is not split + next if $splitDefine == 1; + } + + # pick up second line of #define statement + if ($splitDefine) + { + print DATA_OUT $line; + + # check line is not split + $splitDefine = ($line =~ m/\\$/); + next; + } + + # test for function declaration + if (!$skip && $line =~ /EXP_FUNC/ && $line !~/\/\*/) + { + $line = transformSignature($line); + $splitFunctionDeclaration = $line !~ /;/; + print DATA_OUT $line; + next; + } + + if ($splitFunctionDeclaration) + { + $line = transformSignature($line); + $splitFunctionDeclaration = $line !~ /;/; + print DATA_OUT $line; + next; + } + } +} + +#=============================================================== + +# Determine which module to build from cammand-line options +use strict; +use Getopt::Std; + +my $module; +my $interfaceFile; +my $data_file; +my $skip; +my $splitLine; +my @raw_data; + +if (not defined $ARGV[0]) +{ + die "Usage: $0 [-java | -perl | -lua]\n"; +} + +if ($ARGV[0] eq "-java") +{ + print "Generating Java interface file\n"; + $module = "axtlsj"; + $interfaceFile = "java/axTLSj.i"; +} +elsif ($ARGV[0] eq "-perl") +{ + print "Generating Perl interface file\n"; + $module = "axtlsp"; + $interfaceFile = "perl/axTLSp.i"; +} +elsif ($ARGV[0] eq "-lua") +{ + print "Generating lua interface file\n"; + $module = "axtlsl"; + $interfaceFile = "lua/axTLSl.i"; +} +else +{ + die "Usage: $0 [-java | -perl | -lua]\n"; +} + +# Input file required to generate SWIG interface file. +$data_file = "../ssl/ssl.h"; + +# Open input files +open(DATA_IN, $data_file) || die("Could not open file ($data_file)!"); +@raw_data = ; + +# Open output file +open(DATA_OUT, ">$interfaceFile") || die("Cannot Open File"); + +# +# I wish I could say it was easy to generate the Perl/Java/Lua bindings, +# but each had their own set of challenges... :-(. +# +print DATA_OUT << "END"; +%module $module\n + +/* include our own header */ +%inline %{ +#include "ssl.h" +%} + +%include "typemaps.i" +/* Some SWIG magic to make the API a bit more Java friendly */ +#ifdef SWIGJAVA + +%apply long { SSL * }; +%apply long { SSL_CTX * }; +%apply long { SSLObjLoader * }; + +/* allow "unsigned char []" to become "byte[]" */ +%include "arrays_java.i" + +/* convert these pointers to use long */ +%apply signed char[] {unsigned char *}; +%apply signed char[] {signed char *}; + +/* allow ssl_get_session_id() to return "byte[]" */ +%typemap(out) unsigned char * ssl_get_session_id \"if (result) jresult = SWIG_JavaArrayOutSchar(jenv, result, ssl_get_session_id_size((SSL const *)arg1));\" + +/* allow ssl_client_new() to have a null session_id input */ +%typemap(in) const signed char session_id[] (jbyte *jarr) { + if (jarg3 == NULL) + { + jresult = (jint)ssl_client_new(arg1,arg2,NULL,0); + return jresult; + } + + if (!SWIG_JavaArrayInSchar(jenv, &jarr, &arg3, jarg3)) return 0; +} + +/* Lot's of work required for an ssl_read() due to its various custom + * requirements. + */ +%native (ssl_read) int ssl_read(SSL *ssl, jobject in_data); +%{ +JNIEXPORT jint JNICALL Java_axTLSj_axtlsjJNI_ssl_1read(JNIEnv *jenv, jclass jcls, jint jarg1, jobject jarg2) { + jint jresult = 0 ; + SSL *arg1; + unsigned char *arg2; + jbyte *jarr; + int result; + JNIEnv e = *jenv; + jclass holder_class; + jfieldID fid; + + arg1 = (SSL *)jarg1; + result = (int)ssl_read(arg1, &arg2); + + /* find the "m_buf" entry in the SSLReadHolder class */ + if (!(holder_class = e->GetObjectClass(jenv,jarg2)) || + !(fid = e->GetFieldID(jenv,holder_class, "m_buf", "[B"))) + return SSL_NOT_OK; + + if (result > SSL_OK) + { + int i; + + /* create a new byte array to hold the read data */ + jbyteArray jarray = e->NewByteArray(jenv, result); + + /* copy the bytes across to the java byte array */ + jarr = e->GetByteArrayElements(jenv, jarray, 0); + for (i = 0; i < result; i++) + jarr[i] = (jbyte)arg2[i]; + + /* clean up and set the new m_buf object */ + e->ReleaseByteArrayElements(jenv, jarray, jarr, 0); + e->SetObjectField(jenv, jarg2, fid, jarray); + } + else /* set to null */ + e->SetObjectField(jenv, jarg2, fid, NULL); + + jresult = (jint)result; + return jresult; +} +%} + +/* Big hack to get hold of a socket's file descriptor */ +%typemap (jtype) long "Object" +%typemap (jstype) long "Object" +%native (getFd) int getFd(long sock); +%{ +JNIEXPORT jint JNICALL Java_axTLSj_axtlsjJNI_getFd(JNIEnv *env, jclass jcls, jobject sock) +{ + JNIEnv e = *env; + jfieldID fid; + jobject impl; + jobject fdesc; + + /* get the SocketImpl from the Socket */ + if (!(jcls = e->GetObjectClass(env,sock)) || + !(fid = e->GetFieldID(env,jcls,"impl","Ljava/net/SocketImpl;")) || + !(impl = e->GetObjectField(env,sock,fid))) return -1; + + /* get the FileDescriptor from the SocketImpl */ + if (!(jcls = e->GetObjectClass(env,impl)) || + !(fid = e->GetFieldID(env,jcls,"fd","Ljava/io/FileDescriptor;")) || + !(fdesc = e->GetObjectField(env,impl,fid))) return -1; + + /* get the fd from the FileDescriptor */ + if (!(jcls = e->GetObjectClass(env,fdesc)) || + !(fid = e->GetFieldID(env,jcls,"fd","I"))) return -1; + + /* return the descriptor */ + return e->GetIntField(env,fdesc,fid); +} +%} + +#endif + +/* Some SWIG magic to make the API a bit more Perl friendly */ +#ifdef SWIGPERL + +/* for ssl_session_id() */ +%typemap(out) const unsigned char * { + SV *svs = newSVpv((unsigned char *)\$1, ssl_get_session_id_size((SSL const *)arg1)); + \$result = newRV(svs); + sv_2mortal(\$result); + argvi++; +} + +/* for ssl_write() */ +%typemap(in) const unsigned char out_data[] { + SV* tempsv; + if (!SvROK(\$input)) + croak("Argument \$argnum is not a reference."); + tempsv = SvRV(\$input); + if (SvTYPE(tempsv) != SVt_PV) + croak("Argument \$argnum is not an string."); + \$1 = (unsigned char *)SvPV(tempsv, PL_na); +} + +/* for ssl_read() */ +%typemap(in) unsigned char **in_data (unsigned char *buf) { + \$1 = &buf; +} + +%typemap(argout) unsigned char **in_data { + if (result > SSL_OK) { + SV *svs = newSVpv(*\$1, result); + \$result = newRV(svs); + sv_2mortal(\$result); + argvi++; + } +} + +/* for ssl_client_new() */ +%typemap(in) const unsigned char session_id[] { + /* check for a reference */ + if (SvOK(\$input) && SvROK(\$input)) { + SV* tempsv = SvRV(\$input); + if (SvTYPE(tempsv) != SVt_PV) + croak("Argument \$argnum is not an string."); + \$1 = (unsigned char *)SvPV(tempsv, PL_na); + } + else + \$1 = NULL; +} + +#endif + +/* Some SWIG magic to make the API a bit more Lua friendly */ +#ifdef SWIGLUA +SWIG_NUMBER_TYPEMAP(unsigned char); +SWIG_TYPEMAP_NUM_ARR(uchar,unsigned char); + +/* for ssl_session_id() */ +%typemap(out) const unsigned char * { + int i; + lua_newtable(L); + for (i = 0; i < ssl_get_session_id_size((SSL const *)arg1); i++){ + lua_pushnumber(L,(lua_Number)result[i]); + lua_rawseti(L,-2,i+1); /* -1 is the number, -2 is the table */ + } + SWIG_arg++; +} + +/* for ssl_read() */ +%typemap(in) unsigned char **in_data (unsigned char *buf) { + \$1 = &buf; +} + +%typemap(argout) unsigned char **in_data { + if (result > SSL_OK) { + int i; + lua_newtable(L); + for (i = 0; i < result; i++){ + lua_pushnumber(L,(lua_Number)buf2[i]); + lua_rawseti(L,-2,i+1); /* -1 is the number, -2 is the table */ + } + SWIG_arg++; + } +} + +/* for ssl_client_new() */ +%typemap(in) const unsigned char session_id[] { + if (lua_isnil(L,\$input)) + \$1 = NULL; + else + \$1 = SWIG_get_uchar_num_array_fixed(L,\$input, ssl_get_session_id((SSL const *)\$1)); +} + +#endif + +END + +# Initialise loop variables +$skip = 1; +$splitLine = 0; + +parseFile(@raw_data); + +close(DATA_IN); +close(DATA_OUT); + +#=============================================================== + diff --git a/tools/sdk/axtls/bindings/java/SSL.java b/tools/sdk/axtls/bindings/java/SSL.java new file mode 100644 index 0000000000..e0400b6016 --- /dev/null +++ b/tools/sdk/axtls/bindings/java/SSL.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2007-2016, 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. + */ + +/* + * A wrapper around the unmanaged interface to give a semi-decent Java API + */ + +package axTLSj; + +import java.io.*; +import java.util.*; + +/** + * @defgroup java_api Java API. + * + * Ensure that the appropriate dispose() methods are called when finished with + * various objects - otherwise memory leaks will result. + */ + +/** + * @class SSL + * @ingroup java_api + * @brief A representation of an SSL connection. + * + */ +public class SSL +{ + public int m_ssl; /**< A pointer to the real SSL type */ + + /** + * @brief Store the reference to an SSL context. + * @param ip [in] A reference to an SSL object. + */ + public SSL(int ip) + { + m_ssl = ip; + } + + /** + * @brief Free any used resources on this connection. + * + * A "Close Notify" message is sent on this connection (if possible). It + * is up to the application to close the socket. + */ + public void dispose() + { + axtlsj.ssl_free(m_ssl); + } + + /** + * @brief Return the result of a handshake. + * @return SSL_OK if the handshake is complete and ok. + * @see ssl.h for the error code list. + */ + public int handshakeStatus() + { + return axtlsj.ssl_handshake_status(m_ssl); + } + + /** + * @brief Return the SSL cipher id. + * @return The cipher id which is one of: + * - SSL_AES128_SHA (0x2f) + * - SSL_AES256_SHA (0x35) + * - SSL_AES128_SHA256 (0x3c) + * - SSL_AES256_SHA256 (0x3d) + */ + public byte getCipherId() + { + return axtlsj.ssl_get_cipher_id(m_ssl); + } + + /** + * @brief Get the session id for a handshake. + * + * This will be a 32 byte sequence and is available after the first + * handshaking messages are sent. + * @return The session id as a 32 byte sequence. + * @note A SSLv23 handshake may have only 16 valid bytes. + */ + public byte[] getSessionId() + { + return axtlsj.ssl_get_session_id(m_ssl); + } + + /** + * @brief Retrieve an X.509 distinguished name component. + * + * When a handshake is complete and a certificate has been exchanged, + * then the details of the remote certificate can be retrieved. + * + * This will usually be used by a client to check that the server's common + * name matches the URL. + * + * A full handshake needs to occur for this call to work. + * + * @param component [in] one of: + * - SSL_X509_CERT_COMMON_NAME + * - SSL_X509_CERT_ORGANIZATION + * - SSL_X509_CERT_ORGANIZATIONAL_NAME + * - SSL_X509_CA_CERT_COMMON_NAME + * - SSL_X509_CA_CERT_ORGANIZATION + * - SSL_X509_CA_CERT_ORGANIZATIONAL_NAME + * @return The appropriate string (or null if not defined) + */ + public String getCertificateDN(int component) + { + return axtlsj.ssl_get_cert_dn(m_ssl, component); + } +} diff --git a/tools/sdk/axtls/compat b/tools/sdk/axtls/compat new file mode 160000 index 0000000000..bc2bf7b61b --- /dev/null +++ b/tools/sdk/axtls/compat @@ -0,0 +1 @@ +Subproject commit bc2bf7b61b9295b07d2fd9b5a9bb7824b1677c85 diff --git a/tools/sdk/axtls/config/makefile.conf b/tools/sdk/axtls/config/makefile.conf new file mode 100644 index 0000000000..702abfd238 --- /dev/null +++ b/tools/sdk/axtls/config/makefile.conf @@ -0,0 +1,134 @@ +# +# Copyright (c) 2007-2016, 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. +# + +# +# A standard makefile for all makefiles +# + +# All executables and libraries go here +STAGE=./_stage + +ifneq ($(MAKECMDGOALS), clean) + +# Give an initial rule +all: + +# Win32 +ifdef CONFIG_PLATFORM_WIN32 + +ifdef CONFIG_VISUAL_STUDIO_7_0 +CONFIG_VISUAL_STUDIO_7_0_BASE_UNIX:=$(shell cygpath -u $(CONFIG_VISUAL_STUDIO_7_0_BASE)) +export INCLUDE=$(shell echo "$(CONFIG_VISUAL_STUDIO_7_0_BASE)\vc7\include;$(CONFIG_VISUAL_STUDIO_7_0_BASE)\vc7\platformsdk\include") +export LIB=$(shell echo "$(CONFIG_VISUAL_STUDIO_7_0_BASE)\vc7\\platformsdk\lib;$(CONFIG_VISUAL_STUDIO_7_0_BASE)\vc7\lib") +PATH:=$(CONFIG_VISUAL_STUDIO_7_0_BASE_UNIX)/vc7/bin:$(CONFIG_VISUAL_STUDIO_7_0_BASE_UNIX)/common7/ide:$(PATH) +endif +ifdef CONFIG_VISUAL_STUDIO_8_0 +CONFIG_VISUAL_STUDIO_8_0_BASE_UNIX:=$(shell cygpath -u $(CONFIG_VISUAL_STUDIO_8_0_BASE)) +export INCLUDE=$(shell echo "$(CONFIG_VISUAL_STUDIO_8_0_BASE)\vc\include;$(CONFIG_VISUAL_STUDIO_8_0_BASE)\vc\platformsdk\include") +export LIB=$(shell echo "$(CONFIG_VISUAL_STUDIO_8_0_BASE)\vc\platformsdk\lib;$(CONFIG_VISUAL_STUDIO_8_0_BASE)\vc\lib") +PATH:=$(CONFIG_VISUAL_STUDIO_8_0_BASE_UNIX)/vc/bin:$(CONFIG_VISUAL_STUDIO_8_0_BASE_UNIX)/common7/ide:$(PATH) +endif +ifdef CONFIG_VISUAL_STUDIO_10_0 +CONFIG_VISUAL_STUDIO_10_0_BASE_UNIX:=$(shell cygpath -u $(CONFIG_VISUAL_STUDIO_10_0_BASE)) +export INCLUDE=$(shell echo "$(CONFIG_VISUAL_STUDIO_10_0_BASE)\vc\include;$(CONFIG_VISUAL_STUDIO_10_0_BASE)\..\Microsoft SDKs\Windows\v7.0A\include") +export LIB=$(shell echo "$(CONFIG_VISUAL_STUDIO_10_0_BASE)\vc\lib;$(CONFIG_VISUAL_STUDIO_10_0_BASE)\..\Microsoft SDKs\Windows\v7.0A\lib") +PATH:=$(CONFIG_VISUAL_STUDIO_10_0_BASE_UNIX)/vc/bin:$(CONFIG_VISUAL_STUDIO_10_0_BASE_UNIX)/common7/ide:$(PATH) +stuff: + @echo $(INCLUDE) +endif + +CC=cl.exe +LD=link.exe +AXTLS_INCLUDE=$(shell cygpath -w $(AXTLS_HOME)) +CFLAGS+=/nologo /W3 /D"WIN32" /D"_MBCS" /D"_CONSOLE" /D"_CRT_SECURE_NO_DEPRECATE" /FD /I"$(AXTLS_INCLUDE)crypto" /I"$(AXTLS_INCLUDE)ssl" /I"$(AXTLS_INCLUDE)config" /c +LDFLAGS=/nologo /subsystem:console /machine:I386 +LDSHARED = /dll +AR=lib /nologo + +ifdef CONFIG_DEBUG + CFLAGS += /Gm /Zi /Od /D "_DEBUG" + LDFLAGS += /debug /incremental:yes +else + CFLAGS += /O2 /D "NDEBUG" + LDFLAGS += /incremental:no +endif + +else # Not Win32 + +-include .depend + +CFLAGS += -I$(AXTLS_HOME)/config -I$(AXTLS_HOME)/ssl -I$(AXTLS_HOME)/crypto +LD=$(CC) +STRIP=$(CROSS)strip + +# Solaris +ifdef CONFIG_PLATFORM_SOLARIS +CFLAGS += -DCONFIG_PLATFORM_SOLARIS +LDFLAGS += -lsocket -lnsl -lc +LDSHARED = -G +# Linux/Cygwin +else +CFLAGS += -Wall -Wstrict-prototypes -Wshadow +LDSHARED = -shared + +# Linux +ifndef CONFIG_PLATFORM_CYGWIN +ifndef CONFIG_PLATFORM_NOMMU +CFLAGS += -fPIC + +# Cygwin +else +CFLAGS += -DCONFIG_PLATFORM_CYGWIN +LDFLAGS += -enable-auto-import +endif +endif +endif + +ifdef CONFIG_DEBUG +CFLAGS += -g +else +LDFLAGS += -s +ifdef CONFIG_PLATFORM_SOLARIS +CFLAGS += -O +else +CFLAGS += -O3 +endif + +endif # CONFIG_DEBUG +endif # WIN32 + +CFLAGS+=$(subst ",, $(strip $(CONFIG_EXTRA_CFLAGS_OPTIONS))) +LDFLAGS+=$(subst ",, $(strip $(CONFIG_EXTRA_LDFLAGS_OPTIONS))) + +endif # not 'clean' + +clean:: + -@rm -f *.o *.obj core* *.out *~ \.depend vc*0* + diff --git a/tools/sdk/axtls/crypto/aes.c b/tools/sdk/axtls/crypto/aes.c new file mode 100644 index 0000000000..af6bd98b7a --- /dev/null +++ b/tools/sdk/axtls/crypto/aes.c @@ -0,0 +1,452 @@ +/* + * Copyright (c) 2007-2016, 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. + */ + +/** + * AES implementation - this is a small code version. There are much faster + * versions around but they are much larger in size (i.e. they use large + * submix tables). + */ + +#include +#include "os_port.h" +#include "crypto.h" + +#define rot1(x) (((x) << 24) | ((x) >> 8)) +#define rot2(x) (((x) << 16) | ((x) >> 16)) +#define rot3(x) (((x) << 8) | ((x) >> 24)) + +/* + * This cute trick does 4 'mul by two' at once. Stolen from + * Dr B. R. Gladman but I'm sure the u-(u>>7) is + * a standard graphics trick + * The key to this is that we need to xor with 0x1b if the top bit is set. + * a 1xxx xxxx 0xxx 0xxx First we mask the 7bit, + * b 1000 0000 0000 0000 then we shift right by 7 putting the 7bit in 0bit, + * c 0000 0001 0000 0000 we then subtract (c) from (b) + * d 0111 1111 0000 0000 and now we and with our mask + * e 0001 1011 0000 0000 + */ +#define mt 0x80808080 +#define ml 0x7f7f7f7f +#define mh 0xfefefefe +#define mm 0x1b1b1b1b +#define mul2(x,t) ((t)=((x)&mt), \ + ((((x)+(x))&mh)^(((t)-((t)>>7))&mm))) + +#define inv_mix_col(x,f2,f4,f8,f9) (\ + (f2)=mul2(x,f2), \ + (f4)=mul2(f2,f4), \ + (f8)=mul2(f4,f8), \ + (f9)=(x)^(f8), \ + (f8)=((f2)^(f4)^(f8)), \ + (f2)^=(f9), \ + (f4)^=(f9), \ + (f8)^=rot3(f2), \ + (f8)^=rot2(f4), \ + (f8)^rot1(f9)) + +/* + * AES S-box + */ +static const uint8_t aes_sbox[256] PROGMEM = +{ + 0x63,0x7C,0x77,0x7B,0xF2,0x6B,0x6F,0xC5, + 0x30,0x01,0x67,0x2B,0xFE,0xD7,0xAB,0x76, + 0xCA,0x82,0xC9,0x7D,0xFA,0x59,0x47,0xF0, + 0xAD,0xD4,0xA2,0xAF,0x9C,0xA4,0x72,0xC0, + 0xB7,0xFD,0x93,0x26,0x36,0x3F,0xF7,0xCC, + 0x34,0xA5,0xE5,0xF1,0x71,0xD8,0x31,0x15, + 0x04,0xC7,0x23,0xC3,0x18,0x96,0x05,0x9A, + 0x07,0x12,0x80,0xE2,0xEB,0x27,0xB2,0x75, + 0x09,0x83,0x2C,0x1A,0x1B,0x6E,0x5A,0xA0, + 0x52,0x3B,0xD6,0xB3,0x29,0xE3,0x2F,0x84, + 0x53,0xD1,0x00,0xED,0x20,0xFC,0xB1,0x5B, + 0x6A,0xCB,0xBE,0x39,0x4A,0x4C,0x58,0xCF, + 0xD0,0xEF,0xAA,0xFB,0x43,0x4D,0x33,0x85, + 0x45,0xF9,0x02,0x7F,0x50,0x3C,0x9F,0xA8, + 0x51,0xA3,0x40,0x8F,0x92,0x9D,0x38,0xF5, + 0xBC,0xB6,0xDA,0x21,0x10,0xFF,0xF3,0xD2, + 0xCD,0x0C,0x13,0xEC,0x5F,0x97,0x44,0x17, + 0xC4,0xA7,0x7E,0x3D,0x64,0x5D,0x19,0x73, + 0x60,0x81,0x4F,0xDC,0x22,0x2A,0x90,0x88, + 0x46,0xEE,0xB8,0x14,0xDE,0x5E,0x0B,0xDB, + 0xE0,0x32,0x3A,0x0A,0x49,0x06,0x24,0x5C, + 0xC2,0xD3,0xAC,0x62,0x91,0x95,0xE4,0x79, + 0xE7,0xC8,0x37,0x6D,0x8D,0xD5,0x4E,0xA9, + 0x6C,0x56,0xF4,0xEA,0x65,0x7A,0xAE,0x08, + 0xBA,0x78,0x25,0x2E,0x1C,0xA6,0xB4,0xC6, + 0xE8,0xDD,0x74,0x1F,0x4B,0xBD,0x8B,0x8A, + 0x70,0x3E,0xB5,0x66,0x48,0x03,0xF6,0x0E, + 0x61,0x35,0x57,0xB9,0x86,0xC1,0x1D,0x9E, + 0xE1,0xF8,0x98,0x11,0x69,0xD9,0x8E,0x94, + 0x9B,0x1E,0x87,0xE9,0xCE,0x55,0x28,0xDF, + 0x8C,0xA1,0x89,0x0D,0xBF,0xE6,0x42,0x68, + 0x41,0x99,0x2D,0x0F,0xB0,0x54,0xBB,0x16, +}; + +/* + * AES is-box + */ +static const uint8_t aes_isbox[256] PROGMEM = +{ + 0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38, + 0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb, + 0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87, + 0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb, + 0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d, + 0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e, + 0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2, + 0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25, + 0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16, + 0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92, + 0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda, + 0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84, + 0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a, + 0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06, + 0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02, + 0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b, + 0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea, + 0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73, + 0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85, + 0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e, + 0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89, + 0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b, + 0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20, + 0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4, + 0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31, + 0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f, + 0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d, + 0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef, + 0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0, + 0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61, + 0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26, + 0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d +}; + +static const unsigned char Rcon[30]= +{ + 0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80, + 0x1b,0x36,0x6c,0xd8,0xab,0x4d,0x9a,0x2f, + 0x5e,0xbc,0x63,0xc6,0x97,0x35,0x6a,0xd4, + 0xb3,0x7d,0xfa,0xef,0xc5,0x91, +}; + +/* ----- static functions ----- */ +static void AES_encrypt(const AES_CTX *ctx, uint32_t *data); +static void AES_decrypt(const AES_CTX *ctx, uint32_t *data); + +/* Perform doubling in Galois Field GF(2^8) using the irreducible polynomial + x^8+x^4+x^3+x+1 */ +static unsigned char AES_xtime(uint32_t x) +{ + return (x&0x80) ? (x<<1)^0x1b : x<<1; +} + +/** + * Set up AES with the key/iv and cipher size. + */ +void AES_set_key(AES_CTX *ctx, const uint8_t *key, + const uint8_t *iv, AES_MODE mode) +{ + int i, ii; + uint32_t *W, tmp, tmp2; + const unsigned char *ip; + int words; + + switch (mode) + { + case AES_MODE_128: + i = 10; + words = 4; + break; + + case AES_MODE_256: + i = 14; + words = 8; + break; + + default: /* fail silently */ + return; + } + + ctx->rounds = i; + ctx->key_size = words; + W = ctx->ks; + for (i = 0; i < words; i+=2) + { + W[i+0]= ((uint32_t)key[ 0]<<24)| + ((uint32_t)key[ 1]<<16)| + ((uint32_t)key[ 2]<< 8)| + ((uint32_t)key[ 3] ); + W[i+1]= ((uint32_t)key[ 4]<<24)| + ((uint32_t)key[ 5]<<16)| + ((uint32_t)key[ 6]<< 8)| + ((uint32_t)key[ 7] ); + key += 8; + } + + ip = Rcon; + ii = 4 * (ctx->rounds+1); + for (i = words; i> 8)&0xff))<<16; + tmp2|=(uint32_t)(ax_array_read_u8(aes_sbox, (tmp>>16)&0xff))<<24; + tmp2|=(uint32_t)(ax_array_read_u8(aes_sbox, (tmp>>24))); + tmp=tmp2^(((unsigned int)*ip)<<24); + ip++; + } + + if ((words == 8) && ((i % words) == 4)) + { + tmp2 =(uint32_t)(ax_array_read_u8(aes_sbox, (tmp )&0xff)) ; + tmp2|=(uint32_t)(ax_array_read_u8(aes_sbox, (tmp>> 8)&0xff))<< 8; + tmp2|=(uint32_t)(ax_array_read_u8(aes_sbox, (tmp>>16)&0xff))<<16; + tmp2|=(uint32_t)(ax_array_read_u8(aes_sbox, (tmp>>24) ))<<24; + tmp=tmp2; + } + + W[i]=W[i-words]^tmp; + } + + /* copy the iv across */ + memcpy(ctx->iv, iv, 16); +} + +/** + * Change a key for decryption. + */ +void AES_convert_key(AES_CTX *ctx) +{ + int i; + uint32_t *k,w,t1,t2,t3,t4; + + k = ctx->ks; + k += 4; + + for (i= ctx->rounds*4; i > 4; i--) + { + w= *k; + w = inv_mix_col(w,t1,t2,t3,t4); + *k++ =w; + } +} + +/** + * Encrypt a byte sequence (with a block size 16) using the AES cipher. + */ +void AES_cbc_encrypt(AES_CTX *ctx, const uint8_t *msg, uint8_t *out, int length) +{ + int i; + uint32_t tin[4], tout[4], iv[4]; + + memcpy(iv, ctx->iv, AES_IV_SIZE); + for (i = 0; i < 4; i++) + tout[i] = ntohl(iv[i]); + + for (length -= AES_BLOCKSIZE; length >= 0; length -= AES_BLOCKSIZE) + { + uint32_t msg_32[4]; + uint32_t out_32[4]; + memcpy(msg_32, msg, AES_BLOCKSIZE); + msg += AES_BLOCKSIZE; + + for (i = 0; i < 4; i++) + tin[i] = ntohl(msg_32[i])^tout[i]; + + AES_encrypt(ctx, tin); + + for (i = 0; i < 4; i++) + { + tout[i] = tin[i]; + out_32[i] = htonl(tout[i]); + } + + memcpy(out, out_32, AES_BLOCKSIZE); + out += AES_BLOCKSIZE; + } + + for (i = 0; i < 4; i++) + iv[i] = htonl(tout[i]); + memcpy(ctx->iv, iv, AES_IV_SIZE); +} + +/** + * Decrypt a byte sequence (with a block size 16) using the AES cipher. + */ +void AES_cbc_decrypt(AES_CTX *ctx, const uint8_t *msg, uint8_t *out, int length) +{ + int i; + uint32_t tin[4], xor[4], tout[4], data[4], iv[4]; + + memcpy(iv, ctx->iv, AES_IV_SIZE); + for (i = 0; i < 4; i++) + xor[i] = ntohl(iv[i]); + + for (length -= 16; length >= 0; length -= 16) + { + uint32_t msg_32[4]; + uint32_t out_32[4]; + memcpy(msg_32, msg, AES_BLOCKSIZE); + msg += AES_BLOCKSIZE; + + for (i = 0; i < 4; i++) + { + tin[i] = ntohl(msg_32[i]); + data[i] = tin[i]; + } + + AES_decrypt(ctx, data); + + for (i = 0; i < 4; i++) + { + tout[i] = data[i]^xor[i]; + xor[i] = tin[i]; + out_32[i] = htonl(tout[i]); + } + + memcpy(out, out_32, AES_BLOCKSIZE); + out += AES_BLOCKSIZE; + } + + for (i = 0; i < 4; i++) + iv[i] = htonl(xor[i]); + memcpy(ctx->iv, iv, AES_IV_SIZE); +} + +/** + * Encrypt a single block (16 bytes) of data + */ +static void AES_encrypt(const AES_CTX *ctx, uint32_t *data) +{ + /* To make this code smaller, generate the sbox entries on the fly. + * This will have a really heavy effect upon performance. + */ + uint32_t tmp[4]; + uint32_t tmp1, old_a0, a0, a1, a2, a3, row; + int curr_rnd; + int rounds = ctx->rounds; + const uint32_t *k = ctx->ks; + + /* Pre-round key addition */ + for (row = 0; row < 4; row++) + data[row] ^= *(k++); + + /* Encrypt one block. */ + for (curr_rnd = 0; curr_rnd < rounds; curr_rnd++) + { + /* Perform ByteSub and ShiftRow operations together */ + for (row = 0; row < 4; row++) + { + a0 = (uint32_t)(ax_array_read_u8(aes_sbox, (data[row%4]>>24)&0xFF)); + a1 = (uint32_t)(ax_array_read_u8(aes_sbox, (data[(row+1)%4]>>16)&0xFF)); + a2 = (uint32_t)(ax_array_read_u8(aes_sbox, (data[(row+2)%4]>>8)&0xFF)); + a3 = (uint32_t)(ax_array_read_u8(aes_sbox, (data[(row+3)%4])&0xFF)); + + /* Perform MixColumn iff not last round */ + if (curr_rnd < (rounds - 1)) + { + tmp1 = a0 ^ a1 ^ a2 ^ a3; + old_a0 = a0; + a0 ^= tmp1 ^ AES_xtime(a0 ^ a1); + a1 ^= tmp1 ^ AES_xtime(a1 ^ a2); + a2 ^= tmp1 ^ AES_xtime(a2 ^ a3); + a3 ^= tmp1 ^ AES_xtime(a3 ^ old_a0); + } + + tmp[row] = ((a0 << 24) | (a1 << 16) | (a2 << 8) | a3); + } + + /* KeyAddition - note that it is vital that this loop is separate from + the MixColumn operation, which must be atomic...*/ + for (row = 0; row < 4; row++) + data[row] = tmp[row] ^ *(k++); + } +} + +/** + * Decrypt a single block (16 bytes) of data + */ +static void AES_decrypt(const AES_CTX *ctx, uint32_t *data) +{ + uint32_t tmp[4]; + uint32_t xt0,xt1,xt2,xt3,xt4,xt5,xt6; + uint32_t a0, a1, a2, a3, row; + int curr_rnd; + int rounds = ctx->rounds; + const uint32_t *k = ctx->ks + ((rounds+1)*4); + + /* pre-round key addition */ + for (row=4; row > 0;row--) + data[row-1] ^= *(--k); + + /* Decrypt one block */ + for (curr_rnd = 0; curr_rnd < rounds; curr_rnd++) + { + /* Perform ByteSub and ShiftRow operations together */ + for (row = 4; row > 0; row--) + { + a0 = ax_array_read_u8(aes_isbox, (data[(row+3)%4]>>24)&0xFF); + a1 = ax_array_read_u8(aes_isbox, (data[(row+2)%4]>>16)&0xFF); + a2 = ax_array_read_u8(aes_isbox, (data[(row+1)%4]>>8)&0xFF); + a3 = ax_array_read_u8(aes_isbox, (data[row%4])&0xFF); + + /* Perform MixColumn iff not last round */ + if (curr_rnd<(rounds-1)) + { + /* The MDS cofefficients (0x09, 0x0B, 0x0D, 0x0E) + are quite large compared to encryption; this + operation slows decryption down noticeably. */ + xt0 = AES_xtime(a0^a1); + xt1 = AES_xtime(a1^a2); + xt2 = AES_xtime(a2^a3); + xt3 = AES_xtime(a3^a0); + xt4 = AES_xtime(xt0^xt1); + xt5 = AES_xtime(xt1^xt2); + xt6 = AES_xtime(xt4^xt5); + + xt0 ^= a1^a2^a3^xt4^xt6; + xt1 ^= a0^a2^a3^xt5^xt6; + xt2 ^= a0^a1^a3^xt4^xt6; + xt3 ^= a0^a1^a2^xt5^xt6; + tmp[row-1] = ((xt0<<24)|(xt1<<16)|(xt2<<8)|xt3); + } + else + tmp[row-1] = ((a0<<24)|(a1<<16)|(a2<<8)|a3); + } + + for (row = 4; row > 0; row--) + data[row-1] = tmp[row-1] ^ *(--k); + } +} diff --git a/tools/sdk/axtls/crypto/bigint.c b/tools/sdk/axtls/crypto/bigint.c new file mode 100644 index 0000000000..d90b093822 --- /dev/null +++ b/tools/sdk/axtls/crypto/bigint.c @@ -0,0 +1,1514 @@ +/* + * 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. + */ + +/** + * @defgroup bigint_api Big Integer API + * @brief The bigint implementation as used by the axTLS project. + * + * The bigint library is for RSA encryption/decryption as well as signing. + * This code tries to minimise use of malloc/free by maintaining a small + * cache. A bigint context may maintain state by being made "permanent". + * It be be later released with a bi_depermanent() and bi_free() call. + * + * It supports the following reduction techniques: + * - Classical + * - Barrett + * - Montgomery + * + * It also implements the following: + * - Karatsuba multiplication + * - Squaring + * - Sliding window exponentiation + * - Chinese Remainder Theorem (implemented in rsa.c). + * + * All the algorithms used are pretty standard, and designed for different + * data bus sizes. Negative numbers are not dealt with at all, so a subtraction + * may need to be tested for negativity. + * + * This library steals some ideas from Jef Poskanzer + * + * and GMP . It gets most of its implementation + * detail from "The Handbook of Applied Cryptography" + * + * @{ + */ + +#include +#include +#include +#include +#include +#include "os_port.h" +#include "bigint.h" + +#define V1 v->comps[v->size-1] /**< v1 for division */ +#define V2 v->comps[v->size-2] /**< v2 for division */ +#define U(j) tmp_u->comps[tmp_u->size-j-1] /**< uj for division */ +#define Q(j) quotient->comps[quotient->size-j-1] /**< qj for division */ + +static bigint *bi_int_multiply(BI_CTX *ctx, bigint *bi, comp i); +static bigint *bi_int_divide(BI_CTX *ctx, bigint *biR, comp denom); +static bigint *alloc(BI_CTX *ctx, int size); +static bigint *trim(bigint *bi); +static void more_comps(bigint *bi, int n); +#if defined(CONFIG_BIGINT_KARATSUBA) || defined(CONFIG_BIGINT_BARRETT) || \ + defined(CONFIG_BIGINT_MONTGOMERY) +static bigint *comp_right_shift(bigint *biR, int num_shifts); +static bigint *comp_left_shift(bigint *biR, int num_shifts); +#endif + +#ifdef CONFIG_BIGINT_CHECK_ON +static void check(const bigint *bi); +#else +#define check(A) /**< disappears in normal production mode */ +#endif + + +/** + * @brief Start a new bigint context. + * @return A bigint context. + */ +BI_CTX *bi_initialize(void) +{ + /* calloc() sets everything to zero */ + BI_CTX *ctx = (BI_CTX *)calloc(1, sizeof(BI_CTX)); + + /* the radix */ + ctx->bi_radix = alloc(ctx, 2); + ctx->bi_radix->comps[0] = 0; + ctx->bi_radix->comps[1] = 1; + bi_permanent(ctx->bi_radix); + return ctx; +} + +/** + * @brief Close the bigint context and free any resources. + * + * Free up any used memory - a check is done if all objects were not + * properly freed. + * @param ctx [in] The bigint session context. + */ +void bi_terminate(BI_CTX *ctx) +{ + bi_depermanent(ctx->bi_radix); + bi_free(ctx, ctx->bi_radix); + + if (ctx->active_count != 0) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("bi_terminate: there were %d un-freed bigints\n", + ctx->active_count); +#endif + abort(); + } + + bi_clear_cache(ctx); + free(ctx); +} + +/** + *@brief Clear the memory cache. + */ +void bi_clear_cache(BI_CTX *ctx) +{ + bigint *p, *pn; + + if (ctx->free_list == NULL) + return; + + for (p = ctx->free_list; p != NULL; p = pn) + { + pn = p->next; + free(p->comps); + free(p); + } + + ctx->free_count = 0; + ctx->free_list = NULL; +} + +/** + * @brief Increment the number of references to this object. + * It does not do a full copy. + * @param bi [in] The bigint to copy. + * @return A reference to the same bigint. + */ +bigint *bi_copy(bigint *bi) +{ + check(bi); + if (bi->refs != PERMANENT) + bi->refs++; + return bi; +} + +/** + * @brief Simply make a bigint object "unfreeable" if bi_free() is called on it. + * + * For this object to be freed, bi_depermanent() must be called. + * @param bi [in] The bigint to be made permanent. + */ +void bi_permanent(bigint *bi) +{ + check(bi); + if (bi->refs != 1) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("bi_permanent: refs was not 1\n"); +#endif + abort(); + } + + bi->refs = PERMANENT; +} + +/** + * @brief Take a permanent object and make it eligible for freedom. + * @param bi [in] The bigint to be made back to temporary. + */ +void bi_depermanent(bigint *bi) +{ + check(bi); + if (bi->refs != PERMANENT) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("bi_depermanent: bigint was not permanent\n"); +#endif + abort(); + } + + bi->refs = 1; +} + +/** + * @brief Free a bigint object so it can be used again. + * + * The memory itself it not actually freed, just tagged as being available + * @param ctx [in] The bigint session context. + * @param bi [in] The bigint to be freed. + */ +void bi_free(BI_CTX *ctx, bigint *bi) +{ + check(bi); + if (bi->refs == PERMANENT) + { + return; + } + + if (--bi->refs > 0) + { + return; + } + + bi->next = ctx->free_list; + ctx->free_list = bi; + ctx->free_count++; + + if (--ctx->active_count < 0) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("bi_free: active_count went negative " + "- double-freed bigint?\n"); +#endif + abort(); + } +} + +/** + * @brief Convert an (unsigned) integer into a bigint. + * @param ctx [in] The bigint session context. + * @param i [in] The (unsigned) integer to be converted. + * + */ +bigint *int_to_bi(BI_CTX *ctx, comp i) +{ + bigint *biR = alloc(ctx, 1); + biR->comps[0] = i; + return biR; +} + +/** + * @brief Do a full copy of the bigint object. + * @param ctx [in] The bigint session context. + * @param bi [in] The bigint object to be copied. + */ +bigint *bi_clone(BI_CTX *ctx, const bigint *bi) +{ + bigint *biR = alloc(ctx, bi->size); + check(bi); + memcpy(biR->comps, bi->comps, bi->size*COMP_BYTE_SIZE); + return biR; +} + +/** + * @brief Perform an addition operation between two bigints. + * @param ctx [in] The bigint session context. + * @param bia [in] A bigint. + * @param bib [in] Another bigint. + * @return The result of the addition. + */ +bigint *bi_add(BI_CTX *ctx, bigint *bia, bigint *bib) +{ + int n; + comp carry = 0; + comp *pa, *pb; + + check(bia); + check(bib); + + n = axtls_max(bia->size, bib->size); + more_comps(bia, n+1); + more_comps(bib, n); + pa = bia->comps; + pb = bib->comps; + + do + { + comp sl, rl, cy1; + sl = *pa + *pb++; + rl = sl + carry; + cy1 = sl < *pa; + carry = cy1 | (rl < sl); + *pa++ = rl; + } while (--n != 0); + + *pa = carry; /* do overflow */ + bi_free(ctx, bib); + return trim(bia); +} + +/** + * @brief Perform a subtraction operation between two bigints. + * @param ctx [in] The bigint session context. + * @param bia [in] A bigint. + * @param bib [in] Another bigint. + * @param is_negative [out] If defined, indicates that the result was negative. + * is_negative may be null. + * @return The result of the subtraction. The result is always positive. + */ +bigint *bi_subtract(BI_CTX *ctx, + bigint *bia, bigint *bib, int *is_negative) +{ + int n = bia->size; + comp *pa, *pb, carry = 0; + + check(bia); + check(bib); + + more_comps(bib, n); + pa = bia->comps; + pb = bib->comps; + + do + { + comp sl, rl, cy1; + sl = *pa - *pb++; + rl = sl - carry; + cy1 = sl > *pa; + carry = cy1 | (rl > sl); + *pa++ = rl; + } while (--n != 0); + + if (is_negative) /* indicate a negative result */ + { + *is_negative = carry; + } + + bi_free(ctx, trim(bib)); /* put bib back to the way it was */ + return trim(bia); +} + +/** + * Perform a multiply between a bigint an an (unsigned) integer + */ +static bigint *bi_int_multiply(BI_CTX *ctx, bigint *bia, comp b) +{ + int j = 0, n = bia->size; + bigint *biR = alloc(ctx, n + 1); + comp carry = 0; + comp *r = biR->comps; + comp *a = bia->comps; + + check(bia); + + /* clear things to start with */ + memset(r, 0, ((n+1)*COMP_BYTE_SIZE)); + + do + { + long_comp tmp = *r + (long_comp)a[j]*b + carry; + *r++ = (comp)tmp; /* downsize */ + carry = (comp)(tmp >> COMP_BIT_SIZE); + } while (++j < n); + + *r = carry; + bi_free(ctx, bia); + return trim(biR); +} + +/** + * @brief Does both division and modulo calculations. + * + * Used extensively when doing classical reduction. + * @param ctx [in] The bigint session context. + * @param u [in] A bigint which is the numerator. + * @param v [in] Either the denominator or the modulus depending on the mode. + * @param is_mod [n] Determines if this is a normal division (0) or a reduction + * (1). + * @return The result of the division/reduction. + */ +bigint *bi_divide(BI_CTX *ctx, bigint *u, bigint *v, int is_mod) +{ + int n = v->size, m = u->size-n; + int j = 0, orig_u_size = u->size; + uint8_t mod_offset = ctx->mod_offset; + comp d; + bigint *quotient, *tmp_u; + comp q_dash; + + check(u); + check(v); + + /* if doing reduction and we are < mod, then return mod */ + if (is_mod && bi_compare(v, u) > 0) + { + bi_free(ctx, v); + return u; + } + + quotient = alloc(ctx, m+1); + tmp_u = alloc(ctx, n+1); + v = trim(v); /* make sure we have no leading 0's */ + d = (comp)((long_comp)COMP_RADIX/(V1+1)); + + /* clear things to start with */ + memset(quotient->comps, 0, ((quotient->size)*COMP_BYTE_SIZE)); + + /* normalise */ + if (d > 1) + { + u = bi_int_multiply(ctx, u, d); + + if (is_mod) + { + v = ctx->bi_normalised_mod[mod_offset]; + } + else + { + v = bi_int_multiply(ctx, v, d); + } + } + + if (orig_u_size == u->size) /* new digit position u0 */ + { + more_comps(u, orig_u_size + 1); + } + + do + { + /* get a temporary short version of u */ + memcpy(tmp_u->comps, &u->comps[u->size-n-1-j], (n+1)*COMP_BYTE_SIZE); + + /* calculate q' */ + if (U(0) == V1) + { + q_dash = COMP_RADIX-1; + } + else + { + q_dash = (comp)(((long_comp)U(0)*COMP_RADIX + U(1))/V1); + + if (v->size > 1 && V2) + { + /* we are implementing the following: + if (V2*q_dash > (((U(0)*COMP_RADIX + U(1) - + q_dash*V1)*COMP_RADIX) + U(2))) ... */ + comp inner = (comp)((long_comp)COMP_RADIX*U(0) + U(1) - + (long_comp)q_dash*V1); + if ((long_comp)V2*q_dash > (long_comp)inner*COMP_RADIX + U(2)) + { + q_dash--; + } + } + } + + /* multiply and subtract */ + if (q_dash) + { + int is_negative; + tmp_u = bi_subtract(ctx, tmp_u, + bi_int_multiply(ctx, bi_copy(v), q_dash), &is_negative); + more_comps(tmp_u, n+1); + + Q(j) = q_dash; + + /* add back */ + if (is_negative) + { + Q(j)--; + tmp_u = bi_add(ctx, tmp_u, bi_copy(v)); + + /* lop off the carry */ + tmp_u->size--; + v->size--; + } + } + else + { + Q(j) = 0; + } + + /* copy back to u */ + memcpy(&u->comps[u->size-n-1-j], tmp_u->comps, (n+1)*COMP_BYTE_SIZE); + } while (++j <= m); + + bi_free(ctx, tmp_u); + bi_free(ctx, v); + + if (is_mod) /* get the remainder */ + { + bi_free(ctx, quotient); + return bi_int_divide(ctx, trim(u), d); + } + else /* get the quotient */ + { + bi_free(ctx, u); + return trim(quotient); + } +} + +/* + * Perform an integer divide on a bigint. + */ +static bigint *bi_int_divide(BI_CTX *ctx, bigint *biR, comp denom) +{ + int i = biR->size - 1; + long_comp r = 0; + + check(biR); + + do + { + r = (r<comps[i]; + biR->comps[i] = (comp)(r / denom); + r %= denom; + } while (--i >= 0); + + return trim(biR); +} + +#ifdef CONFIG_BIGINT_MONTGOMERY +/** + * There is a need for the value of integer N' such that B^-1(B-1)-N^-1N'=1, + * where B^-1(B-1) mod N=1. Actually, only the least significant part of + * N' is needed, hence the definition N0'=N' mod b. We reproduce below the + * simple algorithm from an article by Dusse and Kaliski to efficiently + * find N0' from N0 and b */ +static comp modular_inverse(bigint *bim) +{ + int i; + comp t = 1; + comp two_2_i_minus_1 = 2; /* 2^(i-1) */ + long_comp two_2_i = 4; /* 2^i */ + comp N = bim->comps[0]; + + for (i = 2; i <= COMP_BIT_SIZE; i++) + { + if ((long_comp)N*t%two_2_i >= two_2_i_minus_1) + { + t += two_2_i_minus_1; + } + + two_2_i_minus_1 <<= 1; + two_2_i <<= 1; + } + + return (comp)(COMP_RADIX-t); +} +#endif + +#if defined(CONFIG_BIGINT_KARATSUBA) || defined(CONFIG_BIGINT_BARRETT) || \ + defined(CONFIG_BIGINT_MONTGOMERY) +/** + * Take each component and shift down (in terms of components) + */ +static bigint *comp_right_shift(bigint *biR, int num_shifts) +{ + int i = biR->size-num_shifts; + comp *x = biR->comps; + comp *y = &biR->comps[num_shifts]; + + check(biR); + + if (i <= 0) /* have we completely right shifted? */ + { + biR->comps[0] = 0; /* return 0 */ + biR->size = 1; + return biR; + } + + do + { + *x++ = *y++; + } while (--i > 0); + + biR->size -= num_shifts; + return biR; +} + +/** + * Take each component and shift it up (in terms of components) + */ +static bigint *comp_left_shift(bigint *biR, int num_shifts) +{ + int i = biR->size-1; + comp *x, *y; + + check(biR); + + if (num_shifts <= 0) + { + return biR; + } + + more_comps(biR, biR->size + num_shifts); + + x = &biR->comps[i+num_shifts]; + y = &biR->comps[i]; + + do + { + *x-- = *y--; + } while (i--); + + memset(biR->comps, 0, num_shifts*COMP_BYTE_SIZE); /* zero LS comps */ + return biR; +} +#endif + +/** + * @brief Allow a binary sequence to be imported as a bigint. + * @param ctx [in] The bigint session context. + * @param data [in] The data to be converted. + * @param size [in] The number of bytes of data. + * @return A bigint representing this data. + */ +bigint *bi_import(BI_CTX *ctx, const uint8_t *data, int size) +{ + bigint *biR = alloc(ctx, (size+COMP_BYTE_SIZE-1)/COMP_BYTE_SIZE); + int i, j = 0, offset = 0; + + memset(biR->comps, 0, biR->size*COMP_BYTE_SIZE); + + for (i = size-1; i >= 0; i--) + { + biR->comps[offset] += data[i] << (j*8); + + if (++j == COMP_BYTE_SIZE) + { + j = 0; + offset ++; + } + } + + return trim(biR); +} + +#ifdef CONFIG_SSL_FULL_MODE +/** + * @brief The testharness uses this code to import text hex-streams and + * convert them into bigints. + * @param ctx [in] The bigint session context. + * @param data [in] A string consisting of hex characters. The characters must + * be in upper case. + * @return A bigint representing this data. + */ +bigint *bi_str_import(BI_CTX *ctx, const char *data) +{ + int size = strlen(data); + bigint *biR = alloc(ctx, (size+COMP_NUM_NIBBLES-1)/COMP_NUM_NIBBLES); + int i, j = 0, offset = 0; + memset(biR->comps, 0, biR->size*COMP_BYTE_SIZE); + + for (i = size-1; i >= 0; i--) + { + int num = (data[i] <= '9') ? (data[i] - '0') : (data[i] - 'A' + 10); + biR->comps[offset] += num << (j*4); + + if (++j == COMP_NUM_NIBBLES) + { + j = 0; + offset ++; + } + } + + return biR; +} + +void bi_print(const char *label, bigint *x) +{ + int i, j; + + if (x == NULL) + { + printf("%s: (null)\n", label); + return; + } + + printf("%s: (size %d)\n", label, x->size); + for (i = x->size-1; i >= 0; i--) + { + for (j = COMP_NUM_NIBBLES-1; j >= 0; j--) + { + comp mask = 0x0f << (j*4); + comp num = (x->comps[i] & mask) >> (j*4); + putc((num <= 9) ? (num + '0') : (num + 'A' - 10), stdout); + } + } + + printf("\n"); +} +#endif + +/** + * @brief Take a bigint and convert it into a byte sequence. + * + * This is useful after a decrypt operation. + * @param ctx [in] The bigint session context. + * @param x [in] The bigint to be converted. + * @param data [out] The converted data as a byte stream. + * @param size [in] The maximum size of the byte stream. Unused bytes will be + * zeroed. + */ +void bi_export(BI_CTX *ctx, bigint *x, uint8_t *data, int size) +{ + int i, j, k = size-1; + + check(x); + memset(data, 0, size); /* ensure all leading 0's are cleared */ + + for (i = 0; i < x->size; i++) + { + for (j = 0; j < COMP_BYTE_SIZE; j++) + { + comp mask = 0xff << (j*8); + int num = (x->comps[i] & mask) >> (j*8); + data[k--] = num; + + if (k < 0) + { + goto buf_done; + } + } + } +buf_done: + + bi_free(ctx, x); +} + +/** + * @brief Pre-calculate some of the expensive steps in reduction. + * + * This function should only be called once (normally when a session starts). + * When the session is over, bi_free_mod() should be called. bi_mod_power() + * relies on this function being called. + * @param ctx [in] The bigint session context. + * @param bim [in] The bigint modulus that will be used. + * @param mod_offset [in] There are three moduluii that can be stored - the + * standard modulus, and its two primes p and q. This offset refers to which + * modulus we are referring to. + * @see bi_free_mod(), bi_mod_power(). + */ +void bi_set_mod(BI_CTX *ctx, bigint *bim, int mod_offset) +{ + int k = bim->size; + comp d = (comp)((long_comp)COMP_RADIX/(bim->comps[k-1]+1)); +#ifdef CONFIG_BIGINT_MONTGOMERY + bigint *R, *R2; +#endif + + ctx->bi_mod[mod_offset] = bim; + bi_permanent(ctx->bi_mod[mod_offset]); + ctx->bi_normalised_mod[mod_offset] = bi_int_multiply(ctx, bim, d); + bi_permanent(ctx->bi_normalised_mod[mod_offset]); + +#if defined(CONFIG_BIGINT_MONTGOMERY) + /* set montgomery variables */ + R = comp_left_shift(bi_clone(ctx, ctx->bi_radix), k-1); /* R */ + R2 = comp_left_shift(bi_clone(ctx, ctx->bi_radix), k*2-1); /* R^2 */ + ctx->bi_RR_mod_m[mod_offset] = bi_mod(ctx, R2); /* R^2 mod m */ + ctx->bi_R_mod_m[mod_offset] = bi_mod(ctx, R); /* R mod m */ + + bi_permanent(ctx->bi_RR_mod_m[mod_offset]); + bi_permanent(ctx->bi_R_mod_m[mod_offset]); + + ctx->N0_dash[mod_offset] = modular_inverse(ctx->bi_mod[mod_offset]); + +#elif defined (CONFIG_BIGINT_BARRETT) + ctx->bi_mu[mod_offset] = + bi_divide(ctx, comp_left_shift( + bi_clone(ctx, ctx->bi_radix), k*2-1), ctx->bi_mod[mod_offset], 0); + bi_permanent(ctx->bi_mu[mod_offset]); +#endif +} + +/** + * @brief Used when cleaning various bigints at the end of a session. + * @param ctx [in] The bigint session context. + * @param mod_offset [in] The offset to use. + * @see bi_set_mod(). + */ +void bi_free_mod(BI_CTX *ctx, int mod_offset) +{ + bi_depermanent(ctx->bi_mod[mod_offset]); + bi_free(ctx, ctx->bi_mod[mod_offset]); +#if defined (CONFIG_BIGINT_MONTGOMERY) + bi_depermanent(ctx->bi_RR_mod_m[mod_offset]); + bi_depermanent(ctx->bi_R_mod_m[mod_offset]); + bi_free(ctx, ctx->bi_RR_mod_m[mod_offset]); + bi_free(ctx, ctx->bi_R_mod_m[mod_offset]); +#elif defined(CONFIG_BIGINT_BARRETT) + bi_depermanent(ctx->bi_mu[mod_offset]); + bi_free(ctx, ctx->bi_mu[mod_offset]); +#endif + bi_depermanent(ctx->bi_normalised_mod[mod_offset]); + bi_free(ctx, ctx->bi_normalised_mod[mod_offset]); +} + +/** + * Perform a standard multiplication between two bigints. + * + * Barrett reduction has no need for some parts of the product, so ignore bits + * of the multiply. This routine gives Barrett its big performance + * improvements over Classical/Montgomery reduction methods. + */ +static bigint *regular_multiply(BI_CTX *ctx, bigint *bia, bigint *bib, + int inner_partial, int outer_partial) +{ + int i = 0, j; + int n = bia->size; + int t = bib->size; + bigint *biR = alloc(ctx, n + t); + comp *sr = biR->comps; + comp *sa = bia->comps; + comp *sb = bib->comps; + + check(bia); + check(bib); + + /* clear things to start with */ + memset(biR->comps, 0, ((n+t)*COMP_BYTE_SIZE)); + + do + { + long_comp tmp; + comp carry = 0; + int r_index = i; + j = 0; + + if (outer_partial && outer_partial-i > 0 && outer_partial < n) + { + r_index = outer_partial-1; + j = outer_partial-i-1; + } + + do + { + if (inner_partial && r_index >= inner_partial) + { + break; + } + + tmp = sr[r_index] + ((long_comp)sa[j])*sb[i] + carry; + sr[r_index++] = (comp)tmp; /* downsize */ + carry = tmp >> COMP_BIT_SIZE; + } while (++j < n); + + sr[r_index] = carry; + } while (++i < t); + + bi_free(ctx, bia); + bi_free(ctx, bib); + return trim(biR); +} + +#ifdef CONFIG_BIGINT_KARATSUBA +/* + * Karatsuba improves on regular multiplication due to only 3 multiplications + * being done instead of 4. The additional additions/subtractions are O(N) + * rather than O(N^2) and so for big numbers it saves on a few operations + */ +static bigint *karatsuba(BI_CTX *ctx, bigint *bia, bigint *bib, int is_square) +{ + bigint *x0, *x1; + bigint *p0, *p1, *p2; + int m; + + if (is_square) + { + m = (bia->size + 1)/2; + } + else + { + m = (axtls_max(bia->size, bib->size) + 1)/2; + } + + x0 = bi_clone(ctx, bia); + x0->size = m; + x1 = bi_clone(ctx, bia); + comp_right_shift(x1, m); + bi_free(ctx, bia); + + /* work out the 3 partial products */ + if (is_square) + { + p0 = bi_square(ctx, bi_copy(x0)); + p2 = bi_square(ctx, bi_copy(x1)); + p1 = bi_square(ctx, bi_add(ctx, x0, x1)); + } + else /* normal multiply */ + { + bigint *y0, *y1; + y0 = bi_clone(ctx, bib); + y0->size = m; + y1 = bi_clone(ctx, bib); + comp_right_shift(y1, m); + bi_free(ctx, bib); + + p0 = bi_multiply(ctx, bi_copy(x0), bi_copy(y0)); + p2 = bi_multiply(ctx, bi_copy(x1), bi_copy(y1)); + p1 = bi_multiply(ctx, bi_add(ctx, x0, x1), bi_add(ctx, y0, y1)); + } + + p1 = bi_subtract(ctx, + bi_subtract(ctx, p1, bi_copy(p2), NULL), bi_copy(p0), NULL); + + comp_left_shift(p1, m); + comp_left_shift(p2, 2*m); + return bi_add(ctx, p1, bi_add(ctx, p0, p2)); +} +#endif + +/** + * @brief Perform a multiplication operation between two bigints. + * @param ctx [in] The bigint session context. + * @param bia [in] A bigint. + * @param bib [in] Another bigint. + * @return The result of the multiplication. + */ +bigint *bi_multiply(BI_CTX *ctx, bigint *bia, bigint *bib) +{ + check(bia); + check(bib); + +#ifdef CONFIG_BIGINT_KARATSUBA + if (axtls_min(bia->size, bib->size) < MUL_KARATSUBA_THRESH) + { + return regular_multiply(ctx, bia, bib, 0, 0); + } + + return karatsuba(ctx, bia, bib, 0); +#else + return regular_multiply(ctx, bia, bib, 0, 0); +#endif +} + +#ifdef CONFIG_BIGINT_SQUARE +/* + * Perform the actual square operion. It takes into account overflow. + */ +static bigint *regular_square(BI_CTX *ctx, bigint *bi) +{ + int t = bi->size; + int i = 0, j; + bigint *biR = alloc(ctx, t*2+1); + comp *w = biR->comps; + comp *x = bi->comps; + long_comp carry; + memset(w, 0, biR->size*COMP_BYTE_SIZE); + + do + { + long_comp tmp = w[2*i] + (long_comp)x[i]*x[i]; + w[2*i] = (comp)tmp; + carry = tmp >> COMP_BIT_SIZE; + + for (j = i+1; j < t; j++) + { + uint8_t c = 0; + long_comp xx = (long_comp)x[i]*x[j]; + if ((COMP_MAX-xx) < xx) + c = 1; + + tmp = (xx<<1); + + if ((COMP_MAX-tmp) < w[i+j]) + c = 1; + + tmp += w[i+j]; + + if ((COMP_MAX-tmp) < carry) + c = 1; + + tmp += carry; + w[i+j] = (comp)tmp; + carry = tmp >> COMP_BIT_SIZE; + + if (c) + carry += COMP_RADIX; + } + + tmp = w[i+t] + carry; + w[i+t] = (comp)tmp; + w[i+t+1] = tmp >> COMP_BIT_SIZE; + } while (++i < t); + + bi_free(ctx, bi); + return trim(biR); +} + +/** + * @brief Perform a square operation on a bigint. + * @param ctx [in] The bigint session context. + * @param bia [in] A bigint. + * @return The result of the multiplication. + */ +bigint *bi_square(BI_CTX *ctx, bigint *bia) +{ + check(bia); + +#ifdef CONFIG_BIGINT_KARATSUBA + if (bia->size < SQU_KARATSUBA_THRESH) + { + return regular_square(ctx, bia); + } + + return karatsuba(ctx, bia, NULL, 1); +#else + return regular_square(ctx, bia); +#endif +} +#endif + +/** + * @brief Compare two bigints. + * @param bia [in] A bigint. + * @param bib [in] Another bigint. + * @return -1 if smaller, 1 if larger and 0 if equal. + */ +int bi_compare(bigint *bia, bigint *bib) +{ + int r, i; + + check(bia); + check(bib); + + if (bia->size > bib->size) + r = 1; + else if (bia->size < bib->size) + r = -1; + else + { + comp *a = bia->comps; + comp *b = bib->comps; + + /* Same number of components. Compare starting from the high end + * and working down. */ + r = 0; + i = bia->size - 1; + + do + { + if (a[i] > b[i]) + { + r = 1; + break; + } + else if (a[i] < b[i]) + { + r = -1; + break; + } + } while (--i >= 0); + } + + return r; +} + +/* + * Allocate and zero more components. Does not consume bi. + */ +static void more_comps(bigint *bi, int n) +{ + if (n > bi->max_comps) + { + bi->max_comps = axtls_max(bi->max_comps * 2, n); + bi->comps = (comp*)realloc(bi->comps, bi->max_comps * COMP_BYTE_SIZE); + } + + if (n > bi->size) + { + memset(&bi->comps[bi->size], 0, (n-bi->size)*COMP_BYTE_SIZE); + } + + bi->size = n; +} + +/* + * Make a new empty bigint. It may just use an old one if one is available. + * Otherwise get one off the heap. + */ +static bigint *alloc(BI_CTX *ctx, int size) +{ + bigint *biR; + + /* Can we recycle an old bigint? */ + if (ctx->free_list != NULL) + { + biR = ctx->free_list; + ctx->free_list = biR->next; + ctx->free_count--; + + if (biR->refs != 0) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("alloc: refs was not 0\n"); +#endif + abort(); /* create a stack trace from a core dump */ + } + + more_comps(biR, size); + } + else + { + /* No free bigints available - create a new one. */ + biR = (bigint *)malloc(sizeof(bigint)); + biR->comps = (comp*)malloc(size * COMP_BYTE_SIZE); + biR->max_comps = size; /* give some space to spare */ + } + + biR->size = size; + biR->refs = 1; + biR->next = NULL; + ctx->active_count++; + return biR; +} + +/* + * Work out the highest '1' bit in an exponent. Used when doing sliding-window + * exponentiation. + */ +static int find_max_exp_index(bigint *biexp) +{ + int i = COMP_BIT_SIZE-1; + comp shift = COMP_RADIX/2; + comp test = biexp->comps[biexp->size-1]; /* assume no leading zeroes */ + + check(biexp); + + do + { + if (test & shift) + { + return i+(biexp->size-1)*COMP_BIT_SIZE; + } + + shift >>= 1; + } while (i-- != 0); + + return -1; /* error - must have been a leading 0 */ +} + +/* + * Is a particular bit is an exponent 1 or 0? Used when doing sliding-window + * exponentiation. + */ +static int exp_bit_is_one(bigint *biexp, int offset) +{ + comp test = biexp->comps[offset / COMP_BIT_SIZE]; + int num_shifts = offset % COMP_BIT_SIZE; + comp shift = 1; + int i; + + check(biexp); + + for (i = 0; i < num_shifts; i++) + { + shift <<= 1; + } + + return (test & shift) != 0; +} + +#ifdef CONFIG_BIGINT_CHECK_ON +/* + * Perform a sanity check on bi. + */ +static void check(const bigint *bi) +{ + if (bi->refs <= 0) + { + printf("check: zero or negative refs in bigint\n"); + abort(); + } + + if (bi->next != NULL) + { + printf("check: attempt to use a bigint from " + "the free list\n"); + abort(); + } +} +#endif + +/* + * Delete any leading 0's (and allow for 0). + */ +static bigint *trim(bigint *bi) +{ + check(bi); + + while (bi->comps[bi->size-1] == 0 && bi->size > 1) + { + bi->size--; + } + + return bi; +} + +#if defined(CONFIG_BIGINT_MONTGOMERY) +/** + * @brief Perform a single montgomery reduction. + * @param ctx [in] The bigint session context. + * @param bixy [in] A bigint. + * @return The result of the montgomery reduction. + */ +bigint *bi_mont(BI_CTX *ctx, bigint *bixy) +{ + int i = 0, n; + uint8_t mod_offset = ctx->mod_offset; + bigint *bim = ctx->bi_mod[mod_offset]; + comp mod_inv = ctx->N0_dash[mod_offset]; + + check(bixy); + + ax_wdt_feed(); + if (ctx->use_classical) /* just use classical instead */ + { + return bi_mod(ctx, bixy); + } + + n = bim->size; + + do + { + bixy = bi_add(ctx, bixy, comp_left_shift( + bi_int_multiply(ctx, bim, bixy->comps[i]*mod_inv), i)); + } while (++i < n); + + comp_right_shift(bixy, n); + + if (bi_compare(bixy, bim) >= 0) + { + bixy = bi_subtract(ctx, bixy, bim, NULL); + } + + return bixy; +} + +#elif defined(CONFIG_BIGINT_BARRETT) +/* + * Stomp on the most significant components to give the illusion of a "mod base + * radix" operation + */ +static bigint *comp_mod(bigint *bi, int mod) +{ + check(bi); + + if (bi->size > mod) + { + bi->size = mod; + } + + return bi; +} + +/** + * @brief Perform a single Barrett reduction. + * @param ctx [in] The bigint session context. + * @param bi [in] A bigint. + * @return The result of the Barrett reduction. + */ +bigint *bi_barrett(BI_CTX *ctx, bigint *bi) +{ + bigint *q1, *q2, *q3, *r1, *r2, *r; + uint8_t mod_offset = ctx->mod_offset; + bigint *bim = ctx->bi_mod[mod_offset]; + int k = bim->size; + + check(bi); + check(bim); + + ax_wdt_feed(); + /* use Classical method instead - Barrett cannot help here */ + if (bi->size > k*2) + { + return bi_mod(ctx, bi); + } + + q1 = comp_right_shift(bi_clone(ctx, bi), k-1); + + /* do outer partial multiply */ + q2 = regular_multiply(ctx, q1, ctx->bi_mu[mod_offset], 0, k-1); + q3 = comp_right_shift(q2, k+1); + r1 = comp_mod(bi, k+1); + + /* do inner partial multiply */ + r2 = comp_mod(regular_multiply(ctx, q3, bim, k+1, 0), k+1); + r = bi_subtract(ctx, r1, r2, NULL); + + /* if (r >= m) r = r - m; */ + if (bi_compare(r, bim) >= 0) + { + r = bi_subtract(ctx, r, bim, NULL); + } + + return r; +} +#endif /* CONFIG_BIGINT_BARRETT */ + +#ifdef CONFIG_BIGINT_SLIDING_WINDOW +/* + * Work out g1, g3, g5, g7... etc for the sliding-window algorithm + */ +static void precompute_slide_window(BI_CTX *ctx, int window, bigint *g1) +{ + int k = 1, i; + bigint *g2; + + for (i = 0; i < window-1; i++) /* compute 2^(window-1) */ + { + k <<= 1; + } + + ctx->g = (bigint **)malloc(k*sizeof(bigint *)); + ctx->g[0] = bi_clone(ctx, g1); + bi_permanent(ctx->g[0]); + g2 = bi_residue(ctx, bi_square(ctx, ctx->g[0])); /* g^2 */ + + for (i = 1; i < k; i++) + { + ctx->g[i] = bi_residue(ctx, bi_multiply(ctx, ctx->g[i-1], bi_copy(g2))); + bi_permanent(ctx->g[i]); + } + + bi_free(ctx, g2); + ctx->window = k; +} +#endif + +/** + * @brief Perform a modular exponentiation. + * + * This function requires bi_set_mod() to have been called previously. This is + * one of the optimisations used for performance. + * @param ctx [in] The bigint session context. + * @param bi [in] The bigint on which to perform the mod power operation. + * @param biexp [in] The bigint exponent. + * @return The result of the mod exponentiation operation + * @see bi_set_mod(). + */ +bigint *bi_mod_power(BI_CTX *ctx, bigint *bi, bigint *biexp) +{ + int i = find_max_exp_index(biexp), j, window_size = 1; + bigint *biR = int_to_bi(ctx, 1); + +#if defined(CONFIG_BIGINT_MONTGOMERY) + uint8_t mod_offset = ctx->mod_offset; + if (!ctx->use_classical) + { + /* preconvert */ + bi = bi_mont(ctx, + bi_multiply(ctx, bi, ctx->bi_RR_mod_m[mod_offset])); /* x' */ + bi_free(ctx, biR); + biR = ctx->bi_R_mod_m[mod_offset]; /* A */ + } +#endif + + check(bi); + check(biexp); + +#ifdef CONFIG_BIGINT_SLIDING_WINDOW + for (j = i; j > 32; j /= 5) /* work out an optimum size */ + window_size++; + + /* work out the slide constants */ + precompute_slide_window(ctx, window_size, bi); +#else /* just one constant */ + ctx->g = (bigint **)malloc(sizeof(bigint *)); + ctx->g[0] = bi_clone(ctx, bi); + ctx->window = 1; + bi_permanent(ctx->g[0]); +#endif + + /* if sliding-window is off, then only one bit will be done at a time and + * will reduce to standard left-to-right exponentiation */ + do + { + if (exp_bit_is_one(biexp, i)) + { + int l = i-window_size+1; + int part_exp = 0; + + if (l < 0) /* LSB of exponent will always be 1 */ + l = 0; + else + { + while (exp_bit_is_one(biexp, l) == 0) + l++; /* go back up */ + } + + /* build up the section of the exponent */ + for (j = i; j >= l; j--) + { + biR = bi_residue(ctx, bi_square(ctx, biR)); + if (exp_bit_is_one(biexp, j)) + part_exp++; + + if (j != l) + part_exp <<= 1; + } + + part_exp = (part_exp-1)/2; /* adjust for array */ + biR = bi_residue(ctx, bi_multiply(ctx, biR, ctx->g[part_exp])); + i = l-1; + } + else /* square it */ + { + biR = bi_residue(ctx, bi_square(ctx, biR)); + i--; + } + } while (i >= 0); + + /* cleanup */ + for (i = 0; i < ctx->window; i++) + { + bi_depermanent(ctx->g[i]); + bi_free(ctx, ctx->g[i]); + } + + free(ctx->g); + bi_free(ctx, bi); + bi_free(ctx, biexp); +#if defined CONFIG_BIGINT_MONTGOMERY + return ctx->use_classical ? biR : bi_mont(ctx, biR); /* convert back */ +#else /* CONFIG_BIGINT_CLASSICAL or CONFIG_BIGINT_BARRETT */ + return biR; +#endif +} + +#ifdef CONFIG_SSL_CERT_VERIFICATION +/** + * @brief Perform a modular exponentiation using a temporary modulus. + * + * We need this function to check the signatures of certificates. The modulus + * of this function is temporary as it's just used for authentication. + * @param ctx [in] The bigint session context. + * @param bi [in] The bigint to perform the exp/mod. + * @param bim [in] The temporary modulus. + * @param biexp [in] The bigint exponent. + * @return The result of the mod exponentiation operation + * @see bi_set_mod(). + */ +bigint *bi_mod_power2(BI_CTX *ctx, bigint *bi, bigint *bim, bigint *biexp) +{ + bigint *biR, *tmp_biR; + + /* Set up a temporary bigint context and transfer what we need between + * them. We need to do this since we want to keep the original modulus + * which is already in this context. This operation is only called when + * doing peer verification, and so is not expensive :-) */ + BI_CTX *tmp_ctx = bi_initialize(); + bi_set_mod(tmp_ctx, bi_clone(tmp_ctx, bim), BIGINT_M_OFFSET); + tmp_biR = bi_mod_power(tmp_ctx, + bi_clone(tmp_ctx, bi), + bi_clone(tmp_ctx, biexp)); + biR = bi_clone(ctx, tmp_biR); + bi_free(tmp_ctx, tmp_biR); + bi_free_mod(tmp_ctx, BIGINT_M_OFFSET); + bi_terminate(tmp_ctx); + + bi_free(ctx, bi); + bi_free(ctx, bim); + bi_free(ctx, biexp); + return biR; +} +#endif + +#ifdef CONFIG_BIGINT_CRT +/** + * @brief Use the Chinese Remainder Theorem to quickly perform RSA decrypts. + * + * @param ctx [in] The bigint session context. + * @param bi [in] The bigint to perform the exp/mod. + * @param dP [in] CRT's dP bigint + * @param dQ [in] CRT's dQ bigint + * @param p [in] CRT's p bigint + * @param q [in] CRT's q bigint + * @param qInv [in] CRT's qInv bigint + * @return The result of the CRT operation + */ +bigint *bi_crt(BI_CTX *ctx, bigint *bi, + bigint *dP, bigint *dQ, + bigint *p, bigint *q, bigint *qInv) +{ + bigint *m1, *m2, *h; + + /* Montgomery has a condition the 0 < x, y < m and these products violate + * that condition. So disable Montgomery when using CRT */ +#if defined(CONFIG_BIGINT_MONTGOMERY) + ctx->use_classical = 1; +#endif + ctx->mod_offset = BIGINT_P_OFFSET; + m1 = bi_mod_power(ctx, bi_copy(bi), dP); + + ctx->mod_offset = BIGINT_Q_OFFSET; + m2 = bi_mod_power(ctx, bi, dQ); + + h = bi_subtract(ctx, bi_add(ctx, m1, p), bi_copy(m2), NULL); + h = bi_multiply(ctx, h, qInv); + ctx->mod_offset = BIGINT_P_OFFSET; + h = bi_residue(ctx, h); +#if defined(CONFIG_BIGINT_MONTGOMERY) + ctx->use_classical = 0; /* reset for any further operation */ +#endif + return bi_add(ctx, m2, bi_multiply(ctx, q, h)); +} +#endif +/** @} */ diff --git a/tools/sdk/axtls/crypto/bigint.h b/tools/sdk/axtls/crypto/bigint.h new file mode 100644 index 0000000000..2966a3edb3 --- /dev/null +++ b/tools/sdk/axtls/crypto/bigint.h @@ -0,0 +1,99 @@ +/* + * 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. + */ + +#ifndef BIGINT_HEADER +#define BIGINT_HEADER + +#include "crypto.h" + +BI_CTX *bi_initialize(void); +void bi_terminate(BI_CTX *ctx); +void bi_permanent(bigint *bi); +void bi_depermanent(bigint *bi); +void bi_clear_cache(BI_CTX *ctx); +void bi_free(BI_CTX *ctx, bigint *bi); +bigint *bi_copy(bigint *bi); +bigint *bi_clone(BI_CTX *ctx, const bigint *bi); +void bi_export(BI_CTX *ctx, bigint *bi, uint8_t *data, int size); +bigint *bi_import(BI_CTX *ctx, const uint8_t *data, int len); +bigint *int_to_bi(BI_CTX *ctx, comp i); + +/* the functions that actually do something interesting */ +bigint *bi_add(BI_CTX *ctx, bigint *bia, bigint *bib); +bigint *bi_subtract(BI_CTX *ctx, bigint *bia, + bigint *bib, int *is_negative); +bigint *bi_divide(BI_CTX *ctx, bigint *bia, bigint *bim, int is_mod); +bigint *bi_multiply(BI_CTX *ctx, bigint *bia, bigint *bib); +bigint *bi_mod_power(BI_CTX *ctx, bigint *bi, bigint *biexp); +bigint *bi_mod_power2(BI_CTX *ctx, bigint *bi, bigint *bim, bigint *biexp); +int bi_compare(bigint *bia, bigint *bib); +void bi_set_mod(BI_CTX *ctx, bigint *bim, int mod_offset); +void bi_free_mod(BI_CTX *ctx, int mod_offset); + +#ifdef CONFIG_SSL_FULL_MODE +void bi_print(const char *label, bigint *bi); +bigint *bi_str_import(BI_CTX *ctx, const char *data); +#endif + +/** + * @def bi_mod + * Find the residue of B. bi_set_mod() must be called before hand. + */ +#define bi_mod(A, B) bi_divide(A, B, ctx->bi_mod[ctx->mod_offset], 1) + +/** + * bi_residue() is technically the same as bi_mod(), but it uses the + * appropriate reduction technique (which is bi_mod() when doing classical + * reduction). + */ +#if defined(CONFIG_BIGINT_MONTGOMERY) +#define bi_residue(A, B) bi_mont(A, B) +bigint *bi_mont(BI_CTX *ctx, bigint *bixy); +#elif defined(CONFIG_BIGINT_BARRETT) +#define bi_residue(A, B) bi_barrett(A, B) +bigint *bi_barrett(BI_CTX *ctx, bigint *bi); +#else /* if defined(CONFIG_BIGINT_CLASSICAL) */ +#define bi_residue(A, B) bi_mod(A, B) +#endif + +#ifdef CONFIG_BIGINT_SQUARE +bigint *bi_square(BI_CTX *ctx, bigint *bi); +#else +#define bi_square(A, B) bi_multiply(A, bi_copy(B), B) +#endif + +#ifdef CONFIG_BIGINT_CRT +bigint *bi_crt(BI_CTX *ctx, bigint *bi, + bigint *dP, bigint *dQ, + bigint *p, bigint *q, + bigint *qInv); +#endif + +#endif diff --git a/tools/sdk/axtls/crypto/bigint_impl.h b/tools/sdk/axtls/crypto/bigint_impl.h new file mode 100644 index 0000000000..b70d32dd32 --- /dev/null +++ b/tools/sdk/axtls/crypto/bigint_impl.h @@ -0,0 +1,129 @@ +/* + * 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. + */ + +#ifndef BIGINT_IMPL_HEADER +#define BIGINT_IMPL_HEADER + +/* Maintain a number of precomputed variables when doing reduction */ +#define BIGINT_M_OFFSET 0 /**< Normal modulo offset. */ +#ifdef CONFIG_BIGINT_CRT +#define BIGINT_P_OFFSET 1 /**< p modulo offset. */ +#define BIGINT_Q_OFFSET 2 /**< q module offset. */ +#define BIGINT_NUM_MODS 3 /**< The number of modulus constants used. */ +#else +#define BIGINT_NUM_MODS 1 +#endif + +/* Architecture specific functions for big ints */ +#if defined(CONFIG_INTEGER_8BIT) +#define COMP_RADIX 256U /**< Max component + 1 */ +#define COMP_MAX 0xFFFFU/**< (Max dbl comp -1) */ +#define COMP_BIT_SIZE 8 /**< Number of bits in a component. */ +#define COMP_BYTE_SIZE 1 /**< Number of bytes in a component. */ +#define COMP_NUM_NIBBLES 2 /**< Used For diagnostics only. */ +typedef uint8_t comp; /**< A single precision component. */ +typedef uint16_t long_comp; /**< A double precision component. */ +typedef int16_t slong_comp; /**< A signed double precision component. */ +#elif defined(CONFIG_INTEGER_16BIT) +#define COMP_RADIX 65536U /**< Max component + 1 */ +#define COMP_MAX 0xFFFFFFFFU/**< (Max dbl comp -1) */ +#define COMP_BIT_SIZE 16 /**< Number of bits in a component. */ +#define COMP_BYTE_SIZE 2 /**< Number of bytes in a component. */ +#define COMP_NUM_NIBBLES 4 /**< Used For diagnostics only. */ +typedef uint16_t comp; /**< A single precision component. */ +typedef uint32_t long_comp; /**< A double precision component. */ +typedef int32_t slong_comp; /**< A signed double precision component. */ +#else /* regular 32 bit */ +#ifdef WIN32 +#define COMP_RADIX 4294967296i64 +#define COMP_MAX 0xFFFFFFFFFFFFFFFFui64 +#else +#define COMP_RADIX 4294967296ULL /**< Max component + 1 */ +#define COMP_MAX 0xFFFFFFFFFFFFFFFFULL/**< (Max dbl comp -1) */ +#endif +#define COMP_BIT_SIZE 32 /**< Number of bits in a component. */ +#define COMP_BYTE_SIZE 4 /**< Number of bytes in a component. */ +#define COMP_NUM_NIBBLES 8 /**< Used For diagnostics only. */ +typedef uint32_t comp; /**< A single precision component. */ +typedef uint64_t long_comp; /**< A double precision component. */ +typedef int64_t slong_comp; /**< A signed double precision component. */ +#endif + +/** + * @struct _bigint + * @brief A big integer basic object + */ +struct _bigint +{ + struct _bigint* next; /**< The next bigint in the cache. */ + short size; /**< The number of components in this bigint. */ + short max_comps; /**< The heapsize allocated for this bigint */ + int refs; /**< An internal reference count. */ + comp* comps; /**< A ptr to the actual component data */ +}; + +typedef struct _bigint bigint; /**< An alias for _bigint */ + +/** + * Maintains the state of the cache, and a number of variables used in + * reduction. + */ +typedef struct /**< A big integer "session" context. */ +{ + bigint *active_list; /**< Bigints currently used. */ + bigint *free_list; /**< Bigints not used. */ + bigint *bi_radix; /**< The radix used. */ + bigint *bi_mod[BIGINT_NUM_MODS]; /**< modulus */ + +#if defined(CONFIG_BIGINT_MONTGOMERY) + bigint *bi_RR_mod_m[BIGINT_NUM_MODS]; /**< R^2 mod m */ + bigint *bi_R_mod_m[BIGINT_NUM_MODS]; /**< R mod m */ + comp N0_dash[BIGINT_NUM_MODS]; +#elif defined(CONFIG_BIGINT_BARRETT) + bigint *bi_mu[BIGINT_NUM_MODS]; /**< Storage for mu */ +#endif + bigint *bi_normalised_mod[BIGINT_NUM_MODS]; /**< Normalised mod storage. */ + bigint **g; /**< Used by sliding-window. */ + int window; /**< The size of the sliding window */ + int active_count; /**< Number of active bigints. */ + int free_count; /**< Number of free bigints. */ + +#ifdef CONFIG_BIGINT_MONTGOMERY + uint8_t use_classical; /**< Use classical reduction. */ +#endif + uint8_t mod_offset; /**< The mod offset we are using */ +} BI_CTX; + +#define axtls_max(a,b) ((a)>(b)?(a):(b)) /**< Find the maximum of 2 numbers. */ +#define axtls_min(a,b) ((a)<(b)?(a):(b)) /**< Find the minimum of 2 numbers. */ + +#define PERMANENT 0x7FFF55AA /**< A magic number for permanents. */ + +#endif diff --git a/tools/sdk/axtls/crypto/crypto.h b/tools/sdk/axtls/crypto/crypto.h new file mode 100644 index 0000000000..da24d31c55 --- /dev/null +++ b/tools/sdk/axtls/crypto/crypto.h @@ -0,0 +1,277 @@ +/* + * Copyright (c) 2007-2016, 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 crypto.h + */ + +#ifndef HEADER_CRYPTO_H +#define HEADER_CRYPTO_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "bigint_impl.h" +#include "bigint.h" + +#ifndef STDCALL +#define STDCALL +#endif +#ifndef EXP_FUNC +#define EXP_FUNC +#endif + + +/* enable features based on a 'super-set' capbaility. */ +#if defined(CONFIG_SSL_FULL_MODE) +#define CONFIG_SSL_ENABLE_CLIENT +#define CONFIG_SSL_CERT_VERIFICATION +#elif defined(CONFIG_SSL_ENABLE_CLIENT) +#define CONFIG_SSL_CERT_VERIFICATION +#endif + +/************************************************************************** + * AES declarations + **************************************************************************/ + +#define AES_MAXROUNDS 14 +#define AES_BLOCKSIZE 16 +#define AES_IV_SIZE 16 + +typedef struct aes_key_st +{ + uint16_t rounds; + uint16_t key_size; + uint32_t ks[(AES_MAXROUNDS+1)*8]; + uint8_t iv[AES_IV_SIZE]; +} AES_CTX; + +typedef enum +{ + AES_MODE_128, + AES_MODE_256 +} AES_MODE; + +void AES_set_key(AES_CTX *ctx, const uint8_t *key, + const uint8_t *iv, AES_MODE mode); +void AES_cbc_encrypt(AES_CTX *ctx, const uint8_t *msg, + uint8_t *out, int length); +void AES_cbc_decrypt(AES_CTX *ks, const uint8_t *in, uint8_t *out, int length); +void AES_convert_key(AES_CTX *ctx); + +/************************************************************************** + * RC4 declarations + **************************************************************************/ + +typedef struct +{ + uint8_t x, y, m[256]; +} RC4_CTX; + +void RC4_setup(RC4_CTX *s, const uint8_t *key, int length); +void RC4_crypt(RC4_CTX *s, const uint8_t *msg, uint8_t *data, int length); + +/************************************************************************** + * SHA1 declarations + **************************************************************************/ + +#define SHA1_SIZE 20 + +/* + * This structure will hold context information for the SHA-1 + * hashing operation + */ +typedef struct +{ + uint32_t Intermediate_Hash[SHA1_SIZE/4]; /* Message Digest */ + uint32_t Length_Low; /* Message length in bits */ + uint32_t Length_High; /* Message length in bits */ + uint16_t Message_Block_Index; /* Index into message block array */ + uint8_t Message_Block[64]; /* 512-bit message blocks */ +} SHA1_CTX; + +void SHA1_Init(SHA1_CTX *); +void SHA1_Update(SHA1_CTX *, const uint8_t * msg, int len); +void SHA1_Final(uint8_t *digest, SHA1_CTX *); + +/************************************************************************** + * SHA256 declarations + **************************************************************************/ + +#define SHA256_SIZE 32 + +typedef struct +{ + uint32_t total[2]; + uint32_t state[8]; + uint8_t buffer[64]; +} SHA256_CTX; + +void SHA256_Init(SHA256_CTX *c); +void SHA256_Update(SHA256_CTX *, const uint8_t *input, int len); +void SHA256_Final(uint8_t *digest, SHA256_CTX *); + +/************************************************************************** + * SHA512 declarations + **************************************************************************/ + +#define SHA512_SIZE 64 + +typedef struct +{ + union + { + uint64_t h[8]; + uint8_t digest[64]; + } h_dig; + union + { + uint64_t w[80]; + uint8_t buffer[128]; + } w_buf; + size_t size; + uint64_t totalSize; +} SHA512_CTX; + +void SHA512_Init(SHA512_CTX *c); +void SHA512_Update(SHA512_CTX *, const uint8_t *input, int len); +void SHA512_Final(uint8_t *digest, SHA512_CTX *); + +/************************************************************************** + * SHA384 declarations + **************************************************************************/ + +#define SHA384_SIZE 48 + +typedef SHA512_CTX SHA384_CTX; +void SHA384_Init(SHA384_CTX *c); +void SHA384_Update(SHA384_CTX *, const uint8_t *input, int len); +void SHA384_Final(uint8_t *digest, SHA384_CTX *); + +/************************************************************************** + * MD5 declarations + **************************************************************************/ + +#define MD5_SIZE 16 + +typedef struct +{ + uint32_t state[4]; /* state (ABCD) */ + uint32_t count[2]; /* number of bits, modulo 2^64 (lsb first) */ + uint8_t buffer[64]; /* input buffer */ +} MD5_CTX; + +EXP_FUNC void STDCALL MD5_Init(MD5_CTX *); +EXP_FUNC void STDCALL MD5_Update(MD5_CTX *, const uint8_t *msg, int len); +EXP_FUNC void STDCALL MD5_Final(uint8_t *digest, MD5_CTX *); + +/************************************************************************** + * HMAC declarations + **************************************************************************/ +void hmac_md5(const uint8_t *msg, int length, const uint8_t *key, + int key_len, uint8_t *digest); +void hmac_sha1(const uint8_t *msg, int length, const uint8_t *key, + int key_len, uint8_t *digest); +void hmac_sha256(const uint8_t *msg, int length, const uint8_t *key, + int key_len, uint8_t *digest); + +/************************************************************************** + * HMAC functions operating on vectors + **************************************************************************/ +void hmac_md5_v(const uint8_t **msg, int* length, int count, const uint8_t *key, + int key_len, uint8_t *digest); +void hmac_sha1_v(const uint8_t **msg, int* length, int count, const uint8_t *key, + int key_len, uint8_t *digest); +void hmac_sha256_v(const uint8_t **msg, int* length, int count, const uint8_t *key, + int key_len, uint8_t *digest); + +/************************************************************************** + * RSA declarations + **************************************************************************/ + +typedef struct +{ + bigint *m; /* modulus */ + bigint *e; /* public exponent */ + bigint *d; /* private exponent */ +#ifdef CONFIG_BIGINT_CRT + bigint *p; /* p as in m = pq */ + bigint *q; /* q as in m = pq */ + bigint *dP; /* d mod (p-1) */ + bigint *dQ; /* d mod (q-1) */ + bigint *qInv; /* q^-1 mod p */ +#endif + int num_octets; + BI_CTX *bi_ctx; +} RSA_CTX; + +void RSA_priv_key_new(RSA_CTX **rsa_ctx, + const uint8_t *modulus, int mod_len, + const uint8_t *pub_exp, int pub_len, + const uint8_t *priv_exp, int priv_len +#ifdef CONFIG_BIGINT_CRT + , const uint8_t *p, int p_len, + const uint8_t *q, int q_len, + const uint8_t *dP, int dP_len, + const uint8_t *dQ, int dQ_len, + const uint8_t *qInv, int qInv_len +#endif + ); +void RSA_pub_key_new(RSA_CTX **rsa_ctx, + const uint8_t *modulus, int mod_len, + const uint8_t *pub_exp, int pub_len); +void RSA_free(RSA_CTX *ctx); +int RSA_decrypt(const RSA_CTX *ctx, const uint8_t *in_data, uint8_t *out_data, + int out_len, int is_decryption); +bigint *RSA_private(const RSA_CTX *c, bigint *bi_msg); +#if defined(CONFIG_SSL_CERT_VERIFICATION) || defined(CONFIG_SSL_GENERATE_X509_CERT) +bigint *RSA_sign_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len, + bigint *modulus, bigint *pub_exp); +bigint *RSA_public(const RSA_CTX * c, bigint *bi_msg); +int RSA_encrypt(const RSA_CTX *ctx, const uint8_t *in_data, uint16_t in_len, + uint8_t *out_data, int is_signing); +void RSA_print(const RSA_CTX *ctx); +#endif + +/************************************************************************** + * RNG declarations + **************************************************************************/ +EXP_FUNC void STDCALL RNG_initialize(void); +EXP_FUNC void STDCALL RNG_custom_init(const uint8_t *seed_buf, int size); +EXP_FUNC void STDCALL RNG_terminate(void); +EXP_FUNC int STDCALL get_random(int num_rand_bytes, uint8_t *rand_data); +int get_random_NZ(int num_rand_bytes, uint8_t *rand_data); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/axtls/crypto/crypto_misc.c b/tools/sdk/axtls/crypto/crypto_misc.c new file mode 100644 index 0000000000..42b0d9827d --- /dev/null +++ b/tools/sdk/axtls/crypto/crypto_misc.c @@ -0,0 +1,385 @@ +/* + * Copyright (c) 2007-2015, 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. + */ + +/** + * Some misc. routines to help things out + */ + +#include +#include +#include +#include +#include "os_port.h" +#include "crypto_misc.h" +#ifdef CONFIG_WIN32_USE_CRYPTO_LIB +#include "wincrypt.h" +#endif + +#ifdef ESP8266 +#define CONFIG_SSL_SKELETON_MODE 1 +uint32_t phy_get_rand(); +#endif + +#if defined(CONFIG_USE_DEV_URANDOM) +static int rng_fd = -1; +#elif defined(CONFIG_WIN32_USE_CRYPTO_LIB) +static HCRYPTPROV gCryptProv; +#endif + +#if (!defined(ESP8266) && !defined(CONFIG_USE_DEV_URANDOM) && !defined(CONFIG_WIN32_USE_CRYPTO_LIB)) +/* change to processor registers as appropriate */ +#define ENTROPY_POOL_SIZE 32 +#define ENTROPY_COUNTER1 ((((uint64_t)tv.tv_sec)<<32) | tv.tv_usec) +#define ENTROPY_COUNTER2 rand() +static uint8_t entropy_pool[ENTROPY_POOL_SIZE]; +#endif + +const char * const unsupported_str = "Error: Feature not supported\n"; + +#if (!defined(get_file) || !defined(CONFIG_SSL_SKELETON_MODE)) +/** + * Retrieve a file and put it into memory + * @return The size of the file, or -1 on failure. + */ +int get_file(const char *filename, uint8_t **buf) +{ + int total_bytes = 0; + int bytes_read = 0; + int filesize; + FILE *stream = fopen(filename, "rb"); + + if (stream == NULL) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("file '%s' does not exist\n", filename); TTY_FLUSH(); +#endif + return -1; + } + + /* Win CE doesn't support stat() */ + fseek(stream, 0, SEEK_END); + filesize = ftell(stream); + *buf = (uint8_t *)malloc(filesize); + fseek(stream, 0, SEEK_SET); + + do + { + bytes_read = fread(*buf+total_bytes, 1, filesize-total_bytes, stream); + total_bytes += bytes_read; + } while (total_bytes < filesize && bytes_read > 0); + + fclose(stream); + return filesize; +} +#endif + +/** + * Initialise the Random Number Generator engine. + * - On Win32 use the platform SDK's crypto engine. + * - On Linux use /dev/urandom + * - If none of these work then use a custom RNG. + */ +EXP_FUNC void STDCALL RNG_initialize() +{ +#if !defined(WIN32) && defined(CONFIG_USE_DEV_URANDOM) + rng_fd = open("/dev/urandom", O_RDONLY); +#elif defined(WIN32) && defined(CONFIG_WIN32_USE_CRYPTO_LIB) + if (!CryptAcquireContext(&gCryptProv, + NULL, NULL, PROV_RSA_FULL, 0)) + { + if (GetLastError() == NTE_BAD_KEYSET && + !CryptAcquireContext(&gCryptProv, + NULL, + NULL, + PROV_RSA_FULL, + CRYPT_NEWKEYSET)) + { + printf("CryptoLib: %x\n", unsupported_str, GetLastError()); + exit(1); + } + } +#elif defined(ESP8266) +#else + /* start of with a stack to copy across */ + int i; + memcpy(entropy_pool, &i, ENTROPY_POOL_SIZE); + rand_r((unsigned int *)entropy_pool); +#endif +} + +/** + * If no /dev/urandom, then initialise the RNG with something interesting. + */ +EXP_FUNC void STDCALL RNG_custom_init(const uint8_t *seed_buf, int size) +{ +#if defined(WIN32) || defined(CONFIG_WIN32_USE_CRYPTO_LIB) + int i; + + for (i = 0; i < ENTROPY_POOL_SIZE && i < size; i++) + entropy_pool[i] ^= seed_buf[i]; +#endif +} + +/** + * Terminate the RNG engine. + */ +EXP_FUNC void STDCALL RNG_terminate(void) +{ +#if defined(CONFIG_USE_DEV_URANDOM) + close(rng_fd); +#elif defined(CONFIG_WIN32_USE_CRYPTO_LIB) + CryptReleaseContext(gCryptProv, 0); +#endif +} + +/** + * Set a series of bytes with a random number. Individual bytes can be 0 + */ +EXP_FUNC int STDCALL get_random(int num_rand_bytes, uint8_t *rand_data) +{ +#if !defined(WIN32) && defined(CONFIG_USE_DEV_URANDOM) + /* use the Linux default - read from /dev/urandom */ + if (read(rng_fd, rand_data, num_rand_bytes) < 0) + return -1; +#elif defined(WIN32) && defined(CONFIG_WIN32_USE_CRYPTO_LIB) + /* use Microsoft Crypto Libraries */ + CryptGenRandom(gCryptProv, num_rand_bytes, rand_data); +#elif defined(ESP8266) + for (size_t cb = 0; cb < num_rand_bytes; cb += 4) { + uint32_t r = phy_get_rand(); + size_t left = num_rand_bytes - cb; + left = (left < 4) ? left : 4; + memcpy(rand_data + cb, &r, left); + } +#else /* nothing else to use, so use a custom RNG */ + /* The method we use when we've got nothing better. Use RC4, time + and a couple of random seeds to generate a random sequence */ + AES_CTX rng_ctx; + struct timeval tv; + MD5_CTX rng_digest_ctx; + uint8_t digest[MD5_SIZE]; + uint64_t *ep; + int i; + + /* A proper implementation would use counters etc for entropy */ + gettimeofday(&tv, NULL); + ep = (uint64_t *)entropy_pool; + ep[0] ^= ENTROPY_COUNTER1; + ep[1] ^= ENTROPY_COUNTER2; + + /* use a digested version of the entropy pool as a key */ + MD5_Init(&rng_digest_ctx); + MD5_Update(&rng_digest_ctx, entropy_pool, ENTROPY_POOL_SIZE); + MD5_Final(digest, &rng_digest_ctx); + + /* come up with the random sequence */ + AES_set_key(&rng_ctx, digest, (const uint8_t *)ep, AES_MODE_128); /* use as a key */ + memcpy(rand_data, entropy_pool, num_rand_bytes < ENTROPY_POOL_SIZE ? + num_rand_bytes : ENTROPY_POOL_SIZE); + AES_cbc_encrypt(&rng_ctx, rand_data, rand_data, num_rand_bytes); + + /* move things along */ + for (i = ENTROPY_POOL_SIZE-1; i >= MD5_SIZE ; i--) + entropy_pool[i] = entropy_pool[i-MD5_SIZE]; + + /* insert the digest at the start of the entropy pool */ + memcpy(entropy_pool, digest, MD5_SIZE); +#endif + return 0; +} + +/** + * Set a series of bytes with a random number. Individual bytes are not zero. + */ +int get_random_NZ(int num_rand_bytes, uint8_t *rand_data) +{ + int i; + if (get_random(num_rand_bytes, rand_data)) + return -1; + + for (i = 0; i < num_rand_bytes; i++) + { + while (rand_data[i] == 0) { + get_random(1, rand_data + i); + } + } + + return 0; +} + +/** + * Some useful diagnostic routines + */ +#if defined(CONFIG_SSL_FULL_MODE) || defined(CONFIG_DEBUG) +int hex_finish; +int hex_index; + +static void print_hex_init(int finish) +{ + hex_finish = finish; + hex_index = 0; +} + +static void print_hex(uint8_t hex) +{ + static int column; + + if (hex_index == 0) + { + column = 0; + } + + printf("%02x ", hex); + if (++column == 8) + { + printf(": "); + } + else if (column >= 16) + { + printf("\n"); + column = 0; + } + + if (++hex_index >= hex_finish && column > 0) + { + printf("\n"); + } +} + +/** + * Spit out a blob of data for diagnostics. The data is is a nice column format + * for easy reading. + * + * @param format [in] The string (with possible embedded format characters) + * @param size [in] The number of numbers to print + * @param data [in] The start of data to use + * @param ... [in] Any additional arguments + */ +EXP_FUNC void STDCALL print_blob(const char *format, + const uint8_t *data, int size, ...) +{ + int i; + char tmp[80]; + va_list(ap); + + va_start(ap, size); + snprintf(tmp, sizeof(tmp), "SSL: %s\n", format); + vprintf(tmp, ap); + print_hex_init(size); + for (i = 0; i < size; i++) + { + print_hex(data[i]); + } + + va_end(ap); + TTY_FLUSH(); +} +#elif defined(WIN32) +/* VC6.0 doesn't handle variadic macros */ +EXP_FUNC void STDCALL print_blob(const char *format, const unsigned char *data, + int size, ...) {} +#endif + +#if defined(CONFIG_SSL_HAS_PEM) || defined(CONFIG_HTTP_HAS_AUTHORIZATION) +/* base64 to binary lookup table */ +static const uint8_t map[128] PROGMEM = +{ + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, + 255, 254, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, + 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, + 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, + 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, + 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, 255, 255, 255, 255, 255 +}; + +EXP_FUNC int STDCALL base64_decode(const char *in, int len, + uint8_t *out, int *outlen) +{ + int g, t, x, y, z; + uint8_t c; + int ret = -1; + + g = 3; + for (x = y = z = t = 0; x < len; x++) + { + if ((c = ax_array_read_u8(map, in[x]&0x7F)) == 0xff) + continue; + + if (c == 254) /* this is the end... */ + { + c = 0; + + if (--g < 0) + goto error; + } + else if (g != 3) /* only allow = at end */ + goto error; + + t = (t<<6) | c; + + if (++y == 4) + { + out[z++] = (uint8_t)((t>>16)&255); + + if (g > 1) + out[z++] = (uint8_t)((t>>8)&255); + + if (g > 2) + out[z++] = (uint8_t)(t&255); + + y = t = 0; + } + + /* check that we don't go past the output buffer */ + if (z > *outlen) + goto error; + } + + if (y != 0) + goto error; + + *outlen = z; + ret = 0; + +error: +#ifdef CONFIG_SSL_FULL_MODE + if (ret < 0) + printf("Error: Invalid base64\n"); TTY_FLUSH(); +#endif + TTY_FLUSH(); + return ret; + +} +#endif diff --git a/tools/sdk/axtls/crypto/hmac.c b/tools/sdk/axtls/crypto/hmac.c new file mode 100644 index 0000000000..a0ae84ccf8 --- /dev/null +++ b/tools/sdk/axtls/crypto/hmac.c @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2007-2016, 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. + */ + +/** + * HMAC implementation - This code was originally taken from RFC2104 + * See http://www.ietf.org/rfc/rfc2104.txt and + * http://www.faqs.org/rfcs/rfc2202.html + */ + +#include +#include "os_port.h" +#include "crypto.h" + +/** + * Perform HMAC-MD5 + * NOTE: does not handle keys larger than the block size. + */ +void hmac_md5(const uint8_t *msg, int length, const uint8_t *key, + int key_len, uint8_t *digest) +{ + hmac_md5_v(&msg, &length, 1, key, key_len, digest); +} + +void hmac_md5_v(const uint8_t **msg, int* length, int count, const uint8_t *key, + int key_len, uint8_t *digest) +{ + MD5_CTX context; + uint8_t k_ipad[64]; + uint8_t k_opad[64]; + int i; + + memset(k_ipad, 0, sizeof k_ipad); + memset(k_opad, 0, sizeof k_opad); + memcpy(k_ipad, key, key_len); + memcpy(k_opad, key, key_len); + + for (i = 0; i < 64; i++) + { + k_ipad[i] ^= 0x36; + k_opad[i] ^= 0x5c; + } + + MD5_Init(&context); + MD5_Update(&context, k_ipad, 64); + for (i = 0; i < count; ++i) + { + MD5_Update(&context, msg[i], length[i]); + } + MD5_Final(digest, &context); + MD5_Init(&context); + MD5_Update(&context, k_opad, 64); + MD5_Update(&context, digest, MD5_SIZE); + MD5_Final(digest, &context); +} + +/** + * Perform HMAC-SHA1 + * NOTE: does not handle keys larger than the block size. + */ +void hmac_sha1(const uint8_t *msg, int length, const uint8_t *key, + int key_len, uint8_t *digest) +{ + hmac_sha1_v(&msg, &length, 1, key, key_len, digest); +} + +void hmac_sha1_v(const uint8_t **msg, int *length, int count, const uint8_t *key, + int key_len, uint8_t *digest) +{ + SHA1_CTX context; + uint8_t k_ipad[64]; + uint8_t k_opad[64]; + int i; + + memset(k_ipad, 0, sizeof k_ipad); + memset(k_opad, 0, sizeof k_opad); + memcpy(k_ipad, key, key_len); + memcpy(k_opad, key, key_len); + + for (i = 0; i < 64; i++) + { + k_ipad[i] ^= 0x36; + k_opad[i] ^= 0x5c; + } + + SHA1_Init(&context); + SHA1_Update(&context, k_ipad, 64); + for (i = 0; i < count; ++i) + { + SHA1_Update(&context, msg[i], length[i]); + } + SHA1_Final(digest, &context); + SHA1_Init(&context); + SHA1_Update(&context, k_opad, 64); + SHA1_Update(&context, digest, SHA1_SIZE); + SHA1_Final(digest, &context); +} + +/** + * Perform HMAC-SHA256 + * NOTE: does not handle keys larger than the block size. + */ +void hmac_sha256(const uint8_t *msg, int length, const uint8_t *key, + int key_len, uint8_t *digest) +{ + hmac_sha256_v(&msg, &length, 1, key, key_len, digest); +} + +void hmac_sha256_v(const uint8_t **msg, int *length, int count, const uint8_t *key, + int key_len, uint8_t *digest) +{ + SHA256_CTX context; + uint8_t k_ipad[64]; + uint8_t k_opad[64]; + int i; + + memset(k_ipad, 0, sizeof k_ipad); + memset(k_opad, 0, sizeof k_opad); + memcpy(k_ipad, key, key_len); + memcpy(k_opad, key, key_len); + + for (i = 0; i < 64; i++) + { + k_ipad[i] ^= 0x36; + k_opad[i] ^= 0x5c; + } + + SHA256_Init(&context); + SHA256_Update(&context, k_ipad, 64); + for (i = 0; i < count; ++i) + { + SHA256_Update(&context, msg[i], length[i]); + } + SHA256_Final(digest, &context); + SHA256_Init(&context); + SHA256_Update(&context, k_opad, 64); + SHA256_Update(&context, digest, SHA256_SIZE); + SHA256_Final(digest, &context); +} + diff --git a/tools/sdk/axtls/crypto/md5.c b/tools/sdk/axtls/crypto/md5.c new file mode 100644 index 0000000000..1a8786f473 --- /dev/null +++ b/tools/sdk/axtls/crypto/md5.c @@ -0,0 +1,301 @@ +/* + * 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. + */ + +/** + * This file implements the MD5 algorithm as defined in RFC1321 + */ + +#include +#include "os_port.h" +#include "crypto.h" + +/* Constants for MD5Transform routine. + */ +#define S11 7 +#define S12 12 +#define S13 17 +#define S14 22 +#define S21 5 +#define S22 9 +#define S23 14 +#define S24 20 +#define S31 4 +#define S32 11 +#define S33 16 +#define S34 23 +#define S41 6 +#define S42 10 +#define S43 15 +#define S44 21 + +/* ----- static functions ----- */ +static void MD5Transform(uint32_t state[4], const uint8_t block[64]); +static void Encode(uint8_t *output, uint32_t *input, uint32_t len); +static void Decode(uint32_t *output, const uint8_t *input, uint32_t len); + +static const uint8_t PADDING[64] PROGMEM = +{ + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +/* F, G, H and I are basic MD5 functions. + */ +#define F(x, y, z) (((x) & (y)) | ((~x) & (z))) +#define G(x, y, z) (((x) & (z)) | ((y) & (~z))) +#define H(x, y, z) ((x) ^ (y) ^ (z)) +#define I(x, y, z) ((y) ^ ((x) | (~z))) + +/* ROTATE_LEFT rotates x left n bits. */ +#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) + +/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. + Rotation is separate from addition to prevent recomputation. */ +#define FF(a, b, c, d, x, s, ac) { \ + (a) += F ((b), (c), (d)) + (x) + (uint32_t)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } +#define GG(a, b, c, d, x, s, ac) { \ + (a) += G ((b), (c), (d)) + (x) + (uint32_t)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } +#define HH(a, b, c, d, x, s, ac) { \ + (a) += H ((b), (c), (d)) + (x) + (uint32_t)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } +#define II(a, b, c, d, x, s, ac) { \ + (a) += I ((b), (c), (d)) + (x) + (uint32_t)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } + +/** + * MD5 initialization - begins an MD5 operation, writing a new ctx. + */ +EXP_FUNC void STDCALL MD5_Init(MD5_CTX *ctx) +{ + ctx->count[0] = ctx->count[1] = 0; + + /* Load magic initialization constants. + */ + ctx->state[0] = 0x67452301; + ctx->state[1] = 0xefcdab89; + ctx->state[2] = 0x98badcfe; + ctx->state[3] = 0x10325476; +} + +/** + * Accepts an array of octets as the next portion of the message. + */ +EXP_FUNC void STDCALL MD5_Update(MD5_CTX *ctx, const uint8_t * msg, int len) +{ + uint32_t x; + int i, partLen; + + /* Compute number of bytes mod 64 */ + x = (uint32_t)((ctx->count[0] >> 3) & 0x3F); + + /* Update number of bits */ + if ((ctx->count[0] += ((uint32_t)len << 3)) < ((uint32_t)len << 3)) + ctx->count[1]++; + ctx->count[1] += ((uint32_t)len >> 29); + + partLen = 64 - x; + + /* Transform as many times as possible. */ + if (len >= partLen) + { + memcpy(&ctx->buffer[x], msg, partLen); + MD5Transform(ctx->state, ctx->buffer); + + for (i = partLen; i + 63 < len; i += 64) + MD5Transform(ctx->state, &msg[i]); + + x = 0; + } + else + i = 0; + + /* Buffer remaining input */ + memcpy(&ctx->buffer[x], &msg[i], len-i); +} + +/** + * Return the 128-bit message digest into the user's array + */ +EXP_FUNC void STDCALL MD5_Final(uint8_t *digest, MD5_CTX *ctx) +{ + uint8_t bits[8]; + uint32_t x, padLen; +#ifdef WITH_PGM_READ_HELPER + uint8_t PADDING_stack[64]; + memcpy(PADDING_stack, PADDING, 64); +#endif + /* Save number of bits */ + Encode(bits, ctx->count, 8); + + /* Pad out to 56 mod 64. + */ + x = (uint32_t)((ctx->count[0] >> 3) & 0x3f); + padLen = (x < 56) ? (56 - x) : (120 - x); +#ifdef WITH_PGM_READ_HELPER + MD5_Update(ctx, PADDING_stack, padLen); +#else + MD5_Update(ctx, PADDING, padLen); +#endif + + /* Append length (before padding) */ + MD5_Update(ctx, bits, 8); + + /* Store state in digest */ + Encode(digest, ctx->state, MD5_SIZE); +} + +/** + * MD5 basic transformation. Transforms state based on block. + */ +static void MD5Transform(uint32_t state[4], const uint8_t block[64]) +{ + uint32_t a = state[0], b = state[1], c = state[2], + d = state[3], x[MD5_SIZE]; + + Decode(x, block, 64); + + /* Round 1 */ + FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ + FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ + FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ + FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ + FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ + FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ + FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ + FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ + FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ + FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ + FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ + FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ + FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ + FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ + FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ + FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ + + /* Round 2 */ + GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ + GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ + GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ + GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ + GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ + GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ + GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ + GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ + GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ + GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ + GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ + GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ + GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ + GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ + GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ + GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ + + /* Round 3 */ + HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ + HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ + HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ + HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ + HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ + HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ + HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ + HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ + HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ + HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ + HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ + HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ + HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ + HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ + HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ + HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ + + /* Round 4 */ + II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ + II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ + II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ + II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ + II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ + II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ + II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ + II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ + II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ + II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ + II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ + II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ + II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ + II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ + II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ + II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ + + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; +} + +/** + * Encodes input (uint32_t) into output (uint8_t). Assumes len is + * a multiple of 4. + */ +static void Encode(uint8_t *output, uint32_t *input, uint32_t len) +{ + uint32_t i, j; + + for (i = 0, j = 0; j < len; i++, j += 4) + { + output[j] = (uint8_t)(input[i] & 0xff); + output[j+1] = (uint8_t)((input[i] >> 8) & 0xff); + output[j+2] = (uint8_t)((input[i] >> 16) & 0xff); + output[j+3] = (uint8_t)((input[i] >> 24) & 0xff); + } +} + +/** + * Decodes input (uint8_t) into output (uint32_t). Assumes len is + * a multiple of 4. + */ +static void Decode(uint32_t *output, const uint8_t *input, uint32_t len) +{ + uint32_t i, j; + + for (i = 0, j = 0; j < len; i++, j += 4) + output[i] = ((uint32_t)input[j]) | (((uint32_t)input[j+1]) << 8) | + (((uint32_t)input[j+2]) << 16) | (((uint32_t)input[j+3]) << 24); +} diff --git a/tools/sdk/axtls/crypto/os_int.h b/tools/sdk/axtls/crypto/os_int.h new file mode 100644 index 0000000000..02e7d2d546 --- /dev/null +++ b/tools/sdk/axtls/crypto/os_int.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2012-2016, 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_int.h + * + * Ensure a consistent bit size + */ + +#ifndef HEADER_OS_INT_H +#define HEADER_OS_INT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* some bool types - just make life easier */ +typedef char bool; +#define false 0 +#define true 1 + +#if defined(WIN32) +typedef UINT8 uint8_t; +typedef INT8 int8_t; +typedef UINT16 uint16_t; +typedef INT16 int16_t; +typedef UINT32 uint32_t; +typedef INT32 int32_t; +typedef UINT64 uint64_t; +typedef INT64 int64_t; +#else /* Not Win32 */ + +#ifdef CONFIG_PLATFORM_SOLARIS +#include +#else +#include +#endif /* Not Solaris */ + +#endif /* Not Win32 */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/axtls/crypto/rc4.c b/tools/sdk/axtls/crypto/rc4.c new file mode 100644 index 0000000000..edfb27a575 --- /dev/null +++ b/tools/sdk/axtls/crypto/rc4.c @@ -0,0 +1,97 @@ +/* + * 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. + */ + +/** + * An implementation of the RC4/ARC4 algorithm. + * Originally written by Christophe Devine. + */ + +#include +#include "os_port.h" +#include "crypto.h" + +/* only used for PKCS12 now */ +#ifdef CONFIG_SSL_USE_PKCS12 + +/** + * Get ready for an encrypt/decrypt operation + */ +void RC4_setup(RC4_CTX *ctx, const uint8_t *key, int length) +{ + int i, j = 0, k = 0, a; + uint8_t *m; + + ctx->x = 0; + ctx->y = 0; + m = ctx->m; + + for (i = 0; i < 256; i++) + m[i] = i; + + for (i = 0; i < 256; i++) + { + a = m[i]; + j = (uint8_t)(j + a + key[k]); + m[i] = m[j]; + m[j] = a; + + if (++k >= length) + k = 0; + } +} + +/** + * Perform the encrypt/decrypt operation (can use it for either since + * this is a stream cipher). + * NOTE: *msg and *out must be the same pointer (performance tweak) + */ +void RC4_crypt(RC4_CTX *ctx, const uint8_t *msg, uint8_t *out, int length) +{ + int i; + uint8_t *m, x, y, a, b; + + x = ctx->x; + y = ctx->y; + m = ctx->m; + + for (i = 0; i < length; i++) + { + a = m[++x]; + y += a; + m[x] = b = m[y]; + m[y] = a; + out[i] ^= m[(uint8_t)(a + b)]; + } + + ctx->x = x; + ctx->y = y; +} + +#endif diff --git a/tools/sdk/axtls/crypto/rsa.c b/tools/sdk/axtls/crypto/rsa.c new file mode 100644 index 0000000000..ab74b4d3be --- /dev/null +++ b/tools/sdk/axtls/crypto/rsa.c @@ -0,0 +1,295 @@ +/* + * Copyright (c) 2007-2014, 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. + */ + +/** + * Implements the RSA public encryption algorithm. Uses the bigint library to + * perform its calculations. + */ + +#include +#include +#include +#include +#include "os_port.h" +#include "crypto.h" + +void RSA_priv_key_new(RSA_CTX **ctx, + const uint8_t *modulus, int mod_len, + const uint8_t *pub_exp, int pub_len, + const uint8_t *priv_exp, int priv_len +#if CONFIG_BIGINT_CRT + , const uint8_t *p, int p_len, + const uint8_t *q, int q_len, + const uint8_t *dP, int dP_len, + const uint8_t *dQ, int dQ_len, + const uint8_t *qInv, int qInv_len +#endif + ) +{ + RSA_CTX *rsa_ctx; + BI_CTX *bi_ctx; + RSA_pub_key_new(ctx, modulus, mod_len, pub_exp, pub_len); + rsa_ctx = *ctx; + bi_ctx = rsa_ctx->bi_ctx; + rsa_ctx->d = bi_import(bi_ctx, priv_exp, priv_len); + bi_permanent(rsa_ctx->d); + +#ifdef CONFIG_BIGINT_CRT + rsa_ctx->p = bi_import(bi_ctx, p, p_len); + rsa_ctx->q = bi_import(bi_ctx, q, q_len); + rsa_ctx->dP = bi_import(bi_ctx, dP, dP_len); + rsa_ctx->dQ = bi_import(bi_ctx, dQ, dQ_len); + rsa_ctx->qInv = bi_import(bi_ctx, qInv, qInv_len); + bi_permanent(rsa_ctx->dP); + bi_permanent(rsa_ctx->dQ); + bi_permanent(rsa_ctx->qInv); + bi_set_mod(bi_ctx, rsa_ctx->p, BIGINT_P_OFFSET); + bi_set_mod(bi_ctx, rsa_ctx->q, BIGINT_Q_OFFSET); +#endif +} + +void RSA_pub_key_new(RSA_CTX **ctx, + const uint8_t *modulus, int mod_len, + const uint8_t *pub_exp, int pub_len) +{ + RSA_CTX *rsa_ctx; + BI_CTX *bi_ctx; + + if (*ctx) /* if we load multiple certs, dump the old one */ + RSA_free(*ctx); + + bi_ctx = bi_initialize(); + *ctx = (RSA_CTX *)calloc(1, sizeof(RSA_CTX)); + rsa_ctx = *ctx; + rsa_ctx->bi_ctx = bi_ctx; + rsa_ctx->num_octets = mod_len; + rsa_ctx->m = bi_import(bi_ctx, modulus, mod_len); + bi_set_mod(bi_ctx, rsa_ctx->m, BIGINT_M_OFFSET); + rsa_ctx->e = bi_import(bi_ctx, pub_exp, pub_len); + bi_permanent(rsa_ctx->e); +} + +/** + * Free up any RSA context resources. + */ +void RSA_free(RSA_CTX *rsa_ctx) +{ + BI_CTX *bi_ctx; + if (rsa_ctx == NULL) /* deal with ptrs that are null */ + return; + + bi_ctx = rsa_ctx->bi_ctx; + + bi_depermanent(rsa_ctx->e); + bi_free(bi_ctx, rsa_ctx->e); + bi_free_mod(rsa_ctx->bi_ctx, BIGINT_M_OFFSET); + + if (rsa_ctx->d) + { + bi_depermanent(rsa_ctx->d); + bi_free(bi_ctx, rsa_ctx->d); +#ifdef CONFIG_BIGINT_CRT + bi_depermanent(rsa_ctx->dP); + bi_depermanent(rsa_ctx->dQ); + bi_depermanent(rsa_ctx->qInv); + bi_free(bi_ctx, rsa_ctx->dP); + bi_free(bi_ctx, rsa_ctx->dQ); + bi_free(bi_ctx, rsa_ctx->qInv); + bi_free_mod(rsa_ctx->bi_ctx, BIGINT_P_OFFSET); + bi_free_mod(rsa_ctx->bi_ctx, BIGINT_Q_OFFSET); +#endif + } + + bi_terminate(bi_ctx); + free(rsa_ctx); +} + +/** + * @brief Use PKCS1.5 for decryption/verification. + * @param ctx [in] The context + * @param in_data [in] The data to decrypt (must be < modulus size-11) + * @param out_data [out] The decrypted data. + * @param out_len [int] The size of the decrypted buffer in bytes + * @param is_decryption [in] Decryption or verify operation. + * @return The number of bytes that were originally encrypted. -1 on error. + * @see http://www.rsasecurity.com/rsalabs/node.asp?id=2125 + */ +int RSA_decrypt(const RSA_CTX *ctx, const uint8_t *in_data, + uint8_t *out_data, int out_len, int is_decryption) +{ + const int byte_size = ctx->num_octets; + int i = 0, size = -1; + bigint *decrypted_bi, *dat_bi; + uint8_t *block = NULL; + int pad_count = 0; + + do + { + if (out_len < byte_size) /* check output has enough size */ + break; + + block = (uint8_t *)malloc(byte_size); + if (!block) + break; + + memset(out_data, 0, out_len); /* initialise */ + + /* decrypt */ + dat_bi = bi_import(ctx->bi_ctx, in_data, byte_size); +#ifdef CONFIG_SSL_CERT_VERIFICATION + decrypted_bi = is_decryption ? /* decrypt or verify? */ + RSA_private(ctx, dat_bi) : RSA_public(ctx, dat_bi); +#else /* always a decryption */ + decrypted_bi = RSA_private(ctx, dat_bi); +#endif + + /* convert to a normal block */ + bi_export(ctx->bi_ctx, decrypted_bi, block, byte_size); + + if (block[i++] != 0) /* leading 0? */ + break; + +#ifdef CONFIG_SSL_CERT_VERIFICATION + if (is_decryption == 0) /* PKCS1.5 signing pads with "0xff"s */ + { + if (block[i++] != 0x01) /* BT correct? */ + break; + + while (block[i++] == 0xff && i < byte_size) + pad_count++; + } + else /* PKCS1.5 encryption padding is random */ +#endif + { + if (block[i++] != 0x02) /* BT correct? */ + break; + + while (block[i++] && i < byte_size) + pad_count++; + } + + /* check separator byte 0x00 - and padding must be 8 or more bytes */ + if (i == byte_size || pad_count < 8) + break; + + size = byte_size - i; + + /* get only the bit we want */ + memcpy(out_data, &block[i], size); + } while(false); + + if(block) + free(block); + + return size; +} + +/** + * Performs m = c^d mod n + */ +bigint *RSA_private(const RSA_CTX *c, bigint *bi_msg) +{ +#ifdef CONFIG_BIGINT_CRT + return bi_crt(c->bi_ctx, bi_msg, c->dP, c->dQ, c->p, c->q, c->qInv); +#else + BI_CTX *ctx = c->bi_ctx; + ctx->mod_offset = BIGINT_M_OFFSET; + return bi_mod_power(ctx, bi_msg, c->d); +#endif +} + +#ifdef CONFIG_SSL_FULL_MODE +/** + * Used for diagnostics. + */ +void RSA_print(const RSA_CTX *rsa_ctx) +{ + if (rsa_ctx == NULL) + return; + + printf("----------------- RSA DEBUG ----------------\n"); + printf("Size:\t%d\n", rsa_ctx->num_octets); + bi_print("Modulus", rsa_ctx->m); + bi_print("Public Key", rsa_ctx->e); + bi_print("Private Key", rsa_ctx->d); +} +#endif + +#if defined(CONFIG_SSL_CERT_VERIFICATION) || defined(CONFIG_SSL_GENERATE_X509_CERT) +/** + * Performs c = m^e mod n + */ +bigint *RSA_public(const RSA_CTX * c, bigint *bi_msg) +{ + c->bi_ctx->mod_offset = BIGINT_M_OFFSET; + return bi_mod_power(c->bi_ctx, bi_msg, c->e); +} + +/** + * Use PKCS1.5 for encryption/signing. + * see http://www.rsasecurity.com/rsalabs/node.asp?id=2125 + */ +int RSA_encrypt(const RSA_CTX *ctx, const uint8_t *in_data, uint16_t in_len, + uint8_t *out_data, int is_signing) +{ + int byte_size = ctx->num_octets; + int num_pads_needed = byte_size-in_len-3; + bigint *dat_bi, *encrypt_bi; + + /* note: in_len+11 must be > byte_size */ + out_data[0] = 0; /* ensure encryption block is < modulus */ + + if (is_signing) + { + out_data[1] = 1; /* PKCS1.5 signing pads with "0xff"'s */ + memset(&out_data[2], 0xff, num_pads_needed); + } + else /* randomize the encryption padding with non-zero bytes */ + { + out_data[1] = 2; + if (get_random_NZ(num_pads_needed, &out_data[2]) < 0) + return -1; + } + + out_data[2+num_pads_needed] = 0; + memcpy(&out_data[3+num_pads_needed], in_data, in_len); + + /* now encrypt it */ + dat_bi = bi_import(ctx->bi_ctx, out_data, byte_size); + encrypt_bi = is_signing ? RSA_private(ctx, dat_bi) : + RSA_public(ctx, dat_bi); + bi_export(ctx->bi_ctx, encrypt_bi, out_data, byte_size); + + /* save a few bytes of memory */ + bi_clear_cache(ctx->bi_ctx); + return byte_size; +} + +#endif /* CONFIG_SSL_CERT_VERIFICATION */ diff --git a/tools/sdk/axtls/crypto/sha1.c b/tools/sdk/axtls/crypto/sha1.c new file mode 100644 index 0000000000..1082733e7e --- /dev/null +++ b/tools/sdk/axtls/crypto/sha1.c @@ -0,0 +1,249 @@ +/* + * 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. + */ + +/** + * SHA1 implementation - as defined in FIPS PUB 180-1 published April 17, 1995. + * This code was originally taken from RFC3174 + */ + +#include +#include "os_port.h" +#include "crypto.h" + +/* + * Define the SHA1 circular left shift macro + */ +#define SHA1CircularShift(bits,word) \ + (((word) << (bits)) | ((word) >> (32-(bits)))) + +/* ----- static functions ----- */ +static void SHA1PadMessage(SHA1_CTX *ctx); +static void SHA1ProcessMessageBlock(SHA1_CTX *ctx); + +/** + * Initialize the SHA1 context + */ +void SHA1_Init(SHA1_CTX *ctx) +{ + ctx->Length_Low = 0; + ctx->Length_High = 0; + ctx->Message_Block_Index = 0; + ctx->Intermediate_Hash[0] = 0x67452301; + ctx->Intermediate_Hash[1] = 0xEFCDAB89; + ctx->Intermediate_Hash[2] = 0x98BADCFE; + ctx->Intermediate_Hash[3] = 0x10325476; + ctx->Intermediate_Hash[4] = 0xC3D2E1F0; +} + +/** + * Accepts an array of octets as the next portion of the message. + */ +void SHA1_Update(SHA1_CTX *ctx, const uint8_t *msg, int len) +{ + while (len--) + { + ctx->Message_Block[ctx->Message_Block_Index++] = (*msg & 0xFF); + ctx->Length_Low += 8; + + if (ctx->Length_Low == 0) + ctx->Length_High++; + + if (ctx->Message_Block_Index == 64) + SHA1ProcessMessageBlock(ctx); + + msg++; + } +} + +/** + * Return the 160-bit message digest into the user's array + */ +void SHA1_Final(uint8_t *digest, SHA1_CTX *ctx) +{ + int i; + + SHA1PadMessage(ctx); + memset(ctx->Message_Block, 0, 64); + ctx->Length_Low = 0; /* and clear length */ + ctx->Length_High = 0; + + for (i = 0; i < SHA1_SIZE; i++) + { + digest[i] = ctx->Intermediate_Hash[i>>2] >> 8 * ( 3 - ( i & 0x03 ) ); + } +} + +/** + * Process the next 512 bits of the message stored in the array. + */ +static void SHA1ProcessMessageBlock(SHA1_CTX *ctx) +{ + const uint32_t K[] = { /* Constants defined in SHA-1 */ + 0x5A827999, + 0x6ED9EBA1, + 0x8F1BBCDC, + 0xCA62C1D6 + }; + int t; /* Loop counter */ + uint32_t temp; /* Temporary word value */ + uint32_t W[80]; /* Word sequence */ + uint32_t A, B, C, D, E; /* Word buffers */ + + /* + * Initialize the first 16 words in the array W + */ + for (t = 0; t < 16; t++) + { + W[t] = ctx->Message_Block[t * 4] << 24; + W[t] |= ctx->Message_Block[t * 4 + 1] << 16; + W[t] |= ctx->Message_Block[t * 4 + 2] << 8; + W[t] |= ctx->Message_Block[t * 4 + 3]; + } + + for (t = 16; t < 80; t++) + { + W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]); + } + + A = ctx->Intermediate_Hash[0]; + B = ctx->Intermediate_Hash[1]; + C = ctx->Intermediate_Hash[2]; + D = ctx->Intermediate_Hash[3]; + E = ctx->Intermediate_Hash[4]; + + for (t = 0; t < 20; t++) + { + temp = SHA1CircularShift(5,A) + + ((B & C) | ((~B) & D)) + E + W[t] + K[0]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + + B = A; + A = temp; + } + + for (t = 20; t < 40; t++) + { + temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + B = A; + A = temp; + } + + for (t = 40; t < 60; t++) + { + temp = SHA1CircularShift(5,A) + + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + B = A; + A = temp; + } + + for (t = 60; t < 80; t++) + { + temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + B = A; + A = temp; + } + + ctx->Intermediate_Hash[0] += A; + ctx->Intermediate_Hash[1] += B; + ctx->Intermediate_Hash[2] += C; + ctx->Intermediate_Hash[3] += D; + ctx->Intermediate_Hash[4] += E; + ctx->Message_Block_Index = 0; +} + +/* + * According to the standard, the message must be padded to an even + * 512 bits. The first padding bit must be a '1'. The last 64 + * bits represent the length of the original message. All bits in + * between should be 0. This function will pad the message + * according to those rules by filling the Message_Block array + * accordingly. It will also call the ProcessMessageBlock function + * provided appropriately. When it returns, it can be assumed that + * the message digest has been computed. + * + * @param ctx [in, out] The SHA1 context + */ +static void SHA1PadMessage(SHA1_CTX *ctx) +{ + /* + * Check to see if the current message block is too small to hold + * the initial padding bits and length. If so, we will pad the + * block, process it, and then continue padding into a second + * block. + */ + if (ctx->Message_Block_Index > 55) + { + ctx->Message_Block[ctx->Message_Block_Index++] = 0x80; + while(ctx->Message_Block_Index < 64) + { + ctx->Message_Block[ctx->Message_Block_Index++] = 0; + } + + SHA1ProcessMessageBlock(ctx); + + while (ctx->Message_Block_Index < 56) + { + ctx->Message_Block[ctx->Message_Block_Index++] = 0; + } + } + else + { + ctx->Message_Block[ctx->Message_Block_Index++] = 0x80; + while(ctx->Message_Block_Index < 56) + { + + ctx->Message_Block[ctx->Message_Block_Index++] = 0; + } + } + + /* + * Store the message length as the last 8 octets + */ + ctx->Message_Block[56] = ctx->Length_High >> 24; + ctx->Message_Block[57] = ctx->Length_High >> 16; + ctx->Message_Block[58] = ctx->Length_High >> 8; + ctx->Message_Block[59] = ctx->Length_High; + ctx->Message_Block[60] = ctx->Length_Low >> 24; + ctx->Message_Block[61] = ctx->Length_Low >> 16; + ctx->Message_Block[62] = ctx->Length_Low >> 8; + ctx->Message_Block[63] = ctx->Length_Low; + SHA1ProcessMessageBlock(ctx); +} diff --git a/tools/sdk/axtls/crypto/sha256.c b/tools/sdk/axtls/crypto/sha256.c new file mode 100644 index 0000000000..ba1ac95fe4 --- /dev/null +++ b/tools/sdk/axtls/crypto/sha256.c @@ -0,0 +1,281 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include +#include "os_port.h" +#include "crypto.h" + +#define GET_UINT32(n,b,i) \ +{ \ + (n) = ((uint32_t) (b)[(i) ] << 24) \ + | ((uint32_t) (b)[(i) + 1] << 16) \ + | ((uint32_t) (b)[(i) + 2] << 8) \ + | ((uint32_t) (b)[(i) + 3] ); \ +} + +#define PUT_UINT32(n,b,i) \ +{ \ + (b)[(i) ] = (uint8_t) ((n) >> 24); \ + (b)[(i) + 1] = (uint8_t) ((n) >> 16); \ + (b)[(i) + 2] = (uint8_t) ((n) >> 8); \ + (b)[(i) + 3] = (uint8_t) ((n) ); \ +} + +static const uint8_t sha256_padding[64] PROGMEM = +{ + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +/** + * Initialize the SHA256 context + */ +void SHA256_Init(SHA256_CTX *ctx) +{ + ctx->total[0] = 0; + ctx->total[1] = 0; + + ctx->state[0] = 0x6A09E667; + ctx->state[1] = 0xBB67AE85; + ctx->state[2] = 0x3C6EF372; + ctx->state[3] = 0xA54FF53A; + ctx->state[4] = 0x510E527F; + ctx->state[5] = 0x9B05688C; + ctx->state[6] = 0x1F83D9AB; + ctx->state[7] = 0x5BE0CD19; +} + +static void SHA256_Process(const uint8_t digest[64], SHA256_CTX *ctx) +{ + uint32_t temp1, temp2, W[64]; + uint32_t A, B, C, D, E, F, G, H; + + GET_UINT32(W[0], digest, 0); + GET_UINT32(W[1], digest, 4); + GET_UINT32(W[2], digest, 8); + GET_UINT32(W[3], digest, 12); + GET_UINT32(W[4], digest, 16); + GET_UINT32(W[5], digest, 20); + GET_UINT32(W[6], digest, 24); + GET_UINT32(W[7], digest, 28); + GET_UINT32(W[8], digest, 32); + GET_UINT32(W[9], digest, 36); + GET_UINT32(W[10], digest, 40); + GET_UINT32(W[11], digest, 44); + GET_UINT32(W[12], digest, 48); + GET_UINT32(W[13], digest, 52); + GET_UINT32(W[14], digest, 56); + GET_UINT32(W[15], digest, 60); + +#define SHR(x,n) ((x & 0xFFFFFFFF) >> n) +#define ROTR(x,n) (SHR(x,n) | (x << (32 - n))) + +#define S0(x) (ROTR(x, 7) ^ ROTR(x,18) ^ SHR(x, 3)) +#define S1(x) (ROTR(x,17) ^ ROTR(x,19) ^ SHR(x,10)) + +#define S2(x) (ROTR(x, 2) ^ ROTR(x,13) ^ ROTR(x,22)) +#define S3(x) (ROTR(x, 6) ^ ROTR(x,11) ^ ROTR(x,25)) + +#define F0(x,y,z) ((x & y) | (z & (x | y))) +#define F1(x,y,z) (z ^ (x & (y ^ z))) + +#define R(t) \ +( \ + W[t] = S1(W[t - 2]) + W[t - 7] + \ + S0(W[t - 15]) + W[t - 16] \ +) + +#define P(a,b,c,d,e,f,g,h,x,K) \ +{ \ + temp1 = h + S3(e) + F1(e,f,g) + K + x; \ + temp2 = S2(a) + F0(a,b,c); \ + d += temp1; h = temp1 + temp2; \ +} + + A = ctx->state[0]; + B = ctx->state[1]; + C = ctx->state[2]; + D = ctx->state[3]; + E = ctx->state[4]; + F = ctx->state[5]; + G = ctx->state[6]; + H = ctx->state[7]; + + P(A, B, C, D, E, F, G, H, W[ 0], 0x428A2F98); + P(H, A, B, C, D, E, F, G, W[ 1], 0x71374491); + P(G, H, A, B, C, D, E, F, W[ 2], 0xB5C0FBCF); + P(F, G, H, A, B, C, D, E, W[ 3], 0xE9B5DBA5); + P(E, F, G, H, A, B, C, D, W[ 4], 0x3956C25B); + P(D, E, F, G, H, A, B, C, W[ 5], 0x59F111F1); + P(C, D, E, F, G, H, A, B, W[ 6], 0x923F82A4); + P(B, C, D, E, F, G, H, A, W[ 7], 0xAB1C5ED5); + P(A, B, C, D, E, F, G, H, W[ 8], 0xD807AA98); + P(H, A, B, C, D, E, F, G, W[ 9], 0x12835B01); + P(G, H, A, B, C, D, E, F, W[10], 0x243185BE); + P(F, G, H, A, B, C, D, E, W[11], 0x550C7DC3); + P(E, F, G, H, A, B, C, D, W[12], 0x72BE5D74); + P(D, E, F, G, H, A, B, C, W[13], 0x80DEB1FE); + P(C, D, E, F, G, H, A, B, W[14], 0x9BDC06A7); + P(B, C, D, E, F, G, H, A, W[15], 0xC19BF174); + P(A, B, C, D, E, F, G, H, R(16), 0xE49B69C1); + P(H, A, B, C, D, E, F, G, R(17), 0xEFBE4786); + P(G, H, A, B, C, D, E, F, R(18), 0x0FC19DC6); + P(F, G, H, A, B, C, D, E, R(19), 0x240CA1CC); + P(E, F, G, H, A, B, C, D, R(20), 0x2DE92C6F); + P(D, E, F, G, H, A, B, C, R(21), 0x4A7484AA); + P(C, D, E, F, G, H, A, B, R(22), 0x5CB0A9DC); + P(B, C, D, E, F, G, H, A, R(23), 0x76F988DA); + P(A, B, C, D, E, F, G, H, R(24), 0x983E5152); + P(H, A, B, C, D, E, F, G, R(25), 0xA831C66D); + P(G, H, A, B, C, D, E, F, R(26), 0xB00327C8); + P(F, G, H, A, B, C, D, E, R(27), 0xBF597FC7); + P(E, F, G, H, A, B, C, D, R(28), 0xC6E00BF3); + P(D, E, F, G, H, A, B, C, R(29), 0xD5A79147); + P(C, D, E, F, G, H, A, B, R(30), 0x06CA6351); + P(B, C, D, E, F, G, H, A, R(31), 0x14292967); + P(A, B, C, D, E, F, G, H, R(32), 0x27B70A85); + P(H, A, B, C, D, E, F, G, R(33), 0x2E1B2138); + P(G, H, A, B, C, D, E, F, R(34), 0x4D2C6DFC); + P(F, G, H, A, B, C, D, E, R(35), 0x53380D13); + P(E, F, G, H, A, B, C, D, R(36), 0x650A7354); + P(D, E, F, G, H, A, B, C, R(37), 0x766A0ABB); + P(C, D, E, F, G, H, A, B, R(38), 0x81C2C92E); + P(B, C, D, E, F, G, H, A, R(39), 0x92722C85); + P(A, B, C, D, E, F, G, H, R(40), 0xA2BFE8A1); + P(H, A, B, C, D, E, F, G, R(41), 0xA81A664B); + P(G, H, A, B, C, D, E, F, R(42), 0xC24B8B70); + P(F, G, H, A, B, C, D, E, R(43), 0xC76C51A3); + P(E, F, G, H, A, B, C, D, R(44), 0xD192E819); + P(D, E, F, G, H, A, B, C, R(45), 0xD6990624); + P(C, D, E, F, G, H, A, B, R(46), 0xF40E3585); + P(B, C, D, E, F, G, H, A, R(47), 0x106AA070); + P(A, B, C, D, E, F, G, H, R(48), 0x19A4C116); + P(H, A, B, C, D, E, F, G, R(49), 0x1E376C08); + P(G, H, A, B, C, D, E, F, R(50), 0x2748774C); + P(F, G, H, A, B, C, D, E, R(51), 0x34B0BCB5); + P(E, F, G, H, A, B, C, D, R(52), 0x391C0CB3); + P(D, E, F, G, H, A, B, C, R(53), 0x4ED8AA4A); + P(C, D, E, F, G, H, A, B, R(54), 0x5B9CCA4F); + P(B, C, D, E, F, G, H, A, R(55), 0x682E6FF3); + P(A, B, C, D, E, F, G, H, R(56), 0x748F82EE); + P(H, A, B, C, D, E, F, G, R(57), 0x78A5636F); + P(G, H, A, B, C, D, E, F, R(58), 0x84C87814); + P(F, G, H, A, B, C, D, E, R(59), 0x8CC70208); + P(E, F, G, H, A, B, C, D, R(60), 0x90BEFFFA); + P(D, E, F, G, H, A, B, C, R(61), 0xA4506CEB); + P(C, D, E, F, G, H, A, B, R(62), 0xBEF9A3F7); + P(B, C, D, E, F, G, H, A, R(63), 0xC67178F2); + + ctx->state[0] += A; + ctx->state[1] += B; + ctx->state[2] += C; + ctx->state[3] += D; + ctx->state[4] += E; + ctx->state[5] += F; + ctx->state[6] += G; + ctx->state[7] += H; +} + +/** + * Accepts an array of octets as the next portion of the message. + */ +void SHA256_Update(SHA256_CTX *ctx, const uint8_t * msg, int len) +{ + uint32_t left = ctx->total[0] & 0x3F; + uint32_t fill = 64 - left; + + ctx->total[0] += len; + ctx->total[0] &= 0xFFFFFFFF; + + if (ctx->total[0] < len) + ctx->total[1]++; + + if (left && len >= fill) + { + memcpy((void *) (ctx->buffer + left), (void *)msg, fill); + SHA256_Process(ctx->buffer, ctx); + len -= fill; + msg += fill; + left = 0; + } + + while (len >= 64) + { + SHA256_Process(msg, ctx); + len -= 64; + msg += 64; + } + + if (len) + { + memcpy((void *) (ctx->buffer + left), (void *) msg, len); + } +} + +/** + * Return the 256-bit message digest into the user's array + */ +void SHA256_Final(uint8_t *digest, SHA256_CTX *ctx) +{ + uint32_t last, padn; + uint32_t high, low; + uint8_t msglen[8]; +#ifdef WITH_PGM_READ_HELPER + uint8_t sha256_padding_ram[64]; + memcpy(sha256_padding_ram, sha256_padding, 64); +#endif + + high = (ctx->total[0] >> 29) + | (ctx->total[1] << 3); + low = (ctx->total[0] << 3); + + PUT_UINT32(high, msglen, 0); + PUT_UINT32(low, msglen, 4); + + last = ctx->total[0] & 0x3F; + padn = (last < 56) ? (56 - last) : (120 - last); +#ifdef WITH_PGM_READ_HELPER + SHA256_Update(ctx, sha256_padding_ram, padn); +#else + SHA256_Update(ctx, sha256_padding, padn); +#endif + SHA256_Update(ctx, msglen, 8); + + PUT_UINT32(ctx->state[0], digest, 0); + PUT_UINT32(ctx->state[1], digest, 4); + PUT_UINT32(ctx->state[2], digest, 8); + PUT_UINT32(ctx->state[3], digest, 12); + PUT_UINT32(ctx->state[4], digest, 16); + PUT_UINT32(ctx->state[5], digest, 20); + PUT_UINT32(ctx->state[6], digest, 24); + PUT_UINT32(ctx->state[7], digest, 28); +} diff --git a/tools/sdk/axtls/crypto/sha384.c b/tools/sdk/axtls/crypto/sha384.c new file mode 100644 index 0000000000..f1071be93b --- /dev/null +++ b/tools/sdk/axtls/crypto/sha384.c @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include +#include "os_port.h" +#include "crypto.h" + +/** +* Initialize the SHA384 context +*/ + void SHA384_Init(SHA384_CTX *ctx) + { + //Set initial hash value + ctx->h_dig.h[0] = 0xCBBB9D5DC1059ED8LL; + ctx->h_dig.h[1] = 0x629A292A367CD507LL; + ctx->h_dig.h[2] = 0x9159015A3070DD17LL; + ctx->h_dig.h[3] = 0x152FECD8F70E5939LL; + ctx->h_dig.h[4] = 0x67332667FFC00B31LL; + ctx->h_dig.h[5] = 0x8EB44A8768581511LL; + ctx->h_dig.h[6] = 0xDB0C2E0D64F98FA7LL; + ctx->h_dig.h[7] = 0x47B5481DBEFA4FA4LL; + + // Number of bytes in the buffer + ctx->size = 0; + // Total length of the message + ctx->totalSize = 0; + } + +/** +* Accepts an array of octets as the next portion of the message. +*/ +void SHA384_Update(SHA384_CTX *ctx, const uint8_t * msg, int len) +{ + // The function is defined in the exact same manner as SHA-512 + SHA512_Update(ctx, msg, len); +} + +/** +* Return the 384-bit message digest into the user's array +*/ +void SHA384_Final(uint8_t *digest, SHA384_CTX *ctx) +{ + // The function is defined in the exact same manner as SHA-512 + SHA512_Final(NULL, ctx); + + // Copy the resulting digest + if (digest != NULL) + memcpy(digest, ctx->h_dig.digest, SHA384_SIZE); +} + diff --git a/tools/sdk/axtls/crypto/sha512.c b/tools/sdk/axtls/crypto/sha512.c new file mode 100644 index 0000000000..b24a28ee02 --- /dev/null +++ b/tools/sdk/axtls/crypto/sha512.c @@ -0,0 +1,220 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include +#include "os_port.h" +#include "crypto.h" + +#define SHR64(a, n) ((a) >> (n)) +#define ROR64(a, n) (((a) >> (n)) | ((a) << (64 - (n)))) +#define CH(x, y, z) (((x) & (y)) | (~(x) & (z))) +#define MAJ(x, y, z) (((x) & (y)) | ((x) & (z)) | ((y) & (z))) +#define SIGMA1(x) (ROR64(x, 28) ^ ROR64(x, 34) ^ ROR64(x, 39)) +#define SIGMA2(x) (ROR64(x, 14) ^ ROR64(x, 18) ^ ROR64(x, 41)) +#define SIGMA3(x) (ROR64(x, 1) ^ ROR64(x, 8) ^ SHR64(x, 7)) +#define SIGMA4(x) (ROR64(x, 19) ^ ROR64(x, 61) ^ SHR64(x, 6)) +#define MIN(x, y) ((x) < (y) ? x : y) + +static const uint8_t padding[128] PROGMEM = +{ + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; + +static const uint64_t k[80] PROGMEM = +{ + 0x428A2F98D728AE22LL, 0x7137449123EF65CDLL, 0xB5C0FBCFEC4D3B2FLL, 0xE9B5DBA58189DBBCLL, + 0x3956C25BF348B538LL, 0x59F111F1B605D019LL, 0x923F82A4AF194F9BLL, 0xAB1C5ED5DA6D8118LL, + 0xD807AA98A3030242LL, 0x12835B0145706FBELL, 0x243185BE4EE4B28CLL, 0x550C7DC3D5FFB4E2LL, + 0x72BE5D74F27B896FLL, 0x80DEB1FE3B1696B1LL, 0x9BDC06A725C71235LL, 0xC19BF174CF692694LL, + 0xE49B69C19EF14AD2LL, 0xEFBE4786384F25E3LL, 0x0FC19DC68B8CD5B5LL, 0x240CA1CC77AC9C65LL, + 0x2DE92C6F592B0275LL, 0x4A7484AA6EA6E483LL, 0x5CB0A9DCBD41FBD4LL, 0x76F988DA831153B5LL, + 0x983E5152EE66DFABLL, 0xA831C66D2DB43210LL, 0xB00327C898FB213FLL, 0xBF597FC7BEEF0EE4LL, + 0xC6E00BF33DA88FC2LL, 0xD5A79147930AA725LL, 0x06CA6351E003826FLL, 0x142929670A0E6E70LL, + 0x27B70A8546D22FFCLL, 0x2E1B21385C26C926LL, 0x4D2C6DFC5AC42AEDLL, 0x53380D139D95B3DFLL, + 0x650A73548BAF63DELL, 0x766A0ABB3C77B2A8LL, 0x81C2C92E47EDAEE6LL, 0x92722C851482353BLL, + 0xA2BFE8A14CF10364LL, 0xA81A664BBC423001LL, 0xC24B8B70D0F89791LL, 0xC76C51A30654BE30LL, + 0xD192E819D6EF5218LL, 0xD69906245565A910LL, 0xF40E35855771202ALL, 0x106AA07032BBD1B8LL, + 0x19A4C116B8D2D0C8LL, 0x1E376C085141AB53LL, 0x2748774CDF8EEB99LL, 0x34B0BCB5E19B48A8LL, + 0x391C0CB3C5C95A63LL, 0x4ED8AA4AE3418ACBLL, 0x5B9CCA4F7763E373LL, 0x682E6FF3D6B2B8A3LL, + 0x748F82EE5DEFB2FCLL, 0x78A5636F43172F60LL, 0x84C87814A1F0AB72LL, 0x8CC702081A6439ECLL, + 0x90BEFFFA23631E28LL, 0xA4506CEBDE82BDE9LL, 0xBEF9A3F7B2C67915LL, 0xC67178F2E372532BLL, + 0xCA273ECEEA26619CLL, 0xD186B8C721C0C207LL, 0xEADA7DD6CDE0EB1ELL, 0xF57D4F7FEE6ED178LL, + 0x06F067AA72176FBALL, 0x0A637DC5A2C898A6LL, 0x113F9804BEF90DAELL, 0x1B710B35131C471BLL, + 0x28DB77F523047D84LL, 0x32CAAB7B40C72493LL, 0x3C9EBE0A15C9BEBCLL, 0x431D67C49C100D4CLL, + 0x4CC5D4BECB3E42B6LL, 0x597F299CFC657E2ALL, 0x5FCB6FAB3AD6FAECLL, 0x6C44198C4A475817LL +}; + +/** +* Initialize the SHA512 context +*/ +void SHA512_Init(SHA512_CTX *ctx) +{ + ctx->h_dig.h[0] = 0x6A09E667F3BCC908LL; + ctx->h_dig.h[1] = 0xBB67AE8584CAA73BLL; + ctx->h_dig.h[2] = 0x3C6EF372FE94F82BLL; + ctx->h_dig.h[3] = 0xA54FF53A5F1D36F1LL; + ctx->h_dig.h[4] = 0x510E527FADE682D1LL; + ctx->h_dig.h[5] = 0x9B05688C2B3E6C1FLL; + ctx->h_dig.h[6] = 0x1F83D9ABFB41BD6BLL; + ctx->h_dig.h[7] = 0x5BE0CD19137E2179LL; + ctx->size = 0; + ctx->totalSize = 0; +} + +static void SHA512_Process(SHA512_CTX *ctx) +{ + int t; + uint64_t temp1; + uint64_t temp2; + + // Initialize the 8 working registers + uint64_t a = ctx->h_dig.h[0]; + uint64_t b = ctx->h_dig.h[1]; + uint64_t c = ctx->h_dig.h[2]; + uint64_t d = ctx->h_dig.h[3]; + uint64_t e = ctx->h_dig.h[4]; + uint64_t f = ctx->h_dig.h[5]; + uint64_t g = ctx->h_dig.h[6]; + uint64_t h = ctx->h_dig.h[7]; + + // Process message in 16-word blocks + uint64_t *w = ctx->w_buf.w; + + // Convert from big-endian byte order to host byte order + for (t = 0; t < 16; t++) + w[t] = be64toh(w[t]); + + // Prepare the message schedule + for (t = 16; t < 80; t++) + w[t] = SIGMA4(w[t - 2]) + w[t - 7] + SIGMA3(w[t - 15]) + w[t - 16]; + + // SHA-512 hash computation + for (t = 0; t < 80; t++) + { + // Calculate T1 and T2 + temp1 = h + SIGMA2(e) + CH(e, f, g) + k[t] + w[t]; + temp2 = SIGMA1(a) + MAJ(a, b, c); + + // Update the working registers + h = g; + g = f; + f = e; + e = d + temp1; + d = c; + c = b; + b = a; + a = temp1 + temp2; + } + + // Update the hash value + ctx->h_dig.h[0] += a; + ctx->h_dig.h[1] += b; + ctx->h_dig.h[2] += c; + ctx->h_dig.h[3] += d; + ctx->h_dig.h[4] += e; + ctx->h_dig.h[5] += f; + ctx->h_dig.h[6] += g; + ctx->h_dig.h[7] += h; + } + +/** +* Accepts an array of octets as the next portion of the message. +*/ +void SHA512_Update(SHA512_CTX *ctx, const uint8_t * msg, int len) +{ + // Process the incoming data + while (len > 0) + { + // The buffer can hold at most 128 bytes + size_t n = MIN(len, 128 - ctx->size); + + // Copy the data to the buffer + memcpy(ctx->w_buf.buffer + ctx->size, msg, n); + + // Update the SHA-512 ctx + ctx->size += n; + ctx->totalSize += n; + // Advance the data pointer + msg = (uint8_t *) msg + n; + // Remaining bytes to process + len -= n; + + // Process message in 16-word blocks + if (ctx->size == 128) + { + // Transform the 16-word block + SHA512_Process(ctx); + // Empty the buffer + ctx->size = 0; + } + } +} + +/** +* Return the 512-bit message digest into the user's array +*/ +void SHA512_Final(uint8_t *digest, SHA512_CTX *ctx) +{ + int i; + size_t paddingSize; + uint64_t totalSize; + + // Length of the original message (before padding) + totalSize = ctx->totalSize * 8; + + // Pad the message so that its length is congruent to 112 modulo 128 + paddingSize = (ctx->size < 112) ? (112 - ctx->size) : + (128 + 112 - ctx->size); + // Append padding + SHA512_Update(ctx, padding, paddingSize); + + // Append the length of the original message + ctx->w_buf.w[14] = 0; + ctx->w_buf.w[15] = be64toh(totalSize); + + // Calculate the message digest + SHA512_Process(ctx); + + // Convert from host byte order to big-endian byte order + for (i = 0; i < 8; i++) + ctx->h_dig.h[i] = be64toh(ctx->h_dig.h[i]); + + // Copy the resulting digest + if (digest != NULL) + memcpy(digest, ctx->h_dig.digest, SHA512_SIZE); + } + diff --git a/tools/sdk/axtls/replacements/time.c b/tools/sdk/axtls/replacements/time.c new file mode 100644 index 0000000000..4972119bb4 --- /dev/null +++ b/tools/sdk/axtls/replacements/time.c @@ -0,0 +1,147 @@ +/* + * time.c - ESP8266-specific functions for SNTP + * Copyright (c) 2015 Peter Dobler. All rights reserved. + * This file is part of the esp8266 core for Arduino environment. + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU Lesser General Public License for more details. + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include +#include + +extern uint32_t system_get_time(void); +extern uint64_t system_mktime(uint32_t year, uint32_t mon, uint32_t day, uint32_t hour, uint32_t min, uint32_t sec); + +static int errno_var = 0; + +int* __errno(void) { + // DEBUGV("__errno is called last error: %d (not current)\n", errno_var); + return &errno_var; +} + +unsigned long millis(void) +{ + return system_get_time() / 1000UL; +} + +unsigned long micros(void) +{ + return system_get_time(); +} + +#ifndef _TIMEVAL_DEFINED +#define _TIMEVAL_DEFINED +struct timeval { + time_t tv_sec; + suseconds_t tv_usec; +}; +#endif + +extern char* sntp_asctime(const struct tm *t); +extern struct tm* sntp_localtime(const time_t *clock); + +// time gap in seconds from 01.01.1900 (NTP time) to 01.01.1970 (UNIX time) +#define DIFF1900TO1970 2208988800UL + +static int s_daylightOffset_sec = 0; +static long s_timezone_sec = 0; +static time_t s_bootTime = 0; + +// calculate offset used in gettimeofday +static void ensureBootTimeIsSet() +{ + if (!s_bootTime) + { + time_t now = sntp_get_current_timestamp(); + if (now) + { + s_bootTime = now - millis() / 1000; + } + } +} + +static void setServer(int id, const char* name_or_ip) +{ + if (name_or_ip) + { + //TODO: check whether server is given by name or IP + sntp_setservername(id, (char*) name_or_ip); + } +} + +void configTime(int timezone, int daylightOffset_sec, const char* server1, const char* server2, const char* server3) +{ + sntp_stop(); + + setServer(0, server1); + setServer(1, server2); + setServer(2, server3); + + s_timezone_sec = timezone; + s_daylightOffset_sec = daylightOffset_sec; + sntp_set_timezone(timezone/3600); + sntp_init(); +} + +int clock_gettime(clockid_t unused, struct timespec *tp) +{ + tp->tv_sec = millis() / 1000; + tp->tv_nsec = micros() * 1000; + return 0; +} + +// seconds since 1970 +time_t mktime(struct tm *t) +{ + // system_mktime expects month in range 1..12 + #define START_MONTH 1 + return DIFF1900TO1970 + system_mktime(t->tm_year, t->tm_mon + START_MONTH, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); +} + +time_t time(time_t * t) +{ + time_t seconds = sntp_get_current_timestamp(); + if (t) + { + *t = seconds; + } + return seconds; +} + +char* asctime(const struct tm *t) +{ + return sntp_asctime(t); +} + +struct tm* localtime(const time_t *clock) +{ + return sntp_localtime(clock); +} + +char* ctime(const time_t *t) +{ + struct tm* p_tm = localtime(t); + char* result = asctime(p_tm); + return result; +} + +int gettimeofday(struct timeval *tp, void *tzp) +{ + if (tp) + { + ensureBootTimeIsSet(); + tp->tv_sec = (s_bootTime + millis()) / 1000; + tp->tv_usec = micros() * 1000; + } + return 0; +} diff --git a/tools/sdk/axtls/samples/c/axssl.c b/tools/sdk/axtls/samples/c/axssl.c new file mode 100644 index 0000000000..2bc872a5e7 --- /dev/null +++ b/tools/sdk/axtls/samples/c/axssl.c @@ -0,0 +1,902 @@ +/* + * Copyright (c) 2007-2016, 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. + */ + +/** + * Demonstrate the use of the axTLS library in C with a set of + * command-line parameters similar to openssl. In fact, openssl clients + * should be able to communicate with axTLS servers and visa-versa. + * + * This code has various bits enabled depending on the configuration. To enable + * the most interesting version, compile with the 'full mode' enabled. + * + * To see what options you have, run the following: + * > axssl s_server -? + * > axssl s_client -? + * + * The axtls shared library must be in the same directory or be found + * by the OS. + */ +#include +#include +#include +#include "os_port.h" +#include "ssl.h" + +/* define standard input */ +#ifndef STDIN_FILENO +#define STDIN_FILENO 0 +#endif + +static void do_server(int argc, char *argv[]); +static void print_options(char *option); +static void print_server_options(char *option); +static void do_client(int argc, char *argv[]); +static void print_client_options(char *option); +static void display_cipher(SSL *ssl); +static void display_session_id(SSL *ssl); + +/** + * Main entry point. Doesn't do much except works out whether we are a client + * or a server. + */ +int main(int argc, char *argv[]) +{ +#ifdef WIN32 + WSADATA wsaData; + WORD wVersionRequested = MAKEWORD(2, 2); + WSAStartup(wVersionRequested, &wsaData); +#elif !defined(CONFIG_PLATFORM_SOLARIS) + signal(SIGPIPE, SIG_IGN); /* ignore pipe errors */ +#endif + + if (argc == 2 && strcmp(argv[1], "version") == 0) + { + printf("axssl %s %s\n", ssl_version(), __DATE__); + exit(0); + } + + if (argc < 2 || ( + strcmp(argv[1], "s_server") && strcmp(argv[1], "s_client"))) + print_options(argc > 1 ? argv[1] : ""); + + strcmp(argv[1], "s_server") ? + do_client(argc, argv) : do_server(argc, argv); + return 0; +} + +/** + * Implement the SSL server logic. + */ +static void do_server(int argc, char *argv[]) +{ + int i = 2; + uint16_t port = 4433; + uint32_t options = SSL_DISPLAY_CERTS; + int client_fd; + SSL_CTX *ssl_ctx; + int server_fd, res = 0; + socklen_t client_len; +#ifndef CONFIG_SSL_SKELETON_MODE + char *private_key_file = NULL; + const char *password = NULL; + char **cert; + int cert_index = 0; + int cert_size = ssl_get_config(SSL_MAX_CERT_CFG_OFFSET); +#endif +#ifdef WIN32 + char yes = 1; +#else + int yes = 1; +#endif + struct sockaddr_in serv_addr; + struct sockaddr_in client_addr; + int quiet = 0; +#ifdef CONFIG_SSL_CERT_VERIFICATION + int ca_cert_index = 0; + int ca_cert_size = ssl_get_config(SSL_MAX_CA_CERT_CFG_OFFSET); + char **ca_cert = (char **)calloc(1, sizeof(char *)*ca_cert_size); +#endif + fd_set read_set; + +#ifndef CONFIG_SSL_SKELETON_MODE + cert = (char **)calloc(1, sizeof(char *)*cert_size); +#endif + + while (i < argc) + { + if (strcmp(argv[i], "-accept") == 0) + { + if (i >= argc-1) + { + print_server_options(argv[i]); + } + + port = atoi(argv[++i]); + } +#ifndef CONFIG_SSL_SKELETON_MODE + else if (strcmp(argv[i], "-cert") == 0) + { + if (i >= argc-1 || cert_index >= cert_size) + { + print_server_options(argv[i]); + } + + cert[cert_index++] = argv[++i]; + } + else if (strcmp(argv[i], "-key") == 0) + { + if (i >= argc-1) + { + print_server_options(argv[i]); + } + + private_key_file = argv[++i]; + options |= SSL_NO_DEFAULT_KEY; + } + else if (strcmp(argv[i], "-pass") == 0) + { + if (i >= argc-1) + { + print_server_options(argv[i]); + } + + password = argv[++i]; + } +#endif + else if (strcmp(argv[i], "-quiet") == 0) + { + quiet = 1; + options &= ~SSL_DISPLAY_CERTS; + } +#ifdef CONFIG_SSL_CERT_VERIFICATION + else if (strcmp(argv[i], "-verify") == 0) + { + options |= SSL_CLIENT_AUTHENTICATION; + } + else if (strcmp(argv[i], "-CAfile") == 0) + { + if (i >= argc-1 || ca_cert_index >= ca_cert_size) + { + print_server_options(argv[i]); + } + + ca_cert[ca_cert_index++] = argv[++i]; + } +#endif +#ifdef CONFIG_SSL_FULL_MODE + else if (strcmp(argv[i], "-debug") == 0) + { + options |= SSL_DISPLAY_BYTES; + } + else if (strcmp(argv[i], "-state") == 0) + { + options |= SSL_DISPLAY_STATES; + } + else if (strcmp(argv[i], "-show-rsa") == 0) + { + options |= SSL_DISPLAY_RSA; + } +#endif + else /* don't know what this is */ + { + print_server_options(argv[i]); + } + + i++; + } + + if ((ssl_ctx = ssl_ctx_new(options, SSL_DEFAULT_SVR_SESS)) == NULL) + { + fprintf(stderr, "Error: Server context is invalid\n"); + exit(1); + } + +#ifndef CONFIG_SSL_SKELETON_MODE + if (private_key_file) + { + int obj_type = SSL_OBJ_RSA_KEY; + + /* auto-detect the key type from the file extension */ + if (strstr(private_key_file, ".p8")) + obj_type = SSL_OBJ_PKCS8; + else if (strstr(private_key_file, ".p12")) + obj_type = SSL_OBJ_PKCS12; + + if (ssl_obj_load(ssl_ctx, obj_type, private_key_file, password)) + { + fprintf(stderr, "Error: Private key '%s' is undefined.\n", + private_key_file); + exit(1); + } + } + + for (i = 0; i < cert_index; i++) + { + if (ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CERT, cert[i], NULL)) + { + printf("Certificate '%s' is undefined.\n", cert[i]); + exit(1); + } + } +#endif + +#ifdef CONFIG_SSL_CERT_VERIFICATION + for (i = 0; i < ca_cert_index; i++) + { + if (ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CACERT, ca_cert[i], NULL)) + { + printf("Certificate '%s' is undefined.\n", ca_cert[i]); + exit(1); + } + } + + free(ca_cert); +#endif +#ifndef CONFIG_SSL_SKELETON_MODE + free(cert); +#endif + + /* Create socket for incoming connections */ + if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) + { + perror("socket"); + return; + } + + setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); + + /* Construct local address structure */ + memset(&serv_addr, 0, sizeof(serv_addr)); /* Zero out structure */ + serv_addr.sin_family = AF_INET; /* Internet address family */ + serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ + serv_addr.sin_port = htons(port); /* Local port */ + + /* Bind to the local address */ + if (bind(server_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) + { + perror("bind"); + exit(1); + } + + if (listen(server_fd, 5) < 0) + { + perror("listen"); + exit(1); + } + + client_len = sizeof(client_addr); + + /************************************************************************* + * This is where the interesting stuff happens. Up until now we've + * just been setting up sockets etc. Now we do the SSL handshake. + *************************************************************************/ + for (;;) + { + SSL *ssl; + int reconnected = 0; + + if (!quiet) + { + printf("ACCEPT\n"); + TTY_FLUSH(); + } + + if ((client_fd = accept(server_fd, + (struct sockaddr *)&client_addr, &client_len)) < 0) + { + break; + } + + ssl = ssl_server_new(ssl_ctx, client_fd); + + /* now read (and display) whatever the client sends us */ + for (;;) + { + /* allow parallel reading of client and standard input */ + FD_ZERO(&read_set); + FD_SET(client_fd, &read_set); + +#ifndef WIN32 + /* win32 doesn't like mixing up stdin and sockets */ + if (isatty(STDIN_FILENO))/* but only if we are in an active shell */ + { + FD_SET(STDIN_FILENO, &read_set); + } + + if ((res = select(client_fd+1, &read_set, NULL, NULL, NULL)) > 0) + { + uint8_t buf[1024]; + + /* read standard input? */ + if (FD_ISSET(STDIN_FILENO, &read_set)) + { + if (fgets((char *)buf, sizeof(buf), stdin) == NULL) + { + res = SSL_ERROR_CONN_LOST; + } + else + { + /* small hack to check renegotiation */ + if (buf[0] == 'r' && (buf[1] == '\n' || buf[1] == '\r')) + { + res = ssl_renegotiate(ssl); + } + else /* write our ramblings to the client */ + { + res = ssl_write(ssl, buf, strlen((char *)buf)+1); + } + } + } + else /* a socket read */ +#endif + { + /* keep reading until we get something interesting */ + uint8_t *read_buf; + + if ((res = ssl_read(ssl, &read_buf)) == SSL_OK) + { + /* are we in the middle of doing a handshake? */ + if (ssl_handshake_status(ssl) != SSL_OK) + { + reconnected = 0; + } + else if (!reconnected) + { + /* we are connected/reconnected */ + if (!quiet) + { + display_session_id(ssl); + display_cipher(ssl); + } + + reconnected = 1; + } + } + + if (res > SSL_OK) /* display our interesting output */ + { + int written = 0; + while (written < res) + { + written += write(STDOUT_FILENO, read_buf+written, + res-written); + } + TTY_FLUSH(); + } + else if (res == SSL_CLOSE_NOTIFY) + { + printf("shutting down SSL\n"); + TTY_FLUSH(); + } + else if (res < SSL_OK && !quiet) + { + ssl_display_error(res); + } + } +#ifndef WIN32 + } +#endif + + if (res < SSL_OK) + { + if (!quiet) + { + printf("CONNECTION CLOSED\n"); + TTY_FLUSH(); + } + + break; + } + } + + /* client was disconnected or the handshake failed. */ + ssl_free(ssl); + SOCKET_CLOSE(client_fd); + } + + ssl_ctx_free(ssl_ctx); +} + +/** + * Implement the SSL client logic. + */ +static void do_client(int argc, char *argv[]) +{ +#ifdef CONFIG_SSL_ENABLE_CLIENT + int res, i = 2; + uint16_t port = 4433; + uint32_t options = SSL_SERVER_VERIFY_LATER|SSL_DISPLAY_CERTS; + int client_fd; + char *private_key_file = NULL; + struct sockaddr_in client_addr; + struct hostent *hostent; + int reconnect = 0; + uint32_t sin_addr; + SSL_CTX *ssl_ctx; + SSL *ssl = NULL; + int quiet = 0; + int cert_index = 0, ca_cert_index = 0; + int cert_size, ca_cert_size; + char **ca_cert, **cert; + uint8_t session_id[SSL_SESSION_ID_SIZE]; + fd_set read_set; + const char *password = NULL; + SSL_EXTENSIONS *extensions = NULL; + + FD_ZERO(&read_set); + sin_addr = inet_addr("127.0.0.1"); + cert_size = ssl_get_config(SSL_MAX_CERT_CFG_OFFSET); + ca_cert_size = ssl_get_config(SSL_MAX_CA_CERT_CFG_OFFSET); + ca_cert = (char **)calloc(1, sizeof(char *)*ca_cert_size); + cert = (char **)calloc(1, sizeof(char *)*cert_size); + + while (i < argc) + { + if (strcmp(argv[i], "-connect") == 0) + { + char *host, *ptr; + + if (i >= argc-1) + { + print_client_options(argv[i]); + } + + host = argv[++i]; + if ((ptr = strchr(host, ':')) == NULL) + { + print_client_options(argv[i]); + } + + *ptr++ = 0; + port = atoi(ptr); + hostent = gethostbyname(host); + + if (hostent == NULL) + { + print_client_options(argv[i]); + } + + sin_addr = *((uint32_t **)hostent->h_addr_list)[0]; + } + else if (strcmp(argv[i], "-cert") == 0) + { + if (i >= argc-1 || cert_index >= cert_size) + { + print_client_options(argv[i]); + } + + cert[cert_index++] = argv[++i]; + } + else if (strcmp(argv[i], "-key") == 0) + { + if (i >= argc-1) + { + print_client_options(argv[i]); + } + + private_key_file = argv[++i]; + options |= SSL_NO_DEFAULT_KEY; + } + else if (strcmp(argv[i], "-CAfile") == 0) + { + if (i >= argc-1 || ca_cert_index >= ca_cert_size) + { + print_client_options(argv[i]); + } + + ca_cert[ca_cert_index++] = argv[++i]; + } + else if (strcmp(argv[i], "-verify") == 0) + { + options &= ~SSL_SERVER_VERIFY_LATER; + } + else if (strcmp(argv[i], "-reconnect") == 0) + { + reconnect = 4; + } + else if (strcmp(argv[i], "-quiet") == 0) + { + quiet = 1; + options &= ~SSL_DISPLAY_CERTS; + } + else if (strcmp(argv[i], "-pass") == 0) + { + if (i >= argc-1) + { + print_client_options(argv[i]); + } + + password = argv[++i]; + } + else if (strcmp(argv[i], "-servername") == 0) + { + if (i >= argc-1) + { + print_client_options(argv[i]); + } + + extensions = ssl_ext_new(); + extensions->host_name = argv[++i]; + } +#ifdef CONFIG_SSL_FULL_MODE + else if (strcmp(argv[i], "-debug") == 0) + { + options |= SSL_DISPLAY_BYTES; + } + else if (strcmp(argv[i], "-state") == 0) + { + options |= SSL_DISPLAY_STATES; + } + else if (strcmp(argv[i], "-show-rsa") == 0) + { + options |= SSL_DISPLAY_RSA; + } +#endif + else /* don't know what this is */ + { + print_client_options(argv[i]); + } + + i++; + } + + if ((ssl_ctx = ssl_ctx_new(options, SSL_DEFAULT_CLNT_SESS)) == NULL) + { + fprintf(stderr, "Error: Client context is invalid\n"); + exit(1); + } + + if (private_key_file) + { + int obj_type = SSL_OBJ_RSA_KEY; + + /* auto-detect the key type from the file extension */ + if (strstr(private_key_file, ".p8")) + obj_type = SSL_OBJ_PKCS8; + else if (strstr(private_key_file, ".p12")) + obj_type = SSL_OBJ_PKCS12; + + if (ssl_obj_load(ssl_ctx, obj_type, private_key_file, password)) + { + fprintf(stderr, "Error: Private key '%s' is undefined.\n", + private_key_file); + exit(1); + } + } + + for (i = 0; i < cert_index; i++) + { + if (ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CERT, cert[i], NULL)) + { + printf("Certificate '%s' is undefined.\n", cert[i]); + exit(1); + } + } + + for (i = 0; i < ca_cert_index; i++) + { + if (ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CACERT, ca_cert[i], NULL)) + { + printf("Certificate '%s' is undefined.\n", ca_cert[i]); + exit(1); + } + } + + free(cert); + free(ca_cert); + + /************************************************************************* + * This is where the interesting stuff happens. Up until now we've + * just been setting up sockets etc. Now we do the SSL handshake. + *************************************************************************/ + client_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + memset(&client_addr, 0, sizeof(client_addr)); + client_addr.sin_family = AF_INET; + client_addr.sin_port = htons(port); + client_addr.sin_addr.s_addr = sin_addr; + + if (connect(client_fd, (struct sockaddr *)&client_addr, + sizeof(client_addr)) < 0) + { + perror("connect"); + exit(1); + } + + if (!quiet) + { + printf("CONNECTED\n"); + TTY_FLUSH(); + } + + /* Try session resumption? */ + if (reconnect) + { + while (reconnect--) + { + ssl = ssl_client_new(ssl_ctx, client_fd, session_id, + sizeof(session_id), extensions); + if ((res = ssl_handshake_status(ssl)) != SSL_OK) + { + if (!quiet) + { + ssl_display_error(res); + } + + ssl_free(ssl); + exit(1); + } + + display_session_id(ssl); + memcpy(session_id, ssl_get_session_id(ssl), SSL_SESSION_ID_SIZE); + + if (reconnect) + { + ssl_free(ssl); + SOCKET_CLOSE(client_fd); + + client_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + connect(client_fd, (struct sockaddr *)&client_addr, + sizeof(client_addr)); + } + } + } + else + { + ssl = ssl_client_new(ssl_ctx, client_fd, NULL, 0, extensions); + } + + /* check the return status */ + if ((res = ssl_handshake_status(ssl)) != SSL_OK) + { + if (!quiet) + { + ssl_display_error(res); + } + + exit(1); + } + + if (!quiet) + { + display_session_id(ssl); + display_cipher(ssl); + } + + for (;;) + { + uint8_t buf[1024]; + + /* allow parallel reading of server and standard input */ + FD_SET(client_fd, &read_set); +#ifndef WIN32 + /* win32 doesn't like mixing up stdin and sockets */ + FD_SET(STDIN_FILENO, &read_set); + + if ((res = select(client_fd+1, &read_set, NULL, NULL, NULL)) > 0) + { + /* read standard input? */ + if (FD_ISSET(STDIN_FILENO, &read_set)) +#endif + { + if (fgets((char *)buf, sizeof(buf), stdin) == NULL) + { + /* bomb out of here */ + ssl_free(ssl); + break; + } + else + { + /* small hack to check renegotiation */ + if (buf[0] == 'R' && (buf[1] == '\n' || buf[1] == '\r')) + { + res = ssl_renegotiate(ssl); + } + else + { + res = ssl_write(ssl, buf, strlen((char *)buf)); + } + } + } +#ifndef WIN32 + else /* a socket read */ + { + uint8_t *read_buf; + + res = ssl_read(ssl, &read_buf); + + if (res > 0) /* display our interesting output */ + { + int written = 0; + while (written < res) + { + written += write(STDOUT_FILENO, read_buf+written, + res-written); + } + TTY_FLUSH(); + } + } + } +#endif + + if (res < 0) + { + if (!quiet) + { + ssl_display_error(res); + } + + break; /* get outta here */ + } + } + + ssl_ctx_free(ssl_ctx); + SOCKET_CLOSE(client_fd); +#else + print_client_options(argv[1]); +#endif +} + +/** + * We've had some sort of command-line error. Print out the basic options. + */ +static void print_options(char *option) +{ + printf("axssl: Error: '%s' is an invalid command.\n", option); + printf("usage: axssl [s_server|s_client|version] [args ...]\n"); + exit(1); +} + +/** + * We've had some sort of command-line error. Print out the server options. + */ +static void print_server_options(char *option) +{ +#ifndef CONFIG_SSL_SKELETON_MODE + int cert_size = ssl_get_config(SSL_MAX_CERT_CFG_OFFSET); +#endif +#ifdef CONFIG_SSL_CERT_VERIFICATION + int ca_cert_size = ssl_get_config(SSL_MAX_CA_CERT_CFG_OFFSET); +#endif + + printf("unknown option %s\n", option); + printf("usage: s_server [args ...]\n"); + printf(" -accept arg\t- port to accept on (default is 4433)\n"); +#ifndef CONFIG_SSL_SKELETON_MODE + printf(" -cert arg\t- certificate file to add (in addition to default)" + " to chain -\n" + "\t\t Can repeat up to %d times\n", cert_size); + printf(" -key arg\t- Private key file to use\n"); + printf(" -pass\t\t- private key file pass phrase source\n"); +#endif + printf(" -quiet\t\t- No server output\n"); +#ifdef CONFIG_SSL_CERT_VERIFICATION + printf(" -verify\t- turn on peer certificate verification\n"); + printf(" -CAfile arg\t- Certificate authority\n"); + printf("\t\t Can repeat up to %d times\n", ca_cert_size); +#endif +#ifdef CONFIG_SSL_FULL_MODE + printf(" -debug\t\t- Print more output\n"); + printf(" -state\t\t- Show state messages\n"); + printf(" -show-rsa\t- Show RSA state\n"); +#endif + exit(1); +} + +/** + * We've had some sort of command-line error. Print out the client options. + */ +static void print_client_options(char *option) +{ +#ifdef CONFIG_SSL_ENABLE_CLIENT + int cert_size = ssl_get_config(SSL_MAX_CERT_CFG_OFFSET); + int ca_cert_size = ssl_get_config(SSL_MAX_CA_CERT_CFG_OFFSET); +#endif + + printf("unknown option %s\n", option); +#ifdef CONFIG_SSL_ENABLE_CLIENT + printf("usage: s_client [args ...]\n"); + printf(" -connect host:port - who to connect to (default " + "is localhost:4433)\n"); + printf(" -verify\t- turn on peer certificate verification\n"); + printf(" -cert arg\t- certificate file to use\n"); + printf("\t\t Can repeat up to %d times\n", cert_size); + printf(" -key arg\t- Private key file to use\n"); + printf(" -CAfile arg\t- Certificate authority\n"); + printf("\t\t Can repeat up to %d times\n", ca_cert_size); + printf(" -quiet\t\t- No client output\n"); + printf(" -reconnect\t- Drop and re-make the connection " + "with the same Session-ID\n"); + printf(" -pass\t\t- Private key file pass phrase source\n"); + printf(" -servername\t- Set TLS extension servername in ClientHello\n"); +#ifdef CONFIG_SSL_FULL_MODE + printf(" -debug\t\t- Print more output\n"); + printf(" -state\t\t- Show state messages\n"); + printf(" -show-rsa\t- Show RSA state\n"); +#endif +#else + printf("Change configuration to allow this feature\n"); +#endif + exit(1); +} + +/** + * Display what cipher we are using + */ +static void display_cipher(SSL *ssl) +{ + printf("CIPHER is "); + switch (ssl_get_cipher_id(ssl)) + { + case SSL_AES128_SHA: + printf("AES128-SHA"); + break; + + case SSL_AES256_SHA: + printf("AES256-SHA"); + break; + + case SSL_AES128_SHA256: + printf("AES128-SHA256"); + break; + + case SSL_AES256_SHA256: + printf("AES256-SHA256"); + break; + + default: + printf("Unknown - %d", ssl_get_cipher_id(ssl)); + break; + } + + printf("\n"); + TTY_FLUSH(); +} + +/** + * Display what session id we have. + */ +static void display_session_id(SSL *ssl) +{ + int i; + const uint8_t *session_id = ssl_get_session_id(ssl); + int sess_id_size = ssl_get_session_id_size(ssl); + + if (sess_id_size > 0) + { + printf("-----BEGIN SSL SESSION PARAMETERS-----\n"); + for (i = 0; i < sess_id_size; i++) + { + printf("%02x", session_id[i]); + } + + printf("\n-----END SSL SESSION PARAMETERS-----\n"); + TTY_FLUSH(); + } +} diff --git a/tools/sdk/axtls/samples/csharp/axssl.cs b/tools/sdk/axtls/samples/csharp/axssl.cs new file mode 100644 index 0000000000..df3c576623 --- /dev/null +++ b/tools/sdk/axtls/samples/csharp/axssl.cs @@ -0,0 +1,758 @@ +/* + * Copyright (c) 2007-2016, 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. + */ + +/** + * Demonstrate the use of the axTLS library in C# with a set of + * command-line parameters similar to openssl. In fact, openssl clients + * should be able to communicate with axTLS servers and visa-versa. + * + * This code has various bits enabled depending on the configuration. To enable + * the most interesting version, compile with the 'full mode' enabled. + * + * To see what options you have, run the following: + * > axssl.csharp.exe s_server -? + * > axssl.csharp.exe s_client -? + * + * The axtls shared library must be in the same directory or be found + * by the OS. + */ + +using System; +using System.Net; +using System.Net.Sockets; +using axTLS; + +public class axssl +{ + /* + * Main() + */ + public static void Main(string[] args) + { + if (args.Length == 1 && args[0] == "version") + { + Console.WriteLine("axssl.csharp " + SSLUtil.Version()); + Environment.Exit(0); + } + + axssl runner = new axssl(); + + if (args.Length < 1 || (args[0] != "s_server" && args[0] != "s_client")) + runner.print_options(args.Length > 0 ? args[0] : ""); + + int build_mode = SSLUtil.BuildMode(); + + if (args[0] == "s_server") + runner.do_server(build_mode, args); + else + runner.do_client(build_mode, args); + } + + /* + * do_server() + */ + private void do_server(int build_mode, string[] args) + { + int i = 1; + int port = 4433; + uint options = axtls.SSL_DISPLAY_CERTS; + bool quiet = false; + string password = null; + string private_key_file = null; + + /* organise the cert/ca_cert lists */ + int cert_size = SSLUtil.MaxCerts(); + int ca_cert_size = SSLUtil.MaxCACerts(); + string[] cert = new string[cert_size]; + string[] ca_cert = new string[ca_cert_size]; + int cert_index = 0; + int ca_cert_index = 0; + + while (i < args.Length) + { + if (args[i] == "-accept") + { + if (i >= args.Length-1) + { + print_server_options(build_mode, args[i]); + } + + port = Int32.Parse(args[++i]); + } + else if (args[i] == "-quiet") + { + quiet = true; + options &= ~(uint)axtls.SSL_DISPLAY_CERTS; + } + else if (build_mode >= axtls.SSL_BUILD_SERVER_ONLY) + { + if (args[i] == "-cert") + { + if (i >= args.Length-1 || cert_index >= cert_size) + { + print_server_options(build_mode, args[i]); + } + + cert[cert_index++] = args[++i]; + } + else if (args[i] == "-key") + { + if (i >= args.Length-1) + { + print_server_options(build_mode, args[i]); + } + + private_key_file = args[++i]; + options |= axtls.SSL_NO_DEFAULT_KEY; + } + else if (args[i] == "-pass") + { + if (i >= args.Length-1) + { + print_server_options(build_mode, args[i]); + } + + password = args[++i]; + } + else if (build_mode >= axtls.SSL_BUILD_ENABLE_VERIFICATION) + { + if (args[i] == "-verify") + { + options |= axtls.SSL_CLIENT_AUTHENTICATION; + } + else if (args[i] == "-CAfile") + { + if (i >= args.Length-1 || ca_cert_index >= ca_cert_size) + { + print_server_options(build_mode, args[i]); + } + + ca_cert[ca_cert_index++] = args[++i]; + } + else if (build_mode == axtls.SSL_BUILD_FULL_MODE) + { + if (args[i] == "-debug") + { + options |= axtls.SSL_DISPLAY_BYTES; + } + else if (args[i] == "-state") + { + options |= axtls.SSL_DISPLAY_STATES; + } + else if (args[i] == "-show-rsa") + { + options |= axtls.SSL_DISPLAY_RSA; + } + else + print_server_options(build_mode, args[i]); + } + else + print_server_options(build_mode, args[i]); + } + else + print_server_options(build_mode, args[i]); + } + else + print_server_options(build_mode, args[i]); + + i++; + } + + /* Create socket for incoming connections */ + IPEndPoint ep = new IPEndPoint(IPAddress.Any, port); + TcpListener server_sock = new TcpListener(ep); + server_sock.Start(); + + /********************************************************************** + * This is where the interesting stuff happens. Up until now we've + * just been setting up sockets etc. Now we do the SSL handshake. + **********************************************************************/ + SSLServer ssl_ctx = new SSLServer( + options, axtls.SSL_DEFAULT_SVR_SESS); + + if (ssl_ctx == null) + { + Console.Error.WriteLine("Error: Server context is invalid"); + Environment.Exit(1); + } + + if (private_key_file != null) + { + int obj_type = axtls.SSL_OBJ_RSA_KEY; + + if (private_key_file.EndsWith(".p8")) + obj_type = axtls.SSL_OBJ_PKCS8; + else if (private_key_file.EndsWith(".p12")) + obj_type = axtls.SSL_OBJ_PKCS12; + + if (ssl_ctx.ObjLoad(obj_type, + private_key_file, password) != axtls.SSL_OK) + { + Console.Error.WriteLine("Private key '" + private_key_file + + "' is undefined."); + Environment.Exit(1); + } + } + + for (i = 0; i < cert_index; i++) + { + if (ssl_ctx.ObjLoad(axtls.SSL_OBJ_X509_CERT, + cert[i], null) != axtls.SSL_OK) + { + Console.WriteLine("Certificate '" + cert[i] + + "' is undefined."); + Environment.Exit(1); + } + } + + for (i = 0; i < ca_cert_index; i++) + { + if (ssl_ctx.ObjLoad(axtls.SSL_OBJ_X509_CACERT, + ca_cert[i], null) != axtls.SSL_OK) + { + Console.WriteLine("Certificate '" + cert[i] + + "' is undefined."); + Environment.Exit(1); + } + } + + byte[] buf = null; + int res; + + for (;;) + { + if (!quiet) + { + Console.WriteLine("ACCEPT"); + } + + Socket client_sock = server_sock.AcceptSocket(); + + SSL ssl = ssl_ctx.Connect(client_sock); + + /* do the actual SSL handshake */ + while ((res = ssl_ctx.Read(ssl, out buf)) == axtls.SSL_OK) + { + /* check when the connection has been established */ + if (ssl.HandshakeStatus() == axtls.SSL_OK) + break; + + /* could do something else here */ + } + + if (res == axtls.SSL_OK) /* connection established and ok */ + { + if (!quiet) + { + display_session_id(ssl); + display_cipher(ssl); + } + + /* now read (and display) whatever the client sends us */ + for (;;) + { + /* keep reading until we get something interesting */ + while ((res = ssl_ctx.Read(ssl, out buf)) == axtls.SSL_OK) + { + /* could do something else here */ + } + + if (res < axtls.SSL_OK) + { + if (!quiet) + { + Console.WriteLine("CONNECTION CLOSED"); + } + + break; + } + + /* convert to string */ + char[] str = new char[res]; + for (i = 0; i < res; i++) + { + str[i] = (char)buf[i]; + } + + Console.Write(str); + } + } + else if (!quiet) + { + SSLUtil.DisplayError(res); + } + + /* client was disconnected or the handshake failed. */ + ssl.Dispose(); + client_sock.Close(); + } + + /* ssl_ctx.Dispose(); */ + } + + /* + * do_client() + */ + private void do_client(int build_mode, string[] args) + { + if (build_mode < axtls.SSL_BUILD_ENABLE_CLIENT) + { + print_client_options(build_mode, args[1]); + } + + int i = 1, res; + int port = 4433; + bool quiet = false; + string password = null; + int reconnect = 0; + string private_key_file = null; + string hostname = "127.0.0.1"; + + /* organise the cert/ca_cert lists */ + int cert_index = 0; + int ca_cert_index = 0; + int cert_size = SSLUtil.MaxCerts(); + int ca_cert_size = SSLUtil.MaxCACerts(); + string[] cert = new string[cert_size]; + string[] ca_cert = new string[ca_cert_size]; + + uint options = axtls.SSL_SERVER_VERIFY_LATER|axtls.SSL_DISPLAY_CERTS; + byte[] session_id = null; + + while (i < args.Length) + { + if (args[i] == "-connect") + { + string host_port; + + if (i >= args.Length-1) + { + print_client_options(build_mode, args[i]); + } + + host_port = args[++i]; + int index_colon; + + if ((index_colon = host_port.IndexOf(':')) < 0) + print_client_options(build_mode, args[i]); + + hostname = new string(host_port.ToCharArray(), + 0, index_colon); + port = Int32.Parse(new String(host_port.ToCharArray(), + index_colon+1, host_port.Length-index_colon-1)); + } + else if (args[i] == "-cert") + { + if (i >= args.Length-1 || cert_index >= cert_size) + { + print_client_options(build_mode, args[i]); + } + + cert[cert_index++] = args[++i]; + } + else if (args[i] == "-key") + { + if (i >= args.Length-1) + { + print_client_options(build_mode, args[i]); + } + + private_key_file = args[++i]; + options |= axtls.SSL_NO_DEFAULT_KEY; + } + else if (args[i] == "-CAfile") + { + if (i >= args.Length-1 || ca_cert_index >= ca_cert_size) + { + print_client_options(build_mode, args[i]); + } + + ca_cert[ca_cert_index++] = args[++i]; + } + else if (args[i] == "-verify") + { + options &= ~(uint)axtls.SSL_SERVER_VERIFY_LATER; + } + else if (args[i] == "-reconnect") + { + reconnect = 4; + } + else if (args[i] == "-quiet") + { + quiet = true; + options &= ~(uint)axtls.SSL_DISPLAY_CERTS; + } + else if (args[i] == "-pass") + { + if (i >= args.Length-1) + { + print_client_options(build_mode, args[i]); + } + + password = args[++i]; + } + else if (build_mode == axtls.SSL_BUILD_FULL_MODE) + { + if (args[i] == "-debug") + { + options |= axtls.SSL_DISPLAY_BYTES; + } + else if (args[i] == "-state") + { + options |= axtls.SSL_DISPLAY_STATES; + } + else if (args[i] == "-show-rsa") + { + options |= axtls.SSL_DISPLAY_RSA; + } + else + print_client_options(build_mode, args[i]); + } + else /* don't know what this is */ + print_client_options(build_mode, args[i]); + + i++; + } + + // IPHostEntry hostInfo = Dns.Resolve(hostname); + IPHostEntry hostInfo = Dns.GetHostEntry(hostname); + IPAddress[] addresses = hostInfo.AddressList; + IPEndPoint ep = new IPEndPoint(addresses[0], port); + Socket client_sock = new Socket(AddressFamily.InterNetwork, + SocketType.Stream, ProtocolType.Tcp); + client_sock.Connect(ep); + + if (!client_sock.Connected) + { + Console.WriteLine("could not connect"); + Environment.Exit(1); + } + + if (!quiet) + { + Console.WriteLine("CONNECTED"); + } + + /********************************************************************** + * This is where the interesting stuff happens. Up until now we've + * just been setting up sockets etc. Now we do the SSL handshake. + **********************************************************************/ + SSLClient ssl_ctx = new SSLClient(options, + axtls.SSL_DEFAULT_CLNT_SESS); + + if (ssl_ctx == null) + { + Console.Error.WriteLine("Error: Client context is invalid"); + Environment.Exit(1); + } + + if (private_key_file != null) + { + int obj_type = axtls.SSL_OBJ_RSA_KEY; + + if (private_key_file.EndsWith(".p8")) + obj_type = axtls.SSL_OBJ_PKCS8; + else if (private_key_file.EndsWith(".p12")) + obj_type = axtls.SSL_OBJ_PKCS12; + + if (ssl_ctx.ObjLoad(obj_type, + private_key_file, password) != axtls.SSL_OK) + { + Console.Error.WriteLine("Private key '" + private_key_file + + "' is undefined."); + Environment.Exit(1); + } + } + + for (i = 0; i < cert_index; i++) + { + if (ssl_ctx.ObjLoad(axtls.SSL_OBJ_X509_CERT, + cert[i], null) != axtls.SSL_OK) + { + Console.WriteLine("Certificate '" + cert[i] + + "' is undefined."); + Environment.Exit(1); + } + } + + for (i = 0; i < ca_cert_index; i++) + { + if (ssl_ctx.ObjLoad(axtls.SSL_OBJ_X509_CACERT, + ca_cert[i], null) != axtls.SSL_OK) + { + Console.WriteLine("Certificate '" + cert[i] + + "' is undefined."); + Environment.Exit(1); + } + } + + SSL ssl = new SSL(new IntPtr(0)); /* keep compiler happy */ + + /* Try session resumption? */ + if (reconnect > 0) + { + while (reconnect-- > 0) + { + ssl = ssl_ctx.Connect(client_sock, session_id); + + if ((res = ssl.HandshakeStatus()) != axtls.SSL_OK) + { + if (!quiet) + { + SSLUtil.DisplayError(res); + } + + ssl.Dispose(); + Environment.Exit(1); + } + + display_session_id(ssl); + session_id = ssl.GetSessionId(); + + if (reconnect > 0) + { + ssl.Dispose(); + client_sock.Close(); + + /* and reconnect */ + client_sock = new Socket(AddressFamily.InterNetwork, + SocketType.Stream, ProtocolType.Tcp); + client_sock.Connect(ep); + } + } + } + else + { + ssl = ssl_ctx.Connect(client_sock, null); + } + + /* check the return status */ + if ((res = ssl.HandshakeStatus()) != axtls.SSL_OK) + { + if (!quiet) + { + SSLUtil.DisplayError(res); + } + + Environment.Exit(1); + } + + if (!quiet) + { + string common_name = + ssl.GetCertificateDN(axtls.SSL_X509_CERT_COMMON_NAME); + + if (common_name != null) + { + Console.WriteLine("Common Name:\t\t\t" + common_name); + } + + display_session_id(ssl); + display_cipher(ssl); + } + + for (;;) + { + string user_input = Console.ReadLine(); + + if (user_input == null) + break; + + byte[] buf = new byte[user_input.Length+2]; + buf[buf.Length-2] = (byte)'\n'; /* add the carriage return */ + buf[buf.Length-1] = 0; /* null terminate */ + + for (i = 0; i < buf.Length-2; i++) + { + buf[i] = (byte)user_input[i]; + } + + if ((res = ssl_ctx.Write(ssl, buf, buf.Length)) < axtls.SSL_OK) + { + if (!quiet) + { + SSLUtil.DisplayError(res); + } + + break; + } + } + + ssl_ctx.Dispose(); + } + + /** + * We've had some sort of command-line error. Print out the basic options. + */ + private void print_options(string option) + { + Console.WriteLine("axssl: Error: '" + option + + "' is an invalid command."); + Console.WriteLine("usage: axssl.csharp [s_server|" + + "s_client|version] [args ...]"); + Environment.Exit(1); + } + + /** + * We've had some sort of command-line error. Print out the server options. + */ + private void print_server_options(int build_mode, string option) + { + int cert_size = SSLUtil.MaxCerts(); + int ca_cert_size = SSLUtil.MaxCACerts(); + + Console.WriteLine("unknown option " + option); + Console.WriteLine("usage: s_server [args ...]"); + Console.WriteLine(" -accept arg\t- port to accept on (default " + + "is 4433)"); + Console.WriteLine(" -quiet\t\t- No server output"); + + if (build_mode >= axtls.SSL_BUILD_SERVER_ONLY) + { + Console.WriteLine(" -cert arg\t- certificate file to add (in " + + "addition to default) to chain -"); + Console.WriteLine("\t\t Can repeat up to " + cert_size + " times"); + Console.WriteLine(" -key arg\t- Private key file to use"); + Console.WriteLine(" -pass\t\t- private key file pass phrase source"); + } + + if (build_mode >= axtls.SSL_BUILD_ENABLE_VERIFICATION) + { + Console.WriteLine(" -verify\t- turn on peer certificate " + + "verification"); + Console.WriteLine(" -CAfile arg\t- Certificate authority."); + Console.WriteLine("\t\t Can repeat up to " + + ca_cert_size + "times"); + } + + if (build_mode == axtls.SSL_BUILD_FULL_MODE) + { + Console.WriteLine(" -debug\t\t- Print more output"); + Console.WriteLine(" -state\t\t- Show state messages"); + Console.WriteLine(" -show-rsa\t- Show RSA state"); + } + + Environment.Exit(1); + } + + /** + * We've had some sort of command-line error. Print out the client options. + */ + private void print_client_options(int build_mode, string option) + { + int cert_size = SSLUtil.MaxCerts(); + int ca_cert_size = SSLUtil.MaxCACerts(); + + Console.WriteLine("unknown option " + option); + + if (build_mode >= axtls.SSL_BUILD_ENABLE_CLIENT) + { + Console.WriteLine("usage: s_client [args ...]"); + Console.WriteLine(" -connect host:port - who to connect to " + + "(default is localhost:4433)"); + Console.WriteLine(" -verify\t- turn on peer certificate " + + "verification"); + Console.WriteLine(" -cert arg\t- certificate file to use"); + Console.WriteLine("\t\t Can repeat up to %d times", cert_size); + Console.WriteLine(" -key arg\t- Private key file to use"); + Console.WriteLine(" -CAfile arg\t- Certificate authority."); + Console.WriteLine("\t\t Can repeat up to " + ca_cert_size + + " times"); + Console.WriteLine(" -quiet\t\t- No client output"); + Console.WriteLine(" -pass\t\t- private key file pass " + + "phrase source"); + Console.WriteLine(" -reconnect\t- Drop and re-make the " + + "connection with the same Session-ID"); + + if (build_mode == axtls.SSL_BUILD_FULL_MODE) + { + Console.WriteLine(" -debug\t\t- Print more output"); + Console.WriteLine(" -state\t\t- Show state messages"); + Console.WriteLine(" -show-rsa\t- Show RSA state"); + } + } + else + { + Console.WriteLine("Change configuration to allow this feature"); + } + + Environment.Exit(1); + } + + /** + * Display what cipher we are using + */ + private void display_cipher(SSL ssl) + { + Console.Write("CIPHER is "); + + switch (ssl.GetCipherId()) + { + case axtls.SSL_AES128_SHA: + Console.WriteLine("AES128-SHA"); + break; + + case axtls.SSL_AES256_SHA: + Console.WriteLine("AES256-SHA"); + break; + + case axtls.SSL_AES128_SHA256: + Console.WriteLine("AES128-SHA256"); + break; + + case axtls.SSL_AES256_SHA256: + Console.WriteLine("AES128-SHA256"); + break; + + default: + Console.WriteLine("Unknown - " + ssl.GetCipherId()); + break; + } + } + + /** + * Display what session id we have. + */ + private void display_session_id(SSL ssl) + { + byte[] session_id = ssl.GetSessionId(); + + if (session_id.Length > 0) + { + Console.WriteLine("-----BEGIN SSL SESSION PARAMETERS-----"); + foreach (byte b in session_id) + { + Console.Write("{0:x02}", b); + } + + Console.WriteLine("\n-----END SSL SESSION PARAMETERS-----"); + } + } +} diff --git a/tools/sdk/axtls/samples/java/Makefile b/tools/sdk/axtls/samples/java/Makefile new file mode 100644 index 0000000000..9c1ed6da2e --- /dev/null +++ b/tools/sdk/axtls/samples/java/Makefile @@ -0,0 +1,51 @@ +# +# Copyright (c) 2007-2016, 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. +# + +include ../../config/.config +include ../../config/makefile.conf +include ../../config/makefile.java.conf + +all : sample +JAR=../../$(STAGE)/axtls.jar +CLASSES=../../bindings/java/classes +sample : $(JAR) + +$(JAR) : $(CLASSES)/axssl.class $(wildcard $(CLASSES)/axTLSj/*.class) + jar mcvf manifest.mf $@ -C $(CLASSES) axTLSj -C $(CLASSES) axssl.class + +JAVA_FILES=axssl.java +JAVA_CLASSES:=$(JAVA_FILES:%.java=$(CLASSES)/axTLSj/%.class) + +$(CLASSES)/%.class : %.java + javac -d $(CLASSES) -classpath $(CLASSES) $^ + +clean:: + -@rm -f $(TARGET) + diff --git a/tools/sdk/axtls/samples/java/axssl.java b/tools/sdk/axtls/samples/java/axssl.java new file mode 100644 index 0000000000..e013c11b47 --- /dev/null +++ b/tools/sdk/axtls/samples/java/axssl.java @@ -0,0 +1,760 @@ +/* + * Copyright (c) 2007-2016, 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. + */ + +/* + * Demonstrate the use of the axTLS library in Java with a set of + * command-line parameters similar to openssl. In fact, openssl clients + * should be able to communicate with axTLS servers and visa-versa. * + * This code has various bits enabled depending on the configuration. To enable + * the most interesting version, compile with the 'full mode' enabled. + * + * To see what options you have, run the following: + * > java -jar axtls.jar s_server -? + * > java -jar axtls.jar s_client -? + * + * The axtls/axtlsj shared libraries must be in the same directory or be found + * by the OS. + */ + +import java.io.*; +import java.util.*; +import java.net.*; +import axTLSj.*; + +public class axssl +{ + /* + * Main() + */ + public static void main(String[] args) + { + if (args.length == 1 && args[0].equals("version")) + { + System.out.println("axtls.jar " + SSLUtil.version()); + System.exit(0); + } + + axssl runner = new axssl(); + + try + { + if (args.length < 1 || + (!args[0].equals("s_server") && + !args[0].equals("s_client"))) + { + runner.print_options(args.length > 0 ? args[0] : ""); + } + + int build_mode = SSLUtil.buildMode(); + + if (args[0].equals("s_server")) + runner.do_server(build_mode, args); + else + runner.do_client(build_mode, args); + } + catch (Exception e) + { + System.out.println(e); + } + } + + /* + * do_server() + */ + private void do_server(int build_mode, String[] args) + throws Exception + { + int i = 1; + int port = 4433; + int options = axtlsj.SSL_DISPLAY_CERTS; + boolean quiet = false; + String password = null; + String private_key_file = null; + + /* organise the cert/ca_cert lists */ + int cert_size = SSLUtil.maxCerts(); + int ca_cert_size = SSLUtil.maxCACerts(); + String[] cert = new String[cert_size]; + String[] ca_cert = new String[ca_cert_size]; + int cert_index = 0; + int ca_cert_index = 0; + + while (i < args.length) + { + if (args[i].equals("-accept")) + { + if (i >= args.length-1) + { + print_server_options(build_mode, args[i]); + } + + port = Integer.parseInt(args[++i]); + } + else if (args[i].equals("-quiet")) + { + quiet = true; + options &= ~(int)axtlsj.SSL_DISPLAY_CERTS; + } + else if (build_mode >= axtlsj.SSL_BUILD_SERVER_ONLY) + { + if (args[i].equals("-cert")) + { + if (i >= args.length-1 || cert_index >= cert_size) + { + print_server_options(build_mode, args[i]); + } + + cert[cert_index++] = args[++i]; + } + else if (args[i].equals("-key")) + { + if (i >= args.length-1) + { + print_server_options(build_mode, args[i]); + } + + private_key_file = args[++i]; + options |= axtlsj.SSL_NO_DEFAULT_KEY; + } + else if (args[i].equals("-pass")) + { + if (i >= args.length-1) + { + print_server_options(build_mode, args[i]); + } + + password = args[++i]; + } + else if (build_mode >= axtlsj.SSL_BUILD_ENABLE_VERIFICATION) + { + if (args[i].equals("-verify")) + { + options |= axtlsj.SSL_CLIENT_AUTHENTICATION; + } + else if (args[i].equals("-CAfile")) + { + if (i >= args.length-1 || ca_cert_index >= ca_cert_size) + { + print_server_options(build_mode, args[i]); + } + + ca_cert[ca_cert_index++] = args[++i]; + } + else if (build_mode == axtlsj.SSL_BUILD_FULL_MODE) + { + if (args[i].equals("-debug")) + { + options |= axtlsj.SSL_DISPLAY_BYTES; + } + else if (args[i].equals("-state")) + { + options |= axtlsj.SSL_DISPLAY_STATES; + } + else if (args[i].equals("-show-rsa")) + { + options |= axtlsj.SSL_DISPLAY_RSA; + } + else + print_server_options(build_mode, args[i]); + } + else + print_server_options(build_mode, args[i]); + } + else + print_server_options(build_mode, args[i]); + } + else + print_server_options(build_mode, args[i]); + + i++; + } + + /* Create socket for incoming connections */ + ServerSocket server_sock = new ServerSocket(port); + + /********************************************************************** + * This is where the interesting stuff happens. Up until now we've + * just been setting up sockets etc. Now we do the SSL handshake. + **********************************************************************/ + SSLServer ssl_ctx = new SSLServer(options, + axtlsj.SSL_DEFAULT_SVR_SESS); + + if (ssl_ctx == null) + throw new Exception("Error: Server context is invalid"); + + if (private_key_file != null) + { + int obj_type = axtlsj.SSL_OBJ_RSA_KEY; + + if (private_key_file.endsWith(".p8")) + obj_type = axtlsj.SSL_OBJ_PKCS8; + else if (private_key_file.endsWith(".p12")) + obj_type = axtlsj.SSL_OBJ_PKCS12; + + if (ssl_ctx.objLoad(obj_type, + private_key_file, password) != axtlsj.SSL_OK) + { + throw new Exception("Error: Private key '" + private_key_file + + "' is undefined."); + } + } + + for (i = 0; i < cert_index; i++) + { + if (ssl_ctx.objLoad(axtlsj.SSL_OBJ_X509_CERT, + cert[i], null) != axtlsj.SSL_OK) + { + throw new Exception("Certificate '" + cert[i] + + "' is undefined."); + } + } + + for (i = 0; i < ca_cert_index; i++) + { + if (ssl_ctx.objLoad(axtlsj.SSL_OBJ_X509_CACERT, + ca_cert[i], null) != axtlsj.SSL_OK) + { + throw new Exception("Certificate '" + ca_cert[i] + + "' is undefined."); + } + } + + int res; + SSLReadHolder rh = new SSLReadHolder(); + + for (;;) + { + if (!quiet) + { + System.out.println("ACCEPT"); + } + + Socket client_sock = server_sock.accept(); + + SSL ssl = ssl_ctx.connect(client_sock); + + while ((res = ssl_ctx.read(ssl, rh)) == axtlsj.SSL_OK) + { + /* check when the connection has been established */ + if (ssl.handshakeStatus() == axtlsj.SSL_OK) + break; + + /* could do something else here */ + } + + if (res == axtlsj.SSL_OK) /* connection established and ok */ + { + if (!quiet) + { + display_session_id(ssl); + display_cipher(ssl); + } + + /* now read (and display) whatever the client sends us */ + for (;;) + { + /* keep reading until we get something interesting */ + while ((res = ssl_ctx.read(ssl, rh)) == axtlsj.SSL_OK) + { + /* could do something else here */ + } + + if (res < axtlsj.SSL_OK) + { + if (!quiet) + { + System.out.println("CONNECTION CLOSED"); + } + + break; + } + + /* convert to String */ + byte[] buf = rh.getData(); + char[] str = new char[res]; + + for (i = 0; i < res; i++) + { + str[i] = (char)buf[i]; + } + + System.out.print(str); + } + } + else if (!quiet) + { + SSLUtil.displayError(res); + } + + /* client was disconnected or the handshake failed. */ + ssl.dispose(); + client_sock.close(); + } + + /* ssl_ctx.dispose(); */ + } + + /* + * do_client() + */ + private void do_client(int build_mode, String[] args) + throws Exception + { + if (build_mode < axtlsj.SSL_BUILD_ENABLE_CLIENT) + print_client_options(build_mode, args[1]); + + int i = 1, res; + int port = 4433; + boolean quiet = false; + String password = null; + int reconnect = 0; + String private_key_file = null; + String hostname = "127.0.0.1"; + + /* organise the cert/ca_cert lists */ + int cert_index = 0; + int ca_cert_index = 0; + int cert_size = SSLUtil.maxCerts(); + int ca_cert_size = SSLUtil.maxCACerts(); + String[] cert = new String[cert_size]; + String[] ca_cert = new String[ca_cert_size]; + + int options = axtlsj.SSL_SERVER_VERIFY_LATER|axtlsj.SSL_DISPLAY_CERTS; + byte[] session_id = null; + + while (i < args.length) + { + if (args[i].equals("-connect")) + { + String host_port; + + if (i >= args.length-1) + { + print_client_options(build_mode, args[i]); + } + + host_port = args[++i]; + int index_colon; + + if ((index_colon = host_port.indexOf(':')) < 0) + print_client_options(build_mode, args[i]); + + hostname = new String(host_port.toCharArray(), + 0, index_colon); + port = Integer.parseInt(new String(host_port.toCharArray(), + index_colon+1, host_port.length()-index_colon-1)); + } + else if (args[i].equals("-cert")) + { + if (i >= args.length-1 || cert_index >= cert_size) + { + print_client_options(build_mode, args[i]); + } + + cert[cert_index++] = args[++i]; + } + else if (args[i].equals("-CAfile")) + { + if (i >= args.length-1 || ca_cert_index >= ca_cert_size) + { + print_client_options(build_mode, args[i]); + } + + ca_cert[ca_cert_index++] = args[++i]; + } + else if (args[i].equals("-key")) + { + if (i >= args.length-1) + { + print_client_options(build_mode, args[i]); + } + + private_key_file = args[++i]; + options |= axtlsj.SSL_NO_DEFAULT_KEY; + } + else if (args[i].equals("-verify")) + { + options &= ~(int)axtlsj.SSL_SERVER_VERIFY_LATER; + } + else if (args[i].equals("-reconnect")) + { + reconnect = 4; + } + else if (args[i].equals("-quiet")) + { + quiet = true; + options &= ~(int)axtlsj.SSL_DISPLAY_CERTS; + } + else if (args[i].equals("-pass")) + { + if (i >= args.length-1) + { + print_server_options(build_mode, args[i]); + } + + password = args[++i]; + } + else if (build_mode == axtlsj.SSL_BUILD_FULL_MODE) + { + if (args[i].equals("-debug")) + { + options |= axtlsj.SSL_DISPLAY_BYTES; + } + else if (args[i].equals("-state")) + { + options |= axtlsj.SSL_DISPLAY_STATES; + } + else if (args[i].equals("-show-rsa")) + { + options |= axtlsj.SSL_DISPLAY_RSA; + } + else + print_client_options(build_mode, args[i]); + } + else /* don't know what this is */ + print_client_options(build_mode, args[i]); + + i++; + } + + Socket client_sock = new Socket(hostname, port); + + if (!client_sock.isConnected()) + { + System.out.println("could not connect"); + throw new Exception(); + } + + if (!quiet) + { + System.out.println("CONNECTED"); + } + + /********************************************************************** + * This is where the interesting stuff happens. Up until now we've + * just been setting up sockets etc. Now we do the SSL handshake. + **********************************************************************/ + SSLClient ssl_ctx = new SSLClient(options, + axtlsj.SSL_DEFAULT_CLNT_SESS); + + if (ssl_ctx == null) + { + throw new Exception("Error: Client context is invalid"); + } + + if (private_key_file != null) + { + int obj_type = axtlsj.SSL_OBJ_RSA_KEY; + + if (private_key_file.endsWith(".p8")) + obj_type = axtlsj.SSL_OBJ_PKCS8; + else if (private_key_file.endsWith(".p12")) + obj_type = axtlsj.SSL_OBJ_PKCS12; + + if (ssl_ctx.objLoad(obj_type, + private_key_file, password) != axtlsj.SSL_OK) + { + throw new Exception("Error: Private key '" + private_key_file + + "' is undefined."); + } + } + + for (i = 0; i < cert_index; i++) + { + if (ssl_ctx.objLoad(axtlsj.SSL_OBJ_X509_CERT, + cert[i], null) != axtlsj.SSL_OK) + { + throw new Exception("Certificate '" + cert[i] + + "' is undefined."); + } + } + + for (i = 0; i < ca_cert_index; i++) + { + if (ssl_ctx.objLoad(axtlsj.SSL_OBJ_X509_CACERT, + ca_cert[i], null) != axtlsj.SSL_OK) + { + throw new Exception("Certificate '" + ca_cert[i] + + "' is undefined."); + } + } + + SSL ssl = null; + + /* Try session resumption? */ + if (reconnect > 0) + { + while (reconnect-- > 0) + { + ssl = ssl_ctx.connect(client_sock, session_id); + + if ((res = ssl.handshakeStatus()) != axtlsj.SSL_OK) + { + if (!quiet) + { + SSLUtil.displayError(res); + } + + ssl.dispose(); + throw new Exception(); + } + + display_session_id(ssl); + session_id = ssl.getSessionId(); + + if (reconnect > 0) + { + ssl.dispose(); + client_sock.close(); + + /* and reconnect */ + client_sock = new Socket(hostname, port); + } + } + } + else + { + ssl = ssl_ctx.connect(client_sock, null); + } + + /* check the return status */ + if ((res = ssl.handshakeStatus()) != axtlsj.SSL_OK) + { + if (!quiet) + { + SSLUtil.displayError(res); + } + + throw new Exception(); + } + + if (!quiet) + { + String common_name = + ssl.getCertificateDN(axtlsj.SSL_X509_CERT_COMMON_NAME); + + if (common_name != null) + { + System.out.println("Common Name:\t\t\t" + common_name); + } + + display_session_id(ssl); + display_cipher(ssl); + } + + BufferedReader in = new BufferedReader( + new InputStreamReader(System.in)); + + for (;;) + { + String user_input = in.readLine(); + + if (user_input == null) + break; + + byte[] buf = new byte[user_input.length()+2]; + buf[buf.length-2] = (byte)'\n'; /* add the carriage return */ + buf[buf.length-1] = 0; /* null terminate */ + + for (i = 0; i < buf.length-2; i++) + { + buf[i] = (byte)user_input.charAt(i); + } + + if ((res = ssl_ctx.write(ssl, buf)) < axtlsj.SSL_OK) + { + if (!quiet) + { + SSLUtil.displayError(res); + } + + break; + } + } + + ssl_ctx.dispose(); + } + + /** + * We've had some sort of command-line error. Print out the basic options. + */ + private void print_options(String option) + { + System.out.println("axssl: Error: '" + option + + "' is an invalid command."); + System.out.println("usage: axtlsj.jar [s_server|s_client|version] " + + "[args ...]"); + System.exit(1); + } + + /** + * We've had some sort of command-line error. Print out the server options. + */ + private void print_server_options(int build_mode, String option) + { + int cert_size = SSLUtil.maxCerts(); + int ca_cert_size = SSLUtil.maxCACerts(); + + System.out.println("unknown option " + option); + System.out.println("usage: s_server [args ...]"); + System.out.println(" -accept arg\t- port to accept on (default " + + "is 4433)"); + System.out.println(" -quiet\t\t- No server output"); + + if (build_mode >= axtlsj.SSL_BUILD_SERVER_ONLY) + { + System.out.println(" -cert arg\t- certificate file to add (in " + + "addition to default) to chain -"); + System.out.println("\t\t Can repeat up to " + cert_size + " times"); + System.out.println(" -key arg\t- Private key file to use"); + System.out.println(" -pass\t\t- private key file pass phrase source"); + } + + if (build_mode >= axtlsj.SSL_BUILD_ENABLE_VERIFICATION) + { + System.out.println(" -verify\t- turn on peer certificate " + + "verification"); + System.out.println(" -CAfile arg\t- Certificate authority. "); + System.out.println("\t\t Can repeat up to " + + ca_cert_size + " times"); + } + + if (build_mode == axtlsj.SSL_BUILD_FULL_MODE) + { + System.out.println(" -debug\t\t- Print more output"); + System.out.println(" -state\t\t- Show state messages"); + System.out.println(" -show-rsa\t- Show RSA state"); + } + + System.exit(1); + } + + /** + * We've had some sort of command-line error. Print out the client options. + */ + private void print_client_options(int build_mode, String option) + { + int cert_size = SSLUtil.maxCerts(); + int ca_cert_size = SSLUtil.maxCACerts(); + + System.out.println("unknown option " + option); + + if (build_mode >= axtlsj.SSL_BUILD_ENABLE_CLIENT) + { + System.out.println("usage: s_client [args ...]"); + System.out.println(" -connect host:port - who to connect to " + + "(default is localhost:4433)"); + System.out.println(" -verify\t- turn on peer certificate " + + "verification"); + System.out.println(" -cert arg\t- certificate file to use"); + System.out.println(" -key arg\t- Private key file to use"); + System.out.println("\t\t Can repeat up to " + cert_size + + " times"); + System.out.println(" -CAfile arg\t- Certificate authority."); + System.out.println("\t\t Can repeat up to " + ca_cert_size + + " times"); + System.out.println(" -quiet\t\t- No client output"); + System.out.println(" -pass\t\t- private key file pass " + + "phrase source"); + System.out.println(" -reconnect\t- Drop and re-make the " + + "connection with the same Session-ID"); + + if (build_mode == axtlsj.SSL_BUILD_FULL_MODE) + { + System.out.println(" -debug\t\t- Print more output"); + System.out.println(" -state\t\t- Show state messages"); + System.out.println(" -show-rsa\t- Show RSA state"); + } + } + else + { + System.out.println("Change configuration to allow this feature"); + } + + System.exit(1); + } + + /** + * Display what cipher we are using + */ + private void display_cipher(SSL ssl) + { + System.out.print("CIPHER is "); + + byte ciph_id = ssl.getCipherId(); + + if (ciph_id == axtlsj.SSL_AES128_SHA) + System.out.println("AES128-SHA"); + else if (ciph_id == axtlsj.SSL_AES256_SHA) + System.out.println("AES256-SHA"); + else if (ciph_id == axtlsj.SSL_AES128_SHA256) + System.out.println("AES128-SHA256"); + else if (ciph_id == axtlsj.SSL_AES256_SHA256) + System.out.println("AES256-SHA256"); + else + System.out.println("Unknown - " + ssl.getCipherId()); + } + + public char toHexChar(int i) + { + if ((0 <= i) && (i <= 9 )) + return (char)('0' + i); + else + return (char)('a' + (i-10)); + } + + public void bytesToHex(byte[] data) + { + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < data.length; i++ ) + { + buf.append(toHexChar((data[i]>>>4)&0x0F)); + buf.append(toHexChar(data[i]&0x0F)); + } + + System.out.println(buf); + } + + + /** + * Display what session id we have. + */ + private void display_session_id(SSL ssl) + { + byte[] session_id = ssl.getSessionId(); + + if (session_id.length > 0) + { + System.out.println("-----BEGIN SSL SESSION PARAMETERS-----"); + bytesToHex(session_id); + System.out.println("-----END SSL SESSION PARAMETERS-----"); + } + } +} diff --git a/tools/sdk/axtls/samples/lua/axssl.lua b/tools/sdk/axtls/samples/lua/axssl.lua new file mode 100755 index 0000000000..b4f24edf04 --- /dev/null +++ b/tools/sdk/axtls/samples/lua/axssl.lua @@ -0,0 +1,562 @@ +#!/usr/local/bin/lua + +-- +-- Copyright (c) 2007-2016, 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. +-- + +-- +-- Demonstrate the use of the axTLS library in Lua with a set of +-- command-line parameters similar to openssl. In fact, openssl clients +-- should be able to communicate with axTLS servers and visa-versa. +-- +-- This code has various bits enabled depending on the configuration. To enable +-- the most interesting version, compile with the 'full mode' enabled. +-- +-- To see what options you have, run the following: +-- > [lua] axssl s_server -? +-- > [lua] axssl s_client -? +-- +-- The axtls/axtlsl shared libraries must be in the same directory or be found +-- by the OS. +-- +-- +require "bit" +require("axtlsl") +local socket = require("socket") + +-- print version? +if #arg == 1 and arg[1] == "version" then + print("axssl.lua "..axtlsl.ssl_version()) + os.exit(1) +end + +-- +-- We've had some sort of command-line error. Print out the basic options. +-- +function print_options(option) + print("axssl: Error: '"..option.."' is an invalid command.") + print("usage: axssl [s_server|s_client|version] [args ...]") + os.exit(1) +end + +-- +-- We've had some sort of command-line error. Print out the server options. +-- +function print_server_options(build_mode, option) + local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET) + local ca_cert_size = axtlsl.ssl_get_config( + axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET) + + print("unknown option "..option) + print("usage: s_server [args ...]") + print(" -accept\t- port to accept on (default is 4433)") + print(" -quiet\t\t- No server output") + + if build_mode >= axtlsl.SSL_BUILD_SERVER_ONLY then + print(" -cert arg\t- certificate file to add (in addition to ".. + "default) to chain -") + print("\t\t Can repeat up to "..cert_size.." times") + print(" -key arg\t- Private key file to use - default DER format") + print(" -pass\t\t- private key file pass phrase source") + end + + if build_mode >= axtlsl.SSL_BUILD_ENABLE_VERIFICATION then + print(" -verify\t- turn on peer certificate verification") + print(" -CAfile arg\t- Certificate authority - default DER format") + print("\t\t Can repeat up to "..ca_cert_size.." times") + end + + if build_mode == axtlsl.SSL_BUILD_FULL_MODE then + print(" -debug\t\t- Print more output") + print(" -state\t\t- Show state messages") + print(" -show-rsa\t- Show RSA state") + end + + os.exit(1) +end + +-- +-- We've had some sort of command-line error. Print out the client options. +-- +function print_client_options(build_mode, option) + local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET) + local ca_cert_size = axtlsl.ssl_get_config( + axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET) + + print("unknown option "..option) + + if build_mode >= axtlsl.SSL_BUILD_ENABLE_CLIENT then + print("usage: s_client [args ...]") + print(" -connect host:port - who to connect to (default ".. + "is localhost:4433)") + print(" -verify\t- turn on peer certificate verification") + print(" -cert arg\t- certificate file to use - default DER format") + print(" -key arg\t- Private key file to use - default DER format") + print("\t\t Can repeat up to "..cert_size.." times") + print(" -CAfile arg\t- Certificate authority - default DER format") + print("\t\t Can repeat up to "..ca_cert_size.."times") + print(" -quiet\t\t- No client output") + print(" -pass\t\t- private key file pass phrase source") + print(" -reconnect\t- Drop and re-make the connection ".. + "with the same Session-ID") + + if build_mode == axtlsl.SSL_BUILD_FULL_MODE then + print(" -debug\t\t- Print more output") + print(" -state\t\t- Show state messages") + print(" -show-rsa\t- Show RSA state") + end + else + print("Change configuration to allow this feature") + end + + os.exit(1) +end + +-- Implement the SSL server logic. +function do_server(build_mode) + local i = 2 + local v + local port = 4433 + local options = axtlsl.SSL_DISPLAY_CERTS + local quiet = false + local password = "" + local private_key_file = nil + local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET) + local ca_cert_size = axtlsl. + ssl_get_config(axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET) + local cert = {} + local ca_cert = {} + + while i <= #arg do + if arg[i] == "-accept" then + if i >= #arg then + print_server_options(build_mode, arg[i]) + end + + i = i + 1 + port = arg[i] + elseif arg[i] == "-quiet" then + quiet = true + options = bit.band(options, bit.bnot(axtlsl.SSL_DISPLAY_CERTS)) + elseif build_mode >= axtlsl.SSL_BUILD_SERVER_ONLY then + if arg[i] == "-cert" then + if i >= #arg or #cert >= cert_size then + print_server_options(build_mode, arg[i]) + end + + i = i + 1 + table.insert(cert, arg[i]) + elseif arg[i] == "-key" then + if i >= #arg then + print_server_options(build_mode, arg[i]) + end + + i = i + 1 + private_key_file = arg[i] + options = bit.bor(options, axtlsl.SSL_NO_DEFAULT_KEY) + elseif arg[i] == "-pass" then + if i >= #arg then + print_server_options(build_mode, arg[i]) + end + + i = i + 1 + password = arg[i] + elseif build_mode >= axtlsl.SSL_BUILD_ENABLE_VERIFICATION then + if arg[i] == "-verify" then + options = bit.bor(options, axtlsl.SSL_CLIENT_AUTHENTICATION) + elseif arg[i] == "-CAfile" then + if i >= #arg or #ca_cert >= ca_cert_size then + print_server_options(build_mode, arg[i]) + end + + i = i + 1 + table.insert(ca_cert, arg[i]) + elseif build_mode == axtlsl.SSL_BUILD_FULL_MODE then + if arg[i] == "-debug" then + options = bit.bor(options, axtlsl.SSL_DISPLAY_BYTES) + elseif arg[i] == "-state" then + options = bit.bor(options, axtlsl.SSL_DISPLAY_STATES) + elseif arg[i] == "-show-rsa" then + options = bit.bor(options, axtlsl.SSL_DISPLAY_RSA) + else + print_server_options(build_mode, arg[i]) + end + else + print_server_options(build_mode, arg[i]) + end + else + print_server_options(build_mode, arg[i]) + end + else + print_server_options(build_mode, arg[i]) + end + + i = i + 1 + end + + -- Create socket for incoming connections + local server_sock = socket.try(socket.bind("*", port)) + + --------------------------------------------------------------------------- + -- This is where the interesting stuff happens. Up until now we've + -- just been setting up sockets etc. Now we do the SSL handshake. + --------------------------------------------------------------------------- + local ssl_ctx = axtlsl.ssl_ctx_new(options, axtlsl.SSL_DEFAULT_SVR_SESS) + if ssl_ctx == nil then error("Error: Server context is invalid") end + + if private_key_file ~= nil then + local obj_type = axtlsl.SSL_OBJ_RSA_KEY + + if string.find(private_key_file, ".p8") then + obj_type = axtlsl.SSL_OBJ_PKCS8 + end + + if string.find(private_key_file, ".p12") then + obj_type = axtlsl.SSL_OBJ_PKCS12 + end + + if axtlsl.ssl_obj_load(ssl_ctx, obj_type, private_key_file, + password) ~= axtlsl.SSL_OK then + error("Private key '" .. private_key_file .. "' is undefined.") + end + end + + for _, v in ipairs(cert) do + if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CERT, v, "") ~= + axtlsl.SSL_OK then + error("Certificate '"..v .. "' is undefined.") + end + end + + for _, v in ipairs(ca_cert) do + if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CACERT, v, "") ~= + axtlsl.SSL_OK then + error("Certificate '"..v .."' is undefined.") + end + end + + while true do + if not quiet then print("ACCEPT") end + local client_sock = server_sock:accept(); + local ssl = axtlsl.ssl_server_new(ssl_ctx, client_sock:getfd()) + + -- do the actual SSL handshake + local connected = false + local res + local buf + + while true do + socket.select({client_sock}, nil) + res, buf = axtlsl.ssl_read(ssl) + + if res == axtlsl.SSL_OK then -- connection established and ok + if axtlsl.ssl_handshake_status(ssl) == axtlsl.SSL_OK then + if not quiet and not connected then + display_session_id(ssl) + display_cipher(ssl) + end + connected = true + end + end + + if res > axtlsl.SSL_OK then + for _, v in ipairs(buf) do + io.write(string.format("%c", v)) + end + elseif res < axtlsl.SSL_OK then + if not quiet then + axtlsl.ssl_display_error(res) + end + break + end + end + + -- client was disconnected or the handshake failed. + print("CONNECTION CLOSED") + axtlsl.ssl_free(ssl) + client_sock:close() + end + + axtlsl.ssl_ctx_free(ssl_ctx) +end + +-- +-- Implement the SSL client logic. +-- +function do_client(build_mode) + local i = 2 + local v + local port = 4433 + local options = + bit.bor(axtlsl.SSL_SERVER_VERIFY_LATER, axtlsl.SSL_DISPLAY_CERTS) + local private_key_file = nil + local reconnect = 0 + local quiet = false + local password = "" + local session_id = {} + local host = "127.0.0.1" + local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET) + local ca_cert_size = axtlsl. + ssl_get_config(axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET) + local cert = {} + local ca_cert = {} + + while i <= #arg do + if arg[i] == "-connect" then + if i >= #arg then + print_client_options(build_mode, arg[i]) + end + + i = i + 1 + local t = string.find(arg[i], ":") + host = string.sub(arg[i], 1, t-1) + port = string.sub(arg[i], t+1) + elseif arg[i] == "-cert" then + if i >= #arg or #cert >= cert_size then + print_client_options(build_mode, arg[i]) + end + + i = i + 1 + table.insert(cert, arg[i]) + elseif arg[i] == "-key" then + if i >= #arg then + print_client_options(build_mode, arg[i]) + end + + i = i + 1 + private_key_file = arg[i] + options = bit.bor(options, axtlsl.SSL_NO_DEFAULT_KEY) + elseif arg[i] == "-CAfile" then + if i >= #arg or #ca_cert >= ca_cert_size then + print_client_options(build_mode, arg[i]) + end + + i = i + 1 + table.insert(ca_cert, arg[i]) + elseif arg[i] == "-verify" then + options = bit.band(options, + bit.bnot(axtlsl.SSL_SERVER_VERIFY_LATER)) + elseif arg[i] == "-reconnect" then + reconnect = 4 + elseif arg[i] == "-quiet" then + quiet = true + options = bit.band(options, bnot(axtlsl.SSL_DISPLAY_CERTS)) + elseif arg[i] == "-pass" then + if i >= #arg then + print_server_options(build_mode, arg[i]) + end + + i = i + 1 + password = arg[i] + elseif build_mode == axtlsl.SSL_BUILD_FULL_MODE then + if arg[i] == "-debug" then + options = bit.bor(options, axtlsl.SSL_DISPLAY_BYTES) + elseif arg[i] == "-state" then + options = bit.bor(axtlsl.SSL_DISPLAY_STATES) + elseif arg[i] == "-show-rsa" then + options = bit.bor(axtlsl.SSL_DISPLAY_RSA) + else -- don't know what this is + print_client_options(build_mode, arg[i]) + end + else -- don't know what this is + print_client_options(build_mode, arg[i]) + end + + i = i + 1 + end + + local client_sock = socket.try(socket.connect(host, port)) + local ssl + local res + + if not quiet then print("CONNECTED") end + + --------------------------------------------------------------------------- + -- This is where the interesting stuff happens. Up until now we've + -- just been setting up sockets etc. Now we do the SSL handshake. + --------------------------------------------------------------------------- + local ssl_ctx = axtlsl.ssl_ctx_new(options, axtlsl.SSL_DEFAULT_CLNT_SESS) + + if ssl_ctx == nil then + error("Error: Client context is invalid") + end + + if private_key_file ~= nil then + local obj_type = axtlsl.SSL_OBJ_RSA_KEY + + if string.find(private_key_file, ".p8") then + obj_type = axtlsl.SSL_OBJ_PKCS8 + end + + if string.find(private_key_file, ".p12") then + obj_type = axtlsl.SSL_OBJ_PKCS12 + end + + if axtlsl.ssl_obj_load(ssl_ctx, obj_type, private_key_file, + password) ~= axtlsl.SSL_OK then + error("Private key '"..private_key_file.."' is undefined.") + end + end + + for _, v in ipairs(cert) do + if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CERT, v, "") ~= + axtlsl.SSL_OK then + error("Certificate '"..v .. "' is undefined.") + end + end + + for _, v in ipairs(ca_cert) do + if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CACERT, v, "") ~= + axtlsl.SSL_OK then + error("Certificate '"..v .."' is undefined.") + end + end + + -- Try session resumption? + if reconnect ~= 0 then + local session_id = nil + local sess_id_size = 0 + + while reconnect > 0 do + reconnect = reconnect - 1 + ssl = axtlsl.ssl_client_new(ssl_ctx, + client_sock:getfd(), session_id, sess_id_size) + + res = axtlsl.ssl_handshake_status(ssl) + if res ~= axtlsl.SSL_OK then + if not quiet then axtlsl.ssl_display_error(res) end + axtlsl.ssl_free(ssl) + os.exit(1) + end + + display_session_id(ssl) + session_id = axtlsl.ssl_get_session_id(ssl) + sess_id_size = axtlsl.ssl_get_session_id_size(ssl) + + if reconnect > 0 then + axtlsl.ssl_free(ssl) + client_sock:close() + client_sock = socket.try(socket.connect(host, port)) + end + + end + else + ssl = axtlsl.ssl_client_new(ssl_ctx, client_sock:getfd(), nil, 0) + end + + -- check the return status + res = axtlsl.ssl_handshake_status(ssl) + if res ~= axtlsl.SSL_OK then + if not quiet then axtlsl.ssl_display_error(res) end + os.exit(1) + end + + if not quiet then + local common_name = axtlsl.ssl_get_cert_dn(ssl, + axtlsl.SSL_X509_CERT_COMMON_NAME) + + if common_name ~= nil then + print("Common Name:\t\t\t"..common_name) + end + + display_session_id(ssl) + display_cipher(ssl) + end + + while true do + local line = io.read() + if line == nil then break end + local bytes = {} + + for i = 1, #line do + bytes[i] = line.byte(line, i) + end + + bytes[#line+1] = 10 -- add carriage return, null + bytes[#line+2] = 0 + + res = axtlsl.ssl_write(ssl, bytes, #bytes) + if res < axtlsl.SSL_OK then + if not quiet then axtlsl.ssl_display_error(res) end + break + end + end + + axtlsl.ssl_ctx_free(ssl_ctx) + client_sock:close() +end + +-- +-- Display what cipher we are using +-- +function display_cipher(ssl) + io.write("CIPHER is ") + local cipher_id = axtlsl.ssl_get_cipher_id(ssl) + + if cipher_id == axtlsl.SSL_AES128_SHA then + print("AES128-SHA") + elseif cipher_id == axtlsl.SSL_AES256_SHA then + print("AES256-SHA") + elseif axtlsl.SSL_AES128_SHA256 then + print("AES128-SHA256") + elseif axtlsl.SSL_AES256_SHA256 then + print("AES256-SHA256") + else + print("Unknown - "..cipher_id) + end +end + +-- +-- Display what session id we have. +-- +function display_session_id(ssl) + local session_id = axtlsl.ssl_get_session_id(ssl) + local v + + if #session_id > 0 then + print("-----BEGIN SSL SESSION PARAMETERS-----") + for _, v in ipairs(session_id) do + io.write(string.format("%02x", v)) + end + print("\n-----END SSL SESSION PARAMETERS-----") + end +end + +-- +-- Main entry point. Doesn't do much except works out whether we are a client +-- or a server. +-- +if #arg == 0 or (arg[1] ~= "s_server" and arg[1] ~= "s_client") then + print_options(#arg > 0 and arg[1] or "") +end + +local build_mode = axtlsl.ssl_get_config(axtlsl.SSL_BUILD_MODE) +_ = arg[1] == "s_server" and do_server(build_mode) or do_client(build_mode) +os.exit(0) + diff --git a/tools/sdk/axtls/samples/perl/axssl.pl b/tools/sdk/axtls/samples/perl/axssl.pl new file mode 100755 index 0000000000..f3b044939c --- /dev/null +++ b/tools/sdk/axtls/samples/perl/axssl.pl @@ -0,0 +1,634 @@ +#!/usr/bin/perl -w +# +# Copyright (c) 2007-2016, 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. +# + +# +# Demonstrate the use of the axTLS library in Perl with a set of +# command-line parameters similar to openssl. In fact, openssl clients +# should be able to communicate with axTLS servers and visa-versa. +# +# This code has various bits enabled depending on the configuration. To enable +# the most interesting version, compile with the 'full mode' enabled. +# +# To see what options you have, run the following: +# > [perl] axssl s_server -? +# > [perl] axssl s_client -? +# +# The axtls/axtlsp shared libraries must be in the same directory or be found +# by the OS. axtlsp.pm must be in this directory or be in @INC. +# +# Under Win32, ActivePerl was used (see +# http://www.activestate.com/Products/ActivePerl/?mp=1) +# +use axtlsp; +use IO::Socket; + +# To get access to Win32 file descriptor stuff +my $is_win32 = 0; + +if ($^O eq "MSWin32") +{ + eval("use Win32API::File 0.08 qw( :ALL )"); + $is_win32 = 1; +} + +use strict; + +# +# Win32 has some problems with socket handles +# +sub get_native_sock +{ + my ($sock) = @_; + return $is_win32 ? FdGetOsFHandle($sock) : $sock; +} + +# print version? +if ($#ARGV == 0 && $ARGV[0] eq "version") +{ + printf("axssl.pl ".axtlsp::ssl_version()."\n"); + exit 0; +} + +# +# Main entry point. Doesn't do much except works out whether we are a client +# or a server. +# +print_options($#ARGV > -1 ? $ARGV[0] : "") + if ($#ARGV < 0 || ($ARGV[0] ne "s_server" && $ARGV[0] ne "s_client")); + + +# Cygwin/Win32 issue - flush our output continuously +select STDOUT; +local $|=1; + +my $build_mode = axtlsp::ssl_get_config($axtlsp::SSL_BUILD_MODE); +$ARGV[0] eq "s_server" ? do_server($build_mode) : do_client($build_mode); + +# +# Implement the SSL server logic. +# +sub do_server +{ + my ($build_mode) = @_; + my $i = 1; + my $port = 4433; + my $options = $axtlsp::SSL_DISPLAY_CERTS; + my $quiet = 0; + my $password = undef; + my $private_key_file = undef; + my $cert_size = axtlsp::ssl_get_config($axtlsp::SSL_MAX_CERT_CFG_OFFSET); + my $ca_cert_size = axtlsp::ssl_get_config( + $axtlsp::SSL_MAX_CA_CERT_CFG_OFFSET); + my @cert; + my @ca_cert; + + while ($i <= $#ARGV) + { + if ($ARGV[$i] eq "-accept") + { + print_server_options($build_mode, $ARGV[$i]) if $i >= $#ARGV; + $port = $ARGV[++$i]; + } + elsif ($ARGV[$i] eq "-quiet") + { + $quiet = 1; + $options &= ~$axtlsp::SSL_DISPLAY_CERTS; + } + elsif ($build_mode >= $axtlsp::SSL_BUILD_SERVER_ONLY) + { + if ($ARGV[$i] eq "-cert") + { + print_server_options($build_mode, $ARGV[$i]) + if $i >= $#ARGV || $#cert >= $cert_size-1; + + push @cert, $ARGV[++$i]; + } + elsif ($ARGV[$i] eq "-key") + { + print_server_options($build_mode, $ARGV[$i]) if $i >= $#ARGV; + $private_key_file = $ARGV[++$i]; + $options |= $axtlsp::SSL_NO_DEFAULT_KEY; + } + elsif ($ARGV[$i] eq "-pass") + { + print_server_options($build_mode, $ARGV[$i]) if $i >= $#ARGV; + $password = $ARGV[++$i]; + } + elsif ($build_mode >= $axtlsp::SSL_BUILD_ENABLE_VERIFICATION) + { + if ($ARGV[$i] eq "-verify") + { + $options |= $axtlsp::SSL_CLIENT_AUTHENTICATION; + } + elsif ($ARGV[$i] eq "-CAfile") + { + print_server_options($build_mode, $ARGV[$i]) + if $i >= $#ARGV || $#ca_cert >= $ca_cert_size-1; + push @ca_cert, $ARGV[++$i]; + } + elsif ($build_mode == $axtlsp::SSL_BUILD_FULL_MODE) + { + if ($ARGV[$i] eq "-debug") + { + $options |= $axtlsp::SSL_DISPLAY_BYTES; + } + elsif ($ARGV[$i] eq "-state") + { + $options |= $axtlsp::SSL_DISPLAY_STATES; + } + elsif ($ARGV[$i] eq "-show-rsa") + { + $options |= $axtlsp::SSL_DISPLAY_RSA; + } + else + { + print_server_options($build_mode, $ARGV[$i]); + } + } + else + { + print_server_options($build_mode, $ARGV[$i]); + } + } + else + { + print_server_options($build_mode, $ARGV[$i]); + } + } + else + { + print_server_options($build_mode, $ARGV[$i]); + } + + $i++; + } + + # Create socket for incoming connections + my $server_sock = IO::Socket::INET->new(Proto => 'tcp', + LocalPort => $port, + Listen => 1, + Reuse => 1) or die $!; + + ########################################################################### + # This is where the interesting stuff happens. Up until now we've + # just been setting up sockets etc. Now we do the SSL handshake. + ########################################################################### + my $ssl_ctx = axtlsp::ssl_ctx_new($options, $axtlsp::SSL_DEFAULT_SVR_SESS); + die "Error: Server context is invalid" if not defined $ssl_ctx; + + if (defined $private_key_file) + { + my $obj_type = $axtlsp::SSL_OBJ_RSA_KEY; + + $obj_type = $axtlsp::SSL_OBJ_PKCS8 if $private_key_file =~ /.p8$/; + $obj_type = $axtlsp::SSL_OBJ_PKCS12 if $private_key_file =~ /.p12$/; + + die "Private key '$private_key_file' is undefined." if + axtlsp::ssl_obj_load($ssl_ctx, $obj_type, + $private_key_file, $password); + } + + foreach (@cert) + { + die "Certificate '$_' is undefined." + if axtlsp::ssl_obj_load($ssl_ctx, $axtlsp::SSL_OBJ_X509_CERT, + $_, undef) != $axtlsp::SSL_OK; + } + + foreach (@ca_cert) + { + die "Certificate '$_' is undefined." + if axtlsp::ssl_obj_load($ssl_ctx, $axtlsp::SSL_OBJ_X509_CACERT, + $_, undef) != $axtlsp::SSL_OK; + } + + for (;;) + { + printf("ACCEPT\n") if not $quiet; + my $client_sock = $server_sock->accept; + my $native_sock = get_native_sock($client_sock->fileno); + + # This doesn't work in Win32 - need to get file descriptor from socket. + my $ssl = axtlsp::ssl_server_new($ssl_ctx, $native_sock); + + # do the actual SSL handshake + my $res; + my $buf; + my $connected = 0; + + while (1) + { + ($res, $buf) = axtlsp::ssl_read($ssl, undef); + last if $res < $axtlsp::SSL_OK; + + if ($res == $axtlsp::SSL_OK) # connection established and ok + { + if (axtlsp::ssl_handshake_status($ssl) == $axtlsp::SSL_OK) + { + if (!$quiet && !$connected) + { + display_session_id($ssl); + display_cipher($ssl); + } + + $connected = 1; + } + } + + if ($res > $axtlsp::SSL_OK) + { + printf($$buf); + } + elsif ($res < $axtlsp::SSL_OK) + { + axtlsp::ssl_display_error($res) if not $quiet; + last; + } + } + + # client was disconnected or the handshake failed. + printf("CONNECTION CLOSED\n") if not $quiet; + axtlsp::ssl_free($ssl); + $client_sock->close; + } + + axtlsp::ssl_ctx_free($ssl_ctx); +} + +# +# Implement the SSL client logic. +# +sub do_client +{ + my ($build_mode) = @_; + my $i = 1; + my $port = 4433; + my $options = $axtlsp::SSL_SERVER_VERIFY_LATER|$axtlsp::SSL_DISPLAY_CERTS; + my $private_key_file = undef; + my $reconnect = 0; + my $quiet = 0; + my $password = undef; + my @session_id; + my $host = "127.0.0.1"; + my @cert; + my @ca_cert; + my $cert_size = axtlsp::ssl_get_config( + $axtlsp::SSL_MAX_CERT_CFG_OFFSET); + my $ca_cert_size = axtlsp::ssl_get_config( + $axtlsp::SSL_MAX_CA_CERT_CFG_OFFSET); + + while ($i <= $#ARGV) + { + if ($ARGV[$i] eq "-connect") + { + print_client_options($build_mode, $ARGV[$i]) if $i >= $#ARGV; + ($host, $port) = split(':', $ARGV[++$i]); + } + elsif ($ARGV[$i] eq "-cert") + { + print_client_options($build_mode, $ARGV[$i]) + if $i >= $#ARGV || $#cert >= $cert_size-1; + + push @cert, $ARGV[++$i]; + } + elsif ($ARGV[$i] eq "-key") + { + print_client_options($build_mode, $ARGV[$i]) if $i >= $#ARGV; + $private_key_file = $ARGV[++$i]; + $options |= $axtlsp::SSL_NO_DEFAULT_KEY; + } + elsif ($ARGV[$i] eq "-CAfile") + { + print_client_options($build_mode, $ARGV[$i]) + if $i >= $#ARGV || $#ca_cert >= $ca_cert_size-1; + + push @ca_cert, $ARGV[++$i]; + } + elsif ($ARGV[$i] eq "-verify") + { + $options &= ~$axtlsp::SSL_SERVER_VERIFY_LATER; + } + elsif ($ARGV[$i] eq "-reconnect") + { + $reconnect = 4; + } + elsif ($ARGV[$i] eq "-quiet") + { + $quiet = 1; + $options &= ~$axtlsp::SSL_DISPLAY_CERTS; + } + elsif ($ARGV[$i] eq "-pass") + { + print_server_options($build_mode, $ARGV[$i]) if $i >= $#ARGV; + $password = $ARGV[++$i]; + } + elsif ($build_mode == $axtlsp::SSL_BUILD_FULL_MODE) + { + if ($ARGV[$i] eq "-debug") + { + $options |= $axtlsp::SSL_DISPLAY_BYTES; + } + elsif ($ARGV[$i] eq "-state") + { + $options |= $axtlsp::SSL_DISPLAY_STATES; + } + elsif ($ARGV[$i] eq "-show-rsa") + { + $options |= $axtlsp::SSL_DISPLAY_RSA; + } + else # don't know what this is + { + print_client_options($build_mode, $ARGV[$i]); + } + } + else # don't know what this is + { + print_client_options($build_mode, $ARGV[$i]); + } + + $i++; + } + + my $client_sock = new IO::Socket::INET ( + PeerAddr => $host, PeerPort => $port, Proto => 'tcp') + || die ("no socket: $!"); + my $ssl; + my $res; + my $native_sock = get_native_sock($client_sock->fileno); + + printf("CONNECTED\n") if not $quiet; + + ########################################################################### + # This is where the interesting stuff happens. Up until now we've + # just been setting up sockets etc. Now we do the SSL handshake. + ########################################################################### + my $ssl_ctx = axtlsp::ssl_ctx_new($options, $axtlsp::SSL_DEFAULT_CLNT_SESS); + die "Error: Client context is invalid" if not defined $ssl_ctx; + + if (defined $private_key_file) + { + my $obj_type = $axtlsp::SSL_OBJ_RSA_KEY; + + $obj_type = $axtlsp::SSL_OBJ_PKCS8 if $private_key_file =~ /.p8$/; + $obj_type = $axtlsp::SSL_OBJ_PKCS12 if $private_key_file =~ /.p12$/; + + die "Private key '$private_key_file' is undefined." if + axtlsp::ssl_obj_load($ssl_ctx, $obj_type, + $private_key_file, $password); + } + + foreach (@cert) + { + die "Certificate '$_' is undefined." + if axtlsp::ssl_obj_load($ssl_ctx, $axtlsp::SSL_OBJ_X509_CERT, + $_, undef) != $axtlsp::SSL_OK; + } + + foreach (@ca_cert) + { + die "Certificate '$_' is undefined." + if axtlsp::ssl_obj_load($ssl_ctx, $axtlsp::SSL_OBJ_X509_CACERT, + $_, undef) != $axtlsp::SSL_OK; + } + + # Try session resumption? + if ($reconnect) + { + my $session_id = undef; + my $sess_id_size = 0; + + while ($reconnect--) + { + $ssl = axtlsp::ssl_client_new($ssl_ctx, $native_sock, + $session_id, $sess_id_size); + + $res = axtlsp::ssl_handshake_status($ssl); + if ($res != $axtlsp::SSL_OK) + { + axtlsp::ssl_display_error($res) if !$quiet; + axtlsp::ssl_free($ssl); + exit 1; + } + + display_session_id($ssl); + $session_id = axtlsp::ssl_get_session_id($ssl); + + if ($reconnect) + { + axtlsp::ssl_free($ssl); + $client_sock->close; + $client_sock = new IO::Socket::INET ( + PeerAddr => $host, PeerPort => $port, Proto => 'tcp') + || die ("no socket: $!"); + + } + } + } + else + { + $ssl = axtlsp::ssl_client_new($ssl_ctx, $native_sock, undef, 0); + } + + # check the return status + $res = axtlsp::ssl_handshake_status($ssl); + if ($res != $axtlsp::SSL_OK) + { + axtlsp::ssl_display_error($res) if not $quiet; + exit 1; + } + + if (!$quiet) + { + my $common_name = axtlsp::ssl_get_cert_dn($ssl, + $axtlsp::SSL_X509_CERT_COMMON_NAME); + + printf("Common Name:\t\t\t%s\n", $common_name) if defined $common_name; + display_session_id($ssl); + display_cipher($ssl); + } + + while () + { + my $cstring = pack("a*x", $_); # add null terminator + $res = axtlsp::ssl_write($ssl, \$cstring, length($cstring)); + if ($res < $axtlsp::SSL_OK) + { + axtlsp::ssl_display_error($res) if not $quiet; + last; + } + } + + axtlsp::ssl_ctx_free($ssl_ctx); + $client_sock->close; +} + +# +# We've had some sort of command-line error. Print out the basic options. +# +sub print_options +{ + my ($option) = @_; + printf("axssl: Error: '%s' is an invalid command.\n", $option); + printf("usage: axssl [s_server|s_client|version] [args ...]\n"); + exit 1; +} + +# +# We've had some sort of command-line error. Print out the server options. +# +sub print_server_options +{ + my ($build_mode, $option) = @_; + my $cert_size = axtlsp::ssl_get_config($axtlsp::SSL_MAX_CERT_CFG_OFFSET); + my $ca_cert_size = axtlsp::ssl_get_config( + $axtlsp::SSL_MAX_CA_CERT_CFG_OFFSET); + + printf("unknown option %s\n", $option); + printf("usage: s_server [args ...]\n"); + printf(" -accept arg\t- port to accept on (default is 4433)\n"); + printf(" -quiet\t\t- No server output\n"); + + if ($build_mode >= $axtlsp::SSL_BUILD_SERVER_ONLY) + { + printf(" -cert arg\t- certificate file to add (in addition to default)". + " to chain -\n". + "\t\t Can repeat up to %d times\n", $cert_size); + printf(" -key arg\t- Private key file to use - default DER format\n"); + printf(" -pass\t\t- private key file pass phrase source\n"); + } + + if ($build_mode >= $axtlsp::SSL_BUILD_ENABLE_VERIFICATION) + { + printf(" -verify\t- turn on peer certificate verification\n"); + printf(" -CAfile arg\t- Certificate authority - default DER format\n"); + printf("\t\t Can repeat up to %d times\n", $ca_cert_size); + } + + if ($build_mode == $axtlsp::SSL_BUILD_FULL_MODE) + { + printf(" -debug\t\t- Print more output\n"); + printf(" -state\t\t- Show state messages\n"); + printf(" -show-rsa\t- Show RSA state\n"); + } + + exit 1; +} + +# +# We've had some sort of command-line error. Print out the client options. +# +sub print_client_options +{ + my ($build_mode, $option) = @_; + my $cert_size = axtlsp::ssl_get_config($axtlsp::SSL_MAX_CERT_CFG_OFFSET); + my $ca_cert_size = axtlsp::ssl_get_config( + $axtlsp::SSL_MAX_CA_CERT_CFG_OFFSET); + + printf("unknown option %s\n", $option); + + if ($build_mode >= $axtlsp::SSL_BUILD_ENABLE_CLIENT) + { + printf("usage: s_client [args ...]\n"); + printf(" -connect host:port - who to connect to (default ". + "is localhost:4433)\n"); + printf(" -verify\t- turn on peer certificate verification\n"); + printf(" -cert arg\t- certificate file to use - default DER format\n"); + printf(" -key arg\t- Private key file to use - default DER format\n"); + printf("\t\t Can repeat up to %d times\n", $cert_size); + printf(" -CAfile arg\t- Certificate authority - default DER format\n"); + printf("\t\t Can repeat up to %d times\n", $ca_cert_size); + printf(" -quiet\t\t- No client output\n"); + printf(" -pass\t\t- private key file pass phrase source\n"); + printf(" -reconnect\t- Drop and re-make the connection ". + "with the same Session-ID\n"); + + if ($build_mode == $axtlsp::SSL_BUILD_FULL_MODE) + { + printf(" -debug\t\t- Print more output\n"); + printf(" -state\t\t- Show state messages\n"); + printf(" -show-rsa\t- Show RSA state\n"); + } + } + else + { + printf("Change configuration to allow this feature\n"); + } + + exit 1; +} + +# +# Display what cipher we are using +# +sub display_cipher +{ + my ($ssl) = @_; + printf("CIPHER is "); + my $cipher_id = axtlsp::ssl_get_cipher_id($ssl); + + if ($cipher_id == $axtlsp::SSL_AES128_SHA) + { + printf("AES128-SHA"); + } + elsif ($cipher_id == $axtlsp::SSL_AES256_SHA) + { + printf("AES256-SHA"); + } + elsif ($axtlsp::SSL_AES128_SHA256) + { + printf("AES128-SHA256"); + } + elsif ($axtlsp::SSL_AES256_SHA256) + { + printf("AES256-SHA256"); + } + else + { + printf("Unknown - %d", $cipher_id); + } + + printf("\n"); +} + +# +# Display what session id we have. +# +sub display_session_id +{ + my ($ssl) = @_; + my $session_id = axtlsp::ssl_get_session_id($ssl); + if (length($$session_id) > 0) + { + printf("-----BEGIN SSL SESSION PARAMETERS-----\n"); + printf(unpack("H*", $$session_id)); + printf("\n-----END SSL SESSION PARAMETERS-----\n"); + } +} diff --git a/tools/sdk/axtls/samples/vbnet/axssl.vb b/tools/sdk/axtls/samples/vbnet/axssl.vb new file mode 100644 index 0000000000..7e5d68277e --- /dev/null +++ b/tools/sdk/axtls/samples/vbnet/axssl.vb @@ -0,0 +1,702 @@ +' +' Copyright (c) 2007-2016, 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. +' + +' +' Demonstrate the use of the axTLS library in VB.NET with a set of +' command-line parameters similar to openssl. In fact, openssl clients +' should be able to communicate with axTLS servers and visa-versa. +' +' This code has various bits enabled depending on the configuration. To enable +' the most interesting version, compile with the 'full mode' enabled. +' +' To see what options you have, run the following: +' > axssl.vbnet.exe s_server -? +' > axssl.vbnet.exe s_client -? +' +' The axtls shared library must be in the same directory or be found +' by the OS. +' + +Imports System +Imports System.Net +Imports System.Net.Sockets +Imports Microsoft.VisualBasic +Imports axTLSvb + +Public Class axssl + ' + ' do_server() + ' + Public Sub do_server(ByVal build_mode As Integer, _ + ByVal args() As String) + Dim i As Integer = 1 + Dim port As Integer = 4433 + Dim options As Integer = axtls.SSL_DISPLAY_CERTS + Dim quiet As Boolean = False + Dim password As String = Nothing + Dim private_key_file As String = Nothing + + ' organise the cert/ca_cert lists + Dim cert_size As Integer = SSLUtil.MaxCerts() + Dim ca_cert_size As Integer = SSLUtil.MaxCACerts() + Dim cert(cert_size) As String + Dim ca_cert(ca_cert_size) As String + Dim cert_index As Integer = 0 + Dim ca_cert_index As Integer = 0 + + While i < args.Length + If args(i) = "-accept" Then + If i >= args.Length-1 + print_server_options(build_mode, args(i)) + End If + + i += 1 + port = Int32.Parse(args(i)) + ElseIf args(i) = "-quiet" + quiet = True + options = options And Not axtls.SSL_DISPLAY_CERTS + ElseIf build_mode >= axtls.SSL_BUILD_SERVER_ONLY + If args(i) = "-cert" + If i >= args.Length-1 Or cert_index >= cert_size + print_server_options(build_mode, args(i)) + End If + + i += 1 + cert(cert_index) = args(i) + cert_index += 1 + ElseIf args(i) = "-key" + If i >= args.Length-1 + print_server_options(build_mode, args(i)) + End If + + i += 1 + private_key_file = args(i) + options = options Or axtls.SSL_NO_DEFAULT_KEY + ElseIf args(i) = "-pass" + If i >= args.Length-1 + print_server_options(build_mode, args(i)) + End If + + i += 1 + password = args(i) + ElseIf build_mode >= axtls.SSL_BUILD_ENABLE_VERIFICATION + If args(i) = "-verify" Then + options = options Or axtls.SSL_CLIENT_AUTHENTICATION + ElseIf args(i) = "-CAfile" + If i >= args.Length-1 Or _ + ca_cert_index >= ca_cert_size Then + print_server_options(build_mode, args(i)) + End If + + i += 1 + ca_cert(ca_cert_index) = args(i) + ca_cert_index += 1 + ElseIf build_mode = axtls.SSL_BUILD_FULL_MODE + If args(i) = "-debug" Then + options = options Or axtls.SSL_DISPLAY_BYTES + ElseIf args(i) = "-state" + options = options Or axtls.SSL_DISPLAY_STATES + ElseIf args(i) = "-show-rsa" + options = options Or axtls.SSL_DISPLAY_RSA + Else + print_server_options(build_mode, args(i)) + End If + Else + print_server_options(build_mode, args(i)) + End If + Else + print_server_options(build_mode, args(i)) + End If + End If + + i += 1 + End While + + ' Create socket for incoming connections + Dim ep As IPEndPoint = New IPEndPoint(IPAddress.Any, port) + Dim server_sock As TcpListener = New TcpListener(ep) + server_sock.Start() + + '********************************************************************* + ' This is where the interesting stuff happens. Up until now we've + ' just been setting up sockets etc. Now we do the SSL handshake. + '*********************************************************************/ + Dim ssl_ctx As SSLServer = New SSLServer(options, _ + axtls.SSL_DEFAULT_SVR_SESS) + + If ssl_ctx Is Nothing Then + Console.Error.WriteLine("Error: Server context is invalid") + Environment.Exit(1) + End If + + If private_key_file <> Nothing Then + Dim obj_type As Integer = axtls.SSL_OBJ_RSA_KEY + + If private_key_file.EndsWith(".p8") Then + obj_type = axtls.SSL_OBJ_PKCS8 + Else If (private_key_file.EndsWith(".p12")) + obj_type = axtls.SSL_OBJ_PKCS12 + End If + + If ssl_ctx.ObjLoad(obj_type, private_key_file, _ + password) <> axtls.SSL_OK Then + Console.Error.WriteLine("Error: Private key '" & _ + private_key_file & "' is undefined.") + Environment.Exit(1) + End If + End If + + For i = 0 To cert_index-1 + If ssl_ctx.ObjLoad(axtls.SSL_OBJ_X509_CERT, _ + cert(i), Nothing) <> axtls.SSL_OK Then + Console.WriteLine("Certificate '" & cert(i) & _ + "' is undefined.") + Environment.Exit(1) + End If + Next + + For i = 0 To ca_cert_index-1 + If ssl_ctx.ObjLoad(axtls.SSL_OBJ_X509_CACERT, _ + ca_cert(i), Nothing) <> axtls.SSL_OK Then + Console.WriteLine("Certificate '" & ca_cert(i) & _ + "' is undefined.") + Environment.Exit(1) + End If + Next + + Dim buf As Byte() = Nothing + Dim res As Integer + Dim ssl As SSL + + While 1 + If Not quiet Then + Console.WriteLine("ACCEPT") + End If + + Dim client_sock As Socket = server_sock.AcceptSocket() + + ssl = ssl_ctx.Connect(client_sock) + + ' do the actual SSL handshake + While 1 + res = ssl_ctx.Read(ssl, buf) + If res <> axtls.SSL_OK Then + Exit While + End If + + ' check when the connection has been established + If ssl.HandshakeStatus() = axtls.SSL_OK + Exit While + End If + + ' could do something else here + End While + + If res = axtls.SSL_OK Then ' connection established and ok + If Not quiet + display_session_id(ssl) + display_cipher(ssl) + End If + + ' now read (and display) whatever the client sends us + While 1 + ' keep reading until we get something interesting + While 1 + res = ssl_ctx.Read(ssl, buf) + If res <> axtls.SSL_OK Then + Exit While + End If + + ' could do something else here + End While + + If res < axtls.SSL_OK + If Not quiet + Console.WriteLine("CONNECTION CLOSED") + End If + + Exit While + End If + + ' convert to String + Dim str(res) As Char + For i = 0 To res-1 + str(i) = Chr(buf(i)) + Next + + Console.Write(str) + End While + ElseIf Not quiet + SSLUtil.DisplayError(res) + End If + + ' client was disconnected or the handshake failed. */ + ssl.Dispose() + client_sock.Close() + End While + + ssl_ctx.Dispose() + End Sub + + ' + ' do_client() + ' + Public Sub do_client(ByVal build_mode As Integer, _ + ByVal args() As String) + + If build_mode < axtls.SSL_BUILD_ENABLE_CLIENT Then + print_client_options(build_mode, args(1)) + End If + + Dim i As Integer = 1 + Dim res As Integer + Dim port As Integer = 4433 + Dim quiet As Boolean = False + Dim password As String = Nothing + Dim reconnect As Integer = 0 + Dim private_key_file As String = Nothing + Dim hostname As String = "127.0.0.1" + + ' organise the cert/ca_cert lists + Dim ssl As SSL = Nothing + Dim cert_size As Integer = SSLUtil.MaxCerts() + Dim ca_cert_size As Integer = SSLUtil.MaxCACerts() + Dim cert(cert_size) As String + Dim ca_cert(ca_cert_size) As String + Dim cert_index As Integer = 0 + Dim ca_cert_index As Integer = 0 + + Dim options As Integer = _ + axtls.SSL_SERVER_VERIFY_LATER Or axtls.SSL_DISPLAY_CERTS + Dim session_id As Byte() = Nothing + + While i < args.Length + If args(i) = "-connect" Then + Dim host_port As String + + If i >= args.Length-1 + print_client_options(build_mode, args(i)) + End If + + i += 1 + host_port = args(i) + + Dim index_colon As Integer = host_port.IndexOf(":"C) + If index_colon < 0 Then + print_client_options(build_mode, args(i)) + End If + + hostname = New String(host_port.ToCharArray(), _ + 0, index_colon) + port = Int32.Parse(New String(host_port.ToCharArray(), _ + index_colon+1, host_port.Length-index_colon-1)) + ElseIf args(i) = "-cert" + If i >= args.Length-1 Or cert_index >= cert_size Then + print_client_options(build_mode, args(i)) + End If + + i += 1 + cert(cert_index) = args(i) + cert_index += 1 + ElseIf args(i) = "-key" + If i >= args.Length-1 + print_client_options(build_mode, args(i)) + End If + + i += 1 + private_key_file = args(i) + options = options Or axtls.SSL_NO_DEFAULT_KEY + ElseIf args(i) = "-CAfile" + If i >= args.Length-1 Or ca_cert_index >= ca_cert_size + print_client_options(build_mode, args(i)) + End If + + i += 1 + ca_cert(ca_cert_index) = args(i) + ca_cert_index += 1 + ElseIf args(i) = "-verify" + options = options And Not axtls.SSL_SERVER_VERIFY_LATER + ElseIf args(i) = "-reconnect" + reconnect = 4 + ElseIf args(i) = "-quiet" + quiet = True + options = options And Not axtls.SSL_DISPLAY_CERTS + ElseIf args(i) = "-pass" + If i >= args.Length-1 + print_client_options(build_mode, args(i)) + End If + + i += 1 + password = args(i) + ElseIf build_mode = axtls.SSL_BUILD_FULL_MODE + If args(i) = "-debug" Then + options = options Or axtls.SSL_DISPLAY_BYTES + ElseIf args(i) = "-state" + options = options Or axtls.SSL_DISPLAY_STATES + ElseIf args(i) = "-show-rsa" + options = options Or axtls.SSL_DISPLAY_RSA + Else + print_client_options(build_mode, args(i)) + End If + Else ' don't know what this is + print_client_options(build_mode, args(i)) + End If + + i += 1 + End While + + 'Dim hostInfo As IPHostEntry = Dns.Resolve(hostname) + Dim hostInfo As IPHostEntry = Dns.GetHostEntry(hostname) + Dim addresses As IPAddress() = hostInfo.AddressList + Dim ep As IPEndPoint = New IPEndPoint(addresses(0), port) + Dim client_sock As Socket = New Socket(AddressFamily.InterNetwork, _ + SocketType.Stream, ProtocolType.Tcp) + client_sock.Connect(ep) + + If Not client_sock.Connected Then + Console.WriteLine("could not connect") + Environment.Exit(1) + End If + + If Not quiet Then + Console.WriteLine("CONNECTED") + End If + + '********************************************************************* + ' This is where the interesting stuff happens. Up until now we've + ' just been setting up sockets etc. Now we do the SSL handshake. + '*********************************************************************/ + Dim ssl_ctx As SSLClient = New SSLClient(options, _ + axtls.SSL_DEFAULT_CLNT_SESS) + + If ssl_ctx Is Nothing Then + Console.Error.WriteLine("Error: Client context is invalid") + Environment.Exit(1) + End If + + If private_key_file <> Nothing Then + Dim obj_type As Integer = axtls.SSL_OBJ_RSA_KEY + + If private_key_file.EndsWith(".p8") Then + obj_type = axtls.SSL_OBJ_PKCS8 + Else If (private_key_file.EndsWith(".p12")) + obj_type = axtls.SSL_OBJ_PKCS12 + End If + + If ssl_ctx.ObjLoad(obj_type, private_key_file, _ + password) <> axtls.SSL_OK Then + Console.Error.WriteLine("Error: Private key '" & _ + private_key_file & "' is undefined.") + Environment.Exit(1) + End If + End If + + For i = 0 To cert_index-1 + If ssl_ctx.ObjLoad(axtls.SSL_OBJ_X509_CERT, _ + cert(i), Nothing) <> axtls.SSL_OK Then + Console.WriteLine("Certificate '" & cert(i) & _ + "' is undefined.") + Environment.Exit(1) + End If + Next + + For i = 0 To ca_cert_index-1 + If ssl_ctx.ObjLoad(axtls.SSL_OBJ_X509_CACERT, _ + ca_cert(i), Nothing) <> axtls.SSL_OK Then + Console.WriteLine("Certificate '" & ca_cert(i) & _ + "' is undefined.") + Environment.Exit(1) + End If + Next + + ' Try session resumption? + If reconnect > 0 Then + While reconnect > 0 + reconnect -= 1 + ssl = ssl_ctx.Connect(client_sock, session_id) + + res = ssl.HandshakeStatus() + If res <> axtls.SSL_OK Then + If Not quiet Then + SSLUtil.DisplayError(res) + End If + + ssl.Dispose() + Environment.Exit(1) + End If + + display_session_id(ssl) + session_id = ssl.GetSessionId() + + If reconnect > 0 Then + ssl.Dispose() + client_sock.Close() + + ' and reconnect + client_sock = New Socket(AddressFamily.InterNetwork, _ + SocketType.Stream, ProtocolType.Tcp) + client_sock.Connect(ep) + End If + End While + Else + ssl = ssl_ctx.Connect(client_sock, Nothing) + End If + + ' check the return status + res = ssl.HandshakeStatus() + If res <> axtls.SSL_OK Then + If Not quiet Then + SSLUtil.DisplayError(res) + End If + + Environment.Exit(1) + End If + + If Not quiet Then + Dim common_name As String = _ + ssl.GetCertificateDN(axtls.SSL_X509_CERT_COMMON_NAME) + + If common_name <> Nothing + Console.WriteLine("Common Name:" & _ + ControlChars.Tab & ControlChars.Tab & _ + ControlChars.Tab & common_name) + End If + + display_session_id(ssl) + display_cipher(ssl) + End If + + While (1) + Dim user_input As String = Console.ReadLine() + + If user_input = Nothing Then + Exit While + End If + + Dim buf(user_input.Length+1) As Byte + buf(buf.Length-2) = Asc(ControlChars.Lf) ' add the carriage return + buf(buf.Length-1) = 0 ' null terminate + + For i = 0 To user_input.Length-1 + buf(i) = Asc(user_input.Chars(i)) + Next + + res = ssl_ctx.Write(ssl, buf, buf.Length) + If res < axtls.SSL_OK Then + If Not quiet Then + SSLUtil.DisplayError(res) + End If + + Exit While + End If + End While + + ssl_ctx.Dispose() + End Sub + + ' + ' Display what cipher we are using + ' + Private Sub display_cipher(ByVal ssl As SSL) + Console.Write("CIPHER is ") + + Select ssl.GetCipherId() + Case axtls.SSL_AES128_SHA + Console.WriteLine("AES128-SHA") + + Case axtls.SSL_AES256_SHA + Console.WriteLine("AES256-SHA") + + Case axtls.SSL_AES128_SHA256 + Console.WriteLine("AES128-SHA256") + + Case axtls.SSL_AES256_SHA256 + Console.WriteLine("AES256-SHA256") + + Case Else + Console.WriteLine("Unknown - " & ssl.GetCipherId()) + End Select + End Sub + + ' + ' Display what session id we have. + ' + Private Sub display_session_id(ByVal ssl As SSL) + Dim session_id As Byte() = ssl.GetSessionId() + + If session_id.Length > 0 Then + Console.WriteLine("-----BEGIN SSL SESSION PARAMETERS-----") + Dim b As Byte + For Each b In session_id + Console.Write("{0:x02}", b) + Next + + Console.WriteLine() + Console.WriteLine("-----END SSL SESSION PARAMETERS-----") + End If + End Sub + + ' + ' We've had some sort of command-line error. Print out the basic options. + ' + Public Sub print_options(ByVal options As String) + Console.WriteLine("axssl: Error: '" & options & _ + "' is an invalid command.") + Console.WriteLine("usage: axssl.vbnet [s_server|s_client|" & _ + "version] [args ...]") + Environment.Exit(1) + End Sub + + ' + ' We've had some sort of command-line error. Print out the server options. + ' + Private Sub print_server_options(ByVal build_mode As Integer, _ + ByVal options As String) + Dim cert_size As Integer = SSLUtil.MaxCerts() + Dim ca_cert_size As Integer = SSLUtil.MaxCACerts() + + Console.WriteLine("unknown option " & options) + Console.WriteLine("usage: s_server [args ...]") + Console.WriteLine(" -accept arg" & ControlChars.Tab & _ + "- port to accept on (default is 4433)") + Console.WriteLine(" -quiet" & ControlChars.Tab & ControlChars.Tab & _ + "- No server output") + If build_mode >= axtls.SSL_BUILD_SERVER_ONLY + Console.WriteLine(" -cert arg" & ControlChars.Tab & _ + "- certificate file to add (in addition to default) to chain -") + Console.WriteLine(ControlChars.Tab & ControlChars.Tab & _ + " Can repeat up to " & cert_size & " times") + Console.WriteLine(" -key arg" & ControlChars.Tab & _ + "- Private key file to use") + Console.WriteLine(" -pass" & ControlChars.Tab & ControlChars.Tab & _ + "- private key file pass phrase source") + End If + + If build_mode >= axtls.SSL_BUILD_ENABLE_VERIFICATION + Console.WriteLine(" -verify" & ControlChars.Tab & _ + "- turn on peer certificate verification") + Console.WriteLine(" -CAfile arg" & ControlChars.Tab & _ + "- Certificate authority") + Console.WriteLine(ControlChars.Tab & ControlChars.Tab & _ + " Can repeat up to " & ca_cert_size & " times") + End If + + If build_mode = axtls.SSL_BUILD_FULL_MODE + Console.WriteLine(" -debug" & _ + ControlChars.Tab & ControlChars.Tab & _ + "- Print more output") + Console.WriteLine(" -state" & _ + ControlChars.Tab & ControlChars.Tab & _ + "- Show state messages") + Console.WriteLine(" -show-rsa" & _ + ControlChars.Tab & "- Show RSA state") + End If + + Environment.Exit(1) + End Sub + + ' + ' We've had some sort of command-line error. Print out the client options. + ' + Private Sub print_client_options(ByVal build_mode As Integer, _ + ByVal options As String) + Dim cert_size As Integer = SSLUtil.MaxCerts() + Dim ca_cert_size As Integer = SSLUtil.MaxCACerts() + + Console.WriteLine("unknown option " & options) + + If build_mode >= axtls.SSL_BUILD_ENABLE_CLIENT Then + Console.WriteLine("usage: s_client [args ...]") + Console.WriteLine(" -connect host:port - who to connect to " & _ + "(default is localhost:4433)") + Console.WriteLine(" -verify" & ControlChars.Tab & _ + "- turn on peer certificate verification") + Console.WriteLine(" -cert arg" & ControlChars.Tab & _ + "- certificate file to use") + Console.WriteLine(ControlChars.Tab & ControlChars.Tab & _ + " Can repeat up to " & cert_size & " times") + Console.WriteLine(" -key arg" & ControlChars.Tab & _ + "- Private key file to use") + Console.WriteLine(" -CAfile arg" & ControlChars.Tab & _ + "- Certificate authority") + Console.WriteLine(ControlChars.Tab & ControlChars.Tab & _ + " Can repeat up to " & ca_cert_size & " times") + Console.WriteLine(" -quiet" & _ + ControlChars.Tab & ControlChars.Tab & "- No client output") + Console.WriteLine(" -pass" & ControlChars.Tab & _ + ControlChars.Tab & _ + "- private key file pass phrase source") + Console.WriteLine(" -reconnect" & ControlChars.Tab & _ + "- Drop and re-make the " & _ + "connection with the same Session-ID") + + If build_mode = axtls.SSL_BUILD_FULL_MODE Then + Console.WriteLine(" -debug" & _ + ControlChars.Tab & ControlChars.Tab & _ + "- Print more output") + Console.WriteLine(" -state" & _ + ControlChars.Tab & ControlChars.Tab & _ + "- Show state messages") + Console.WriteLine(" -show-rsa" & ControlChars.Tab & _ + "- Show RSA state") + End If + Else + Console.WriteLine("Change configuration to allow this feature") + End If + + Environment.Exit(1) + End Sub + +End Class + +Public Module MyMain + Function Main(ByVal args() As String) As Integer + Dim runner As axssl = New axssl() + + If args.Length = 1 And args(0) = "version" Then + Console.WriteLine("axssl.vbnet " & SSLUtil.Version()) + Environment.Exit(0) + End If + + If args.Length < 1 + runner.print_options("") + ElseIf args(0) <> "s_server" And args(0) <> "s_client" + runner.print_options(args(0)) + End If + + Dim build_mode As Integer = SSLUtil.BuildMode() + + If args(0) = "s_server" Then + runner.do_server(build_mode, args) + Else + runner.do_client(build_mode, args) + End If + End Function +End Module diff --git a/tools/sdk/axtls/ssl/asn1.c b/tools/sdk/axtls/ssl/asn1.c new file mode 100644 index 0000000000..b53562cd9e --- /dev/null +++ b/tools/sdk/axtls/ssl/asn1.c @@ -0,0 +1,782 @@ +/* + * Copyright (c) 2007-2016, 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. + */ + +/** + * Some primitive asn methods for extraction ASN.1 data. + */ + +#include +#include +#include +#include +#include "os_port.h" +#include "crypto.h" +#include "crypto_misc.h" + +/* 1.2.840.113549.1.1 OID prefix - handle the following */ +/* md5WithRSAEncryption(4) */ +/* sha1WithRSAEncryption(5) */ +/* sha256WithRSAEncryption (11) */ +/* sha384WithRSAEncryption (12) */ +/* sha512WithRSAEncryption (13) */ +static const uint8_t sig_oid_prefix[] = +{ + 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01 +}; + +/* 1.3.14.3.2.29 SHA1 with RSA signature */ +static const uint8_t sig_sha1WithRSAEncrypt[] = +{ + 0x2b, 0x0e, 0x03, 0x02, 0x1d +}; + +/* 2.16.840.1.101.3.4.2.1 SHA-256 */ +static const uint8_t sig_sha256[] = +{ + 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01 +}; + +/* 2.16.840.1.101.3.4.2.2 SHA-384 */ +static const uint8_t sig_sha384[] = +{ + 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02 +}; + +/* 2.16.840.1.101.3.4.2.3 SHA-512 */ +static const uint8_t sig_sha512[] = +{ + 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03 +}; + +static const uint8_t sig_subject_alt_name[] = +{ + 0x55, 0x1d, 0x11 +}; + +static const uint8_t sig_basic_constraints[] = +{ + 0x55, 0x1d, 0x13 +}; + +static const uint8_t sig_key_usage[] = +{ + 0x55, 0x1d, 0x0f +}; + +/* CN, O, OU, L, C, ST */ +static const uint8_t g_dn_types[] = { 3, 10, 11, 7, 6, 8 }; + +uint32_t get_asn1_length(const uint8_t *buf, int *offset) +{ + int i; + uint32_t len; + + if (!(buf[*offset] & 0x80)) /* short form */ + { + len = buf[(*offset)++]; + } + else /* long form */ + { + int length_bytes = buf[(*offset)++]&0x7f; + if (length_bytes > 4) /* limit number of bytes */ + return 0; + + len = 0; + for (i = 0; i < length_bytes; i++) + { + len <<= 8; + len += buf[(*offset)++]; + } + } + + return len; +} + +/** + * Skip the ASN1.1 object type and its length. Get ready to read the object's + * data. + */ +int asn1_next_obj(const uint8_t *buf, int *offset, int obj_type) +{ + if (buf[*offset] != obj_type) + return X509_NOT_OK; + + (*offset)++; + return get_asn1_length(buf, offset); +} + +/** + * Skip over an ASN.1 object type completely. Get ready to read the next + * object. + */ +int asn1_skip_obj(const uint8_t *buf, int *offset, int obj_type) +{ + int len; + + if (buf[*offset] != obj_type) + return X509_NOT_OK; + (*offset)++; + len = get_asn1_length(buf, offset); + *offset += len; + return 0; +} + +/** + * Read an integer value for ASN.1 data + * Note: This function allocates memory which must be freed by the user. + */ +int asn1_get_big_int(const uint8_t *buf, int *offset, uint8_t **object) +{ + int len; + + if ((len = asn1_next_obj(buf, offset, ASN1_INTEGER)) < 0) + goto end_big_int; + + if (len > 1 && buf[*offset] == 0x00) /* ignore the negative byte */ + { + len--; + (*offset)++; + } + + *object = (uint8_t *)malloc(len); + memcpy(*object, &buf[*offset], len); + *offset += len; + +end_big_int: + return len; +} + +/** + * Read an integer value for ASN.1 data + */ +int asn1_get_int(const uint8_t *buf, int *offset, int32_t *val) +{ + int res = X509_OK; + int len; + int i; + + if ((len = asn1_next_obj(buf, offset, ASN1_INTEGER)) < 0 || + len > sizeof(int32_t)) + { + res = X509_NOT_OK; + goto end_int; + } + + *val = 0; + for (i = 0; i < len; i++) + { + *val <<= 8; + *val |= buf[(*offset)++]; + } + +end_int: + return res; +} + +/** + * Read an boolean value for ASN.1 data + */ +int asn1_get_bool(const uint8_t *buf, int *offset, bool *val) +{ + int res = X509_OK; + + if (asn1_next_obj(buf, offset, ASN1_BOOLEAN) != 1) + { + res = X509_NOT_OK; + goto end_bool; + } + + /* DER demands that "If the encoding represents the boolean value TRUE, + its single contents octet shall have all eight bits set to one." + Thus only 0 and 255 are valid encoded values. */ + *val = buf[(*offset)++] == 0xFF; + +end_bool: + return res; +} + +/** + * Convert an ASN.1 bit string into a 32 bit integer. Used for key usage + */ +int asn1_get_bit_string_as_int(const uint8_t *buf, int *offset, uint32_t *val) +{ + int res = X509_OK; + int len, i; + int ignore_bits; + + if ((len = asn1_next_obj(buf, offset, ASN1_BIT_STRING)) < 0 || len > 5) + { + res = X509_NOT_OK; + goto end_bit_string_as_int; + } + + /* number of bits left unused in the final byte of content */ + ignore_bits = buf[(*offset)++]; + len--; + *val = 0; + + /* not sure why key usage doesn't used proper DER spec version */ + for (i = len-1; i >= 0; --i) + { + *val <<= 8; + *val |= buf[(*offset) + i]; + } + + *offset += len; + + /*for (i = 0; i < ignore_bits; i++) + { + *val >>= 1; + }*/ + +end_bit_string_as_int: + return res; +} + +/** + * Get all the RSA private key specifics from an ASN.1 encoded file + */ +int asn1_get_private_key(const uint8_t *buf, int len, RSA_CTX **rsa_ctx) +{ + int offset = 7; + uint8_t *modulus = NULL, *priv_exp = NULL, *pub_exp = NULL; + int mod_len, priv_len, pub_len; +#ifdef CONFIG_BIGINT_CRT + uint8_t *p = NULL, *q = NULL, *dP = NULL, *dQ = NULL, *qInv = NULL; + int p_len, q_len, dP_len, dQ_len, qInv_len; +#endif + + /* not in der format */ + if (buf[0] != ASN1_SEQUENCE) /* basic sanity check */ + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: This is not a valid ASN.1 file\n"); +#endif + return X509_INVALID_PRIV_KEY; + } + + /* Use the private key to mix up the RNG if possible. */ + RNG_custom_init(buf, len); + + mod_len = asn1_get_big_int(buf, &offset, &modulus); + pub_len = asn1_get_big_int(buf, &offset, &pub_exp); + priv_len = asn1_get_big_int(buf, &offset, &priv_exp); + + if (mod_len <= 0 || pub_len <= 0 || priv_len <= 0) + return X509_INVALID_PRIV_KEY; + +#ifdef CONFIG_BIGINT_CRT + p_len = asn1_get_big_int(buf, &offset, &p); + q_len = asn1_get_big_int(buf, &offset, &q); + dP_len = asn1_get_big_int(buf, &offset, &dP); + dQ_len = asn1_get_big_int(buf, &offset, &dQ); + qInv_len = asn1_get_big_int(buf, &offset, &qInv); + + if (p_len <= 0 || q_len <= 0 || dP_len <= 0 || dQ_len <= 0 || qInv_len <= 0) + return X509_INVALID_PRIV_KEY; + + RSA_priv_key_new(rsa_ctx, + modulus, mod_len, pub_exp, pub_len, priv_exp, priv_len, + p, p_len, q, p_len, dP, dP_len, dQ, dQ_len, qInv, qInv_len); + + free(p); + free(q); + free(dP); + free(dQ); + free(qInv); +#else + RSA_priv_key_new(rsa_ctx, + modulus, mod_len, pub_exp, pub_len, priv_exp, priv_len); +#endif + + free(modulus); + free(priv_exp); + free(pub_exp); + return X509_OK; +} + +/** + * Get the time of a certificate. Ignore hours/minutes/seconds. + */ +static int asn1_get_utc_time(const uint8_t *buf, int *offset, time_t *t) +{ + int ret = X509_NOT_OK, len, t_offset, abs_year; + struct tm tm; + + /* see http://tools.ietf.org/html/rfc5280#section-4.1.2.5 */ + if (buf[*offset] == ASN1_UTC_TIME) + { + (*offset)++; + + len = get_asn1_length(buf, offset); + t_offset = *offset; + + memset(&tm, 0, sizeof(struct tm)); + tm.tm_year = (buf[t_offset] - '0')*10 + (buf[t_offset+1] - '0'); + + if (tm.tm_year < 50) /* 1951-2050 thing */ + { + tm.tm_year += 100; + } + + tm.tm_mon = (buf[t_offset+2] - '0')*10 + (buf[t_offset+3] - '0') - 1; + tm.tm_mday = (buf[t_offset+4] - '0')*10 + (buf[t_offset+5] - '0'); + tm.tm_hour = (buf[t_offset+6] - '0')*10 + (buf[t_offset+7] - '0'); + tm.tm_min = (buf[t_offset+8] - '0')*10 + (buf[t_offset+9] - '0'); + tm.tm_sec = (buf[t_offset+10] - '0')*10 + (buf[t_offset+11] - '0'); + *t = mktime(&tm); + *offset += len; + ret = X509_OK; + } + else if (buf[*offset] == ASN1_GENERALIZED_TIME) + { + (*offset)++; + + len = get_asn1_length(buf, offset); + t_offset = *offset; + + memset(&tm, 0, sizeof(struct tm)); + abs_year = ((buf[t_offset] - '0')*1000 + + (buf[t_offset+1] - '0')*100 + (buf[t_offset+2] - '0')*10 + + (buf[t_offset+3] - '0')); + + if (abs_year <= 1901) + { + tm.tm_year = 1; + tm.tm_mon = 0; + tm.tm_mday = 1; + } + else + { + tm.tm_year = abs_year - 1900; + tm.tm_mon = (buf[t_offset+4] - '0')*10 + + (buf[t_offset+5] - '0') - 1; + tm.tm_mday = (buf[t_offset+6] - '0')*10 + (buf[t_offset+7] - '0'); + tm.tm_hour = (buf[t_offset+8] - '0')*10 + (buf[t_offset+9] - '0'); + tm.tm_min = (buf[t_offset+10] - '0')*10 + (buf[t_offset+11] - '0'); + tm.tm_sec = (buf[t_offset+12] - '0')*10 + (buf[t_offset+13] - '0'); + *t = mktime(&tm); + } + + *offset += len; + ret = X509_OK; + } + + return ret; +} + +/** + * Get the version type of a certificate + */ +int asn1_version(const uint8_t *cert, int *offset, int *val) +{ + (*offset) += 2; /* get past explicit tag */ + return asn1_get_int(cert, offset, val); +} + +/** + * Retrieve the notbefore and notafter certificate times. + */ +int asn1_validity(const uint8_t *cert, int *offset, X509_CTX *x509_ctx) +{ + return (asn1_next_obj(cert, offset, ASN1_SEQUENCE) < 0 || + asn1_get_utc_time(cert, offset, &x509_ctx->not_before) || + asn1_get_utc_time(cert, offset, &x509_ctx->not_after)); +} + +/** + * Get the components of a distinguished name + */ +static int asn1_get_oid_x520(const uint8_t *buf, int *offset) +{ + int dn_type = 0; + int len; + + if ((len = asn1_next_obj(buf, offset, ASN1_OID)) < 0) + goto end_oid; + + /* expect a sequence of 2.5.4.[x] where x is a one of distinguished name + components we are interested in. */ + if (len == 3 && buf[(*offset)++] == 0x55 && buf[(*offset)++] == 0x04) + dn_type = buf[(*offset)++]; + else + { + *offset += len; /* skip over it */ + } + +end_oid: + return dn_type; +} + +/** + * Obtain an ASN.1 printable string type. + */ +static int asn1_get_printable_str(const uint8_t *buf, int *offset, char **str) +{ + int len = X509_NOT_OK; + int asn1_type = buf[*offset]; + + /* some certs have this awful crud in them for some reason */ + if (asn1_type != ASN1_PRINTABLE_STR && + asn1_type != ASN1_PRINTABLE_STR2 && + asn1_type != ASN1_TELETEX_STR && + asn1_type != ASN1_IA5_STR && + asn1_type != ASN1_UNICODE_STR) + goto end_pnt_str; + + (*offset)++; + len = get_asn1_length(buf, offset); + + if (asn1_type == ASN1_UNICODE_STR) + { + int i; + *str = (char *)malloc(len/2+1); /* allow for null */ + + for (i = 0; i < len; i += 2) + (*str)[i/2] = buf[*offset + i + 1]; + + (*str)[len/2] = 0; /* null terminate */ + } + else + { + *str = (char *)malloc(len+1); /* allow for null */ + memcpy(*str, &buf[*offset], len); + (*str)[len] = 0; /* null terminate */ + } + + *offset += len; + +end_pnt_str: + return len; +} + +/** + * Get the subject name (or the issuer) of a certificate. + */ +int asn1_name(const uint8_t *cert, int *offset, char *dn[]) +{ + int ret = X509_NOT_OK; + int dn_type; + char *tmp; + + if (asn1_next_obj(cert, offset, ASN1_SEQUENCE) < 0) + goto end_name; + + while (asn1_next_obj(cert, offset, ASN1_SET) >= 0) + { + int i, found = 0; + + if (asn1_next_obj(cert, offset, ASN1_SEQUENCE) < 0 || + (dn_type = asn1_get_oid_x520(cert, offset)) < 0) + goto end_name; + + tmp = NULL; + + if (asn1_get_printable_str(cert, offset, &tmp) < 0) + { + free(tmp); + goto end_name; + } + + /* find the distinguished named type */ + for (i = 0; i < X509_NUM_DN_TYPES; i++) + { + if (dn_type == g_dn_types[i]) + { + if (dn[i] == NULL) + { + dn[i] = tmp; + found = 1; + break; + } + } + } + + if (found == 0) /* not found so get rid of it */ + { + free(tmp); + } + } + + ret = X509_OK; +end_name: + return ret; +} + +/** + * Read the modulus and public exponent of a certificate. + */ +int asn1_public_key(const uint8_t *cert, int *offset, X509_CTX *x509_ctx) +{ + int ret = X509_NOT_OK, mod_len, pub_len; + uint8_t *modulus = NULL, *pub_exp = NULL; + + if (asn1_next_obj(cert, offset, ASN1_SEQUENCE) < 0 || + asn1_skip_obj(cert, offset, ASN1_SEQUENCE) || + asn1_next_obj(cert, offset, ASN1_BIT_STRING) < 0) + goto end_pub_key; + + (*offset)++; /* ignore the padding bit field */ + + if (asn1_next_obj(cert, offset, ASN1_SEQUENCE) < 0) + goto end_pub_key; + + mod_len = asn1_get_big_int(cert, offset, &modulus); + pub_len = asn1_get_big_int(cert, offset, &pub_exp); + + RSA_pub_key_new(&x509_ctx->rsa_ctx, modulus, mod_len, pub_exp, pub_len); + + free(modulus); + free(pub_exp); + ret = X509_OK; + +end_pub_key: + return ret; +} + +#ifdef CONFIG_SSL_CERT_VERIFICATION +/** + * Read the signature of the certificate. + */ +int asn1_signature(const uint8_t *cert, int *offset, X509_CTX *x509_ctx) +{ + int ret = X509_NOT_OK; + + if (cert[(*offset)++] != ASN1_BIT_STRING) + goto end_sig; + + x509_ctx->sig_len = get_asn1_length(cert, offset)-1; + (*offset)++; /* ignore bit string padding bits */ + x509_ctx->signature = (uint8_t *)malloc(x509_ctx->sig_len); + memcpy(x509_ctx->signature, &cert[*offset], x509_ctx->sig_len); + *offset += x509_ctx->sig_len; + ret = X509_OK; + +end_sig: + return ret; +} + +/* + * Compare 2 distinguished name components for equality + * @return 0 if a match + */ +static int asn1_compare_dn_comp(const char *dn1, const char *dn2) +{ + int ret; + + if (dn1 == NULL && dn2 == NULL) + ret = 0; + else + ret = (dn1 && dn2) ? strcmp(dn1, dn2) : 1; + + return ret; +} + +/** + * Clean up all of the CA certificates. + */ +void remove_ca_certs(CA_CERT_CTX *ca_cert_ctx) +{ + int i = 0; + + if (ca_cert_ctx == NULL) + return; + + while (i < CONFIG_X509_MAX_CA_CERTS && ca_cert_ctx->cert[i]) + { + x509_free(ca_cert_ctx->cert[i]); + ca_cert_ctx->cert[i++] = NULL; + } + + free(ca_cert_ctx); +} + +/* + * Compare 2 distinguished names for equality + * @return 0 if a match + */ +int asn1_compare_dn(char * const dn1[], char * const dn2[]) +{ + int i; + + for (i = 0; i < X509_NUM_DN_TYPES; i++) + { + if (asn1_compare_dn_comp(dn1[i], dn2[i])) + return 1; + } + + return 0; /* all good */ +} + +int asn1_find_oid(const uint8_t* cert, int* offset, + const uint8_t* oid, int oid_length) +{ + int seqlen; + if ((seqlen = asn1_next_obj(cert, offset, ASN1_SEQUENCE))> 0) + { + int end = *offset + seqlen; + + while (*offset < end) + { + int type = cert[(*offset)++]; + int length = get_asn1_length(cert, offset); + int noffset = *offset + length; + + if (type == ASN1_SEQUENCE) + { + type = cert[(*offset)++]; + length = get_asn1_length(cert, offset); + + if (type == ASN1_OID && length == oid_length && + memcmp(cert + *offset, oid, oid_length) == 0) + { + *offset += oid_length; + return 1; + } + } + + *offset = noffset; + } + } + + return 0; +} + +int asn1_is_subject_alt_name(const uint8_t *cert, int offset) +{ + if (asn1_find_oid(cert, &offset, sig_subject_alt_name, + sizeof(sig_subject_alt_name))) + { + return offset; + } + + return 0; +} + +int asn1_is_basic_constraints(const uint8_t *cert, int offset) +{ + if (asn1_find_oid(cert, &offset, sig_basic_constraints, + sizeof(sig_basic_constraints))) + { + return offset; + } + + return 0; +} + +int asn1_is_key_usage(const uint8_t *cert, int offset) +{ + if (asn1_find_oid(cert, &offset, sig_key_usage, + sizeof(sig_key_usage))) + { + return offset; + } + + return 0; +} + +bool asn1_is_critical_ext(const uint8_t *buf, int *offset) +{ + /* critical is optional */ + bool res = false; + + if (asn1_next_obj(buf, offset, ASN1_BOOLEAN) == 1) + res = buf[(*offset)++] == 0xFF; + + return res; +} + +#endif /* CONFIG_SSL_CERT_VERIFICATION */ + +/** + * Read the signature type of the certificate. We only support RSA-MD5 and + * RSA-SHA1 signature types. + */ +int asn1_signature_type(const uint8_t *cert, + int *offset, X509_CTX *x509_ctx) +{ + int ret = X509_NOT_OK, len; + + if (cert[(*offset)++] != ASN1_OID) + goto end_check_sig; + + len = get_asn1_length(cert, offset); + + if (len == sizeof(sig_sha1WithRSAEncrypt) && + memcmp(sig_sha1WithRSAEncrypt, &cert[*offset], + sizeof(sig_sha1WithRSAEncrypt)) == 0) + { + x509_ctx->sig_type = SIG_TYPE_SHA1; + } + else if (len == sizeof(sig_sha256) && + memcmp(sig_sha256, &cert[*offset], + sizeof(sig_sha256)) == 0) + { + x509_ctx->sig_type = SIG_TYPE_SHA256; + } + else if (len == sizeof(sig_sha384) && + memcmp(sig_sha384, &cert[*offset], + sizeof(sig_sha384)) == 0) + { + x509_ctx->sig_type = SIG_TYPE_SHA384; + } + else if (len == sizeof(sig_sha512) && + memcmp(sig_sha512, &cert[*offset], + sizeof(sig_sha512)) == 0) + { + x509_ctx->sig_type = SIG_TYPE_SHA512; + } + else + { + if (memcmp(sig_oid_prefix, &cert[*offset], sizeof(sig_oid_prefix))) + { +#ifdef CONFIG_SSL_FULL_MODE + int i; + printf("invalid digest: "); + + for (i = 0; i < len; i++) + printf("%02x ", cert[*offset + i]); + + printf("\n"); +#endif + goto end_check_sig; /* unrecognised cert type */ + } + + x509_ctx->sig_type = cert[*offset + sizeof(sig_oid_prefix)]; + } + + *offset += len; + asn1_skip_obj(cert, offset, ASN1_NULL); /* if it's there */ + ret = X509_OK; + +end_check_sig: + return ret; +} + diff --git a/tools/sdk/axtls/ssl/cert.h b/tools/sdk/axtls/ssl/cert.h new file mode 100644 index 0000000000..40234b9b1c --- /dev/null +++ b/tools/sdk/axtls/ssl/cert.h @@ -0,0 +1,54 @@ +unsigned char default_certificate[] = { + 0x30, 0x82, 0x02, 0x58, 0x30, 0x82, 0x01, 0x40, 0x02, 0x09, 0x00, 0xa5, + 0x2a, 0xc8, 0x78, 0x87, 0xf2, 0xe7, 0xc5, 0x30, 0x0d, 0x06, 0x09, 0x2a, + 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x34, + 0x31, 0x32, 0x30, 0x30, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x29, 0x61, + 0x78, 0x54, 0x4c, 0x53, 0x20, 0x50, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, + 0x20, 0x44, 0x6f, 0x64, 0x67, 0x79, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, + 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6f, + 0x72, 0x69, 0x74, 0x79, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x36, 0x31, 0x32, + 0x33, 0x30, 0x32, 0x31, 0x30, 0x34, 0x32, 0x37, 0x5a, 0x17, 0x0d, 0x33, + 0x30, 0x30, 0x39, 0x30, 0x38, 0x32, 0x31, 0x30, 0x34, 0x32, 0x37, 0x5a, + 0x30, 0x2c, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, + 0x0d, 0x61, 0x78, 0x54, 0x4c, 0x53, 0x20, 0x50, 0x72, 0x6f, 0x6a, 0x65, + 0x63, 0x74, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, + 0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74, 0x30, 0x81, + 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, + 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81, 0x89, 0x02, + 0x81, 0x81, 0x00, 0xbd, 0x0f, 0xd4, 0x42, 0xa8, 0x74, 0x87, 0x54, 0xaa, + 0xb9, 0x3a, 0x1f, 0x8b, 0xce, 0xbd, 0xb7, 0x65, 0xfb, 0x40, 0x3d, 0xd0, + 0x11, 0x9a, 0x9c, 0xdc, 0x82, 0x7c, 0xea, 0xa8, 0x17, 0xe1, 0x74, 0xf3, + 0x05, 0x0e, 0x61, 0xc1, 0xc1, 0x78, 0x8a, 0xb2, 0xba, 0x15, 0x22, 0x5a, + 0xff, 0x9b, 0xb8, 0x7a, 0x2e, 0x0f, 0x88, 0xb7, 0x74, 0xde, 0x04, 0x99, + 0xa5, 0xa2, 0x99, 0x53, 0x8b, 0xad, 0x78, 0x5a, 0x31, 0xed, 0xbc, 0x01, + 0xe7, 0xdf, 0xe9, 0xec, 0x2f, 0xa0, 0x5d, 0x53, 0xf6, 0xe6, 0x8a, 0xa0, + 0xc8, 0x6d, 0x41, 0x45, 0x63, 0x23, 0xb3, 0xcf, 0x4e, 0x50, 0x1f, 0x28, + 0xdf, 0x36, 0xe2, 0x73, 0xdf, 0xd6, 0xa1, 0xb3, 0x46, 0x4f, 0x6e, 0xbb, + 0x0d, 0x9b, 0xef, 0xa8, 0xf9, 0x4c, 0xa5, 0x71, 0xa1, 0x88, 0xdd, 0x07, + 0xa9, 0x86, 0x0d, 0x3f, 0xcd, 0x99, 0x23, 0xa2, 0x84, 0x77, 0x0f, 0x02, + 0x03, 0x01, 0x00, 0x01, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, + 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, + 0x32, 0xe0, 0x3c, 0x6e, 0x21, 0xe6, 0xa6, 0xf4, 0xb8, 0x10, 0x9f, 0x8a, + 0xe6, 0x0b, 0x84, 0x4e, 0x2c, 0xe5, 0x14, 0xca, 0x56, 0x81, 0x3f, 0xc0, + 0x2c, 0xa3, 0x39, 0x89, 0x24, 0xce, 0xaf, 0x47, 0x2e, 0x19, 0x62, 0xb2, + 0xe4, 0x76, 0x91, 0x25, 0xbc, 0xe1, 0xa8, 0xee, 0x6a, 0x68, 0x3a, 0x77, + 0xb9, 0xb2, 0x62, 0x97, 0x0c, 0x25, 0x3c, 0x5e, 0x13, 0x48, 0x87, 0x80, + 0xa3, 0x91, 0xd9, 0x2e, 0xe6, 0x92, 0x2b, 0x1c, 0x52, 0x24, 0xb1, 0x77, + 0xc6, 0xf6, 0xde, 0xd8, 0x9b, 0xd9, 0x57, 0x37, 0x56, 0x68, 0x17, 0x32, + 0x66, 0x01, 0x08, 0x38, 0x08, 0x9a, 0xc1, 0x8c, 0x5e, 0x3f, 0xe7, 0xc9, + 0x44, 0xcb, 0x62, 0xb9, 0x48, 0xc7, 0x89, 0xa6, 0xff, 0x8e, 0x7d, 0x3d, + 0xe1, 0x46, 0x32, 0x9c, 0x13, 0x06, 0x9a, 0xd1, 0x17, 0xab, 0x3f, 0xa9, + 0x90, 0x04, 0x33, 0x2d, 0x3f, 0x81, 0x0a, 0xa5, 0x55, 0xce, 0xb6, 0x95, + 0x54, 0xad, 0xf1, 0x4f, 0xa2, 0xca, 0xc3, 0xf6, 0x25, 0x7b, 0x71, 0xd2, + 0x68, 0x85, 0xe9, 0x72, 0xb6, 0x99, 0x34, 0x6d, 0xe5, 0x5f, 0xf6, 0x74, + 0x1c, 0xb9, 0xa2, 0xda, 0x2b, 0x04, 0xff, 0x82, 0xc5, 0x09, 0x04, 0xc4, + 0xba, 0xbc, 0x82, 0x3e, 0xb4, 0x72, 0x18, 0x8e, 0x30, 0x68, 0x48, 0x4a, + 0x0d, 0xa7, 0x3d, 0xb5, 0xf4, 0x42, 0x3a, 0x97, 0x60, 0x7d, 0xa8, 0x61, + 0x8a, 0x9e, 0x98, 0xc4, 0x7e, 0x65, 0x99, 0xea, 0x7e, 0xca, 0x75, 0xe7, + 0xdb, 0x21, 0x5d, 0xce, 0x7c, 0x66, 0x3d, 0x7e, 0xdc, 0x14, 0xfe, 0x55, + 0x04, 0x97, 0xa8, 0x64, 0x12, 0xb4, 0xb5, 0x30, 0x48, 0x72, 0xbc, 0xdb, + 0xeb, 0x5b, 0x4f, 0xa6, 0xfb, 0x87, 0x01, 0x41, 0x91, 0xec, 0x98, 0x98, + 0xf1, 0x4b, 0x38, 0xa2, 0x40, 0xf1, 0x05, 0x90, 0xbb, 0x9b, 0x5d, 0x96, + 0xb1, 0x22, 0x6b, 0x50 +}; +unsigned int default_certificate_len = 604; diff --git a/tools/sdk/axtls/ssl/config.h b/tools/sdk/axtls/ssl/config.h new file mode 100644 index 0000000000..8731430703 --- /dev/null +++ b/tools/sdk/axtls/ssl/config.h @@ -0,0 +1,127 @@ +/* + * Automatically generated header file: don't edit + */ + +#define HAVE_DOT_CONFIG 1 +#undef CONFIG_PLATFORM_LINUX +#define CONFIG_PLATFORM_CYGWIN 1 +#undef CONFIG_PLATFORM_WIN32 + +/* + * General Configuration + */ +#define PREFIX "/usr/local" +#define CONFIG_DEBUG 1 +#undef CONFIG_STRIP_UNWANTED_SECTIONS +#undef CONFIG_VISUAL_STUDIO_7_0 +#undef CONFIG_VISUAL_STUDIO_8_0 +#undef CONFIG_VISUAL_STUDIO_10_0 +#define CONFIG_VISUAL_STUDIO_7_0_BASE "" +#define CONFIG_VISUAL_STUDIO_8_0_BASE "" +#define CONFIG_VISUAL_STUDIO_10_0_BASE "" +#define CONFIG_EXTRA_CFLAGS_OPTIONS "" +#define CONFIG_EXTRA_LDFLAGS_OPTIONS "" + +/* + * SSL Library + */ +#undef CONFIG_SSL_SERVER_ONLY +#define CONFIG_SSL_CERT_VERIFICATION +#undef CONFIG_SSL_ENABLE_CLIENT +#define CONFIG_SSL_FULL_MODE 1 +#undef CONFIG_SSL_SKELETON_MODE +#undef CONFIG_SSL_PROT_LOW +#define CONFIG_SSL_PROT_MEDIUM 1 +#undef CONFIG_SSL_PROT_HIGH +#undef CONFIG_SSL_USE_DEFAULT_KEY +#define CONFIG_SSL_PRIVATE_KEY_LOCATION "" +#define CONFIG_SSL_PRIVATE_KEY_PASSWORD "" +#define CONFIG_SSL_X509_CERT_LOCATION "" +#undef CONFIG_SSL_GENERATE_X509_CERT +#define CONFIG_SSL_X509_COMMON_NAME "" +#define CONFIG_SSL_X509_ORGANIZATION_NAME "" +#define CONFIG_SSL_X509_ORGANIZATION_UNIT_NAME "" +#undef CONFIG_SSL_ENABLE_V23_HANDSHAKE +#define CONFIG_SSL_HAS_PEM 1 +#undef CONFIG_SSL_USE_PKCS12 +#define CONFIG_SSL_EXPIRY_TIME 24 +#define CONFIG_X509_MAX_CA_CERTS 10 +#define CONFIG_SSL_MAX_CERTS 1 +#undef CONFIG_SSL_CTX_MUTEXING +#undef CONFIG_USE_DEV_URANDOM +#undef CONFIG_WIN32_USE_CRYPTO_LIB +#undef CONFIG_OPENSSL_COMPATIBLE +#undef CONFIG_PERFORMANCE_TESTING +#define CONFIG_SSL_TEST 1 +#undef CONFIG_AXTLSWRAP +#define CONFIG_AXHTTPD 1 + +/* + * Axhttpd Configuration + */ +#undef CONFIG_HTTP_STATIC_BUILD +#define CONFIG_HTTP_PORT 80 +#define CONFIG_HTTP_HTTPS_PORT 443 +#define CONFIG_HTTP_SESSION_CACHE_SIZE 5 +#define CONFIG_HTTP_WEBROOT "../www" +#define CONFIG_HTTP_TIMEOUT 300 + +/* + * CGI + */ +#undef CONFIG_HTTP_HAS_CGI +#define CONFIG_HTTP_CGI_EXTENSIONS ".lua,.lp,.php" +#define CONFIG_HTTP_ENABLE_LUA 1 +#define CONFIG_HTTP_LUA_PREFIX "/usr" +#undef CONFIG_HTTP_BUILD_LUA +#define CONFIG_HTTP_CGI_LAUNCHER "/usr/bin/cgi" +#define CONFIG_HTTP_DIRECTORIES 1 +#define CONFIG_HTTP_HAS_AUTHORIZATION 1 +#undef CONFIG_HTTP_HAS_IPV6 +#undef CONFIG_HTTP_ENABLE_DIFFERENT_USER +#define CONFIG_HTTP_USER "" +#define CONFIG_HTTP_VERBOSE 0 +#undef CONFIG_HTTP_IS_DAEMON + +/* + * Language Bindings + */ +#undef CONFIG_BINDINGS +#undef CONFIG_CSHARP_BINDINGS +#undef CONFIG_VBNET_BINDINGS +#define CONFIG_DOT_NET_FRAMEWORK_BASE "" +#undef CONFIG_JAVA_BINDINGS +#define CONFIG_JAVA_HOME "" +#undef CONFIG_PERL_BINDINGS +#define CONFIG_PERL_CORE "" +#define CONFIG_PERL_LIB "" +#undef CONFIG_LUA_BINDINGS +#define CONFIG_LUA_CORE "" + +/* + * Samples + */ +#define CONFIG_SAMPLES 1 +#define CONFIG_C_SAMPLES 1 +#undef CONFIG_CSHARP_SAMPLES +#undef CONFIG_VBNET_SAMPLES +#undef CONFIG_JAVA_SAMPLES +#undef CONFIG_PERL_SAMPLES +#undef CONFIG_LUA_SAMPLES + +/* + * BigInt Options + */ +#undef CONFIG_BIGINT_CLASSICAL +#undef CONFIG_BIGINT_MONTGOMERY +#define CONFIG_BIGINT_BARRETT 1 +#define CONFIG_BIGINT_CRT 1 +#undef CONFIG_BIGINT_KARATSUBA +#define MUL_KARATSUBA_THRESH +#define SQU_KARATSUBA_THRESH +#define CONFIG_BIGINT_SLIDING_WINDOW 1 +#define CONFIG_BIGINT_SQUARE 1 +#define CONFIG_BIGINT_CHECK_ON 1 +#define CONFIG_INTEGER_32BIT 1 +#undef CONFIG_INTEGER_16BIT +#undef CONFIG_INTEGER_8BIT diff --git a/tools/sdk/axtls/ssl/crypto_misc.h b/tools/sdk/axtls/ssl/crypto_misc.h new file mode 100644 index 0000000000..4f3837a4cb --- /dev/null +++ b/tools/sdk/axtls/ssl/crypto_misc.h @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2007-2016, 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 crypto_misc.h + */ + +#ifndef HEADER_CRYPTO_MISC_H +#define HEADER_CRYPTO_MISC_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "../crypto/crypto.h" +#include "../crypto/bigint.h" + +/************************************************************************** + * X509 declarations + **************************************************************************/ +#define X509_OK 0 +#define X509_NOT_OK -1 +#define X509_VFY_ERROR_NO_TRUSTED_CERT -2 +#define X509_VFY_ERROR_BAD_SIGNATURE -3 +#define X509_VFY_ERROR_NOT_YET_VALID -4 +#define X509_VFY_ERROR_EXPIRED -5 +#define X509_VFY_ERROR_SELF_SIGNED -6 +#define X509_VFY_ERROR_INVALID_CHAIN -7 +#define X509_VFY_ERROR_UNSUPPORTED_DIGEST -8 +#define X509_INVALID_PRIV_KEY -9 +#define X509_MAX_CERTS -10 +#define X509_VFY_ERROR_BASIC_CONSTRAINT -11 + +/* + * The Distinguished Name + */ +#define X509_NUM_DN_TYPES 6 +#define X509_COMMON_NAME 0 +#define X509_ORGANIZATION 1 +#define X509_ORGANIZATIONAL_UNIT 2 +#define X509_LOCATION 3 +#define X509_COUNTRY 4 +#define X509_STATE 5 + +/* + * Key Usage bits + */ +#define IS_SET_KEY_USAGE_FLAG(A, B) (A->key_usage & B) + +#define KEY_USAGE_DIGITAL_SIGNATURE 0x0080 +#define KEY_USAGE_NON_REPUDIATION 0x0040 +#define KEY_USAGE_KEY_ENCIPHERMENT 0x0020 +#define KEY_USAGE_DATA_ENCIPHERMENT 0x0010 +#define KEY_USAGE_KEY_AGREEMENT 0x0008 +#define KEY_USAGE_KEY_CERT_SIGN 0x0004 +#define KEY_USAGE_CRL_SIGN 0x0002 +#define KEY_USAGE_ENCIPHER_ONLY 0x0001 +#define KEY_USAGE_DECIPHER_ONLY 0x8000 + +struct _x509_ctx +{ + char *ca_cert_dn[X509_NUM_DN_TYPES]; + char *cert_dn[X509_NUM_DN_TYPES]; + char **subject_alt_dnsnames; + time_t not_before; + time_t not_after; + uint8_t *signature; + RSA_CTX *rsa_ctx; + bigint *digest; + uint8_t *fingerprint; + uint8_t *spki_sha256; + uint16_t sig_len; + uint8_t sig_type; + bool basic_constraint_present; + bool basic_constraint_is_critical; + bool key_usage_present; + bool key_usage_is_critical; + bool subject_alt_name_present; + bool subject_alt_name_is_critical; + bool basic_constraint_cA; + int basic_constraint_pathLenConstraint; + uint32_t key_usage; + struct _x509_ctx *next; +}; + +typedef struct _x509_ctx X509_CTX; + +#ifdef CONFIG_SSL_CERT_VERIFICATION +typedef struct +{ + X509_CTX *cert[CONFIG_X509_MAX_CA_CERTS]; +} CA_CERT_CTX; +#endif + +int x509_new(const uint8_t *cert, int *len, X509_CTX **ctx); +void x509_free(X509_CTX *x509_ctx); +#ifdef CONFIG_SSL_CERT_VERIFICATION +int x509_verify(const CA_CERT_CTX *ca_cert_ctx, const X509_CTX *cert, + int *pathLenConstraint); +#endif +#ifdef CONFIG_SSL_FULL_MODE +void x509_print(const X509_CTX *cert, CA_CERT_CTX *ca_cert_ctx); +const char * x509_display_error(int error, char *buff); +#endif + +/************************************************************************** + * ASN1 declarations + **************************************************************************/ +#define ASN1_BOOLEAN 0x01 +#define ASN1_INTEGER 0x02 +#define ASN1_BIT_STRING 0x03 +#define ASN1_OCTET_STRING 0x04 +#define ASN1_NULL 0x05 +#define ASN1_PRINTABLE_STR2 0x0C +#define ASN1_OID 0x06 +#define ASN1_PRINTABLE_STR2 0x0C +#define ASN1_PRINTABLE_STR 0x13 +#define ASN1_TELETEX_STR 0x14 +#define ASN1_IA5_STR 0x16 +#define ASN1_UTC_TIME 0x17 +#define ASN1_GENERALIZED_TIME 0x18 +#define ASN1_UNICODE_STR 0x1e +#define ASN1_SEQUENCE 0x30 +#define ASN1_CONTEXT_DNSNAME 0x82 +#define ASN1_SET 0x31 +#define ASN1_V3_DATA 0xa3 +#define ASN1_IMPLICIT_TAG 0x80 +#define ASN1_CONTEXT_DNSNAME 0x82 +#define ASN1_EXPLICIT_TAG 0xa0 +#define ASN1_V3_DATA 0xa3 + +#define SIG_TYPE_MD5 0x04 +#define SIG_TYPE_SHA1 0x05 +#define SIG_TYPE_SHA256 0x0b +#define SIG_TYPE_SHA384 0x0c +#define SIG_TYPE_SHA512 0x0d + +uint32_t get_asn1_length(const uint8_t *buf, int *offset); +int asn1_get_private_key(const uint8_t *buf, int len, RSA_CTX **rsa_ctx); +int asn1_next_obj(const uint8_t *buf, int *offset, int obj_type); +int asn1_skip_obj(const uint8_t *buf, int *offset, int obj_type); +int asn1_get_big_int(const uint8_t *buf, int *offset, uint8_t **object); +int asn1_get_int(const uint8_t *buf, int *offset, int32_t *val); +int asn1_get_bool(const uint8_t *buf, int *offset, bool *val); +int asn1_get_bit_string_as_int(const uint8_t *buf, int *offset, uint32_t *val); +int asn1_version(const uint8_t *cert, int *offset, int *val); +int asn1_validity(const uint8_t *cert, int *offset, X509_CTX *x509_ctx); +int asn1_name(const uint8_t *cert, int *offset, char *dn[]); +int asn1_public_key(const uint8_t *cert, int *offset, X509_CTX *x509_ctx); +#ifdef CONFIG_SSL_CERT_VERIFICATION +int asn1_signature(const uint8_t *cert, int *offset, X509_CTX *x509_ctx); +int asn1_compare_dn(char * const dn1[], char * const dn2[]); +int asn1_is_subject_alt_name(const uint8_t *cert, int offset); +int asn1_is_basic_constraints(const uint8_t *cert, int offset); +int asn1_is_key_usage(const uint8_t *cert, int offset); +bool asn1_is_critical_ext(const uint8_t *buf, int *offset); +#endif /* CONFIG_SSL_CERT_VERIFICATION */ +int asn1_signature_type(const uint8_t *cert, + int *offset, X509_CTX *x509_ctx); + +/************************************************************************** + * MISC declarations + **************************************************************************/ +#define SALT_SIZE 8 + +extern const char * const unsupported_str; + +typedef void (*crypt_func)(void *, const uint8_t *, uint8_t *, int); +typedef void (*hmac_func)(const uint8_t *msg, int length, const uint8_t *key, + int key_len, uint8_t *digest); +typedef void (*hmac_func_v)(const uint8_t **msg, int *length, int count, const uint8_t *key, + int key_len, uint8_t *digest); + +#ifndef ESP8266 +int get_file(const char *filename, uint8_t **buf); +#endif + +#if defined(CONFIG_SSL_FULL_MODE) || defined(WIN32) || defined(CONFIG_DEBUG) +EXP_FUNC void STDCALL print_blob(const char *format, const uint8_t *data, int size, ...); +#else + #define print_blob(...) +#endif + +EXP_FUNC int STDCALL base64_decode(const char *in, int len, + uint8_t *out, int *outlen); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/axtls/ssl/gen_cert.c b/tools/sdk/axtls/ssl/gen_cert.c new file mode 100644 index 0000000000..093ae9c093 --- /dev/null +++ b/tools/sdk/axtls/ssl/gen_cert.c @@ -0,0 +1,374 @@ +/* + * Copyright (c) 2007-2014, 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. + */ + +#include "config.h" + +#ifdef CONFIG_SSL_GENERATE_X509_CERT +#include +#include +#include "os_port.h" +#include "ssl.h" + +/** + * Generate a basic X.509 certificate + */ + +static uint8_t set_gen_length(int len, uint8_t *buf, int *offset) +{ + if (len < 0x80) /* short form */ + { + buf[(*offset)++] = len; + return 1; + } + else /* long form */ + { + int i, length_bytes = 0; + + if (len & 0x00FF0000) + length_bytes = 3; + else if (len & 0x0000FF00) + length_bytes = 2; + else if (len & 0x000000FF) + length_bytes = 1; + + buf[(*offset)++] = 0x80 + length_bytes; + + for (i = length_bytes-1; i >= 0; i--) + { + buf[*offset+i] = len & 0xFF; + len >>= 8; + } + + *offset += length_bytes; + return length_bytes+1; + } +} + +static int pre_adjust_with_size(uint8_t type, + int *seq_offset, uint8_t *buf, int *offset) +{ + buf[(*offset)++] = type; + *seq_offset = *offset; + *offset += 4; /* fill in later */ + return *offset; +} + +static void adjust_with_size(int seq_size, int seq_start, + uint8_t *buf, int *offset) +{ + uint8_t seq_byte_size; + int orig_seq_size = seq_size; + int orig_seq_start = seq_start; + + seq_size = *offset-seq_size; + seq_byte_size = set_gen_length(seq_size, buf, &seq_start); + + if (seq_byte_size != 4) + { + memmove(&buf[orig_seq_start+seq_byte_size], + &buf[orig_seq_size], seq_size); + *offset -= 4-seq_byte_size; + } +} + +static void gen_serial_number(uint8_t *buf, int *offset) +{ + static const uint8_t ser_oid[] = { ASN1_INTEGER, 1, 0x7F }; + memcpy(&buf[*offset], ser_oid , sizeof(ser_oid)); + *offset += sizeof(ser_oid); +} + +static void gen_signature_alg(uint8_t *buf, int *offset) +{ + /* OBJECT IDENTIFIER sha1withRSAEncryption (1 2 840 113549 1 1 5) */ + static const uint8_t sig_oid[] = + { + ASN1_SEQUENCE, 0x0d, ASN1_OID, 0x09, + 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, + ASN1_NULL, 0x00 + }; + + memcpy(&buf[*offset], sig_oid, sizeof(sig_oid)); + *offset += sizeof(sig_oid); +} + +static int gen_dn(const char *name, uint8_t dn_type, + uint8_t *buf, int *offset) +{ + int ret = X509_OK; + int name_size = strlen(name); + + if (name_size > 0x70) /* just too big */ + { + ret = X509_NOT_OK; + goto error; + } + + buf[(*offset)++] = ASN1_SET; + set_gen_length(9+name_size, buf, offset); + buf[(*offset)++] = ASN1_SEQUENCE; + set_gen_length(7+name_size, buf, offset); + buf[(*offset)++] = ASN1_OID; + buf[(*offset)++] = 3; + buf[(*offset)++] = 0x55; + buf[(*offset)++] = 0x04; + buf[(*offset)++] = dn_type; + buf[(*offset)++] = ASN1_PRINTABLE_STR; + buf[(*offset)++] = name_size; + strcpy((char *)&buf[*offset], name); + *offset += name_size; + +error: + return ret; +} + +static int gen_issuer(const char * dn[], uint8_t *buf, int *offset) +{ + int ret = X509_OK; + int seq_offset; + int seq_size = pre_adjust_with_size( + ASN1_SEQUENCE, &seq_offset, buf, offset); + char fqdn[128]; + + /* we need the common name, so if not configured, work out the fully + * qualified domain name */ + if (dn[X509_COMMON_NAME] == NULL || strlen(dn[X509_COMMON_NAME]) == 0) + { + int fqdn_len; + gethostname(fqdn, sizeof(fqdn)); + fqdn_len = strlen(fqdn); + fqdn[fqdn_len++] = '.'; + + if (getdomainname(&fqdn[fqdn_len], sizeof(fqdn)-fqdn_len) < 0) + { + ret = X509_NOT_OK; + goto error; + } + + fqdn_len = strlen(fqdn); + + if (fqdn[fqdn_len-1] == '.') /* ensure '.' is not last char */ + fqdn[fqdn_len-1] = 0; + + dn[X509_COMMON_NAME] = fqdn; + } + + if ((ret = gen_dn(dn[X509_COMMON_NAME], 3, buf, offset))) + goto error; + + if (dn[X509_ORGANIZATION] != NULL && strlen(dn[X509_ORGANIZATION]) > 0) + { + if ((ret = gen_dn(dn[X509_ORGANIZATION], 10, buf, offset))) + goto error; + } + + if (dn[X509_ORGANIZATIONAL_UNIT] != NULL && + strlen(dn[X509_ORGANIZATIONAL_UNIT]) > 0) + { + if ((ret = gen_dn(dn[X509_ORGANIZATIONAL_UNIT], 11, buf, offset))) + goto error; + } + + adjust_with_size(seq_size, seq_offset, buf, offset); + +error: + return ret; +} + +static void gen_utc_time(uint8_t *buf, int *offset) +{ + static const uint8_t time_seq[] = + { + ASN1_SEQUENCE, 30, + ASN1_UTC_TIME, 13, + '0', '7', '0', '1', '0', '1', '0', '0', '0', '0', '0', '0', 'Z', + ASN1_UTC_TIME, 13, /* make it good for 30 or so years */ + '3', '8', '0', '1', '0', '1', '0', '0', '0', '0', '0', '0', 'Z' + }; + + /* fixed time */ + memcpy(&buf[*offset], time_seq, sizeof(time_seq)); + *offset += sizeof(time_seq); +} + +static void gen_pub_key2(const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset) +{ + static const uint8_t pub_key_seq[] = + { + ASN1_INTEGER, 0x03, 0x01, 0x00, 0x01 /* INTEGER 65537 */ + }; + + int seq_offset; + int pub_key_size = rsa_ctx->num_octets; + uint8_t *block = (uint8_t *)malloc(pub_key_size); + int seq_size = pre_adjust_with_size( + ASN1_SEQUENCE, &seq_offset, buf, offset); + buf[(*offset)++] = ASN1_INTEGER; + bi_export(rsa_ctx->bi_ctx, rsa_ctx->m, block, pub_key_size); + + if (*block & 0x80) /* make integer positive */ + { + set_gen_length(pub_key_size+1, buf, offset); + buf[(*offset)++] = 0; + } + else + set_gen_length(pub_key_size, buf, offset); + + memcpy(&buf[*offset], block, pub_key_size); + free(block); + *offset += pub_key_size; + memcpy(&buf[*offset], pub_key_seq, sizeof(pub_key_seq)); + *offset += sizeof(pub_key_seq); + adjust_with_size(seq_size, seq_offset, buf, offset); +} + +static void gen_pub_key1(const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset) +{ + int seq_offset; + int seq_size = pre_adjust_with_size( + ASN1_BIT_STRING, &seq_offset, buf, offset); + buf[(*offset)++] = 0; /* bit string is multiple of 8 */ + gen_pub_key2(rsa_ctx, buf, offset); + adjust_with_size(seq_size, seq_offset, buf, offset); +} + +static void gen_pub_key(const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset) +{ + /* OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1) */ + static const uint8_t rsa_enc_oid[] = + { + ASN1_SEQUENCE, 0x0d, ASN1_OID, 0x09, + 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, + ASN1_NULL, 0x00 + }; + + int seq_offset; + int seq_size = pre_adjust_with_size( + ASN1_SEQUENCE, &seq_offset, buf, offset); + + memcpy(&buf[*offset], rsa_enc_oid, sizeof(rsa_enc_oid)); + *offset += sizeof(rsa_enc_oid); + gen_pub_key1(rsa_ctx, buf, offset); + adjust_with_size(seq_size, seq_offset, buf, offset); +} + +static void gen_signature(const RSA_CTX *rsa_ctx, const uint8_t *sha_dgst, + uint8_t *buf, int *offset) +{ + static const uint8_t asn1_sig[] = + { + ASN1_SEQUENCE, 0x21, ASN1_SEQUENCE, 0x09, ASN1_OID, 0x05, + 0x2b, 0x0e, 0x03, 0x02, 0x1a, /* sha1 (1 3 14 3 2 26) */ + ASN1_NULL, 0x00, ASN1_OCTET_STRING, 0x14 + }; + + uint8_t *enc_block = (uint8_t *)malloc(rsa_ctx->num_octets); + uint8_t *block = (uint8_t *)malloc(sizeof(asn1_sig) + SHA1_SIZE); + int sig_size; + + /* add the digest as an embedded asn.1 sequence */ + memcpy(block, asn1_sig, sizeof(asn1_sig)); + memcpy(&block[sizeof(asn1_sig)], sha_dgst, SHA1_SIZE); + + sig_size = RSA_encrypt(rsa_ctx, block, + sizeof(asn1_sig) + SHA1_SIZE, enc_block, 1); + + buf[(*offset)++] = ASN1_BIT_STRING; + set_gen_length(sig_size+1, buf, offset); + buf[(*offset)++] = 0; /* bit string is multiple of 8 */ + memcpy(&buf[*offset], enc_block, sig_size); + free(enc_block); + free(block); + *offset += sig_size; +} + +static int gen_tbs_cert(const char * dn[], + const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset, + uint8_t *sha_dgst) +{ + int ret = X509_OK; + SHA1_CTX sha_ctx; + int seq_offset; + int begin_tbs = *offset; + int seq_size = pre_adjust_with_size( + ASN1_SEQUENCE, &seq_offset, buf, offset); + + gen_serial_number(buf, offset); + gen_signature_alg(buf, offset); + + /* CA certicate issuer */ + if ((ret = gen_issuer(dn, buf, offset))) + goto error; + + gen_utc_time(buf, offset); + + /* certificate issuer */ + if ((ret = gen_issuer(dn, buf, offset))) + goto error; + + gen_pub_key(rsa_ctx, buf, offset); + adjust_with_size(seq_size, seq_offset, buf, offset); + + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx, &buf[begin_tbs], *offset-begin_tbs); + SHA1_Final(sha_dgst, &sha_ctx); + +error: + return ret; +} + +/** + * Create a new certificate. + */ +EXP_FUNC int STDCALL ssl_x509_create(SSL_CTX *ssl_ctx, uint32_t options, const char * dn[], uint8_t **cert_data) +{ + int ret = X509_OK, offset = 0, seq_offset; + /* allocate enough space to load a new certificate */ + uint8_t *buf = (uint8_t *)malloc(ssl_ctx->rsa_ctx->num_octets*2 + 512); + uint8_t sha_dgst[SHA1_SIZE]; + int seq_size = pre_adjust_with_size(ASN1_SEQUENCE, + &seq_offset, buf, &offset); + + if ((ret = gen_tbs_cert(dn, ssl_ctx->rsa_ctx, buf, &offset, sha_dgst)) < 0) + goto error; + + gen_signature_alg(buf, &offset); + gen_signature(ssl_ctx->rsa_ctx, sha_dgst, buf, &offset); + adjust_with_size(seq_size, seq_offset, buf, &offset); + *cert_data = (uint8_t *)malloc(offset); /* create the exact memory for it */ + memcpy(*cert_data, buf, offset); + +error: + free(buf); + return ret < 0 ? ret : offset; +} + +#endif + diff --git a/tools/sdk/axtls/ssl/loader.c b/tools/sdk/axtls/ssl/loader.c new file mode 100644 index 0000000000..3d07323900 --- /dev/null +++ b/tools/sdk/axtls/ssl/loader.c @@ -0,0 +1,490 @@ +/* + * Copyright (c) 2007-2014, 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. + */ + +/** + * Load certificates/keys into memory. These can be in many different formats. + * PEM support and other formats can be processed here. + * + * The PEM private keys may be optionally encrypted with AES128 or AES256. + * The encrypted PEM keys were generated with something like: + * + * openssl genrsa -aes128 -passout pass:abcd -out axTLS.key_aes128.pem 512 + */ + +#include +#include +#include +#include "os_port.h" +#include "ssl.h" + +static int do_obj(SSL_CTX *ssl_ctx, int obj_type, + SSLObjLoader *ssl_obj, const char *password); +#ifdef CONFIG_SSL_HAS_PEM +static int ssl_obj_PEM_load(SSL_CTX *ssl_ctx, int obj_type, + SSLObjLoader *ssl_obj, const char *password); +#endif + +/* + * Load a file into memory that is in binary DER (or ascii PEM) format. + */ +EXP_FUNC int STDCALL ssl_obj_load(SSL_CTX *ssl_ctx, int obj_type, + const char *filename, const char *password) +{ +#ifndef CONFIG_SSL_SKELETON_MODE + static const char * const begin = "-----BEGIN"; + int ret = SSL_OK; + SSLObjLoader *ssl_obj = NULL; + + if (filename == NULL) + { + ret = SSL_ERROR_INVALID_KEY; + goto error; + } + + ssl_obj = (SSLObjLoader *)calloc(1, sizeof(SSLObjLoader)); + ssl_obj->len = get_file(filename, &ssl_obj->buf); + if (ssl_obj->len <= 0) + { + ret = SSL_ERROR_INVALID_KEY; + goto error; + } + + /* is the file a PEM file? */ + if (strstr((char *)ssl_obj->buf, begin) != NULL) + { +#ifdef CONFIG_SSL_HAS_PEM + ret = ssl_obj_PEM_load(ssl_ctx, obj_type, ssl_obj, password); +#else +#ifdef CONFIG_SSL_FULL_MODE + printf("%s", unsupported_str); +#endif + ret = SSL_ERROR_NOT_SUPPORTED; +#endif + } + else + ret = do_obj(ssl_ctx, obj_type, ssl_obj, password); + +error: + ssl_obj_free(ssl_obj); + return ret; +#else +#ifdef CONFIG_SSL_FULL_MODE + printf("%s", unsupported_str); +#endif + return SSL_ERROR_NOT_SUPPORTED; +#endif /* CONFIG_SSL_SKELETON_MODE */ +} + +/* + * Transfer binary data into the object loader. + */ +EXP_FUNC int STDCALL ssl_obj_memory_load(SSL_CTX *ssl_ctx, int mem_type, + const uint8_t *data, int len, const char *password) +{ + int ret; + SSLObjLoader *ssl_obj; + + ssl_obj = (SSLObjLoader *)calloc(1, sizeof(SSLObjLoader)); + ssl_obj->buf = (uint8_t *)malloc(len); + memcpy(ssl_obj->buf, data, len); + ssl_obj->len = len; + ret = do_obj(ssl_ctx, mem_type, ssl_obj, password); + ssl_obj_free(ssl_obj); + return ret; +} + +/* + * Actually work out what we are doing + */ +static int do_obj(SSL_CTX *ssl_ctx, int obj_type, + SSLObjLoader *ssl_obj, const char *password) +{ + int ret = SSL_OK; + + switch (obj_type) + { + case SSL_OBJ_RSA_KEY: + ret = add_private_key(ssl_ctx, ssl_obj); + break; + + case SSL_OBJ_X509_CERT: + ret = add_cert(ssl_ctx, ssl_obj->buf, ssl_obj->len); + break; + +#ifdef CONFIG_SSL_CERT_VERIFICATION + case SSL_OBJ_X509_CACERT: + add_cert_auth(ssl_ctx, ssl_obj->buf, ssl_obj->len); + break; +#endif + +#ifdef CONFIG_SSL_USE_PKCS12 + case SSL_OBJ_PKCS8: + ret = pkcs8_decode(ssl_ctx, ssl_obj, password); + break; + + case SSL_OBJ_PKCS12: + ret = pkcs12_decode(ssl_ctx, ssl_obj, password); + break; +#endif + default: +#ifdef CONFIG_SSL_FULL_MODE + printf("%s", unsupported_str); +#endif + ret = SSL_ERROR_NOT_SUPPORTED; + break; + } + + return ret; +} + +/* + * Clean up our mess. + */ +void ssl_obj_free(SSLObjLoader *ssl_obj) +{ + if (ssl_obj) + { + free(ssl_obj->buf); + free(ssl_obj); + } +} + +/* + * Support for PEM encoded keys/certificates. + */ +#ifdef CONFIG_SSL_HAS_PEM + +#define NUM_PEM_TYPES 4 +#define IV_SIZE 16 +#define IS_RSA_PRIVATE_KEY 0 +#define IS_ENCRYPTED_PRIVATE_KEY 1 +#define IS_PRIVATE_KEY 2 +#define IS_CERTIFICATE 3 + +static const char * const begins[NUM_PEM_TYPES] = +{ + "-----BEGIN RSA PRIVATE KEY-----", + "-----BEGIN ENCRYPTED PRIVATE KEY-----", + "-----BEGIN PRIVATE KEY-----", + "-----BEGIN CERTIFICATE-----", +}; + +static const char * const ends[NUM_PEM_TYPES] = +{ + "-----END RSA PRIVATE KEY-----", + "-----END ENCRYPTED PRIVATE KEY-----", + "-----END PRIVATE KEY-----", + "-----END CERTIFICATE-----", +}; + +static const char * const aes_str[2] = +{ + "DEK-Info: AES-128-CBC,", + "DEK-Info: AES-256-CBC," +}; + +/** + * Take a base64 blob of data and decrypt it (using AES) into its + * proper ASN.1 form. + */ +static int pem_decrypt(const char *where, const char *end, + const char *password, SSLObjLoader *ssl_obj) +{ + int ret = -1; + int is_aes_256 = 0; + char *start = NULL; + uint8_t iv[IV_SIZE]; + int i, pem_size; + MD5_CTX md5_ctx; + AES_CTX aes_ctx; + uint8_t key[32]; /* AES256 size */ + + if (password == NULL || strlen(password) == 0) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: Need a password for this PEM file\n"); +#endif + goto error; + } + + if ((start = strstr((const char *)where, aes_str[0]))) /* AES128? */ + { + start += strlen(aes_str[0]); + } + else if ((start = strstr((const char *)where, aes_str[1]))) /* AES256? */ + { + is_aes_256 = 1; + start += strlen(aes_str[1]); + } + else + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: Unsupported password cipher\n"); +#endif + goto error; + } + + /* convert from hex to binary - assumes uppercase hex */ + for (i = 0; i < IV_SIZE; i++) + { + char c = *start++ - '0'; + iv[i] = (c > 9 ? c + '0' - 'A' + 10 : c) << 4; + c = *start++ - '0'; + iv[i] += (c > 9 ? c + '0' - 'A' + 10 : c); + } + + while (*start == '\r' || *start == '\n') + start++; + + /* turn base64 into binary */ + pem_size = (int)(end-start); + if (base64_decode(start, pem_size, ssl_obj->buf, &ssl_obj->len) != 0) + goto error; + + /* work out the key */ + MD5_Init(&md5_ctx); + MD5_Update(&md5_ctx, (const uint8_t *)password, strlen(password)); + MD5_Update(&md5_ctx, iv, SALT_SIZE); + MD5_Final(key, &md5_ctx); + + if (is_aes_256) + { + MD5_Init(&md5_ctx); + MD5_Update(&md5_ctx, key, MD5_SIZE); + MD5_Update(&md5_ctx, (const uint8_t *)password, strlen(password)); + MD5_Update(&md5_ctx, iv, SALT_SIZE); + MD5_Final(&key[MD5_SIZE], &md5_ctx); + } + + /* decrypt using the key/iv */ + AES_set_key(&aes_ctx, key, iv, is_aes_256 ? AES_MODE_256 : AES_MODE_128); + AES_convert_key(&aes_ctx); + AES_cbc_decrypt(&aes_ctx, ssl_obj->buf, ssl_obj->buf, ssl_obj->len); + ret = 0; + +error: + return ret; +} + +/** + * Take a base64 blob of data and turn it into its proper ASN.1 form. + */ +static int new_pem_obj(SSL_CTX *ssl_ctx, int is_cacert, char *where, + int remain, const char *password) +{ + int ret = SSL_ERROR_BAD_CERTIFICATE; + SSLObjLoader *ssl_obj = NULL; + + while (remain > 0) + { + int i, pem_size, obj_type; + char *start = NULL, *end = NULL; + + for (i = 0; i < NUM_PEM_TYPES; i++) + { + if ((start = strstr(where, begins[i])) && + (end = strstr(where, ends[i]))) + { + remain -= (int)(end-where); + start += strlen(begins[i]); + pem_size = (int)(end-start); + + ssl_obj = (SSLObjLoader *)calloc(1, sizeof(SSLObjLoader)); + + /* 4/3 bigger than what we need but so what */ + ssl_obj->buf = (uint8_t *)calloc(1, pem_size); + ssl_obj->len = pem_size; + + if (i == IS_RSA_PRIVATE_KEY && + strstr(start, "Proc-Type:") && + strstr(start, "4,ENCRYPTED")) + { + /* check for encrypted PEM file */ + if (pem_decrypt(start, end, password, ssl_obj) < 0) + { + ret = SSL_ERROR_BAD_CERTIFICATE; + goto error; + } + } + else + { + ssl_obj->len = pem_size; + if (base64_decode(start, pem_size, + ssl_obj->buf, &ssl_obj->len) != 0) + { + ret = SSL_ERROR_BAD_CERTIFICATE; + goto error; + } + } + + switch (i) + { + case IS_RSA_PRIVATE_KEY: + obj_type = SSL_OBJ_RSA_KEY; + break; + + case IS_ENCRYPTED_PRIVATE_KEY: + case IS_PRIVATE_KEY: + obj_type = SSL_OBJ_PKCS8; + break; + + case IS_CERTIFICATE: + obj_type = is_cacert ? + SSL_OBJ_X509_CACERT : SSL_OBJ_X509_CERT; + break; + + default: + ret = SSL_ERROR_BAD_CERTIFICATE; + goto error; + } + + /* In a format we can now understand - so process it */ + if ((ret = do_obj(ssl_ctx, obj_type, ssl_obj, password))) + goto error; + + end += strlen(ends[i]); + remain -= strlen(ends[i]); + while (remain > 0 && (*end == '\r' || *end == '\n')) + { + end++; + remain--; + } + + where = end; + break; + } + } + + ssl_obj_free(ssl_obj); + ssl_obj = NULL; + if (start == NULL) + break; + } +error: + ssl_obj_free(ssl_obj); + return ret; +} + +/* + * Load a file into memory that is in ASCII PEM format. + */ +static int ssl_obj_PEM_load(SSL_CTX *ssl_ctx, int obj_type, + SSLObjLoader *ssl_obj, const char *password) +{ + char *start; + + /* add a null terminator */ + ssl_obj->len++; + ssl_obj->buf = (uint8_t *)realloc(ssl_obj->buf, ssl_obj->len); + ssl_obj->buf[ssl_obj->len-1] = 0; + start = (char *)ssl_obj->buf; + return new_pem_obj(ssl_ctx, obj_type == SSL_OBJ_X509_CACERT, + start, ssl_obj->len, password); +} +#endif /* CONFIG_SSL_HAS_PEM */ + +/** + * Load the key/certificates in memory depending on compile-time and user + * options. + */ +int load_key_certs(SSL_CTX *ssl_ctx) +{ + int ret = SSL_OK; + uint32_t options = ssl_ctx->options; +#ifdef CONFIG_SSL_GENERATE_X509_CERT + uint8_t *cert_data = NULL; + int cert_size; + static const char *dn[] = + { + CONFIG_SSL_X509_COMMON_NAME, + CONFIG_SSL_X509_ORGANIZATION_NAME, + CONFIG_SSL_X509_ORGANIZATION_UNIT_NAME + }; +#endif + + /* do the private key first */ + if (strlen(CONFIG_SSL_PRIVATE_KEY_LOCATION) > 0) + { + if ((ret = ssl_obj_load(ssl_ctx, SSL_OBJ_RSA_KEY, + CONFIG_SSL_PRIVATE_KEY_LOCATION, + CONFIG_SSL_PRIVATE_KEY_PASSWORD)) < 0) + goto error; + } + else if (!(options & SSL_NO_DEFAULT_KEY)) + { +#if defined(CONFIG_SSL_USE_DEFAULT_KEY) || defined(CONFIG_SSL_SKELETON_MODE) + extern const unsigned char* default_private_key; + extern const unsigned int default_private_key_len; + if (default_private_key != NULL && default_private_key_len > 0) + ssl_obj_memory_load(ssl_ctx, SSL_OBJ_RSA_KEY, default_private_key, + default_private_key_len, NULL); +#endif + } + + /* now load the certificate */ +#ifdef CONFIG_SSL_GENERATE_X509_CERT + if ((cert_size = ssl_x509_create(ssl_ctx, 0, dn, &cert_data)) < 0) + { + ret = cert_size; + goto error; + } + + ssl_obj_memory_load(ssl_ctx, SSL_OBJ_X509_CERT, cert_data, cert_size, NULL); + free(cert_data); +#else + if (strlen(CONFIG_SSL_X509_CERT_LOCATION)) + { + if ((ret = ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CERT, + CONFIG_SSL_X509_CERT_LOCATION, NULL)) < 0) + goto error; + } + else if (!(options & SSL_NO_DEFAULT_KEY)) + { +#if defined(CONFIG_SSL_USE_DEFAULT_KEY) || defined(CONFIG_SSL_SKELETON_MODE) + extern const unsigned char* default_certificate; + extern const unsigned int default_certificate_len; + if (default_certificate != NULL && default_certificate_len > 0) + ssl_obj_memory_load(ssl_ctx, SSL_OBJ_X509_CERT, + default_certificate, default_certificate_len, NULL); +#endif + } +#endif + +error: +#ifdef CONFIG_SSL_FULL_MODE + if (ret) + { + printf("Error: Certificate or key not loaded\n"); + } +#endif + + return ret; + +} diff --git a/tools/sdk/axtls/ssl/openssl.c b/tools/sdk/axtls/ssl/openssl.c new file mode 100644 index 0000000000..d0343e5680 --- /dev/null +++ b/tools/sdk/axtls/ssl/openssl.c @@ -0,0 +1,318 @@ +/* + * Copyright (c) 2007-2016, 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. + */ + +/* + * Enable a subset of openssl compatible functions. We don't aim to be 100% + * compatible - just to be able to do basic ports etc. + * + * Only really tested on mini_httpd, so I'm not too sure how extensive this + * port is. + */ + +#include "config.h" + +#ifdef CONFIG_OPENSSL_COMPATIBLE +#include +#include +#include +#include "os_port.h" +#include "ssl.h" + +#define OPENSSL_CTX_ATTR ((OPENSSL_CTX *)ssl_ctx->bonus_attr) + +static char *key_password = NULL; + +void *SSLv3_server_method(void) { return NULL; } +void *TLSv1_server_method(void) { return NULL; } +void *SSLv3_client_method(void) { return NULL; } +void *TLSv1_client_method(void) { return NULL; } + +typedef void * (*ssl_func_type_t)(void); +typedef void * (*bio_func_type_t)(void); + +typedef struct +{ + ssl_func_type_t ssl_func_type; +} OPENSSL_CTX; + +SSL_CTX * SSL_CTX_new(ssl_func_type_t meth) +{ + SSL_CTX *ssl_ctx = ssl_ctx_new(0, 5); + ssl_ctx->bonus_attr = malloc(sizeof(OPENSSL_CTX)); + OPENSSL_CTX_ATTR->ssl_func_type = meth; + return ssl_ctx; +} + +void SSL_CTX_free(SSL_CTX * ssl_ctx) +{ + free(ssl_ctx->bonus_attr); + ssl_ctx_free(ssl_ctx); +} + +SSL * SSL_new(SSL_CTX *ssl_ctx) +{ + SSL *ssl; +#ifdef CONFIG_SSL_ENABLE_CLIENT + ssl_func_type_t ssl_func_type = OPENSSL_CTX_ATTR->ssl_func_type; +#endif + + ssl = ssl_new(ssl_ctx, -1); /* fd is set later */ +#ifdef CONFIG_SSL_ENABLE_CLIENT + if (ssl_func_type == SSLv3_client_method || + ssl_func_type == TLSv1_client_method) + { + SET_SSL_FLAG(SSL_IS_CLIENT); + } + else +#endif + { + ssl->next_state = HS_CLIENT_HELLO; + } + + return ssl; +} + +int SSL_set_fd(SSL *s, int fd) +{ + s->client_fd = fd; + return 1; /* always succeeds */ +} + +int SSL_accept(SSL *ssl) +{ + while (ssl_read(ssl, NULL) == SSL_OK) + { + if (ssl->next_state == HS_CLIENT_HELLO) + return 1; /* we're done */ + } + + return -1; +} + +#ifdef CONFIG_SSL_ENABLE_CLIENT +int SSL_connect(SSL *ssl) +{ + return do_client_connect(ssl) == SSL_OK ? 1 : -1; +} +#endif + +void SSL_free(SSL *ssl) +{ + ssl_free(ssl); +} + +int SSL_read(SSL *ssl, void *buf, int num) +{ + uint8_t *read_buf; + int ret; + + while ((ret = ssl_read(ssl, &read_buf)) == SSL_OK); + + if (ret > SSL_OK) + { + memcpy(buf, read_buf, ret > num ? num : ret); + } + + return ret; +} + +int SSL_write(SSL *ssl, const void *buf, int num) +{ + return ssl_write(ssl, buf, num); +} + +int SSL_CTX_use_certificate_file(SSL_CTX *ssl_ctx, const char *file, int type) +{ + return (ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CERT, file, NULL) == SSL_OK); +} + +int SSL_CTX_use_PrivateKey_file(SSL_CTX *ssl_ctx, const char *file, int type) +{ + return (ssl_obj_load(ssl_ctx, SSL_OBJ_RSA_KEY, file, key_password) == SSL_OK); +} + +int SSL_CTX_use_certificate_ASN1(SSL_CTX *ssl_ctx, int len, const uint8_t *d) +{ + return (ssl_obj_memory_load(ssl_ctx, + SSL_OBJ_X509_CERT, d, len, NULL) == SSL_OK); +} + +int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx, + unsigned int sid_ctx_len) +{ + return 1; +} + +int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx) +{ + return 1; +} + +int SSL_CTX_use_certificate_chain_file(SSL_CTX *ssl_ctx, const char *file) +{ + return (ssl_obj_load(ssl_ctx, + SSL_OBJ_X509_CERT, file, NULL) == SSL_OK); +} + +int SSL_shutdown(SSL *ssl) +{ + return 1; +} + +/*** get/set session ***/ +SSL_SESSION *SSL_get1_session(SSL *ssl) +{ + return (SSL_SESSION *)ssl_get_session_id(ssl); /* note: wrong cast */ +} + +int SSL_set_session(SSL *ssl, SSL_SESSION *session) +{ + memcpy(ssl->session_id, (uint8_t *)session, SSL_SESSION_ID_SIZE); + return 1; +} + +void SSL_SESSION_free(SSL_SESSION *session) { } +/*** end get/set session ***/ + +long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg) +{ + return 0; +} + +void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, + int (*verify_callback)(int, void *)) { } + +void SSL_CTX_set_verify_depth(SSL_CTX *ctx,int depth) { } + +int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile, + const char *CApath) +{ + return 1; +} + +void *SSL_load_client_CA_file(const char *file) +{ + return (void *)file; +} + +void SSL_CTX_set_client_CA_list(SSL_CTX *ssl_ctx, void *file) +{ + + ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CERT, (const char *)file, NULL); +} + +void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, void *cb) { } + +void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u) +{ + key_password = (char *)u; +} + +int SSL_peek(SSL *ssl, void *buf, int num) +{ + memcpy(buf, ssl->bm_data, num); + return num; +} + +void SSL_set_bio(SSL *ssl, void *rbio, void *wbio) { } + +long SSL_get_verify_result(const SSL *ssl) +{ + return ssl_handshake_status(ssl); +} + +int SSL_state(SSL *ssl) +{ + return 0x03; // ok state +} + +/** end of could do better list */ + +void *SSL_get_peer_certificate(const SSL *ssl) +{ + return &ssl->ssl_ctx->certs[0]; +} + +int SSL_clear(SSL *ssl) +{ + return 1; +} + + +int SSL_CTX_check_private_key(const SSL_CTX *ctx) +{ + return 1; +} + +int SSL_CTX_set_cipher_list(SSL *s, const char *str) +{ + return 1; +} + +int SSL_get_error(const SSL *ssl, int ret) +{ + ssl_display_error(ret); + return 0; /* TODO: return proper return code */ +} + +void SSL_CTX_set_options(SSL_CTX *ssl_ctx, int option) {} +int SSL_library_init(void ) { return 1; } +void SSL_load_error_strings(void ) {} +void ERR_print_errors_fp(FILE *fp) {} + +#ifndef CONFIG_SSL_SKELETON_MODE +long SSL_CTX_get_timeout(const SSL_CTX *ssl_ctx) { + return CONFIG_SSL_EXPIRY_TIME*3600; } +long SSL_CTX_set_timeout(SSL_CTX *ssl_ctx, long t) { + return SSL_CTX_get_timeout(ssl_ctx); } +#endif +void BIO_printf(FILE *f, const char *format, ...) +{ + va_list(ap); + va_start(ap, format); + vfprintf(f, format, ap); + va_end(ap); +} + +void* BIO_s_null(void) { return NULL; } +FILE *BIO_new(bio_func_type_t func) +{ + if (func == BIO_s_null) + return fopen("/dev/null", "r"); + else + return NULL; +} + +FILE *BIO_new_fp(FILE *stream, int close_flag) { return stream; } +int BIO_free(FILE *a) { if (a != stdout && a != stderr) fclose(a); return 1; } + + + +#endif diff --git a/tools/sdk/axtls/ssl/os_int.h b/tools/sdk/axtls/ssl/os_int.h new file mode 100644 index 0000000000..a6207f1d42 --- /dev/null +++ b/tools/sdk/axtls/ssl/os_int.h @@ -0,0 +1,8 @@ +#ifndef OS_INT_H +#define OS_INT_H + +#include +#include +#include + +#endif //OS_INT_H \ No newline at end of file diff --git a/tools/sdk/axtls/ssl/os_port.c b/tools/sdk/axtls/ssl/os_port.c new file mode 100644 index 0000000000..060bc073a5 --- /dev/null +++ b/tools/sdk/axtls/ssl/os_port.c @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2007-2016, 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 +#include +#include +#include +#include +#include "os_port.h" + +#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 + diff --git a/tools/sdk/axtls/ssl/os_port.h b/tools/sdk/axtls/ssl/os_port.h new file mode 100644 index 0000000000..6b5dc1f1d9 --- /dev/null +++ b/tools/sdk/axtls/ssl/os_port.h @@ -0,0 +1,284 @@ +/* + * Copyright (c) 2007-2016, 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.h + * + * Some stuff to minimise the differences between windows and linux/unix + */ + +#ifndef HEADER_OS_PORT_H +#define HEADER_OS_PORT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "os_int.h" +#include "config.h" +#include + +#ifdef WIN32 +#define STDCALL __stdcall +#define EXP_FUNC __declspec(dllexport) +#else +#define STDCALL +#define EXP_FUNC +#endif + +#if defined(_WIN32_WCE) +#undef WIN32 +#define WIN32 +#endif + +#if defined(ESP8266) + +#include "util/time.h" +#include +#define alloca(size) __builtin_alloca(size) +#define TTY_FLUSH() +#ifdef putc +#undef putc +#endif +#define putc(x, f) ets_putc(x) + +#define SOCKET_READ(A,B,C) ax_port_read(A,B,C) +#define SOCKET_WRITE(A,B,C) ax_port_write(A,B,C) +#define SOCKET_CLOSE(A) ax_port_close(A) +#define get_file ax_get_file +#define EWOULDBLOCK EAGAIN + +#define hmac_sha1 ax_hmac_sha1 +#define hmac_sha256 ax_hmac_sha256 +#define hmac_md5 ax_hmac_md5 + +#ifndef be64toh +# define __bswap_constant_64(x) \ + ((((x) & 0xff00000000000000ull) >> 56) \ + | (((x) & 0x00ff000000000000ull) >> 40) \ + | (((x) & 0x0000ff0000000000ull) >> 24) \ + | (((x) & 0x000000ff00000000ull) >> 8) \ + | (((x) & 0x00000000ff000000ull) << 8) \ + | (((x) & 0x0000000000ff0000ull) << 24) \ + | (((x) & 0x000000000000ff00ull) << 40) \ + | (((x) & 0x00000000000000ffull) << 56)) +#define be64toh(x) __bswap_constant_64(x) +#endif + +void ax_wdt_feed(); + +#ifndef PROGMEM +#define PROGMEM __attribute__((aligned(4))) __attribute__((section(".irom.text"))) +#endif + +// #ifndef WITH_PGM_READ_HELPER +// #define ax_array_read_u8(x, y) x[y] +// #else + +// static inline uint8_t pgm_read_byte(const void* addr) { +// register uint32_t res; +// __asm__("extui %0, %1, 0, 2\n" /* Extract offset within word (in bytes) */ +// "sub %1, %1, %0\n" /* Subtract offset from addr, yielding an aligned address */ +// "l32i.n %1, %1, 0x0\n" /* Load word from aligned address */ +// "slli %0, %0, 3\n" /* Multiply offset by 8, yielding an offset in bits */ +// "ssr %0\n" /* Prepare to shift by offset (in bits) */ +// "srl %0, %1\n" /* Shift right; now the requested byte is the first one */ +// :"=r"(res), "=r"(addr) +// :"1"(addr) +// :); +// return (uint8_t) res; /* This masks the lower byte from the returned word */ +// } + +// #define ax_array_read_u8(x, y) pgm_read_byte((x)+(y)) +// #endif //WITH_PGM_READ_HELPER + +// #ifdef printf +// #undef printf +// #endif + +//#define printf(...) ets_printf(__VA_ARGS__) +// #define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0];})) +// #define PGM_VOID_P const void * +// static inline void* memcpy_P(void* dest, PGM_VOID_P src, size_t count) { +// const uint8_t* read = (const uint8_t*)(src); +// uint8_t* write = (uint8_t*)(dest); + +// while (count) +// { +// *write++ = pgm_read_byte(read++); +// count--; +// } + +// return dest; +// } +//#define printf(fmt, ...) do { static const char fstr[] PROGMEM = fmt; char rstr[sizeof(fmt)]; memcpy_P(rstr, fstr, sizeof(rstr)); ets_printf(rstr, ##__VA_ARGS__); } while (0) +//#define strcpy_P(dst, src) do { static const char fstr[] PROGMEM = src; memcpy_P(dst, fstr, sizeof(src)); } while (0) + +#elif defined(WIN32) + +/* Windows CE stuff */ +#if defined(_WIN32_WCE) +#include +#define abort() exit(1) +#else +#include +#include +#include +#include +#endif /* _WIN32_WCE */ + +#include +#include +#undef getpid +#undef open +#undef close +#undef sleep +#undef gettimeofday +#undef dup2 +#undef unlink + +#define SOCKET_READ(A,B,C) recv(A,B,C,0) +#define SOCKET_WRITE(A,B,C) send(A,B,C,0) +#define SOCKET_CLOSE(A) closesocket(A) +#define srandom(A) srand(A) +#define random() rand() +#define getpid() _getpid() +#define snprintf _snprintf +#define open(A,B) _open(A,B) +#define dup2(A,B) _dup2(A,B) +#define unlink(A) _unlink(A) +#define close(A) _close(A) +#define read(A,B,C) _read(A,B,C) +#define write(A,B,C) _write(A,B,C) +#define sleep(A) Sleep(A*1000) +#define usleep(A) Sleep(A/1000) +#define strdup(A) _strdup(A) +#define chroot(A) _chdir(A) +#define chdir(A) _chdir(A) +#define alloca(A) _alloca(A) +#ifndef lseek +#define lseek(A,B,C) _lseek(A,B,C) +#endif + +/* This fix gets around a problem where a win32 application on a cygwin xterm + doesn't display regular output (until a certain buffer limit) - but it works + fine under a normal DOS window. This is a hack to get around the issue - + see http://www.khngai.com/emacs/tty.php */ +#define TTY_FLUSH() if (!_isatty(_fileno(stdout))) fflush(stdout); + +/* + * automatically build some library dependencies. + */ +#pragma comment(lib, "WS2_32.lib") +#pragma comment(lib, "AdvAPI32.lib") + +typedef int socklen_t; + +EXP_FUNC void STDCALL gettimeofday(struct timeval* t,void* timezone); +EXP_FUNC int STDCALL strcasecmp(const char *s1, const char *s2); +EXP_FUNC int STDCALL getdomainname(char *buf, int buf_size); + +#else /* Not Win32 */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SOCKET_READ(A,B,C) read(A,B,C) +#define SOCKET_WRITE(A,B,C) write(A,B,C) +#define SOCKET_CLOSE(A) if (A >= 0) close(A) +#define TTY_FLUSH() + +#ifndef be64toh +#define be64toh(x) __be64_to_cpu(x) +#endif + +#endif /* Not Win32 */ + +/* some functions to mutate the way these work */ +inline uint32_t htonl(uint32_t n){ + return ((n & 0xff) << 24) | + ((n & 0xff00) << 8) | + ((n & 0xff0000UL) >> 8) | + ((n & 0xff000000UL) >> 24); +} + +#define ntohl htonl + +EXP_FUNC int STDCALL ax_open(const char *pathname, int flags); + +#ifdef CONFIG_PLATFORM_LINUX +void exit_now(const char *format, ...) __attribute((noreturn)); +#else +void exit_now(const char *format, ...); +#endif + +/* Mutexing definitions */ +#if defined(CONFIG_SSL_CTX_MUTEXING) +#if defined(WIN32) +#define SSL_CTX_MUTEX_TYPE HANDLE +#define SSL_CTX_MUTEX_INIT(A) A=CreateMutex(0, FALSE, 0) +#define SSL_CTX_MUTEX_DESTROY(A) CloseHandle(A) +#define SSL_CTX_LOCK(A) WaitForSingleObject(A, INFINITE) +#define SSL_CTX_UNLOCK(A) ReleaseMutex(A) +#else +#include +#define SSL_CTX_MUTEX_TYPE pthread_mutex_t +#define SSL_CTX_MUTEX_INIT(A) pthread_mutex_init(&A, NULL) +#define SSL_CTX_MUTEX_DESTROY(A) pthread_mutex_destroy(&A) +#define SSL_CTX_LOCK(A) pthread_mutex_lock(&A) +#define SSL_CTX_UNLOCK(A) pthread_mutex_unlock(&A) +#endif +#else /* no mutexing */ +#define SSL_CTX_MUTEX_INIT(A) +#define SSL_CTX_MUTEX_DESTROY(A) +#define SSL_CTX_LOCK(A) +#define SSL_CTX_UNLOCK(A) +#endif + +#ifndef PROGMEM +#define PROGMEM +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/axtls/ssl/p12.c b/tools/sdk/axtls/ssl/p12.c new file mode 100644 index 0000000000..5bd2394626 --- /dev/null +++ b/tools/sdk/axtls/ssl/p12.c @@ -0,0 +1,483 @@ +/* + * 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. + */ + +/** + * Process PKCS#8/PKCS#12 keys. + * + * The decoding of a PKCS#12 key is fairly specific - this code was tested on a + * key generated with: + * + * openssl pkcs12 -export -in axTLS.x509_1024.pem -inkey axTLS.key_1024.pem + * -keypbe PBE-SHA1-RC4-128 -certpbe PBE-SHA1-RC4-128 + * -name "p12_withoutCA" -out axTLS.withoutCA.p12 -password pass:abcd + * + * or with a certificate chain: + * + * openssl pkcs12 -export -in axTLS.x509_1024.pem -inkey axTLS.key_1024.pem + * -certfile axTLS.ca_x509.pem -keypbe PBE-SHA1-RC4-128 -certpbe + * PBE-SHA1-RC4-128 -name "p12_withCA" -out axTLS.withCA.p12 -password pass:abcd + * + * Note that the PBE has to be specified with PBE-SHA1-RC4-128. The + * private/public keys/certs have to use RSA encryption. Both the integrity + * and privacy passwords are the same. + * + * The PKCS#8 files were generated with something like: + * + * PEM format: + * openssl pkcs8 -in axTLS.key_512.pem -passout pass:abcd -topk8 -v1 + * PBE-SHA1-RC4-128 -out axTLS.encrypted_pem.p8 + * + * DER format: + * openssl pkcs8 -in axTLS.key_512.pem -passout pass:abcd -topk8 -outform DER + * -v1 PBE-SHA1-RC4-128 -out axTLS.encrypted.p8 + */ + +#include +#include +#include +#include "os_port.h" +#include "ssl.h" + +/* all commented out if not used */ +#ifdef CONFIG_SSL_USE_PKCS12 + +#define BLOCK_SIZE 64 +#define PKCS12_KEY_ID 1 +#define PKCS12_IV_ID 2 +#define PKCS12_MAC_ID 3 + +static char *make_uni_pass(const char *password, int *uni_pass_len); +static int p8_decrypt(const char *uni_pass, int uni_pass_len, + const uint8_t *salt, int iter, + uint8_t *priv_key, int priv_key_len, int id); +static int p8_add_key(SSL_CTX *ssl_ctx, uint8_t *priv_key); +static int get_pbe_params(uint8_t *buf, int *offset, + const uint8_t **salt, int *iterations); + +/* + * Take a raw pkcs8 block and then decrypt it and turn it into a normal key. + */ +int pkcs8_decode(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj, const char *password) +{ + uint8_t *buf = ssl_obj->buf; + int len, offset = 0; + int iterations; + int ret = SSL_NOT_OK; + uint8_t *version = NULL; + const uint8_t *salt; + uint8_t *priv_key; + int uni_pass_len; + char *uni_pass = make_uni_pass(password, &uni_pass_len); + + if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: Invalid p8 ASN.1 file\n"); +#endif + goto error; + } + + /* unencrypted key? */ + if (asn1_get_big_int(buf, &offset, &version) > 0 && *version == 0) + { + ret = p8_add_key(ssl_ctx, buf); + goto error; + } + + if (get_pbe_params(buf, &offset, &salt, &iterations) < 0) + goto error; + + if ((len = asn1_next_obj(buf, &offset, ASN1_OCTET_STRING)) < 0) + goto error; + + priv_key = &buf[offset]; + + p8_decrypt(uni_pass, uni_pass_len, salt, + iterations, priv_key, len, PKCS12_KEY_ID); + ret = p8_add_key(ssl_ctx, priv_key); + +error: + free(version); + free(uni_pass); + return ret; +} + +/* + * Take the unencrypted pkcs8 and turn it into a private key + */ +static int p8_add_key(SSL_CTX *ssl_ctx, uint8_t *priv_key) +{ + uint8_t *buf = priv_key; + int len, offset = 0; + int ret = SSL_NOT_OK; + + /* Skip the preamble and go straight to the private key. + We only support rsaEncryption (1.2.840.113549.1.1.1) */ + if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + asn1_skip_obj(buf, &offset, ASN1_INTEGER) < 0 || + asn1_skip_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OCTET_STRING)) < 0) + goto error; + + ret = asn1_get_private_key(&buf[offset], len, &ssl_ctx->rsa_ctx); + +error: + return ret; +} + +/* + * Create the unicode password + */ +static char *make_uni_pass(const char *password, int *uni_pass_len) +{ + int pass_len = 0, i; + char *uni_pass; + + if (password == NULL) + { + password = ""; + } + + uni_pass = (char *)malloc((strlen(password)+1)*2); + + /* modify the password into a unicode version */ + for (i = 0; i < (int)strlen(password); i++) + { + uni_pass[pass_len++] = 0; + uni_pass[pass_len++] = password[i]; + } + + uni_pass[pass_len++] = 0; /* null terminate */ + uni_pass[pass_len++] = 0; + *uni_pass_len = pass_len; + return uni_pass; +} + +/* + * Decrypt a pkcs8 block. + */ +static int p8_decrypt(const char *uni_pass, int uni_pass_len, + const uint8_t *salt, int iter, + uint8_t *priv_key, int priv_key_len, int id) +{ + uint8_t p[BLOCK_SIZE*2]; + uint8_t d[BLOCK_SIZE]; + uint8_t Ai[SHA1_SIZE]; + SHA1_CTX sha_ctx; + RC4_CTX rc4_ctx; + int i; + + for (i = 0; i < BLOCK_SIZE; i++) + { + p[i] = salt[i % SALT_SIZE]; + p[BLOCK_SIZE+i] = uni_pass[i % uni_pass_len]; + d[i] = id; + } + + /* get the key - no IV since we are using RC4 */ + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx, d, sizeof(d)); + SHA1_Update(&sha_ctx, p, sizeof(p)); + SHA1_Final(Ai, &sha_ctx); + + for (i = 1; i < iter; i++) + { + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx, Ai, SHA1_SIZE); + SHA1_Final(Ai, &sha_ctx); + } + + /* do the decryption */ + if (id == PKCS12_KEY_ID) + { + RC4_setup(&rc4_ctx, Ai, 16); + RC4_crypt(&rc4_ctx, priv_key, priv_key, priv_key_len); + } + else /* MAC */ + memcpy(priv_key, Ai, SHA1_SIZE); + + return 0; +} + +/* + * Take a raw pkcs12 block and the decrypt it and turn it into a certificate(s) + * and keys. + */ +int pkcs12_decode(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj, const char *password) +{ + uint8_t *buf = ssl_obj->buf; + int len, iterations, auth_safes_start, + auth_safes_end, auth_safes_len, key_offset, offset = 0; + int all_certs = 0; + uint8_t *version = NULL, *auth_safes = NULL, *cert, *orig_mac; + uint8_t key[SHA1_SIZE]; + uint8_t mac[SHA1_SIZE]; + const uint8_t *salt; + int uni_pass_len, ret = SSL_OK; + char *uni_pass = make_uni_pass(password, &uni_pass_len); + static const uint8_t pkcs_data[] = /* pkc7 data */ + { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01 }; + static const uint8_t pkcs_encrypted[] = /* pkc7 encrypted */ + { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x06 }; + static const uint8_t pkcs8_key_bag[] = /* 1.2.840.113549.1.12.10.1.2 */ + { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x0a, 0x01, 0x02 }; + + if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: Invalid p12 ASN.1 file\n"); +#endif + goto error; + } + + if (asn1_get_big_int(buf, &offset, &version) < 0 || *version != 3) + { + ret = SSL_ERROR_INVALID_VERSION; + goto error; + } + + /* remove all the boring pcks7 bits */ + if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OID)) < 0 || + len != sizeof(pkcs_data) || + memcmp(&buf[offset], pkcs_data, sizeof(pkcs_data))) + goto error; + + offset += len; + + if (asn1_next_obj(buf, &offset, ASN1_EXPLICIT_TAG) < 0 || + asn1_next_obj(buf, &offset, ASN1_OCTET_STRING) < 0) + goto error; + + /* work out the MAC start/end points (done on AuthSafes) */ + auth_safes_start = offset; + auth_safes_end = offset; + if (asn1_skip_obj(buf, &auth_safes_end, ASN1_SEQUENCE) < 0) + goto error; + + auth_safes_len = auth_safes_end - auth_safes_start; + auth_safes = malloc(auth_safes_len); + + memcpy(auth_safes, &buf[auth_safes_start], auth_safes_len); + + if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OID)) < 0 || + (len != sizeof(pkcs_encrypted) || + memcmp(&buf[offset], pkcs_encrypted, sizeof(pkcs_encrypted)))) + goto error; + + offset += len; + + if (asn1_next_obj(buf, &offset, ASN1_EXPLICIT_TAG) < 0 || + asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + asn1_skip_obj(buf, &offset, ASN1_INTEGER) < 0 || + asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OID)) < 0 || + len != sizeof(pkcs_data) || + memcmp(&buf[offset], pkcs_data, sizeof(pkcs_data))) + goto error; + + offset += len; + + /* work out the salt for the certificate */ + if (get_pbe_params(buf, &offset, &salt, &iterations) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_IMPLICIT_TAG)) < 0) + goto error; + + /* decrypt the certificate */ + cert = &buf[offset]; + if ((ret = p8_decrypt(uni_pass, uni_pass_len, salt, iterations, cert, + len, PKCS12_KEY_ID)) < 0) + goto error; + + offset += len; + + /* load the certificate */ + key_offset = 0; + all_certs = asn1_next_obj(cert, &key_offset, ASN1_SEQUENCE); + + /* keep going until all certs are loaded */ + while (key_offset < all_certs) + { + int cert_offset = key_offset; + + if (asn1_skip_obj(cert, &cert_offset, ASN1_SEQUENCE) < 0 || + asn1_next_obj(cert, &key_offset, ASN1_SEQUENCE) < 0 || + asn1_skip_obj(cert, &key_offset, ASN1_OID) < 0 || + asn1_next_obj(cert, &key_offset, ASN1_EXPLICIT_TAG) < 0 || + asn1_next_obj(cert, &key_offset, ASN1_SEQUENCE) < 0 || + asn1_skip_obj(cert, &key_offset, ASN1_OID) < 0 || + asn1_next_obj(cert, &key_offset, ASN1_EXPLICIT_TAG) < 0 || + (len = asn1_next_obj(cert, &key_offset, ASN1_OCTET_STRING)) < 0) + goto error; + + if ((ret = add_cert(ssl_ctx, &cert[key_offset], len)) < 0) + goto error; + + key_offset = cert_offset; + } + + if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OID)) < 0 || + len != sizeof(pkcs_data) || + memcmp(&buf[offset], pkcs_data, sizeof(pkcs_data))) + goto error; + + offset += len; + + if (asn1_next_obj(buf, &offset, ASN1_EXPLICIT_TAG) < 0 || + asn1_next_obj(buf, &offset, ASN1_OCTET_STRING) < 0 || + asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OID)) < 0 || + (len != sizeof(pkcs8_key_bag)) || + memcmp(&buf[offset], pkcs8_key_bag, sizeof(pkcs8_key_bag))) + goto error; + + offset += len; + + /* work out the salt for the private key */ + if (asn1_next_obj(buf, &offset, ASN1_EXPLICIT_TAG) < 0 || + asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + get_pbe_params(buf, &offset, &salt, &iterations) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OCTET_STRING)) < 0) + goto error; + + /* decrypt the private key */ + cert = &buf[offset]; + if ((ret = p8_decrypt(uni_pass, uni_pass_len, salt, iterations, cert, + len, PKCS12_KEY_ID)) < 0) + goto error; + + offset += len; + + /* load the private key */ + if ((ret = p8_add_key(ssl_ctx, cert)) < 0) + goto error; + + /* miss out on friendly name, local key id etc */ + if (asn1_skip_obj(buf, &offset, ASN1_SET) < 0) + goto error; + + /* work out the MAC */ + if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + asn1_skip_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OCTET_STRING)) < 0 || + len != SHA1_SIZE) + goto error; + + orig_mac = &buf[offset]; + offset += len; + + /* get the salt */ + if ((len = asn1_next_obj(buf, &offset, ASN1_OCTET_STRING)) < 0 || len != 8) + goto error; + + salt = &buf[offset]; + + /* work out what the mac should be */ + if ((ret = p8_decrypt(uni_pass, uni_pass_len, salt, iterations, + key, SHA1_SIZE, PKCS12_MAC_ID)) < 0) + goto error; + + hmac_sha1(auth_safes, auth_safes_len, key, SHA1_SIZE, mac); + + if (memcmp(mac, orig_mac, SHA1_SIZE)) + { + ret = SSL_ERROR_INVALID_HMAC; + goto error; + } + +error: + free(version); + free(uni_pass); + free(auth_safes); + return ret; +} + +/* + * Retrieve the salt/iteration details from a PBE block. + */ +static int get_pbe_params(uint8_t *buf, int *offset, + const uint8_t **salt, int *iterations) +{ + static const uint8_t pbeSH1RC4[] = /* pbeWithSHAAnd128BitRC4 */ + { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x01, 0x01 }; + + int i, len; + uint8_t *iter = NULL; + int error_code = SSL_ERROR_NOT_SUPPORTED; + + /* Get the PBE type */ + if (asn1_next_obj(buf, offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, offset, ASN1_OID)) < 0) + goto error; + + /* we expect pbeWithSHAAnd128BitRC4 (1.2.840.113549.1.12.1.1) + which is the only algorithm we support */ + if (len != sizeof(pbeSH1RC4) || + memcmp(&buf[*offset], pbeSH1RC4, sizeof(pbeSH1RC4))) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: pkcs8/pkcs12 must use \"PBE-SHA1-RC4-128\"\n"); +#endif + goto error; + } + + *offset += len; + + if (asn1_next_obj(buf, offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, offset, ASN1_OCTET_STRING)) < 0 || + len != 8) + goto error; + + *salt = &buf[*offset]; + *offset += len; + + if ((len = asn1_get_big_int(buf, offset, &iter)) < 0) + goto error; + + *iterations = 0; + for (i = 0; i < len; i++) + { + (*iterations) <<= 8; + (*iterations) += iter[i]; + } + + free(iter); + error_code = SSL_OK; /* got here - we are ok */ + +error: + return error_code; +} + +#endif diff --git a/tools/sdk/axtls/ssl/private_key.h b/tools/sdk/axtls/ssl/private_key.h new file mode 100644 index 0000000000..f72bee23ae --- /dev/null +++ b/tools/sdk/axtls/ssl/private_key.h @@ -0,0 +1,54 @@ +unsigned char default_private_key[] = { + 0x30, 0x82, 0x02, 0x5d, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, 0x00, 0xbd, + 0x0f, 0xd4, 0x42, 0xa8, 0x74, 0x87, 0x54, 0xaa, 0xb9, 0x3a, 0x1f, 0x8b, + 0xce, 0xbd, 0xb7, 0x65, 0xfb, 0x40, 0x3d, 0xd0, 0x11, 0x9a, 0x9c, 0xdc, + 0x82, 0x7c, 0xea, 0xa8, 0x17, 0xe1, 0x74, 0xf3, 0x05, 0x0e, 0x61, 0xc1, + 0xc1, 0x78, 0x8a, 0xb2, 0xba, 0x15, 0x22, 0x5a, 0xff, 0x9b, 0xb8, 0x7a, + 0x2e, 0x0f, 0x88, 0xb7, 0x74, 0xde, 0x04, 0x99, 0xa5, 0xa2, 0x99, 0x53, + 0x8b, 0xad, 0x78, 0x5a, 0x31, 0xed, 0xbc, 0x01, 0xe7, 0xdf, 0xe9, 0xec, + 0x2f, 0xa0, 0x5d, 0x53, 0xf6, 0xe6, 0x8a, 0xa0, 0xc8, 0x6d, 0x41, 0x45, + 0x63, 0x23, 0xb3, 0xcf, 0x4e, 0x50, 0x1f, 0x28, 0xdf, 0x36, 0xe2, 0x73, + 0xdf, 0xd6, 0xa1, 0xb3, 0x46, 0x4f, 0x6e, 0xbb, 0x0d, 0x9b, 0xef, 0xa8, + 0xf9, 0x4c, 0xa5, 0x71, 0xa1, 0x88, 0xdd, 0x07, 0xa9, 0x86, 0x0d, 0x3f, + 0xcd, 0x99, 0x23, 0xa2, 0x84, 0x77, 0x0f, 0x02, 0x03, 0x01, 0x00, 0x01, + 0x02, 0x81, 0x80, 0x26, 0x3f, 0xec, 0x96, 0xab, 0xd4, 0x1f, 0x89, 0x0e, + 0x9d, 0x38, 0xd8, 0x27, 0x05, 0xe5, 0xb6, 0x14, 0x08, 0xd7, 0xff, 0x69, + 0x78, 0x16, 0x4a, 0xc4, 0x06, 0x16, 0x55, 0xb7, 0x3a, 0x55, 0x9f, 0xbe, + 0x86, 0xf8, 0x58, 0xe8, 0xc5, 0x46, 0xa8, 0xf0, 0xed, 0xda, 0xd6, 0xbf, + 0x88, 0x55, 0x2d, 0xe6, 0x72, 0x29, 0x2c, 0x64, 0xc9, 0x5d, 0x1d, 0x9b, + 0x24, 0x3a, 0x98, 0x40, 0xa1, 0xd2, 0xaf, 0x5c, 0xab, 0x23, 0xe4, 0x33, + 0xd0, 0xea, 0x60, 0x52, 0xe7, 0x7a, 0x9e, 0x73, 0x5f, 0x2e, 0x80, 0xd1, + 0xdc, 0x6f, 0x47, 0x0f, 0x97, 0x80, 0x36, 0xd2, 0x30, 0x07, 0xdd, 0xd6, + 0xd7, 0x15, 0x89, 0x2b, 0x74, 0xd5, 0x7e, 0x8a, 0xbc, 0x63, 0x42, 0x0a, + 0xf2, 0x31, 0x29, 0xbf, 0xf9, 0xf9, 0xf0, 0x88, 0x8f, 0x8a, 0xc2, 0x22, + 0x6e, 0x15, 0x26, 0xb7, 0x5e, 0x5b, 0x58, 0x44, 0x1c, 0x3b, 0x79, 0x02, + 0x41, 0x00, 0xe1, 0xf1, 0xb2, 0xe5, 0xc8, 0x80, 0x93, 0x40, 0x50, 0x74, + 0x14, 0xdd, 0xb2, 0xf2, 0x27, 0x5c, 0x0c, 0x3d, 0xc0, 0x5f, 0xee, 0x9c, + 0x45, 0x6c, 0x13, 0x00, 0xdf, 0xd0, 0xd9, 0x83, 0xfa, 0x90, 0x2c, 0x84, + 0xf2, 0xaa, 0xc2, 0xdd, 0xfb, 0xcf, 0x03, 0x41, 0x88, 0x10, 0xc6, 0xbb, + 0x5e, 0xb7, 0xb6, 0x2e, 0xa6, 0x1d, 0xaa, 0xba, 0xfb, 0x4a, 0x72, 0xd8, + 0x9a, 0xad, 0x88, 0x0d, 0x6a, 0x15, 0x02, 0x41, 0x00, 0xd6, 0x36, 0x23, + 0xf3, 0x5d, 0x77, 0xc8, 0xd3, 0x49, 0xc1, 0x93, 0xfe, 0xca, 0x0d, 0xeb, + 0x9b, 0xda, 0xbd, 0x47, 0x28, 0x73, 0x97, 0xa0, 0x50, 0xd7, 0x4c, 0x24, + 0xdf, 0x9b, 0x0b, 0x37, 0xae, 0xc3, 0x31, 0xb5, 0x4f, 0x62, 0x08, 0xca, + 0xe5, 0xef, 0x97, 0x7b, 0x43, 0xa0, 0xda, 0x2b, 0x1f, 0xbf, 0xa8, 0x08, + 0x93, 0xd2, 0x16, 0x1c, 0x89, 0x99, 0xf1, 0xdf, 0x26, 0xd1, 0x42, 0x99, + 0x93, 0x02, 0x41, 0x00, 0xb1, 0x41, 0xe4, 0x7e, 0xdf, 0x20, 0xf7, 0xe4, + 0xf1, 0xf9, 0x4f, 0xd1, 0x6a, 0x2d, 0x0d, 0xf1, 0xe9, 0xec, 0x9c, 0x3a, + 0xe6, 0xc0, 0x94, 0xba, 0x27, 0xe2, 0x7c, 0xb4, 0xa5, 0xa1, 0x23, 0xf6, + 0xed, 0xe6, 0x53, 0x56, 0xe2, 0x50, 0x32, 0xd8, 0x02, 0x8e, 0xeb, 0xc7, + 0x75, 0x91, 0xd3, 0xca, 0x3e, 0xd4, 0x34, 0x20, 0x7c, 0x2b, 0xfb, 0x2f, + 0x3a, 0x10, 0x72, 0xb1, 0x07, 0x56, 0xb6, 0xcd, 0x02, 0x40, 0x1e, 0x3b, + 0xf2, 0x03, 0x0d, 0x74, 0x34, 0xb2, 0x2d, 0xbc, 0xd6, 0xc8, 0xa5, 0x78, + 0x25, 0x83, 0x0f, 0xf2, 0x9b, 0x32, 0x88, 0x6e, 0x24, 0x40, 0x84, 0xc2, + 0xc8, 0x89, 0x8e, 0xf6, 0x9c, 0x5b, 0x5c, 0x4d, 0x8d, 0xcb, 0xb0, 0x88, + 0x91, 0x2a, 0xb7, 0x10, 0x68, 0x63, 0x79, 0x36, 0x91, 0xd3, 0x9f, 0x57, + 0x76, 0x2e, 0x76, 0xfe, 0x8b, 0xf4, 0x97, 0xf7, 0xdd, 0x89, 0x3b, 0x0b, + 0xed, 0x65, 0x02, 0x41, 0x00, 0xb9, 0xaf, 0xbf, 0x09, 0xc9, 0x90, 0x26, + 0xf3, 0x72, 0x8b, 0xbf, 0xb3, 0x7c, 0xe7, 0x6f, 0x6f, 0x5b, 0xa3, 0x95, + 0xb8, 0x9e, 0x03, 0xb9, 0xcf, 0xa0, 0x53, 0xba, 0x32, 0xc1, 0xd3, 0xad, + 0x85, 0xbb, 0x79, 0x48, 0x09, 0xd6, 0x3f, 0x9c, 0xd9, 0x37, 0x91, 0x11, + 0x0d, 0x04, 0xd5, 0x3b, 0xca, 0x74, 0x5d, 0x1c, 0x91, 0x8d, 0x3d, 0xf1, + 0xf8, 0xf9, 0xbe, 0x35, 0xd7, 0xb2, 0x53, 0x50, 0x1d +}; +unsigned int default_private_key_len = 609; diff --git a/libraries/ESP8266WiFi/src/include/ssl.h b/tools/sdk/axtls/ssl/ssl.h similarity index 92% rename from libraries/ESP8266WiFi/src/include/ssl.h rename to tools/sdk/axtls/ssl/ssl.h index a10e9dfb7e..df4fed9bc4 100644 --- a/libraries/ESP8266WiFi/src/include/ssl.h +++ b/tools/sdk/axtls/ssl/ssl.h @@ -1,18 +1,18 @@ /* * Copyright (c) 2007-2016, Cameron Rich - * + * * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without + * + * 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, + * * 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 + * * 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 + * * 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 @@ -45,20 +45,20 @@ * - Portable across many platforms (written in ANSI C), and has language * bindings in C, C#, VB.NET, Java, Perl and Lua. * - Partial openssl API compatibility (via a wrapper). - * - A very small footprint (around 50-60kB for the library in 'server-only' + * - A very small footprint (around 50-60kB for the library in 'server-only' * mode). * - No dependencies on sockets - can use serial connections for example. * - A very simple API - ~ 20 functions/methods. * * A list of these functions/methods are described below. * - * @ref c_api + * @ref c_api * - * @ref bigint_api + * @ref bigint_api * - * @ref csharp_api + * @ref csharp_api * - * @ref java_api + * @ref java_api */ #ifndef HEADER_SSL_H #define HEADER_SSL_H @@ -67,15 +67,12 @@ extern "C" { #endif +#include + /* need to predefine before ssl_lib.h gets to it */ #define SSL_SESSION_ID_SIZE 32 -#define EXP_FUNC -#define STDCALL -// struct SSL_CTX_; -typedef struct SSL_CTX_ SSL_CTX; -typedef struct SSL_ SSL; -typedef struct SSL_EXTENSIONS_ SSL_EXTENSIONS; +#include "tls1.h" /* The optional parameters that can be given to the client/server SSL engine */ #define SSL_CLIENT_AUTHENTICATION 0x00010000 @@ -162,9 +159,15 @@ typedef struct SSL_EXTENSIONS_ SSL_EXTENSIONS; #define SSL_X509_CERT_COMMON_NAME 0 #define SSL_X509_CERT_ORGANIZATION 1 #define SSL_X509_CERT_ORGANIZATIONAL_NAME 2 -#define SSL_X509_CA_CERT_COMMON_NAME 3 -#define SSL_X509_CA_CERT_ORGANIZATION 4 -#define SSL_X509_CA_CERT_ORGANIZATIONAL_NAME 5 +#define SSL_X509_CERT_LOCATION 3 +#define SSL_X509_CERT_COUNTRY 4 +#define SSL_X509_CERT_STATE 5 +#define SSL_X509_CA_CERT_COMMON_NAME 6 +#define SSL_X509_CA_CERT_ORGANIZATION 7 +#define SSL_X509_CA_CERT_ORGANIZATIONAL_NAME 8 +#define SSL_X509_CA_CERT_LOCATION 9 +#define SSL_X509_CA_CERT_COUNTRY 10 +#define SSL_X509_CA_CERT_STATE 11 /* SSL object loader types */ #define SSL_OBJ_X509_CERT 1 @@ -182,16 +185,16 @@ typedef struct SSL_EXTENSIONS_ SSL_EXTENSIONS; /** * @brief Establish a new client/server context. * - * This function is called before any client/server SSL connections are made. + * This function is called before any client/server SSL connections are made. * - * Each new connection will use the this context's private key and - * certificate chain. If a different certificate chain is required, then a + * Each new connection will use the this context's private key and + * certificate chain. If a different certificate chain is required, then a * different context needs to be be used. * * There are two threading models supported - a single thread with one - * SSL_CTX can support any number of SSL connections - and multiple threads can - * support one SSL_CTX object each (the default). But if a single SSL_CTX - * object uses many SSL objects in individual threads, then the + * SSL_CTX can support any number of SSL connections - and multiple threads can + * support one SSL_CTX object each (the default). But if a single SSL_CTX + * object uses many SSL objects in individual threads, then the * CONFIG_SSL_CTX_MUTEXING option needs to be configured. * * @param options [in] Any particular options. At present the options @@ -210,7 +213,7 @@ typedef struct SSL_EXTENSIONS_ SSL_EXTENSIONS; * are passed during a handshake. * - SSL_DISPLAY_RSA (full mode build only): Display the RSA key details that * are passed during a handshake. - * - SSL_CONNECT_IN_PARTS (client only): To use a non-blocking version of + * - SSL_CONNECT_IN_PARTS (client only): To use a non-blocking version of * ssl_client_new(). * @param num_sessions [in] The number of sessions to be used for session * caching. If this value is 0, then there is no session caching. This option @@ -222,7 +225,7 @@ EXP_FUNC SSL_CTX * STDCALL ssl_ctx_new(uint32_t options, int num_sessions); /** * @brief Remove a client/server context. * - * Frees any used resources used by this context. Each connection will be + * Frees any used resources used by this context. Each connection will be * sent a "Close Notify" alert (if possible). * @param ssl_ctx [in] The client/server context. */ @@ -234,7 +237,7 @@ EXP_FUNC void STDCALL ssl_ctx_free(SSL_CTX *ssl_ctx); * @return ssl_ext Pointer to SSL_EXTENSIONS structure * */ -EXP_FUNC SSL_EXTENSIONS * STDCALL ssl_ext_new(); +EXP_FUNC SSL_EXTENSIONS * STDCALL ssl_ext_new(void); /** * @brief Set the host name for SNI extension @@ -264,7 +267,7 @@ EXP_FUNC void STDCALL ssl_ext_free(SSL_EXTENSIONS *ssl_ext); * It is up to the application to establish the logical connection (whether it * is a socket, serial connection etc). * @param ssl_ctx [in] The server context. - * @param client_fd [in] The client's file descriptor. + * @param client_fd [in] The client's file descriptor. * @return An SSL object reference. */ EXP_FUNC SSL * STDCALL ssl_server_new(SSL_CTX *ssl_ctx, int client_fd); @@ -272,28 +275,29 @@ EXP_FUNC SSL * STDCALL ssl_server_new(SSL_CTX *ssl_ctx, int client_fd); /** * @brief (client only) Establish a new SSL connection to an SSL server. * - * It is up to the application to establish the initial logical connection + * It is up to the application to establish the initial logical connection * (whether it is a socket, serial connection etc). * - * This is a normally a blocking call - it will finish when the handshake is - * complete (or has failed). To use in non-blocking mode, set + * This is a normally a blocking call - it will finish when the handshake is + * complete (or has failed). To use in non-blocking mode, set * SSL_CONNECT_IN_PARTS in ssl_ctx_new(). * @param ssl_ctx [in] The client context. * @param client_fd [in] The client's file descriptor. - * @param session_id [in] A 32 byte session id for session resumption. This + * @param session_id [in] A 32 byte session id for session resumption. This * can be null if no session resumption is being used or required. This option * is not used in skeleton mode. * @param sess_id_size The size of the session id (max 32) - * @param ssl_ext pointer to a structure with the activated SSL extensions and their values - * @return An SSL object reference. Use ssl_handshake_status() to check + * @param ssl_ext pointer to a structure with the activated SSL extensions + * and their values + * @return An SSL object reference. Use ssl_handshake_status() to check * if a handshake succeeded. */ EXP_FUNC SSL * STDCALL ssl_client_new(SSL_CTX *ssl_ctx, int client_fd, const uint8_t *session_id, uint8_t sess_id_size, SSL_EXTENSIONS* ssl_ext); /** - * @brief Free any used resources on this connection. - - * A "Close Notify" message is sent on this connection (if possible). It is up + * @brief Free any used resources on this connection. + + * A "Close Notify" message is sent on this connection (if possible). It is up * to the application to close the socket or file descriptor. * @param ssl [in] The ssl object reference. */ @@ -308,9 +312,9 @@ EXP_FUNC void STDCALL ssl_free(SSL *ssl); * buffer will be here. Do NOT ever free this memory as this buffer is used in * sucessive calls. If the call was unsuccessful, this value will be null. * @return The number of decrypted bytes: - * - if > 0, then the handshaking is complete and we are returning the number - * of decrypted bytes. - * - SSL_OK if the handshaking stage is successful (but not yet complete). + * - if > 0, then the handshaking is complete and we are returning the number + * of decrypted bytes. + * - SSL_OK if the handshaking stage is successful (but not yet complete). * - < 0 if an error. * @see ssl.h for the error code list. * @note Use in_data before doing any successive ssl calls. @@ -318,7 +322,7 @@ EXP_FUNC void STDCALL ssl_free(SSL *ssl); EXP_FUNC int STDCALL ssl_read(SSL *ssl, uint8_t **in_data); /** - * @brief Write to the SSL data stream. + * @brief Write to the SSL data stream. * if the socket is non-blocking and data is blocked then a check is made * to ensure that all data is sent (i.e. blocked mode is forced). * @param ssl [in] An SSL obect reference. @@ -345,14 +349,14 @@ EXP_FUNC int STDCALL ssl_calculate_write_length(SSL *ssl, int out_len); * to look for a file descriptor match. * @param ssl_ctx [in] The client/server context. * @param client_fd [in] The file descriptor. - * @return A reference to the SSL object. Returns null if the object could not + * @return A reference to the SSL object. Returns null if the object could not * be found. */ EXP_FUNC SSL * STDCALL ssl_find(SSL_CTX *ssl_ctx, int client_fd); /** - * @brief Get the session id for a handshake. - * + * @brief Get the session id for a handshake. + * * This will be a 32 byte sequence and is available after the first * handshaking messages are sent. * @param ssl [in] An SSL object reference. @@ -362,8 +366,8 @@ EXP_FUNC SSL * STDCALL ssl_find(SSL_CTX *ssl_ctx, int client_fd); EXP_FUNC const uint8_t * STDCALL ssl_get_session_id(const SSL *ssl); /** - * @brief Get the session id size for a handshake. - * + * @brief Get the session id size for a handshake. + * * This will normally be 32 but could be 0 (no session id) or something else. * @param ssl [in] An SSL object reference. * @return The size of the session id. @@ -376,15 +380,15 @@ EXP_FUNC uint8_t STDCALL ssl_get_session_id_size(const SSL *ssl); * @return The cipher id. This will be one of the following: * - SSL_AES128_SHA (0x2f) * - SSL_AES256_SHA (0x35) - * - SSL_RC4_128_SHA (0x05) - * - SSL_RC4_128_MD5 (0x04) + * - SSL_AES128_SHA256 (0x3c) + * - SSL_AES256_SHA256 (0x3d) */ EXP_FUNC uint8_t STDCALL ssl_get_cipher_id(const SSL *ssl); /** * @brief Return the status of the handshake. * @param ssl [in] An SSL object reference. - * @return SSL_OK if the handshake is complete and ok. + * @return SSL_OK if the handshake is complete and ok. * @see ssl.h for the error code list. */ EXP_FUNC int STDCALL ssl_handshake_status(const SSL *ssl); @@ -416,7 +420,7 @@ EXP_FUNC void STDCALL ssl_display_error(int error_code); /** * @brief Authenticate a received certificate. - * + * * This call is usually made by a client after a handshake is complete and the * context is in SSL_SERVER_VERIFY_LATER mode. * @param ssl [in] An SSL object reference. @@ -444,11 +448,11 @@ EXP_FUNC int STDCALL ssl_match_spki_sha256(const SSL *ssl, const uint8_t* hash); /** * @brief Retrieve an X.509 distinguished name component. - * + * * When a handshake is complete and a certificate has been exchanged, then the * details of the remote certificate can be retrieved. * - * This will usually be used by a client to check that the server's common + * This will usually be used by a client to check that the server's common * name matches the URL. * * @param ssl [in] An SSL object reference. @@ -456,9 +460,15 @@ EXP_FUNC int STDCALL ssl_match_spki_sha256(const SSL *ssl, const uint8_t* hash); * - SSL_X509_CERT_COMMON_NAME * - SSL_X509_CERT_ORGANIZATION * - SSL_X509_CERT_ORGANIZATIONAL_NAME + * - SSL_X509_CERT_LOCATION + * - SSL_X509_CERT_COUNTRY + * - SSL_X509_CERT_STATE * - SSL_X509_CA_CERT_COMMON_NAME * - SSL_X509_CA_CERT_ORGANIZATION * - SSL_X509_CA_CERT_ORGANIZATIONAL_NAME + * - SSL_X509_CA_CERT_LOCATION + * - SSL_X509_CA_CERT_COUNTRY + * - SSL_X509_CA_CERT_STATE * @return The appropriate string (or null if not defined) * @note Verification build mode must be enabled. */ @@ -470,7 +480,7 @@ EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component); * When a handshake is complete and a certificate has been exchanged, then the * details of the remote certificate can be retrieved. * - * This will usually be used by a client to check that the server's DNS + * This will usually be used by a client to check that the server's DNS * name matches the URL. * * @param ssl [in] An SSL object reference. @@ -532,9 +542,9 @@ EXP_FUNC int STDCALL ssl_obj_memory_load(SSL_CTX *ssl_ctx, int obj_type, const u #ifdef CONFIG_SSL_GENERATE_X509_CERT /** - * @brief Create an X.509 certificate. - * - * This certificate is a self-signed v1 cert with a fixed start/stop validity + * @brief Create an X.509 certificate. + * + * This certificate is a self-signed v1 cert with a fixed start/stop validity * times. It is signed with an internal private key in ssl_ctx. * * @param ssl_ctx [in] The client/server context. @@ -542,10 +552,10 @@ EXP_FUNC int STDCALL ssl_obj_memory_load(SSL_CTX *ssl_ctx, int obj_type, const u * @param dn [in] An array of distinguished name strings. The array is defined * by: * - SSL_X509_CERT_COMMON_NAME (0) - * - If SSL_X509_CERT_COMMON_NAME is empty or not defined, then the + * - If SSL_X509_CERT_COMMON_NAME is empty or not defined, then the * hostname will be used. * - SSL_X509_CERT_ORGANIZATION (1) - * - If SSL_X509_CERT_ORGANIZATION is empty or not defined, then $USERNAME + * - If SSL_X509_CERT_ORGANIZATION is empty or not defined, then $USERNAME * will be used. * - SSL_X509_CERT_ORGANIZATIONAL_NAME (2) * - SSL_X509_CERT_ORGANIZATIONAL_NAME is optional. diff --git a/tools/sdk/axtls/ssl/test/axTLS.ca_key.pem b/tools/sdk/axtls/ssl/test/axTLS.ca_key.pem new file mode 100644 index 0000000000..0c8c19b3fb --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.ca_key.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEAsSMwkpYHlwIsi1oxllJLjAPjjycx9t6Q3BOzXBSoZHc1wA+r +QVuKHarpe8tYOKlNP8b79ejbCv/1U3NlVkMJJtLZUPtDwTEwUZNEG17ixS438mGI +1AbHXvwhPaoT24UymEOcbJxAZuClDfzKpN7Cl6OzN7Ox44gHmBCBSnUhRAnJYxD6 +x8wBLw8HdH0bMdoc2+H4KyW31uMGva7C9YlUCPVQGPJsTP1DLRskqy+zO1NERUTO +XytHeYLlh/X/o+NYVvUf7WKu6qC3I4HK+OZ5OW3E+EaE73oYRmUVDaVavL7bRKEf +2NSbzowU+VsFEnyXIF7YnRFp0D1yrMzaC49bDQIDAQABAoIBAQCwOrNLUunwKaCJ +b00gIXW5sfDGbhc+ZUU3Pn5V4NN7SEJ4dt5JYrnxNCWgHLkDfiQ1jFEF4QlzUx0O +TiMGhCDpuCGueJx66uYIcnvywx7XT1kn0jNfxfK6JBsqDzg8ULL6W2GXiIhmEZ8E +YHh3OIvec2WMyED1flMXzWvj2M4ksfMgZH290T9BSxzlEj9X7dZu55K4sFtu0XNi +7uJDB0vF8KfW5gLpwj6pd7i32Cm/Pgpl+7lcqMNpDHo0U2dMyWeH1EmWinS4rHxd +mGDm0N0qK4BOYAJdasq7HwRjzDZkAPuNqcH0gOzSq3aYCI2tP2E6IvprM/vbqA4I +ooo+GDJhAoGBAORiphxweuGBRTpSqoi9qEICM2WMC2NZW8bpFyWn79CuALGzvvc+ +Buw8W3LVElByUyTVWBnBQQ1iXZGe9f1x2P9q8R1Bdl0rpePg3J9ff9674VRLrcov +M85/NUHkj1fJ+2CkCx7KG5BFm3GaAb74e+7MceEW/eErMmCqtNgkR2Z5AoGBAMaO +O9SnVNd4wgnJAjVgN4fqaXWNzZz6NYWtnFVIcTTO7vU1P9t5NjgcsdF9+SnLA/jV +Ylo5Pl0fLPKg5QtIvlooZjXB8hgKVjrVGRLFt9TN0tJMeJ//11Bo88MNMOf0OQPg +i2OMWI3w/oRFJthmpeYWOgXNlLOcoSW1LsnWR0Q1AoGBALAXi+KTq3tiM+FzSb/j +E+/JSJ28bC9u/7+Pi2RiZxrsfuaFI/H4ZlgRdaVFujhC3e6hfKtnAWRzepfEDAEd +neXaLAyVo9DUzbS1dQaBGNPA400eiOJCoNxP4t1qgEd9GhB6i4Ry6uvDb8YYq832 +Q4BtLEUUeC38I3y7QnMBDfhpAoGAZ13InA54xqvhKELy2WK7xhAs0rv93MkNcAhP +qL5L4RgRoqoUEmfp6BBYKh2Qx0cfTD2aNCo04znFppJIazV1k24Qt8+9/vHyrjIe +GX3BFBIKvNx+t5zzNLNOo66MVVT5EaGmLy7zMwHRHn75mBLoLv5HOpop3c+evQiz +0POyqjkCgYA2+ql0jS7Qbk7EPyFXftQhHcD/Ld8TKjonShkASoudSEHKwuQGBuit +ftPsg/E5YfhlRpQB6p00kXb4vZsdpFV38eXkyLuLwg0kbpaLedahIujIENNvWP1w +89T/ueiafWPqvwu3M7sAkkd/ReAQ0LcPwrsBHlOk0uujq+WV+b+Xfw== +-----END RSA PRIVATE KEY----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.ca_x509.cer b/tools/sdk/axtls/ssl/test/axTLS.ca_x509.cer new file mode 100644 index 0000000000..7bde7b0a42 Binary files /dev/null and b/tools/sdk/axtls/ssl/test/axTLS.ca_x509.cer differ diff --git a/tools/sdk/axtls/ssl/test/axTLS.ca_x509.pem b/tools/sdk/axtls/ssl/test/axTLS.ca_x509.pem new file mode 100644 index 0000000000..0dfd1f4d59 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.ca_x509.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDDjCCAfagAwIBAgIJAORglrABpAToMA0GCSqGSIb3DQEBBQUAMDQxMjAwBgNV +BAoTKWF4VExTIFByb2plY3QgRG9kZ3kgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MB4X +DTE2MTIzMDIxMDQyN1oXDTMwMDkwODIxMDQyN1owNDEyMDAGA1UEChMpYXhUTFMg +UHJvamVjdCBEb2RneSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQCxIzCSlgeXAiyLWjGWUkuMA+OPJzH23pDcE7Nc +FKhkdzXAD6tBW4odqul7y1g4qU0/xvv16NsK//VTc2VWQwkm0tlQ+0PBMTBRk0Qb +XuLFLjfyYYjUBsde/CE9qhPbhTKYQ5xsnEBm4KUN/Mqk3sKXo7M3s7HjiAeYEIFK +dSFECcljEPrHzAEvDwd0fRsx2hzb4fgrJbfW4wa9rsL1iVQI9VAY8mxM/UMtGySr +L7M7U0RFRM5fK0d5guWH9f+j41hW9R/tYq7qoLcjgcr45nk5bcT4RoTvehhGZRUN +pVq8vttEoR/Y1JvOjBT5WwUSfJcgXtidEWnQPXKszNoLj1sNAgMBAAGjIzAhMA8G +A1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBBQUAA4IB +AQByY8+gtxSKO5ASYKArY8Sb4xJw0MNwsosARm17sT/8UTerS9CssUQXkW4LaU3T +SzFVxRUz9O+74yu87W58IaxGNq80quFkOfpS39eCtbqD2e4Y/JuC30hK/GmhBquD +gVh3z3hD8+DUXq83T1+9zgjCppLeQfaFejbaJSwQ7+K6gJn5JZNiaHVGN1GO6lT6 +5W3zqep5zU6a4T5UeZqkYyuzfTBbIkgEga0JzPaCdd5JOrwFR3UNWlICOxr7htDI +FqiTrA0RH2ZNmrmJDcM1pFWlQAPnvDoRLeMpmvWZDnGrWYDzyt0j5G0bIPL7214c +b5kxOvfGlM4E6v+lMSw/HDrI +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.ca_x509_sha256.pem b/tools/sdk/axtls/ssl/test/axTLS.ca_x509_sha256.pem new file mode 100644 index 0000000000..0771ca651c --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.ca_x509_sha256.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDDjCCAfagAwIBAgIJAJRCXZlKhZeHMA0GCSqGSIb3DQEBCwUAMDQxMjAwBgNV +BAoTKWF4VExTIFByb2plY3QgRG9kZ3kgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MB4X +DTE2MTIzMDIxMDQyN1oXDTMwMDkwODIxMDQyN1owNDEyMDAGA1UEChMpYXhUTFMg +UHJvamVjdCBEb2RneSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQCxIzCSlgeXAiyLWjGWUkuMA+OPJzH23pDcE7Nc +FKhkdzXAD6tBW4odqul7y1g4qU0/xvv16NsK//VTc2VWQwkm0tlQ+0PBMTBRk0Qb +XuLFLjfyYYjUBsde/CE9qhPbhTKYQ5xsnEBm4KUN/Mqk3sKXo7M3s7HjiAeYEIFK +dSFECcljEPrHzAEvDwd0fRsx2hzb4fgrJbfW4wa9rsL1iVQI9VAY8mxM/UMtGySr +L7M7U0RFRM5fK0d5guWH9f+j41hW9R/tYq7qoLcjgcr45nk5bcT4RoTvehhGZRUN +pVq8vttEoR/Y1JvOjBT5WwUSfJcgXtidEWnQPXKszNoLj1sNAgMBAAGjIzAhMA8G +A1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4IB +AQAm3qU+APMkgTRCWhw0m4+06gc2iGaf7l+3i/Kg6EvDB9js4cI1sqzRpSdqdjTZ +BwVlIURlB6BnEMCB3hP69IF/oSnqrnIxx2KIeVJt4CCwW1mXKsBwxNMXwHYD3A02 +08eFTRkP0ofn+YBRfUYFkDFebqba4V3NBZtBW497YtQk/ssKAL1xaI0V26M4E/VH +jkJtk99mcMjfuD8HPoqjTeVBGtY2h0A3j2LQPmOJNdSxv30SJuVjvpG7vejQripq +9MW0kPMBIRKhBpUBLIthLLxm/2VBe0IHU34kpe60YpQdJqebbldtOG1Uxe4F2JpN +LfUXs2/UCNpEHS60Xl8UDJXA +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.encrypted.p8 b/tools/sdk/axtls/ssl/test/axTLS.encrypted.p8 new file mode 100644 index 0000000000..07feaac9b5 Binary files /dev/null and b/tools/sdk/axtls/ssl/test/axTLS.encrypted.p8 differ diff --git a/tools/sdk/axtls/ssl/test/axTLS.encrypted_pem.p8 b/tools/sdk/axtls/ssl/test/axTLS.encrypted_pem.p8 new file mode 100644 index 0000000000..bc28403bba --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.encrypted_pem.p8 @@ -0,0 +1,17 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIICnTAcBgoqhkiG9w0BDAEBMA4ECLZOmsNEeDZnAgIIAASCAnu22JX3BRRr9cTr +j4x62+iDbrqcwmhQkybM1xShFgWObY3/OQf1NJfH4DO4zGQN45ZN0X9zSUVRu8Dd +ycHls5qsROJ96PYQ8d1xnuh1C9TWmFiLieM0qUyn35raHcKPQiBl8PYHtNr3+m0K +bsql6T23hE5ZjVhbRtcRdRd9MsQeTZ6n4mdWPEhzN1+rmSPV8ybCbrtJl3/Dh1v8 +LnswXB92T6WcmHRyRiNsbAXR9SQkOaXFZ/1RUXDNqoRYZjlWPBWdcQf48mzgaDjq +3RXF1mjbOlX2x4/V4qVwH1qZADlT38fSRk/iVdRfureS+wfOuJgJ/g9Riwa0o41K +2q+sOEcTOv4rShXRGp/0ckeuwhARDdSMymlSBhgBWdf14qdgxCx0rAXYlRAc/4Ze +Zl9ErfydwdUfDJoPK+QlGZMF//hFRF+vdO/wJHleLsels4KaqN9v/sB+BrGWaeUC +ScKMISixquCwfWi2qGiqLQGsxHn0d6ejiMblZR4kTf7dcuWVWGXdf5VZqxLNP8Xg +zzjjeP59OxHRVH0ytGBUejTehcxWDKq+6ESAuujzVXa0v1+5QzZXsJ8rPyZOINzj +bdpN4Cr3tZj9ALrNzoC2oG62+OO45U7lg54cV1nyrQ2QiI4XFnt0WA06K1G1JrRW +a/y6nZkntGybbCpuuIBiWl2FfdcTepctiXcJ0vCYqVNOTT4L2Y1RwajDzALhgb7e +wOy0eA8gmOmMLNozSlMV7siL0LeE1WlotLwK+AHMU1lmPMqS7jK9nycXtZyg4IKl +eBAnW052fnKZhT4zNlfJkZqpcp6YWpCU16PWx6L+/FDzFPzswluHyfB72oVqRniI +2A== +-----END ENCRYPTED PRIVATE KEY----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.key_1024 b/tools/sdk/axtls/ssl/test/axTLS.key_1024 new file mode 100644 index 0000000000..e39791ec8b Binary files /dev/null and b/tools/sdk/axtls/ssl/test/axTLS.key_1024 differ diff --git a/tools/sdk/axtls/ssl/test/axTLS.key_1024.pem b/tools/sdk/axtls/ssl/test/axTLS.key_1024.pem new file mode 100644 index 0000000000..fd8226eba1 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.key_1024.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXQIBAAKBgQC9D9RCqHSHVKq5Oh+Lzr23ZftAPdARmpzcgnzqqBfhdPMFDmHB +wXiKsroVIlr/m7h6Lg+It3TeBJmloplTi614WjHtvAHn3+nsL6BdU/bmiqDIbUFF +YyOzz05QHyjfNuJz39ahs0ZPbrsNm++o+UylcaGI3Qephg0/zZkjooR3DwIDAQAB +AoGAJj/slqvUH4kOnTjYJwXlthQI1/9peBZKxAYWVbc6VZ++hvhY6MVGqPDt2ta/ +iFUt5nIpLGTJXR2bJDqYQKHSr1yrI+Qz0OpgUud6nnNfLoDR3G9HD5eANtIwB93W +1xWJK3TVfoq8Y0IK8jEpv/n58IiPisIibhUmt15bWEQcO3kCQQDh8bLlyICTQFB0 +FN2y8idcDD3AX+6cRWwTAN/Q2YP6kCyE8qrC3fvPA0GIEMa7Xre2LqYdqrr7SnLY +mq2IDWoVAkEA1jYj8113yNNJwZP+yg3rm9q9Ryhzl6BQ10wk35sLN67DMbVPYgjK +5e+Xe0Og2isfv6gIk9IWHImZ8d8m0UKZkwJBALFB5H7fIPfk8flP0WotDfHp7Jw6 +5sCUuififLSloSP27eZTVuJQMtgCjuvHdZHTyj7UNCB8K/svOhBysQdWts0CQB47 +8gMNdDSyLbzWyKV4JYMP8psyiG4kQITCyImO9pxbXE2Ny7CIkSq3EGhjeTaR059X +di52/ov0l/fdiTsL7WUCQQC5r78JyZAm83KLv7N8529vW6OVuJ4Duc+gU7oywdOt +hbt5SAnWP5zZN5ERDQTVO8p0XRyRjT3x+Pm+NdeyU1Ad +-----END RSA PRIVATE KEY----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.key_2048 b/tools/sdk/axtls/ssl/test/axTLS.key_2048 new file mode 100644 index 0000000000..00989873bb Binary files /dev/null and b/tools/sdk/axtls/ssl/test/axTLS.key_2048 differ diff --git a/tools/sdk/axtls/ssl/test/axTLS.key_2048.pem b/tools/sdk/axtls/ssl/test/axTLS.key_2048.pem new file mode 100644 index 0000000000..5ef719db71 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.key_2048.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEA+Vp2PKclcZoKZ3OicQZNA4XpGZbD96Gasb5E66voMPub7l+y +ln6A9CYveBna0i/cQHRCwpYuzzbHQgOjAAw7rcveiIqm8nJMxA8BFNMJCHv0knDl +RT3H28xoTt08Z/MCfCYyOXoVsJOS6BSOSdFVyzhfU6nAie5iskYnmKecmhYaFm94 +S8WWJMNgEvwzPyhdmE4rpqUBHRSu3zPgHUnRRIOfui5KdZGzKpaC+i1Gn58MOC4W +L8kguEMDCEkQD6zxFq0PX5GBgu+zVqCFByX7soxZB027FsmJUN6WNoo3hR/H1QV8 +RdXvgMbT00yymEnYVfn9ZL7nXShKI70Pi5Y11QIDAQABAoIBAQDQQBrrgPUmsW3r +BIowNwDu5lHNizrTf+ZAeBX7dbEP57NNHCN8yN5OCe4vMfis/kfGlNKEzQT/DlLP +8VWa3pyhA9kw1AumBIvUWmuexrmOmmeiPiNc9sIJ8edTpjWi4zO6F/RuSGYA+N8C +cNh9EhXDCaujpewlxjArj6fWOHXzwMewghiGCm/fW0rWri5HCQ7ec+WuHPC2KQGQ +mRDpkXUsxWzTIMIsMKe3M2jYD+pk4xkJqN1+OV/APmQfLyshkGD4EN/qG1dieMQ0 +e85HxxCxbFETOzip0+pHXMbtxY/ok25/SCdtBXkBUJK1KqAysEZdHtOWmmk4HDaz +Dx2PBbKpAoGBAP+BT/WXeVgtOv1idyv9RG34kOJCDaROtVk3g5MNLfj9mIklcwEd +SylhpFxvvrFQAWQIDFPzFkukMs8aIuC0Gm4zxH+8RF45lwhgcXlXP87IiIyW6Bqu +aglmWAM9UHol3/b2AD1UdpqGe0nvWo0rIqs4pdtGTA5BSSUYeaZXhzFDAoGBAPnW +GWqDarzSbZM4TWcrx6O+cjLnstxDW+cgSCIrm9iVq2ys+Hn5O03aN9SsklyGxXgo +ygdGvbYnnPl3ugT139KEiIeUSCBU15WP/NZejpHmtUHduDw1Y6SlBJ9T+p5CSDE+ +2kJoZu1zG7W3eBprZsyqNWtw3Dwc2N+emrF+NF8HAoGBANzErAVFq6if9E+KK/SL +cvwegXmun0DwbUu4ZuzBv45b+NfPzu4QlKgd4TmpqDhnK7x2I8jJyuLy7p/6Mla7 +5/Z+rnO8hcpwsmqfgozY8Z5HsYzgu46KU77penTaHtZcMYefCZf0ikJ8nrzEnxZJ +RjxxxwWPWRocGQp/emVbTconAoGAUClmFkr8YIGULvyNuWDOubdNpQ+6z/m87zfo +bS5Y3vGHA2OshlZ1tNEjwNVuUMndamSMDjGghWXIdDL6OMU7f6yOshHd4qHWWmLM +2WuVizLfTbb6ejcXNajNBuJHM6hIyaRFG7Gr9NxOM8weeTukzF6ArWyU/aSz4Wxe +bjz0SNkCgYBVC0xdMPauqO1Ie/Gp6SPrIx9+bDDlwEvnDki/2RN7z5IkmBnRFxPy +6wqBiMFRxJXI4q3SSSbicb+7TQlK2/Vq/bL6QfjjQM8ZEzpPenYpP/wyMQXdVxfh +1GFDTzeiAhXTvBsZVj8R64VNhNaNn4naMlC4hqxaZ2KA0wrjTRKR0g== +-----END RSA PRIVATE KEY----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.key_4096 b/tools/sdk/axtls/ssl/test/axTLS.key_4096 new file mode 100644 index 0000000000..df8a8fde95 Binary files /dev/null and b/tools/sdk/axtls/ssl/test/axTLS.key_4096 differ diff --git a/tools/sdk/axtls/ssl/test/axTLS.key_4096.pem b/tools/sdk/axtls/ssl/test/axTLS.key_4096.pem new file mode 100644 index 0000000000..73fb75f899 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.key_4096.pem @@ -0,0 +1,51 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIJJwIBAAKCAgEAwApOo9f0syXI8DmEkP88eHCgZZ8FumcICcqcFe0OywR9UsXU +dQhMqKfMLi8Wlco+rNqFcDfsNyAllCDiq89dp/aNj3inCVAoXnaJuiZQ6dX9UtBR +VEW9cr/z6RjgrZQ9+MkbOx+MXVd44I8jEWVuW2oK1eQzU+FUb12dj45mTaLpL6Bx +XcXGC7e2KSeO75iWwitMyGmJQirV8fttUNa6VfKu7isxESz5jaUmuSsMZIl6Hjm/ +KxmZxkBuFv1Zm2KkKqItV/WqQYCrngil1I5zJLjHWFNjA634U63yWZo5LWQY8pp5 +wy0stC87yJD70rsszjm3zejtXAVipm27+GWe1bKI6UAVfyG3y+bEAKOGc9b6UpUJ +7iRPd32DrZCJ1xubVW3Lx+gK5YILsf7fQARPAbc1KbuJ2GJ2v9ihINzkqyT6N6FJ +ns/BcZnHAXk+KorS03xDMgI/CMKEjoc5YjFY9ioOUvvtpeg2kb0VUqvAHOm4i+DU +f5pQ82uH16tHVk2YyZqNWNVu8cbYsLAKFYPtyur9EO2TeKhCI+vAjl5FNw3TQAjy +1N4P7olDpJh1Vkx5q2fbaQvIq1HMovSmGKKvObXjjAoqlwVaiCukkr/djV1Teu1J +T50aP7tqCOOrBYBaWHO1IOB6xFOSfpAkuZVf4gqHsl2jTiLY6zDhkafJgoECAwEA +AQKCAgAlKVlyZzXY/PTXV6oJjPqcq96+C3nGSm3Jx0VREOCN9L5zqAim5QZAlMf0 +H/SU4+Ag/uBXiNrTCAt9kKeMa8JJ4HIgU06vhK1rKjEYrpV1yo0M23cBgcVZUT/X +2ZKQxGEBpZj5Ze95mJWxjsFQenpSgkC6h0BPeQkny8vTndC6MU5Cgx+s77qVReWg +LSGBx9tUk6B2H8YJ4dQo0Wij/gls3FtxhzYlhrh76nuF1Yi+Y8QX2UDfDEMvlAQ5 +uqj+YqY2AdAYd1eM+WM8X5wHd9FcR817kBdW/PFS8BQ3tppd6ELTn4T0eedurr04 +4KV6b/IJri2dUPetmPUwE4gOV0vW5LP1DSNS+sBD1OrsQ+Ytovht868GLMQ/d6M+ +82IDz2at0lDQ+6JLGBrY2rOXYi22fqGgSg2ErDENgYU1dft1Yc8sAzCTl5WC/Bhg +IxbfUChsYqURvq7faaqVfb50FcMYUcj/rAXVSLOuix2HUgLsQSj2MTtvuR7+BUgh +2KEmiCaMJy6CQyIgtOTjhmPqMr5Se/JYi1SRG0SxZpsYhGRPfjC8jg1k/VmRoAmS +pvqfhqgUMB0vAjfynoxFOZGNZIVrSR+yuC3xaORBW5UAPGvZHS1XzuxdybjpPm74 +0NB1JIc3ylAWcJEWdpnpk8OzZCAhifx0Farrq6Xauk6/ZLtd4QKCAQEA4a0DaHcp +OqFTudM8kC/N21FuE9U5MRLtJ2HP42iTEAfMi1bpZjO35giqYhfxNJiyTPnWDbkS +HVvNuSLAG58/Xs0KTuXCEgWuALBFtgg39BrPTT9Kw2CdqCgIpx5ArBwF+3lDfGIH +lIeoOhR7OKnN8a1/6l7KVOHxV4FMX9aVmom8FKKqjZYcObY86MgLObMtt50v0cKY +GgNZCy1HLoXHRGJ+3pypZEV0qxbOt2jGAhEpDf/LdX9Ez4AIYK16/a5AvUnNJlvN +d28LPgTCvPK8Mhz/m+7ms8IfZ2j0hJgm2j9jiMTK0QvyhWq57TfrU+8HWCKzsUfH +M1Riwt0z8u9HpQKCAQEA2dhE79/lyaGe3lxqJmzxdLG3Khp3wAk4/SM6CP9elN9J +4kg7UFGIE1AUs73HPwlXmoOyE1r+g6W2CaNMds5qqJKOIIS/89mrGZs68hpTLbdR +rTrNNeTLlOQcF/txNfawYEtPwAedjIxUFATKDibbDwfe0p3mRZSm/ji0N3n5ehJl +yDwfaSVsZsoHWm0GUfhMVGwu1OZjAGGpGZIf/tcjMNQ3cKAmqAvRpRrlc51eUw5M ++Z+POgRY2mnrKgTUREFzaLG62umaTVTGC6dn++QLPmFgoFuloSUJNUbRRvIg9d+a +aatn2eiusBILVarQcHGWdysuMFqxUJ9VHQqCNqI4rQKCAQBjPcZF5kEHO3KqQS5c +6ejJDaIurpGb9wq7StQ02QPzBLr6e5ngC9ZPHnhu8sBrtMqT9zoehshkiL6LL7Dz +dLBVbC2gTIFvk3fVba76Qdr5SeDnw3GJQa+TByfm9fLSvPAUilsXE7TpqE5eXCtj +26hpIzchRdYMRd/v7zg63Q6lCvTezjnaUazP5EgcxfvJv/XWzRT+VWi158r8k0i+ +OK5McFQCaTpEkhagNkNpfHW26vz23woF/ZWw+ki02xU/AaYOl6nTuIM+hmKXP1iz +5rrD/uSZGhHx8ugEfa8psA9F4qJOvtvB2lMoQKrKmtCt9GtyYrBKwZnkBLP5pXT2 +3CrRAoIBABiIz/LIH6QezLq0Y8wiFuuSnFNkmboKD94Kmp2qzSctIrAWfH+mPxIV +wc8gf5Es5y3iySp+5A1Fm4PoXVNAGikUIGevK8M175w5rGDZ8CZE8DD3X2dDdl41 +dqiIzA5M0z51HO0+rlLG9y0uAOepHqDJvSGxYN7TSB93mWxqE1vZOJddlhgMe/Hz +rPJVNxICSe50JK4bqGjBlv7nQy07Y547OGc50kC43AqhRdhIj/gAs1Cl1Mau+KbY +qQCZfKKXUH0pDydaieNNueRUHVT0MQP8iZpl1/iXKDtU13sLCAVJAqYGBPM4znvL +/HTQgRs4375aIaCWhkPTPg3AQjwO9x0CggEANIoxDPtty49prkkd8xQQceySEbnf +CeTljNd1uUEqki5DSJMfXajwuSkUrhZAnSevT7k9BjsAzqHM9sWqo3C3PQpFA2Q/ +seTA7lSIxyKvQ4bt/ZaMMeryCzC/WKH81+F35IoQ616nzJz+A7khHX/+l6ZdS9Ud +LYmYUEB1PQVd0PFQQ67dnNCJ265Hi54XLez9rzuYbuNFIb+wg4FsjV8NHUQSMow3 +LQLLMO16nqs9lQA17WdTlhyR6fYrovh6h7puGzONesSF0s9uLSyiOQ9UDKenNPPb +nBdM3Bwq5M72o11IKwTPvq95e09o2eFY0SlqwqLdqeD9lrbh/HWfO9VpWA== +-----END RSA PRIVATE KEY----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.key_aes128.pem b/tools/sdk/axtls/ssl/test/axTLS.key_aes128.pem new file mode 100644 index 0000000000..470f29b514 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.key_aes128.pem @@ -0,0 +1,18 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: AES-128-CBC,7BFA0887B7740C1BBA458D0362E75F89 + +aBIhF2zVGRMFZAWg8s11WnxoTQhGabdzchHBxPltnipEgvwOM9FGmYnVIDsFPvyb +hSA2HgmN972SPeRG4hITzrIXiRZMBOd6Lchz9p2Ui/mqkR6RUfnUBkUtkgxGymSa +oD7WAmbpNG73+7KX4gV36tevC1dM9lQzbClhhXQL9FH9LFh11cS7ZFa9L/esWHbb +sxgicR8zG919UEA+XvhLPVXpYD3AVHTcyEHbPWiGY49SIEI+GOcLi6rvxQizcXKY +pFtmlk/jM06OdZWur5/qLg3HqGP/o8GUjjA6KuAe5SIWVrmlkHCYHj6c1KFLVQJZ +7qAUNvjVaELXOc3+SE64Fl4OMP/4MiUA5WJ+gcdIKFtX/qksjywzF7goNTsxB1ZX +8g9JP6m5BF2VS/Woz+9ypekzk7DEKST4Knh8cYBNdz6yYwX73FBb93jk1aPMXv2K +SzhupTSHyAt7ddvXm+QYXBrklpZgUcuvinrkb7TNYEDcc2h3iDkLMHhI2VW0fiSF +JcL2DZWLu1UChg+Nkc43+9f8Ao76tjJHdV+IkWfINlKz8cpKthIfOiUSQWYK4Czr +0E3dyUrljIqFyKmZGokQ2QH+kdMmcm2/R+8NwL4s0Y4k1ylB0mZ5+A55t0ESaUVC +8NJtoIMrLz2pyhf2ohXMVepcjvR/Id8vNxSlLFResmIwSo4orTZOnsHBlQqm5hJl +9dr8G0o7n7WVfGbHLlpuPHoKegn1OK5xLbDbAi14HnZIi7/lUnbQHMbFFBjyS5EE +v+SMbI7JU+5zeJc34WLUTm1zll1ZNpFH/76vlP7tUWxYqVUZfKYHOndqS4b1rAs2 +-----END RSA PRIVATE KEY----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.key_aes256.pem b/tools/sdk/axtls/ssl/test/axTLS.key_aes256.pem new file mode 100644 index 0000000000..5e9c5fd46d --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.key_aes256.pem @@ -0,0 +1,18 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: AES-256-CBC,5AA67B48694516B66EECE19E0F3BB048 + +eXbuyN1kJR84JMhFruS9yeJ/WnyD0V6h9w/6fhEcPfxW0HmFqgIk35IE4c4QYazZ +aMC0J1S19Yb4kKnRd7j0+92IDBw3B7zeJKjPDrcRDSo8R8K7O7+6MYwcmJJ/DZlC +yqcaHr3cJEiS4I8NS3EdffffFA37Uf2O4C26b96ewg899YZXmPtai6uOvKbF1A90 +aRV4PdCpJdJq0q69VfoSeQ5p//Wokb4RfDGWTNxpgclYr0SK2F8qfITjCNDbqR+E +r+6tRsy9VcHVRjswuewU19HOQNQzaPlIiNaoGBGvOVRHLdE0s8b1Czyh3oeuRAZi +EK/SPEdZ5JMWbtxpKi+rdqFZhW3sGE5T9QItYqAWezScOCcuZw7ivVITWj0HuAJl +YZnkL4CS2qMKfQ7oz/YBAuShDvfl/W1M2YXt8caoYIox8NWnGaifHbk+eP7sQRE3 +UMA/71gfz4AOUSKOWTNCen+qeAImyRi++6kFOVyAZnmvGAj1INv76xh6tHP9aDN+ +0ROlEMeL+4EyqEeTeRL5+i9xEGtA247hMjtwB6i8SDl2N9RZkIzGOj6GmJpWQhHK +qRSu+PvoDfSHqfHYXof0rtvCuKj6pAhYgKeL5Ycfc0FtJX6gTvErlKWENUrsJxgV +RJNcRbltxcOylmdYP2tUe/PxQCSFcYIzFbQbXJDoZ9hMgJRv086fzn/QWiZEx59o +9r8kKQrYhKjS34Aq13ghFBf/Mr+GKrB8JtO5DnlC4N9AnapVlDgeZn2NmXyVZygA +mcIq5MTJcZzCdX6PdzNVBsttRfYeItN9M8aP5q5YodBfuLXPOvFhV2J7wc5Bgt4i +-----END RSA PRIVATE KEY----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.key_device.pem b/tools/sdk/axtls/ssl/test/axTLS.key_device.pem new file mode 100644 index 0000000000..5c9a845847 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.key_device.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEAvV0Pomdmpxx7s19ue0itPlPusWrTSwofoWEU141dp7cS9eXc +SnQV5pfvYvvw21HsZHy+xW2cupjQBzvqPtrrqAz4p2E9VHTMuzvDSScj6GU0BUD+ +GQ3qthLkXMfh7pJZFN5DYtVqzSE+ufZlYlfBqsT1BON9eRs2fTf6OnMFApx0ANjJ +yFElu2cEf3iif/3Z6PF0iUNtKaDNDVvVBoiRa9mUuj4vxnyH4HmyzThp2bXDLMUO +Viz/WWZs9Nl/QoJduyJZGEii1UM5VS81qQnu2dT1g/E0yPXwtOQUnVgjSMPfW+CA +yJ1XTdSwVDSsyXApyxxtSEYbM81t3GGvmmCf+QIDAQABAoIBAFFO4COvmlgu1r6S +P3IYJqsYhukPIWKbGjHE6ZoUTR5ycWW8KPafGbhFjLhHzYeeiY4sMg27nwxQCSLS +CyaqAX3K9AmKqzbUYAQVCSkj8TscGVYYLgK8Awfi3MMp4Ez78dwQA4cwdAdYOwLG +VYoAfFvC7iIHPB0AHklt+7eVI5WWsYlOIf9aS6+PDVii86GVoCpBE0eNZjE3JJo7 +hC0ctcjOqSVZRPC4p5KLFI8QkwyEK3vstyIiQOKSCFbZIn5Wi0+d6A9K96WhwssM +OpmenLv3xgz4zrUkRDbv0cPAU+/e7ZVPCiIbL/Y78qk3lBjUuyztX6fwQ/eDFadw +BS6LcvECgYEA+Nlwgi1Kzcd46xKG7xryI0mYjHO4cbZMsTcB4FQK5xXkGlg6j+WD +NAi/LKDJhaKcBKIYDhYi8tY1ye7JSDmyrPfZ0WvQF8K4yprUAqidNIuwOPMASjTW +CEBgTfMwCATNYNiaQ8eRuTLyknF4I2lrc4Ifby7cYEZrJ6aLGyolvdcCgYEAws4J +rGQS8W1DmzrL9mIDlSUtMFkTWqhx7nvG4lCYWVGpMByiQwf4DRvcqmXhwPr0syaj +qE6nu8G3iuOywSx2qrPX1a6NzeoZZybOSL7poaVmnpxgtS1xXyo1Bdc5ZPPOom1T +apb1QXHIPFVFKsuKsrQvyXfYLFGlQbYh3TGrtq8CgYEAmDqT+95vI0ECNHNp/f0y +4OlVm53y2AUYF1S6Hhvra3/VwVP1xy80uvEa2dcmUEywOplaM8vQ51KpJvWfRkKd +jfg01Eqqys5AsxhR16qEOK+3Rq9InxyBThzrjOPWnyEo7jSy8gG0oGGNSI6HWspT +hB620hINmAub426bLCv1WJMCgYEAkdfBZEAT8o30BH5TfyVIO1v25fB6TfA4Q+yF +LKBcPtqlSPDXBkosClxmq2fVSS5ZDtsJwZMJfsb8C86G4JrSSOCV4VNqtNPjqtdh +rxLHRQ7YsjyvJlVcQHwP8Ex+mrbxZ6djwTQ9b36pA4pvWyfBsiK2eCXyQNPrXjPm +THzIat8CgYAXN7CO+EUKtBil/r3PTj8FpWxvfZiKMbmktiHKD9ntcN3te2hrOWVs +1SmrIzr8/eBIsh7OGS3LUZTb4wKGtY29N6fTHuoA8pYILeRcJALGZnmrsTyFDzGH +iXBSkZ94EXpywxWHAEglow028nQ9UNugKk9SIkpg42u4vrqhRitMqw== +-----END RSA PRIVATE KEY----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.key_end_chain.pem b/tools/sdk/axtls/ssl/test/axTLS.key_end_chain.pem new file mode 100644 index 0000000000..7c1cb6cbf3 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.key_end_chain.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEA7R4S75j5ZfknrzbsAvUnqS997FNk545sGo0YraDQ7CeJXGqe +DyUTpdwtzBt8H8/axNP1BFdgNEWnF1C1HXVbhqWxq16IlakqZYkYldHJMPQgFa3Y +uRN4Y0i8sn8A1Fbe69D//57JZr1wt+qxAJWWn0anPGXmR0HlO0At1ACQkKGSE+aj +TB2TnO7UTsjKRrXPv16FdWTXkJTVHUdVuAs6IfgAKkvQQ5zA8D6IXgjWsToWdFzl +I8eTDHZqZJiw8gPg7xG0jepN9JU05JRc4NduzeVj/0WT0tdilO0jQP/+8FgikdOe +DU6wo4/e0Ta5bdZe7apqOBfdDnq3EUnHO1ZQbQIDAQABAoIBADbu47Yse4L7YQ0/ +rRfWUfTpMsQgYd0far4P+Cqpeh1r32/Qp4OctFuVkeqaZ3w7PFSjQj1aPMh/ZoGJ +ShxkBus/0dSA1yXNBix1wYNcEb9Mn25GU1I1R4vA2y6DK98FrSl2xwgickhiFQ4W +yiD3huiphq8AcIQLqR679KIL63IF+lMnHmYTrm9/rkGvO/wiW55OMhLvhuR4w7/n +5g+PMBLF4vEqtN6wEpb5f3Q8ugNCG35ykpgBMFWI6FGGmcZkYgux+xnTweZ9+Xol +tBQRrq9cY3/ouIrRX4K30e/EcaJN0eA0Cx9WerEHfYO45BWUJGySsxPab9vk6Qep +uxRnHoECgYEA+uv054HQKGQOZPjgZ9lCqfPB4wQ98T4hNSLgNwAkd85D7UtF6Wb9 +GMsEecJ5aPIQjDN6dTT6Nb45AV4e0XWtQFtxHFXP6SKfyIlf0Zcl0cd8Fvt7CX/e +ghZF6ndUxHaWtAltALVwo+Fi6LOgEN7+dsBjkAZf994cZNfqrr6B1s0CgYEA8eqY +u2p/QE7YNfw7naMUKDqgqGzo41IjF915rznYOyuO4hu+zGrL2D+7EeZnLWfSCSxl +t0uowOzDOKkm6XeungMyJFH0DnzhYEgh6K9AXMi3QF0zfgGrh7hhK5wFEt+a4nOY +hIAnqhANqISRhOOd0iT2VIt+igQhEQv8XLjAICECgYAVvkKfmQkfpuP0bfiMJzB2 +p6/Ca0iu0fJwt0/0lCeU1iPeuSoaupjuABGoN2jr5iX28DMJWwjfhVdNPgmvnuHf +dM0NZoY4ro5oAzdxYwac8gtXtn0H6rOuVB3E3ohS6e/PNA3lBNP473vxrDcPnzMv +uSYngdXpFa8iMe+dKtb3dQKBgQCAzse56q+Mvy5yODZJ7f4amXTXmP27pA1ZdKyI +90TB5KR0kg9aanbVUsG5ezNuwrvb9I7INPnKl4Yu0ioM35PTQKJfIl/PowChsmaT +rVSY0qp4E+gJ7Lu3TR44CR/Od87RSnln+5CjBV8wXj3ZQxTSQqoCRDABLseoevhJ +Knnp4QKBgEHHHpegaCXl7+kaPzD/qD38iN6AmoAya9ZUxCUH55bDmkTFu1ZGgA6S +87fuXQ2tzwFyOtaxAftPuOkSKMpZYRPJY92SalHA4WyN1pl0MhWMZQiyKOh0QQ7A +yaHjrLn5wPrhHhkpmYu2L1ZNiN+NIFDuD/j+APCX+wqb9otfbfxk +-----END RSA PRIVATE KEY----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.key_intermediate_ca.pem b/tools/sdk/axtls/ssl/test/axTLS.key_intermediate_ca.pem new file mode 100644 index 0000000000..57fef36137 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.key_intermediate_ca.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAzhdv9CgZ895+JuF4J5ttgKS8HDKL5uCAYOS2B+o1OkGzYRkS +I+vA41BpPfE8D8P9lgjcbzAOrOvgYHPZneE3Ix1mhlyPwbnXesC48AahbWXeHFJL +u3Hr3EfjIVngptIHF0/FXmLtOjcxLpP/mXyUTX7bm0NMhgEvxAX34fPfgM4r6AwP +YLwxJGl0c4rrb9choDmXp7+72NnjiO/pXzrUkI0VL+fV6U/cT9ro6p6wJYewvfXA +zqV01B76xf+QhYGp6h/HSZQntTQfA2KIp3H7jhaVXgC/CyyZ/fvx1QUAVCy8pMck +Fs7YuLtVuhAOZ1KpeZzaQotwRjTEeRkF99iCxwIDAQABAoIBAFNxi+O4hOGHuV42 +tjabKNgIWx2znY+KYJBaqhVET+7ZgS6UPxMKNlwTR7lLvjzH5xnjVpUySQ7cpkmH +Ppo9AN0X31YRjicq/sL12ytcE+o+b5LaA03Oz2euN5leUaZZrYNTyh7wQQrsI96v +D7NujIFgFryjoA0118gvfnEfE+SLW5q4m+n7D4cZ2D1nolDnOo2noLhKhMVWT9jp +UVoa5sO+9/Ap71ElAaet2LawNsKbyjjRuI84544G09zQ+YUfcelADaqtXyYZpSJL +iWrmHasD1w8NfiHB84y2hWHySoiuTBfVBJFfTjg075TaxBwCtDbzzEe0ecDCVGnb +gZfkevECgYEA5+5cUFf9LXt7Cwqc/lnuIUYmX7pvTPVVZbdjEzd1MUvu12p01cRN +QYk4K41LZsQYwDrCk82TFn1+hDbVt27i5r4FPJ9GbkSh4AiqUFDkqpqE/U06ZiUX +JOosU6laI6MmguWbXAAQuv2OwK7xVA0575HdbsEK8LRP2bSTRUYNFjkCgYEA43qb +FaKixVC4KOm8dyNYFHB5oldZW0u4ieemum8B+a9wd2BEG8FdxFw6IuGnKyMQ1BWu +NVwN2wZsHbosmCYxGO7cX4OT37711hdCr4pCGQhQ3gf9eNls4ZjjykZp8EHWQnx8 +SYl7sjQMQUjhfqePKwR396IGx4KSrc/l1rxKYP8CgYEAjYPPJ+bIQFw7s30CVeAh +gIQBHh/vkZGQTcQb27nW9AFU9nOqXlSsnvRPJaPNAiNcxs4Ts4OX3/0qmRmsRYSP +RiNjpp24p8eQzdX7tY3mOIKX6saYf4LaIFgSO+n1ahE+ilf296fCjZXw6HjWH2cC +lr710YJQXpZmsnuP8JDRo2ECgYBrasL+5WydZi+ASldPnuYByNb3HO46GTiMDlKB +6Ndy8zBVfqTKwnWnurFNNWc+DHHu5En+Mnjse0zkgLx8IFTA5FI13Ckg18i4jwVT +ZSMvNOkS340G2wz6PrsaEkQGSuCFRsld5Ej/7mn3DhZFO5R0iMipq94tqe/fmbN7 +wjAROwKBgHLl/XNhPTI/ed76ZjmCpbCvQlKZeYLhNbTS4lHvKCuniHKQsPz4BxjB +fuVCUDH61yQT7WM31zIMfzQZjx9hTgFYYvnptRWj9zIBlIZJEieX3//flvEJ3Qmd +/tbSoADa/1y+Y58biKkgmM4f4qS9h0AkVe88OCbpm14Xs2u7/4Nu +-----END RSA PRIVATE KEY----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.key_intermediate_ca2.pem b/tools/sdk/axtls/ssl/test/axTLS.key_intermediate_ca2.pem new file mode 100644 index 0000000000..5a4dbee96a --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.key_intermediate_ca2.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAqhp+ySEP4Oods+29nF39auqEmJ/qTUqQCz+9iWyOhp6NU5pJ +2LZiQNxVWIzasFHp9I1cvmf+4fnstMpaFl/TtdCpQnuV+eFIe7alEP6+Pc3YiFrO +zyO0XnqJcZwmmkpr5omvGcx9FbcrKflzfgmn4ZvGIdgtwkA+ZAj6WkpZHGGpzqLY +yAFz86fwANeT4I3a90aGwOEo/on+jvJA+O8KARsFx+yspxrfSZtNVTNWFfQfkIIt +7vOWnevZNAEkMnHxY8jDFq8EACNGDo3r0j+G5imRl8P0hdklpN261OS1hANVM3l2 +t2INNN/UkZjJe3/T7RW30A0VZ3Wk/nz3IgKlDwIDAQABAoIBACV6FurrPNtZ2Vd2 +DqtvzdCLgNE7klybC+dekLzBTRl9vzdnK9PyQu11XdxXlCr6sSfvKTrOIMrazHr8 +hiKd1EAfi9sY7W8TYmvXTsDSz0lAm+9Wym+6txeFudhtBdhCg0lUll6BviFVrM3f +psFjETjUoC9+uH4ut1BE5huUe9OTmOXxupLWdETcHViMc2VrpnDsNKX/lFIMFSo7 +3JDVojyTA/xdawJgkksCmQyHLICDvqJrIbLaDKxCfEiMKMyjVqgf9qwR33WAJ73e +ES8XMVtgIce2Zpzx6OITf+gNhS0ekqsxZJ56iiacOVHxpphNKk+BwSj1bBxHLRoo +narBebkCgYEA1BuLsbfr5lXAmGxE4JG1XrOZ7YtTqQNMYzy03s6fndoITqS+YpHk +dtPqM/lQ6qByqLbaPZFVEqecIb9EVRoG1m+9rIkAutiWf/vAWwr7w7yIbFID2YBH +50crmdtbK+1eoml/MkNx2grmgelqtMy5iOzwbPcFzmgXaTBzXvJvZEUCgYEAzU3F +f3QP0xgbrT0iK6138waegsuPaLoBdq+arlZ0LMzuN7T3KTKiNfkJKWbxoaECmu1p +PpJsQpG+0cQxyKU1PK9Pz+9qUXaPf/OsRKTcvpiS2kdBFXLPEgGi2JeSoPZxErYM +WuaqLIM8krYrV0JBRgGv38Pd0u0VaSbQvPx5u0MCgYEAidFoIE6IKf64CJH44w3q +EiGSt8Va06u/+48bWtZY4kEkOq1Sw0tWbltdhu3NRNaCCdvdzDldVKSxjz/vD3i8 +zqKGVNAkOEO47mnO35kwY0tiPTfBJpbyoXUeAHeGMvGmFtODgU5PcMS6Z9kZq2aG +e1CxG6waCraZ15BStnPCKx0CgYA2n7Olhp7TPn3WqQZXcq8QdTlleX2tkpfjGTPh +oNUGOnxDTB3a00L/c0QxxNcTdwB3ciVnZZPyXk7UBwxr4zD39XkZzQyPoijqFU5H +cUneWD/yXbT+XO6lTtQiJqn3s7pADTnaUbcDYuOR8XA0pkcxti8yLS3u+e+Ra6ds +MQy+ewKBgDfHrvBhbxyYskxc/xHnSeAZjrKsKoFNmV3/n9XTmms3WAVoCYydIEou +Pm3p5kDiaiTTqLBpxoa4g2tuaEXBJpgLwxq79Jod4PA1bnip45ERRrk4kRROIaFg +eHV6U0+PQTrdFhiJkvK7CgNZVr+NLiS1V1pM3x7xI81nAV9Sv4c5 +-----END RSA PRIVATE KEY----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.noname.p12 b/tools/sdk/axtls/ssl/test/axTLS.noname.p12 new file mode 100644 index 0000000000..0383293487 Binary files /dev/null and b/tools/sdk/axtls/ssl/test/axTLS.noname.p12 differ diff --git a/tools/sdk/axtls/ssl/test/axTLS.unencrypted.p8 b/tools/sdk/axtls/ssl/test/axTLS.unencrypted.p8 new file mode 100644 index 0000000000..df7c2e2160 Binary files /dev/null and b/tools/sdk/axtls/ssl/test/axTLS.unencrypted.p8 differ diff --git a/tools/sdk/axtls/ssl/test/axTLS.unencrypted_pem.p8 b/tools/sdk/axtls/ssl/test/axTLS.unencrypted_pem.p8 new file mode 100644 index 0000000000..dee0ed461e --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.unencrypted_pem.p8 @@ -0,0 +1,16 @@ +-----BEGIN PRIVATE KEY----- +MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL0P1EKodIdUqrk6 +H4vOvbdl+0A90BGanNyCfOqoF+F08wUOYcHBeIqyuhUiWv+buHouD4i3dN4EmaWi +mVOLrXhaMe28Aeff6ewvoF1T9uaKoMhtQUVjI7PPTlAfKN824nPf1qGzRk9uuw2b +76j5TKVxoYjdB6mGDT/NmSOihHcPAgMBAAECgYAmP+yWq9QfiQ6dONgnBeW2FAjX +/2l4FkrEBhZVtzpVn76G+FjoxUao8O3a1r+IVS3mciksZMldHZskOphAodKvXKsj +5DPQ6mBS53qec18ugNHcb0cPl4A20jAH3dbXFYkrdNV+irxjQgryMSm/+fnwiI+K +wiJuFSa3XltYRBw7eQJBAOHxsuXIgJNAUHQU3bLyJ1wMPcBf7pxFbBMA39DZg/qQ +LITyqsLd+88DQYgQxrtet7Yuph2quvtKctiarYgNahUCQQDWNiPzXXfI00nBk/7K +Deub2r1HKHOXoFDXTCTfmws3rsMxtU9iCMrl75d7Q6DaKx+/qAiT0hYciZnx3ybR +QpmTAkEAsUHkft8g9+Tx+U/Rai0N8ensnDrmwJS6J+J8tKWhI/bt5lNW4lAy2AKO +68d1kdPKPtQ0IHwr+y86EHKxB1a2zQJAHjvyAw10NLItvNbIpXglgw/ymzKIbiRA +hMLIiY72nFtcTY3LsIiRKrcQaGN5NpHTn1d2Lnb+i/SX992JOwvtZQJBALmvvwnJ +kCbzcou/s3znb29bo5W4ngO5z6BTujLB062Fu3lICdY/nNk3kRENBNU7ynRdHJGN +PfH4+b4117JTUB0= +-----END PRIVATE KEY----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.withCA.p12 b/tools/sdk/axtls/ssl/test/axTLS.withCA.p12 new file mode 100644 index 0000000000..0a89e7358b Binary files /dev/null and b/tools/sdk/axtls/ssl/test/axTLS.withCA.p12 differ diff --git a/tools/sdk/axtls/ssl/test/axTLS.withoutCA.p12 b/tools/sdk/axtls/ssl/test/axTLS.withoutCA.p12 new file mode 100644 index 0000000000..10e28fa01a Binary files /dev/null and b/tools/sdk/axtls/ssl/test/axTLS.withoutCA.p12 differ diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_1024.cer b/tools/sdk/axtls/ssl/test/axTLS.x509_1024.cer new file mode 100644 index 0000000000..784e26ffb7 Binary files /dev/null and b/tools/sdk/axtls/ssl/test/axTLS.x509_1024.cer differ diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_1024.pem b/tools/sdk/axtls/ssl/test/axTLS.x509_1024.pem new file mode 100644 index 0000000000..0a5c7a69f1 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.x509_1024.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICWDCCAUACCQClKsh4h/LnxTANBgkqhkiG9w0BAQUFADA0MTIwMAYDVQQKEylh +eFRMUyBQcm9qZWN0IERvZGd5IENlcnRpZmljYXRlIEF1dGhvcml0eTAeFw0xNjEy +MzAyMTA0MjdaFw0zMDA5MDgyMTA0MjdaMCwxFjAUBgNVBAoTDWF4VExTIFByb2pl +Y3QxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC +gYEAvQ/UQqh0h1SquTofi869t2X7QD3QEZqc3IJ86qgX4XTzBQ5hwcF4irK6FSJa +/5u4ei4PiLd03gSZpaKZU4uteFox7bwB59/p7C+gXVP25oqgyG1BRWMjs89OUB8o +3zbic9/WobNGT267DZvvqPlMpXGhiN0HqYYNP82ZI6KEdw8CAwEAATANBgkqhkiG +9w0BAQUFAAOCAQEAMuA8biHmpvS4EJ+K5guETizlFMpWgT/ALKM5iSTOr0cuGWKy +5HaRJbzhqO5qaDp3ubJilwwlPF4TSIeAo5HZLuaSKxxSJLF3xvbe2JvZVzdWaBcy +ZgEIOAiawYxeP+fJRMtiuUjHiab/jn094UYynBMGmtEXqz+pkAQzLT+BCqVVzraV +VK3xT6LKw/Yle3HSaIXpcraZNG3lX/Z0HLmi2isE/4LFCQTEuryCPrRyGI4waEhK +Dac9tfRCOpdgfahhip6YxH5lmep+ynXn2yFdznxmPX7cFP5VBJeoZBK0tTBIcrzb +61tPpvuHAUGR7JiY8Us4okDxBZC7m12WsSJrUA== +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_1024_sha256.pem b/tools/sdk/axtls/ssl/test/axTLS.x509_1024_sha256.pem new file mode 100644 index 0000000000..b1059b4385 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.x509_1024_sha256.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICWDCCAUACCQClKsh4h/LnxjANBgkqhkiG9w0BAQsFADA0MTIwMAYDVQQKEylh +eFRMUyBQcm9qZWN0IERvZGd5IENlcnRpZmljYXRlIEF1dGhvcml0eTAeFw0xNjEy +MzAyMTA0MjdaFw0zMDA5MDgyMTA0MjdaMCwxFjAUBgNVBAoTDWF4VExTIFByb2pl +Y3QxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC +gYEAvQ/UQqh0h1SquTofi869t2X7QD3QEZqc3IJ86qgX4XTzBQ5hwcF4irK6FSJa +/5u4ei4PiLd03gSZpaKZU4uteFox7bwB59/p7C+gXVP25oqgyG1BRWMjs89OUB8o +3zbic9/WobNGT267DZvvqPlMpXGhiN0HqYYNP82ZI6KEdw8CAwEAATANBgkqhkiG +9w0BAQsFAAOCAQEAbpbFPGnc74yvFgxKiNGA8+9azns10+KionRirc6g/1X1zBnJ +7vBXW9aXwUr2y9G3jnmX82eut0YnaJ3xlU5rp2NbGSH43fQd/OvWC+6yDFBeHfJG +JqbyP9oBkrUSuaXO/svsGUr8z1YVnxvtN7A1NGt+xQmgTyNq2QWg3MSQQwVtNsQt +84mQqU0BmmyRyi14LOCi2dHxjduXFVgHIcM6XzVL8lxQ1oaabA1mP5u8dzH+n+sT +uVDMmn6ABDZsnnCo9i7WidPI8pfJ4k6xR5l0wUdcOQeY8ynwUmILBt7lhKhxtAIG +j9SHuiQYstmr5+6wIBv6LRwjuXNDEwcqdT+o1g== +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_1024_sha384.pem b/tools/sdk/axtls/ssl/test/axTLS.x509_1024_sha384.pem new file mode 100644 index 0000000000..cbdca1d1b3 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.x509_1024_sha384.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICWDCCAUACCQClKsh4h/LnxzANBgkqhkiG9w0BAQwFADA0MTIwMAYDVQQKEylh +eFRMUyBQcm9qZWN0IERvZGd5IENlcnRpZmljYXRlIEF1dGhvcml0eTAeFw0xNjEy +MzAyMTA0MjdaFw0zMDA5MDgyMTA0MjdaMCwxFjAUBgNVBAoTDWF4VExTIFByb2pl +Y3QxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC +gYEAvQ/UQqh0h1SquTofi869t2X7QD3QEZqc3IJ86qgX4XTzBQ5hwcF4irK6FSJa +/5u4ei4PiLd03gSZpaKZU4uteFox7bwB59/p7C+gXVP25oqgyG1BRWMjs89OUB8o +3zbic9/WobNGT267DZvvqPlMpXGhiN0HqYYNP82ZI6KEdw8CAwEAATANBgkqhkiG +9w0BAQwFAAOCAQEAcVYgGWa/OFtWSpsH55h4iHan1Hj8WMzhvczirWDP8EaG3N1P +WVo7LQdfhs9OvQwLlacAym3eawwsMe7ODU6Iq2vsbajeKMuF0jb5teghb7dMIiIW +UIy3zRe9pmOZZpIcwJfuzTMTXMq+UksNfSzgB8mGqnIj+4D3UPXce5KYMvxzAjYU +HAAFR9+ZkTdpratH/qFlk14DJ4CKlH69/RUpekkXcn3lk1DutfQ15kaTnaFObTUs +HvGr2pX5PsofeR7DW4NStIMbOwMvTby6thCw8zImI2yyouCv+LkilGxmxEMAV85X +ZKu5dNZXbJwfOFjkmHEtDfmISsdl8NoQxyz55A== +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_1024_sha512.pem b/tools/sdk/axtls/ssl/test/axTLS.x509_1024_sha512.pem new file mode 100644 index 0000000000..83648e6630 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.x509_1024_sha512.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICWDCCAUACCQClKsh4h/LnyDANBgkqhkiG9w0BAQ0FADA0MTIwMAYDVQQKEylh +eFRMUyBQcm9qZWN0IERvZGd5IENlcnRpZmljYXRlIEF1dGhvcml0eTAeFw0xNjEy +MzAyMTA0MjdaFw0zMDA5MDgyMTA0MjdaMCwxFjAUBgNVBAoTDWF4VExTIFByb2pl +Y3QxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC +gYEAvQ/UQqh0h1SquTofi869t2X7QD3QEZqc3IJ86qgX4XTzBQ5hwcF4irK6FSJa +/5u4ei4PiLd03gSZpaKZU4uteFox7bwB59/p7C+gXVP25oqgyG1BRWMjs89OUB8o +3zbic9/WobNGT267DZvvqPlMpXGhiN0HqYYNP82ZI6KEdw8CAwEAATANBgkqhkiG +9w0BAQ0FAAOCAQEAbrG+mMdCorMaq6VHQC071CdXzqdUGFgXM/qpVjNo3tKjqUbD +73FJOYYoSgXO7aJPebraaZTdSpgHO2vdJrifUjrJg+2RKDwIzCP853fgi3Nm4n+R +7uDsd6K/cj4xvcnhIdmQZC3TPIJFujjbMy0Tw9EQ5Zoz5rNwR0Oy++HtWoULOjTe +xsVsagshFaGajLF6RXoH+caKHIi4HANlWwJvHCBpqQYUyhUCAHUm9Pdo0+h7Viuj +evzm3SPr5rOisE8xTDU4WPOhwel3lggZWfh6nbDG7+1sWmT4qTtAkv3V1m1o1h+8 +4TeJUOV9QHm88a2UUqWIZocaLxPYB6NThoBNVg== +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_2048.cer b/tools/sdk/axtls/ssl/test/axTLS.x509_2048.cer new file mode 100644 index 0000000000..45a291293a Binary files /dev/null and b/tools/sdk/axtls/ssl/test/axTLS.x509_2048.cer differ diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_2048.pem b/tools/sdk/axtls/ssl/test/axTLS.x509_2048.pem new file mode 100644 index 0000000000..95bdb5a3a2 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.x509_2048.pem @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIC3DCCAcQCCQClKsh4h/LnyTANBgkqhkiG9w0BAQUFADA0MTIwMAYDVQQKEylh +eFRMUyBQcm9qZWN0IERvZGd5IENlcnRpZmljYXRlIEF1dGhvcml0eTAeFw0xNjEy +MzAyMTA0MjdaFw0zMDA5MDgyMTA0MjdaMCwxFjAUBgNVBAoTDWF4VExTIFByb2pl +Y3QxEjAQBgNVBAMTCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC +AQoCggEBAPladjynJXGaCmdzonEGTQOF6RmWw/ehmrG+ROur6DD7m+5fspZ+gPQm +L3gZ2tIv3EB0QsKWLs82x0IDowAMO63L3oiKpvJyTMQPARTTCQh79JJw5UU9x9vM +aE7dPGfzAnwmMjl6FbCTkugUjknRVcs4X1OpwInuYrJGJ5innJoWGhZveEvFliTD +YBL8Mz8oXZhOK6alAR0Urt8z4B1J0USDn7ouSnWRsyqWgvotRp+fDDguFi/JILhD +AwhJEA+s8RatD1+RgYLvs1aghQcl+7KMWQdNuxbJiVDeljaKN4Ufx9UFfEXV74DG +09NMsphJ2FX5/WS+510oSiO9D4uWNdUCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA +HKqK24TYW7NvGoIifLaFyaSwAQV/OODpiZmTie3X5RBHR34v9fnBk5qnBf7EZEfC +uMg/mdMQm2Fst4uBzx9q8PltfcmCaX+/1M0F5nzhEszJ3cDevMBexNl7Q4nfYNTN +QShJyhSgr9cQ/K48k9IA64RRcRP9DWtSNzt0zzA4UCqlkBvKd6TdcC+rAzOigdhT +z0e1a9KVfKSxtXxyCAQZyKdsfWlhVyXPWd2urd8IfLfHdiFMKwyyreCCc4tCDjcA +QcJkv2bfL8Cb4cUd2vtI8kic9zUBFaOWyz9tOicGG2k3SBjN99iQfBAsqbHjtGnj ++dKbDCxXy4udsNINgfE3aA== +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_4096.cer b/tools/sdk/axtls/ssl/test/axTLS.x509_4096.cer new file mode 100644 index 0000000000..f90fb1cc28 Binary files /dev/null and b/tools/sdk/axtls/ssl/test/axTLS.x509_4096.cer differ diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_4096.pem b/tools/sdk/axtls/ssl/test/axTLS.x509_4096.pem new file mode 100644 index 0000000000..e6aaf2573d --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.x509_4096.pem @@ -0,0 +1,23 @@ +-----BEGIN CERTIFICATE----- +MIID3DCCAsQCCQClKsh4h/LnyjANBgkqhkiG9w0BAQUFADA0MTIwMAYDVQQKEylh +eFRMUyBQcm9qZWN0IERvZGd5IENlcnRpZmljYXRlIEF1dGhvcml0eTAeFw0xNjEy +MzAyMTA0MjdaFw0zMDA5MDgyMTA0MjdaMCwxFjAUBgNVBAoTDWF4VExTIFByb2pl +Y3QxEjAQBgNVBAMTCWxvY2FsaG9zdDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCC +AgoCggIBAMAKTqPX9LMlyPA5hJD/PHhwoGWfBbpnCAnKnBXtDssEfVLF1HUITKin +zC4vFpXKPqzahXA37DcgJZQg4qvPXaf2jY94pwlQKF52ibomUOnV/VLQUVRFvXK/ +8+kY4K2UPfjJGzsfjF1XeOCPIxFlbltqCtXkM1PhVG9dnY+OZk2i6S+gcV3Fxgu3 +tiknju+YlsIrTMhpiUIq1fH7bVDWulXyru4rMREs+Y2lJrkrDGSJeh45vysZmcZA +bhb9WZtipCqiLVf1qkGAq54IpdSOcyS4x1hTYwOt+FOt8lmaOS1kGPKaecMtLLQv +O8iQ+9K7LM45t83o7VwFYqZtu/hlntWyiOlAFX8ht8vmxACjhnPW+lKVCe4kT3d9 +g62Qidcbm1Vty8foCuWCC7H+30AETwG3NSm7idhidr/YoSDc5Ksk+jehSZ7PwXGZ +xwF5PiqK0tN8QzICPwjChI6HOWIxWPYqDlL77aXoNpG9FVKrwBzpuIvg1H+aUPNr +h9erR1ZNmMmajVjVbvHG2LCwChWD7crq/RDtk3ioQiPrwI5eRTcN00AI8tTeD+6J +Q6SYdVZMeatn22kLyKtRzKL0phiirzm144wKKpcFWogrpJK/3Y1dU3rtSU+dGj+7 +agjjqwWAWlhztSDgesRTkn6QJLmVX+IKh7Jdo04i2Osw4ZGnyYKBAgMBAAEwDQYJ +KoZIhvcNAQEFBQADggEBABPkfLZVIJ5z5cIhmiN5yqjMKotzGMwi7ihiPx8YSgBc +2grI7Aqyojn/gPBTvKXGRYCGC7aXIBo69RlbnZy0VW1fLqoNo8y6+zLiryCtxsv6 +3orQmHslh2WofzzhkNyazT3WoGvzV4qhzK5KU7vkrFpHcwiLFRglBMP4ruoOq8jY +4wKDrP3FpgaSpY4NOm7ro7LiYzmVcj6A9Gci6mm55er6ZGX0yI9O1FXOZCxABPJF +kDEAk4GQScbaEDBZWjFAhkmdwYnE3n6usPnURwp08vDRkd4bGdrMT2KtP5ASNigQ +vEaYj2pQJLS8Eljwc6nEBeGrZ14fGXXaVh+p9TKrpM8= +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_aes128.pem b/tools/sdk/axtls/ssl/test/axTLS.x509_aes128.pem new file mode 100644 index 0000000000..1eeb6013ca --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.x509_aes128.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICWDCCAUACCQClKsh4h/Ln0DANBgkqhkiG9w0BAQUFADA0MTIwMAYDVQQKEylh +eFRMUyBQcm9qZWN0IERvZGd5IENlcnRpZmljYXRlIEF1dGhvcml0eTAeFw0xNjEy +MzAyMTA0MjhaFw0zMDA5MDgyMTA0MjhaMCwxFjAUBgNVBAoTDWF4VExTIFByb2pl +Y3QxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC +gYEA8k4Lr67fner/JtPfbCJe9+RMyq4ErKmXDlxQnXDEcvn/7Mw/CcNQXDPDRTN2 +/pw0Cwb45Pgv0bqTAFPK2sWhp68QMiuyl+lIUGSrgXX69nW7B2cAp4YSNW55M8SQ +EISL3QOkzl1oHW3iuxxGeuCGuVv0i4gRxhQ1XkHdoGOc4G0CAwEAATANBgkqhkiG +9w0BAQUFAAOCAQEAPbTh7YlIYA/XOKC1Laf0SQ0HQU4hC9rd1IowBIyKYT5YlKVM +VIrmqN7B3ytUZbP3eL9ZO63G5NHmGk/i+RpxF+O0oX09uhIPWHlupZ1LeEHDwsSG +5OjZ1scU0bbIX/aBNPDL8hU7/TSTtL7NY9939cHE5LVwdSuOqndXl5nPFKxyJjfB +npworzs+UUwXLAcJSRHTruyRf6fvSfl1NdMabWiR/L7+tzDV0842+HwUsJLUlWFv +osK0avS8ER8PrFMRnKqGIK416B38ZMjn65G/J5v1j/RSHDAWjp+SYAFHaxiU0gEk +WOAZlVmG1vVlFk/ubTJ/vd+RAk0QYI+THgwlbQ== +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_aes256.pem b/tools/sdk/axtls/ssl/test/axTLS.x509_aes256.pem new file mode 100644 index 0000000000..89fe526af9 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.x509_aes256.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICWDCCAUACCQClKsh4h/Ln0TANBgkqhkiG9w0BAQUFADA0MTIwMAYDVQQKEylh +eFRMUyBQcm9qZWN0IERvZGd5IENlcnRpZmljYXRlIEF1dGhvcml0eTAeFw0xNjEy +MzAyMTA0MjhaFw0zMDA5MDgyMTA0MjhaMCwxFjAUBgNVBAoTDWF4VExTIFByb2pl +Y3QxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC +gYEAqn/ZBpw3WLD87W/rVp8rdvg2yoml5CSMfePkcXKCfbWMAkZOJJtMupPoMFC9 +CbQ5EUmSV47BHGTh0xnQK/4s4bc6lPVtkK7dJtFfonCsiTErW0p6z0q7tQfWFEd3 +NGNFv/qVIsB0hJDOJn8x30wYWCOY+gC+53KJzRVcRMoM75sCAwEAATANBgkqhkiG +9w0BAQUFAAOCAQEAqI4YkmyznQ9lE0+2cSkRX7ELJeKGedGFCCKJZaee5k9R4PBc +fg97WsEMARSl2WLzAkK3rjSQWslbRxb/u1NYhd2uBdrYGIMXgPyBIjV7sSoI0TkC +3muhke+W2yZsVp55DoJpfsX9dIfzbM0ICbaD509xuClfraIafO/6VLrw/+BzTTVM +DECTo1dCheYYXyOJPgdgdcABKKb3WkTLJPkV6SCK0D8xAHpTRR8AtT0xu60JDRoq +wcKZie02AXOgg3mEQPdvmVDb+cgOL2Cb/nyraS2OVKPRTZfQfvhve0mU3DN/TVDB +7N9bVd1WNst+bsNIE0SbnYiF/oSdnHGNQxaLGA== +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_bad_after.pem b/tools/sdk/axtls/ssl/test/axTLS.x509_bad_after.pem new file mode 100644 index 0000000000..c90d630499 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.x509_bad_after.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICWDCCAUACCQClKsh4h/Ln0zANBgkqhkiG9w0BAQUFADA0MTIwMAYDVQQKEylh +eFRMUyBQcm9qZWN0IERvZGd5IENlcnRpZmljYXRlIEF1dGhvcml0eTAeFw0xNjEy +MzAyMTA0MjhaFw0xNTEyMzEyMTA0MjhaMCwxFjAUBgNVBAoTDWF4VExTIFByb2pl +Y3QxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC +gYEAvQ/UQqh0h1SquTofi869t2X7QD3QEZqc3IJ86qgX4XTzBQ5hwcF4irK6FSJa +/5u4ei4PiLd03gSZpaKZU4uteFox7bwB59/p7C+gXVP25oqgyG1BRWMjs89OUB8o +3zbic9/WobNGT267DZvvqPlMpXGhiN0HqYYNP82ZI6KEdw8CAwEAATANBgkqhkiG +9w0BAQUFAAOCAQEAqk3O/LBqyketDzFqMe7L8nqmM/crpmjZ93KEwhrc7uRKJgXm +CjfTSm7D43l4xbz/NbHnNvSFnblFoioAQP23opotJV/WutmrGCIjpidLc682GvcP +DvhlOTAqoVFFWmjL6gj2iKEtIUzxCMI7K/h/znQvk/NrsfvOF0uZtpMoLqqo4o3Y +V2vogbTEPpr77952JMpsLvJYatwiYo8G7Pc8qdl86mk3tx1Kqn/Pl9CgMgj8tgFi +tcBRFePe3WvAiK7vnSqz7H4NUXrcv0RTA7f/bUXNWoRUI98GbYKVpxgIY7uFmLF8 +0jb92pWMlA9Ps0fAdMKs98c7dIaJi0buM5Mtuw== +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_bad_before.pem b/tools/sdk/axtls/ssl/test/axTLS.x509_bad_before.pem new file mode 100644 index 0000000000..3d65fe60b8 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.x509_bad_before.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICWDCCAUACCQClKsh4h/Ln0jANBgkqhkiG9w0BAQUFADA0MTIwMAYDVQQKEylh +eFRMUyBQcm9qZWN0IERvZGd5IENlcnRpZmljYXRlIEF1dGhvcml0eTAeFw0yNDEy +MzExNDAwMDBaFw0yNTEyMzExNDAwMDBaMCwxFjAUBgNVBAoTDWF4VExTIFByb2pl +Y3QxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC +gYEAvQ/UQqh0h1SquTofi869t2X7QD3QEZqc3IJ86qgX4XTzBQ5hwcF4irK6FSJa +/5u4ei4PiLd03gSZpaKZU4uteFox7bwB59/p7C+gXVP25oqgyG1BRWMjs89OUB8o +3zbic9/WobNGT267DZvvqPlMpXGhiN0HqYYNP82ZI6KEdw8CAwEAATANBgkqhkiG +9w0BAQUFAAOCAQEALWtzVdl7s7NHPKslDc0NN2N/kqd8V5Ug93s9POLPQV6Cq7fH +WPzxdU/IcLwocngqDzYEADlKJL1prRIP7IEtclRW109kVf5ge4waL7BIFogX0iII +WzjSlLTdYFo6ZK/oxwg86+zVA9UbkWbvQwSGE60Hqr8GEaqon09CxYUpFTtOq7qZ +Ikjjf1Rz/t1AAGXoN2Yls1hm2ONYFuxQq+dBME0sSL7hdhwFoOi/u3Q0QXmg4Z1Y +xe0J3Pg1mt5nsh4cY0QDNZdSbZz1p4jVY5RxQsoYzgyVYQWBeDJGKs2RN8o1CFko +EMQ4Bq65fSUs5hPnYGl4iibWmQQgAWkasKZwaw== +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_device.pem b/tools/sdk/axtls/ssl/test/axTLS.x509_device.pem new file mode 100644 index 0000000000..2ecdabefaa --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.x509_device.pem @@ -0,0 +1,34 @@ +-----BEGIN CERTIFICATE----- +MIICUjCCAbsCCQClKsh4h/LnyzANBgkqhkiG9w0BAQUFADAsMRYwFAYDVQQKEw1h +eFRMUyBQcm9qZWN0MRIwEAYDVQQDEwlsb2NhbGhvc3QwHhcNMTYxMjMwMjEwNDI3 +WhcNMzAwOTA4MjEwNDI3WjArMSkwJwYDVQQKEyBheFRMUyBQcm9qZWN0IERldmlj +ZSBDZXJ0aWZpY2F0ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL1d +D6JnZqcce7NfbntIrT5T7rFq00sKH6FhFNeNXae3EvXl3Ep0FeaX72L78NtR7GR8 +vsVtnLqY0Ac76j7a66gM+KdhPVR0zLs7w0knI+hlNAVA/hkN6rYS5FzH4e6SWRTe +Q2LVas0hPrn2ZWJXwarE9QTjfXkbNn03+jpzBQKcdADYychRJbtnBH94on/92ejx +dIlDbSmgzQ1b1QaIkWvZlLo+L8Z8h+B5ss04adm1wyzFDlYs/1lmbPTZf0KCXbsi +WRhIotVDOVUvNakJ7tnU9YPxNMj18LTkFJ1YI0jD31vggMidV03UsFQ0rMlwKcsc +bUhGGzPNbdxhr5pgn/kCAwEAATANBgkqhkiG9w0BAQUFAAOBgQBX+beg1jGMSqQd +6Q/d07mQCLuEwmXmmz7hc0lgp6IumjsxulO2xLiotXie7e3GIRAVgJsd6ysRJKim +IioOMxcwUMWw0CcqjcwqorczJjsqzW99dzCd3NcDiDxx+7Pye58D8qOLHGtafC9n +TjQELV6dNIUX5IfH/18jAkPEmFcOUg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDDjCCAfagAwIBAgIJAORglrABpAToMA0GCSqGSIb3DQEBBQUAMDQxMjAwBgNV +BAoTKWF4VExTIFByb2plY3QgRG9kZ3kgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MB4X +DTE2MTIzMDIxMDQyN1oXDTMwMDkwODIxMDQyN1owNDEyMDAGA1UEChMpYXhUTFMg +UHJvamVjdCBEb2RneSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQCxIzCSlgeXAiyLWjGWUkuMA+OPJzH23pDcE7Nc +FKhkdzXAD6tBW4odqul7y1g4qU0/xvv16NsK//VTc2VWQwkm0tlQ+0PBMTBRk0Qb +XuLFLjfyYYjUBsde/CE9qhPbhTKYQ5xsnEBm4KUN/Mqk3sKXo7M3s7HjiAeYEIFK +dSFECcljEPrHzAEvDwd0fRsx2hzb4fgrJbfW4wa9rsL1iVQI9VAY8mxM/UMtGySr +L7M7U0RFRM5fK0d5guWH9f+j41hW9R/tYq7qoLcjgcr45nk5bcT4RoTvehhGZRUN +pVq8vttEoR/Y1JvOjBT5WwUSfJcgXtidEWnQPXKszNoLj1sNAgMBAAGjIzAhMA8G +A1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBBQUAA4IB +AQByY8+gtxSKO5ASYKArY8Sb4xJw0MNwsosARm17sT/8UTerS9CssUQXkW4LaU3T +SzFVxRUz9O+74yu87W58IaxGNq80quFkOfpS39eCtbqD2e4Y/JuC30hK/GmhBquD +gVh3z3hD8+DUXq83T1+9zgjCppLeQfaFejbaJSwQ7+K6gJn5JZNiaHVGN1GO6lT6 +5W3zqep5zU6a4T5UeZqkYyuzfTBbIkgEga0JzPaCdd5JOrwFR3UNWlICOxr7htDI +FqiTrA0RH2ZNmrmJDcM1pFWlQAPnvDoRLeMpmvWZDnGrWYDzyt0j5G0bIPL7214c +b5kxOvfGlM4E6v+lMSw/HDrI +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_end_chain.pem b/tools/sdk/axtls/ssl/test/axTLS.x509_end_chain.pem new file mode 100644 index 0000000000..c0a4eb3c78 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.x509_end_chain.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDJDCCAgygAwIBAgIJAKUqyHiH8ufOMA0GCSqGSIb3DQEBCwUAMCgxJjAkBgNV +BAoTHWF4VExTIFByb2plY3QgSW50ZXJtZWRpYXRlIENBMB4XDTE2MTIzMDIxMDQy +OFoXDTMwMDkwODIxMDQyOFowLDEWMBQGA1UEChMNYXhUTFMgUHJvamVjdDESMBAG +A1UEAxMJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA +7R4S75j5ZfknrzbsAvUnqS997FNk545sGo0YraDQ7CeJXGqeDyUTpdwtzBt8H8/a +xNP1BFdgNEWnF1C1HXVbhqWxq16IlakqZYkYldHJMPQgFa3YuRN4Y0i8sn8A1Fbe +69D//57JZr1wt+qxAJWWn0anPGXmR0HlO0At1ACQkKGSE+ajTB2TnO7UTsjKRrXP +v16FdWTXkJTVHUdVuAs6IfgAKkvQQ5zA8D6IXgjWsToWdFzlI8eTDHZqZJiw8gPg +7xG0jepN9JU05JRc4NduzeVj/0WT0tdilO0jQP/+8FgikdOeDU6wo4/e0Ta5bdZe +7apqOBfdDnq3EUnHO1ZQbQIDAQABo00wSzAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB +/wQEAwIF4DArBgNVHREEJDAigg93d3cuZXhhbXBsZS5uZXSCD3d3dy5leGFtcGxl +Lm9yZzANBgkqhkiG9w0BAQsFAAOCAQEAbPQ1Y205Ricl1K2ByVa2RHJyYGP0Qj+H +5mWj4A92N1vAb6uOrliqFYOClYINGsKKC8YDZdyA4c8ZglCKZ2RePwOSdaWIw7wi +Efhysyq3WLSlo5jEcnkO7o5dV/7V7FX/+65UEXu35ZqaE8ZY++eotmLzccnInYP3 +1e4oaF5hyZIHVNCXnywNvchSkXjN0HhvIpeLTyzC5MQkQMMEOi8EBOgTGAo4UvL9 +eau3YhhpvfnCDlrRB6N79RcTLmJyOj5g1YO/9wn/du+EMwEkKUg5QJHzwUB2+ISp +57JjKh2BQt0g/XJfRugHQcNtjUu73Ziexpl0qaXjNjb8mvsuV9RX0g== +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_end_chain_bad.pem b/tools/sdk/axtls/ssl/test/axTLS.x509_end_chain_bad.pem new file mode 100644 index 0000000000..743dbc07e0 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.x509_end_chain_bad.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDJjCCAg6gAwIBAgIJAKUqyHiH8ufPMA0GCSqGSIb3DQEBCwUAMCoxKDAmBgNV +BAoTH2F4VExTIFByb2plY3QgSW50ZXJtZWRpYXRlIDIgQ0EwHhcNMTYxMjMwMjEw +NDI4WhcNMzAwOTA4MjEwNDI4WjAsMRYwFAYDVQQKEw1heFRMUyBQcm9qZWN0MRIw +EAYDVQQDEwlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB +AQDtHhLvmPll+SevNuwC9SepL33sU2TnjmwajRitoNDsJ4lcap4PJROl3C3MG3wf +z9rE0/UEV2A0RacXULUddVuGpbGrXoiVqSpliRiV0ckw9CAVrdi5E3hjSLyyfwDU +Vt7r0P//nslmvXC36rEAlZafRqc8ZeZHQeU7QC3UAJCQoZIT5qNMHZOc7tROyMpG +tc+/XoV1ZNeQlNUdR1W4Czoh+AAqS9BDnMDwPoheCNaxOhZ0XOUjx5MMdmpkmLDy +A+DvEbSN6k30lTTklFzg127N5WP/RZPS12KU7SNA//7wWCKR054NTrCjj97RNrlt +1l7tqmo4F90OercRScc7VlBtAgMBAAGjTTBLMAwGA1UdEwEB/wQCMAAwDgYDVR0P +AQH/BAQDAgXgMCsGA1UdEQQkMCKCD3d3dy5leGFtcGxlLm5ldIIPd3d3LmV4YW1w +bGUub3JnMA0GCSqGSIb3DQEBCwUAA4IBAQBGJydzARx5fNYprptRG9c3pqecGKlX +ArxbLe+K+83wS427HnWONnuZ5LJKGkuXjIeh1G/2AfKYXJz/SMN0IPYY3ro5Lt1Z +GOPyn01qcj6OkfyiUPCDIsVFS9V0TVLTBLTMZFa1j6nMHs8Ajmm10Fkf/NQP/CVk +zEgoktjb+wLqw1iPUGqkVepVtp3wg7VQY6E07SliNp/06Q3ue6xLJnYlKqFhUQf7 +064JyRIH9W/C2WnxWbKRBjsE4gCRnMvKQrCrfR64VohCr6XvygIIufwCG/CLJogn +4OJMqz1oDkABPgSgjNhOdwnt+3dvxbjQBiRy1ERfNAJLo+V6x6aO1Gqz +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_intermediate_ca.pem b/tools/sdk/axtls/ssl/test/axTLS.x509_intermediate_ca.pem new file mode 100644 index 0000000000..4fbad81b05 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.x509_intermediate_ca.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDAjCCAeqgAwIBAgIJAKUqyHiH8ufMMA0GCSqGSIb3DQEBCwUAMDQxMjAwBgNV +BAoTKWF4VExTIFByb2plY3QgRG9kZ3kgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MB4X +DTE2MTIzMDIxMDQyN1oXDTMwMDkwODIxMDQyN1owKDEmMCQGA1UEChMdYXhUTFMg +UHJvamVjdCBJbnRlcm1lZGlhdGUgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQDOF2/0KBnz3n4m4Xgnm22ApLwcMovm4IBg5LYH6jU6QbNhGRIj68Dj +UGk98TwPw/2WCNxvMA6s6+Bgc9md4TcjHWaGXI/Budd6wLjwBqFtZd4cUku7cevc +R+MhWeCm0gcXT8VeYu06NzEuk/+ZfJRNftubQ0yGAS/EBffh89+AzivoDA9gvDEk +aXRziutv1yGgOZenv7vY2eOI7+lfOtSQjRUv59XpT9xP2ujqnrAlh7C99cDOpXTU +HvrF/5CFganqH8dJlCe1NB8DYoincfuOFpVeAL8LLJn9+/HVBQBULLykxyQWzti4 +u1W6EA5nUql5nNpCi3BGNMR5GQX32ILHAgMBAAGjIzAhMBIGA1UdEwEB/wQIMAYB +Af8CAQAwCwYDVR0PBAQDAgGGMA0GCSqGSIb3DQEBCwUAA4IBAQAYt1Wq1XsZjOWf +mH9XzI3k8UEtErTkBX5SXH10siY5tYmHzH02jaZVRC1yNrxQevqARhR1yj3daKg3 ++innX8foKlYRCxTfFeE/HELcm7rIt5mrIGdGAFn2fnImO5kpXxbPk6IAXRTp6lN8 +QS08Ah1Aaeh0ae2Ruzx2TOnG/IuB7ChliJxepo0KtRw6RN6ETvC2KS0glSf5fPW7 +c18UPbTesecrki12FlaGbPD/sWHOltBIpPXzgef7G8b6CiYqaX0T3T/47RLRwrMm +SAcbMerJZoyudbLd+OHGtvz5kOmYCoZYkay121MSvtFucHnR3UjEui2lUbL1Qi92 +2L3MUIVn +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/axTLS.x509_intermediate_ca2.pem b/tools/sdk/axtls/ssl/test/axTLS.x509_intermediate_ca2.pem new file mode 100644 index 0000000000..ea8ab7d7df --- /dev/null +++ b/tools/sdk/axtls/ssl/test/axTLS.x509_intermediate_ca2.pem @@ -0,0 +1,37 @@ +-----BEGIN CERTIFICATE----- +MIIC+TCCAeGgAwIBAgIJAKUqyHiH8ufNMA0GCSqGSIb3DQEBCwUAMCgxJjAkBgNV +BAoTHWF4VExTIFByb2plY3QgSW50ZXJtZWRpYXRlIENBMB4XDTE2MTIzMDIxMDQy +N1oXDTMwMDkwODIxMDQyN1owKjEoMCYGA1UEChMfYXhUTFMgUHJvamVjdCBJbnRl +cm1lZGlhdGUgMiBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKoa +fskhD+DqHbPtvZxd/WrqhJif6k1KkAs/vYlsjoaejVOaSdi2YkDcVViM2rBR6fSN +XL5n/uH57LTKWhZf07XQqUJ7lfnhSHu2pRD+vj3N2Ihazs8jtF56iXGcJppKa+aJ +rxnMfRW3Kyn5c34Jp+GbxiHYLcJAPmQI+lpKWRxhqc6i2MgBc/On8ADXk+CN2vdG +hsDhKP6J/o7yQPjvCgEbBcfsrKca30mbTVUzVhX0H5CCLe7zlp3r2TQBJDJx8WPI +wxavBAAjRg6N69I/huYpkZfD9IXZJaTdutTktYQDVTN5drdiDTTf1JGYyXt/0+0V +t9ANFWd1pP589yICpQ8CAwEAAaMkMCIwEgYDVR0TAQH/BAgwBgEB/wIBCjAMBgNV +HQ8EBQMDBwWAMA0GCSqGSIb3DQEBCwUAA4IBAQBNWDjqxlO0BwMdyxfUs1wDsLiq +4hOmUFwCv8TuTFsL9aNe7OIJRT8IF2pHw07qyvAxJVEWUCLK/KLq0HrRTzRZO/tK +eNroHMHS+fBwFuHFp+1RGMK2rHLajxVVB6X0aeLWKrNKrvUQZL+Tx+NZ3dEO62rq +rANnElCrnyI1bIBKwHdUbOMOHeZAECr7H0KfvaX8F67aln4IwPzCauQM3DFf9h9Z +FvmxUdVgjRZK4e5he9k4gT/Faom0z/ApnW4DJRF8rpCPWqN872aNpL8NPZuOFtiD +Gzg5O4wJYx7OWIPa/qcQ0hTbn5waPzC68X448tlJTPiwyeKsYT3JwWqLi6o5 +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDAjCCAeqgAwIBAgIJAKUqyHiH8ufMMA0GCSqGSIb3DQEBCwUAMDQxMjAwBgNV +BAoTKWF4VExTIFByb2plY3QgRG9kZ3kgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MB4X +DTE2MTIzMDIxMDQyN1oXDTMwMDkwODIxMDQyN1owKDEmMCQGA1UEChMdYXhUTFMg +UHJvamVjdCBJbnRlcm1lZGlhdGUgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQDOF2/0KBnz3n4m4Xgnm22ApLwcMovm4IBg5LYH6jU6QbNhGRIj68Dj +UGk98TwPw/2WCNxvMA6s6+Bgc9md4TcjHWaGXI/Budd6wLjwBqFtZd4cUku7cevc +R+MhWeCm0gcXT8VeYu06NzEuk/+ZfJRNftubQ0yGAS/EBffh89+AzivoDA9gvDEk +aXRziutv1yGgOZenv7vY2eOI7+lfOtSQjRUv59XpT9xP2ujqnrAlh7C99cDOpXTU +HvrF/5CFganqH8dJlCe1NB8DYoincfuOFpVeAL8LLJn9+/HVBQBULLykxyQWzti4 +u1W6EA5nUql5nNpCi3BGNMR5GQX32ILHAgMBAAGjIzAhMBIGA1UdEwEB/wQIMAYB +Af8CAQAwCwYDVR0PBAQDAgGGMA0GCSqGSIb3DQEBCwUAA4IBAQAYt1Wq1XsZjOWf +mH9XzI3k8UEtErTkBX5SXH10siY5tYmHzH02jaZVRC1yNrxQevqARhR1yj3daKg3 ++innX8foKlYRCxTfFeE/HELcm7rIt5mrIGdGAFn2fnImO5kpXxbPk6IAXRTp6lN8 +QS08Ah1Aaeh0ae2Ruzx2TOnG/IuB7ChliJxepo0KtRw6RN6ETvC2KS0glSf5fPW7 +c18UPbTesecrki12FlaGbPD/sWHOltBIpPXzgef7G8b6CiYqaX0T3T/47RLRwrMm +SAcbMerJZoyudbLd+OHGtvz5kOmYCoZYkay121MSvtFucHnR3UjEui2lUbL1Qi92 +2L3MUIVn +-----END CERTIFICATE----- diff --git a/tools/sdk/axtls/ssl/test/ssltest.c b/tools/sdk/axtls/ssl/test/ssltest.c new file mode 100644 index 0000000000..ceb241ea19 --- /dev/null +++ b/tools/sdk/axtls/ssl/test/ssltest.c @@ -0,0 +1,2589 @@ +/* + * Copyright (c) 2007-2016, 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. + */ + +/* + * The testing of the crypto and ssl stuff goes here. Keeps the individual code + * modules from being uncluttered with test code. + * + * This is test code - I make no apologies for the quality! + */ + +#include +#include +#include +#include +#include +#include +#include + +#ifndef WIN32 +#include +#endif + +#include "os_port.h" +#include "ssl.h" + +#define DEFAULT_CERT "../ssl/test/axTLS.x509_1024.cer" +#define DEFAULT_KEY "../ssl/test/axTLS.key_1024" +//#define DEFAULT_SVR_OPTION SSL_DISPLAY_BYTES|SSL_DISPLAY_STATES +#define DEFAULT_SVR_OPTION 0 +//#define DEFAULT_CLNT_OPTION SSL_DISPLAY_BYTES|SSL_DISPLAY_STATES +#define DEFAULT_CLNT_OPTION 0 + +/* hack to remove gcc warning */ +#define SYSTEM(A) if (system(A) < 0) printf("system call error\n"); + +static int g_port = 19001; + +/************************************************************************** + * AES tests + * + * Run through a couple of the RFC3602 tests to verify that AES is correct. + **************************************************************************/ +#define TEST1_SIZE 16 +#define TEST2_SIZE 32 + +static int AES_test(BI_CTX *bi_ctx) +{ + AES_CTX aes_key; + int res = 1; + uint8_t key[TEST1_SIZE]; + uint8_t iv[TEST1_SIZE]; + + { + /* + Case #1: Encrypting 16 bytes (1 block) using AES-CBC + Key : 0x06a9214036b8a15b512e03d534120006 + IV : 0x3dafba429d9eb430b422da802c9fac41 + Plaintext : "Single block msg" + Ciphertext: 0xe353779c1079aeb82708942dbe77181a + + */ + char *in_str = "Single block msg"; + uint8_t ct[TEST1_SIZE]; + uint8_t enc_data[TEST1_SIZE]; + uint8_t dec_data[TEST1_SIZE]; + + bigint *key_bi = bi_str_import( + bi_ctx, "06A9214036B8A15B512E03D534120006"); + bigint *iv_bi = bi_str_import( + bi_ctx, "3DAFBA429D9EB430B422DA802C9FAC41"); + bigint *ct_bi = bi_str_import( + bi_ctx, "E353779C1079AEB82708942DBE77181A"); + bi_export(bi_ctx, key_bi, key, TEST1_SIZE); + bi_export(bi_ctx, iv_bi, iv, TEST1_SIZE); + bi_export(bi_ctx, ct_bi, ct, TEST1_SIZE); + + AES_set_key(&aes_key, key, iv, AES_MODE_128); + AES_cbc_encrypt(&aes_key, (const uint8_t *)in_str, + enc_data, sizeof(enc_data)); + if (memcmp(enc_data, ct, sizeof(ct))) + { + printf("Error: AES ENCRYPT #1 failed\n"); + goto end; + } + + AES_set_key(&aes_key, key, iv, AES_MODE_128); + AES_convert_key(&aes_key); + AES_cbc_decrypt(&aes_key, enc_data, dec_data, sizeof(enc_data)); + + if (memcmp(dec_data, in_str, sizeof(dec_data))) + { + printf("Error: AES DECRYPT #1 failed\n"); + goto end; + } + } + + { + /* + Case #2: Encrypting 32 bytes (2 blocks) using AES-CBC + Key : 0xc286696d887c9aa0611bbb3e2025a45a + IV : 0x562e17996d093d28ddb3ba695a2e6f58 + Plaintext : 0x000102030405060708090a0b0c0d0e0f + 101112131415161718191a1b1c1d1e1f + Ciphertext: 0xd296cd94c2cccf8a3a863028b5e1dc0a + 7586602d253cfff91b8266bea6d61ab1 + */ + uint8_t in_data[TEST2_SIZE]; + uint8_t ct[TEST2_SIZE]; + uint8_t enc_data[TEST2_SIZE]; + uint8_t dec_data[TEST2_SIZE]; + + bigint *in_bi = bi_str_import(bi_ctx, + "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"); + bigint *key_bi = bi_str_import( + bi_ctx, "C286696D887C9AA0611BBB3E2025A45A"); + bigint *iv_bi = bi_str_import( + bi_ctx, "562E17996D093D28DDB3BA695A2E6F58"); + bigint *ct_bi = bi_str_import(bi_ctx, + "D296CD94C2CCCF8A3A863028B5E1DC0A7586602D253CFFF91B8266BEA6D61AB1"); + bi_export(bi_ctx, in_bi, in_data, TEST2_SIZE); + bi_export(bi_ctx, key_bi, key, TEST1_SIZE); + bi_export(bi_ctx, iv_bi, iv, TEST1_SIZE); + bi_export(bi_ctx, ct_bi, ct, TEST2_SIZE); + + AES_set_key(&aes_key, key, iv, AES_MODE_128); + AES_cbc_encrypt(&aes_key, (const uint8_t *)in_data, + enc_data, sizeof(enc_data)); + + if (memcmp(enc_data, ct, sizeof(ct))) + { + printf("Error: ENCRYPT #2 failed\n"); + goto end; + } + + AES_set_key(&aes_key, key, iv, AES_MODE_128); + AES_convert_key(&aes_key); + AES_cbc_decrypt(&aes_key, enc_data, dec_data, sizeof(enc_data)); + if (memcmp(dec_data, in_data, sizeof(dec_data))) + { + printf("Error: DECRYPT #2 failed\n"); + goto end; + } + } + + res = 0; + printf("All AES tests passed\n"); + +end: + return res; +} + +/************************************************************************** + * SHA1 tests + * + * Run through a couple of the RFC3174 tests to verify that SHA1 is correct. + **************************************************************************/ +static int SHA1_test(BI_CTX *bi_ctx) +{ + SHA1_CTX ctx; + uint8_t ct[SHA1_SIZE]; + uint8_t digest[SHA1_SIZE]; + int res = 1; + + { + const char *in_str = "abc"; + bigint *ct_bi = bi_str_import(bi_ctx, + "A9993E364706816ABA3E25717850C26C9CD0D89D"); + bi_export(bi_ctx, ct_bi, ct, SHA1_SIZE); + + SHA1_Init(&ctx); + SHA1_Update(&ctx, (const uint8_t *)in_str, strlen(in_str)); + SHA1_Final(digest, &ctx); + + if (memcmp(digest, ct, sizeof(ct))) + { + printf("Error: SHA1 #1 failed\n"); + goto end; + } + } + + { + const char *in_str = + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; + bigint *ct_bi = bi_str_import(bi_ctx, + "84983E441C3BD26EBAAE4AA1F95129E5E54670F1"); + bi_export(bi_ctx, ct_bi, ct, SHA1_SIZE); + + SHA1_Init(&ctx); + SHA1_Update(&ctx, (const uint8_t *)in_str, strlen(in_str)); + SHA1_Final(digest, &ctx); + + if (memcmp(digest, ct, sizeof(ct))) + { + printf("Error: SHA1 #2 failed\n"); + goto end; + } + } + + res = 0; + printf("All SHA1 tests passed\n"); + +end: + return res; +} + +/************************************************************************** + * SHA256 tests + * + * Run through a couple of the SHA-2 tests to verify that SHA256 is correct. + **************************************************************************/ +static int SHA256_test(BI_CTX *bi_ctx) +{ + SHA256_CTX ctx; + uint8_t ct[SHA256_SIZE]; + uint8_t digest[SHA256_SIZE]; + int res = 1; + + { + const char *in_str = "abc"; + bigint *ct_bi = bi_str_import(bi_ctx, + "BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD"); + bi_export(bi_ctx, ct_bi, ct, SHA256_SIZE); + + SHA256_Init(&ctx); + SHA256_Update(&ctx, (const uint8_t *)in_str, strlen(in_str)); + SHA256_Final(digest, &ctx); + + if (memcmp(digest, ct, sizeof(ct))) + { + printf("Error: SHA256 #1 failed\n"); + goto end; + } + } + + { + const char *in_str = + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; + bigint *ct_bi = bi_str_import(bi_ctx, + "248D6A61D20638B8E5C026930C3E6039A33CE45964FF2167F6ECEDD419DB06C1"); + bi_export(bi_ctx, ct_bi, ct, SHA256_SIZE); + + SHA256_Init(&ctx); + SHA256_Update(&ctx, (const uint8_t *)in_str, strlen(in_str)); + SHA256_Final(digest, &ctx); + + if (memcmp(digest, ct, sizeof(ct))) + { + printf("Error: SHA256 #2 failed\n"); + goto end; + } + } + + res = 0; + printf("All SHA256 tests passed\n"); + +end: + return res; +} + +/************************************************************************** + * SHA384 tests + * + * Run through a couple of the SHA-2 tests to verify that SHA384 is correct. + **************************************************************************/ +static int SHA384_test(BI_CTX *bi_ctx) +{ + SHA384_CTX ctx; + uint8_t ct[SHA384_SIZE]; + uint8_t digest[SHA384_SIZE]; + int res = 1; + + { + const char *in_str = "abc"; + bigint *ct_bi = bi_str_import(bi_ctx, + "CB00753F45A35E8BB5A03D699AC65007272C32AB0EDED1631A8B605A43FF5BED8086072BA1E7CC2358BAECA134C825A7"); + bi_export(bi_ctx, ct_bi, ct, SHA384_SIZE); + + SHA384_Init(&ctx); + SHA384_Update(&ctx, (const uint8_t *)in_str, strlen(in_str)); + SHA384_Final(digest, &ctx); + + if (memcmp(digest, ct, sizeof(ct))) + { + printf("Error: SHA384 #1 failed\n"); + goto end; + } + } + + { + const char *in_str = + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; + bigint *ct_bi = bi_str_import(bi_ctx, + "3391FDDDFC8DC7393707A65B1B4709397CF8B1D162AF05ABFE8F450DE5F36BC6B0455A8520BC4E6F5FE95B1FE3C8452B"); + bi_export(bi_ctx, ct_bi, ct, SHA384_SIZE); + + SHA384_Init(&ctx); + SHA384_Update(&ctx, (const uint8_t *)in_str, strlen(in_str)); + SHA384_Final(digest, &ctx); + + if (memcmp(digest, ct, sizeof(ct))) + { + printf("Error: SHA384 #2 failed\n"); + goto end; + } + } + + res = 0; + printf("All SHA384 tests passed\n"); + +end: + return res; +} +/************************************************************************** + * SHA512 tests + * + * Run through a couple of the SHA-2 tests to verify that SHA512 is correct. + **************************************************************************/ +static int SHA512_test(BI_CTX *bi_ctx) +{ + SHA512_CTX ctx; + uint8_t ct[SHA512_SIZE]; + uint8_t digest[SHA512_SIZE]; + int res = 1; + + { + const char *in_str = "abc"; + bigint *ct_bi = bi_str_import(bi_ctx, + "DDAF35A193617ABACC417349AE20413112E6FA4E89A97EA20A9EEEE64B55D39A2192992A274FC1A836BA3C23A3FEEBBD454D4423643CE80E2A9AC94FA54CA49F"); + bi_export(bi_ctx, ct_bi, ct, SHA512_SIZE); + + SHA512_Init(&ctx); + SHA512_Update(&ctx, (const uint8_t *)in_str, strlen(in_str)); + SHA512_Final(digest, &ctx); + + if (memcmp(digest, ct, sizeof(ct))) + { + printf("Error: SHA512 #1 failed\n"); + goto end; + } + } + + { + const char *in_str = + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; + bigint *ct_bi = bi_str_import(bi_ctx, + "204A8FC6DDA82F0A0CED7BEB8E08A41657C16EF468B228A8279BE331A703C33596FD15C13B1B07F9AA1D3BEA57789CA031AD85C7A71DD70354EC631238CA3445"); + bi_export(bi_ctx, ct_bi, ct, SHA512_SIZE); + + SHA512_Init(&ctx); + SHA512_Update(&ctx, (const uint8_t *)in_str, strlen(in_str)); + SHA512_Final(digest, &ctx); + + if (memcmp(digest, ct, sizeof(ct))) + { + printf("Error: SHA512 #2 failed\n"); + goto end; + } + } + + res = 0; + printf("All SHA512 tests passed\n"); + +end: + return res; +} +/************************************************************************** + * MD5 tests + * + * Run through a couple of the RFC1321 tests to verify that MD5 is correct. + **************************************************************************/ +static int MD5_test(BI_CTX *bi_ctx) +{ + MD5_CTX ctx; + uint8_t ct[MD5_SIZE]; + uint8_t digest[MD5_SIZE]; + int res = 1; + + { + const char *in_str = "abc"; + bigint *ct_bi = bi_str_import(bi_ctx, + "900150983CD24FB0D6963F7D28E17F72"); + bi_export(bi_ctx, ct_bi, ct, MD5_SIZE); + + MD5_Init(&ctx); + MD5_Update(&ctx, (const uint8_t *)in_str, strlen(in_str)); + MD5_Final(digest, &ctx); + + if (memcmp(digest, ct, sizeof(ct))) + { + printf("Error: MD5 #1 failed\n"); + goto end; + } + } + + { + const char *in_str = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + bigint *ct_bi = bi_str_import( + bi_ctx, "D174AB98D277D9F5A5611C2C9F419D9F"); + bi_export(bi_ctx, ct_bi, ct, MD5_SIZE); + + MD5_Init(&ctx); + MD5_Update(&ctx, (const uint8_t *)in_str, strlen(in_str)); + MD5_Final(digest, &ctx); + + if (memcmp(digest, ct, sizeof(ct))) + { + printf("Error: MD5 #2 failed\n"); + goto end; + } + } + res = 0; + printf("All MD5 tests passed\n"); + +end: + return res; +} + +/************************************************************************** + * HMAC tests + * + * Run through a couple of the RFC2202 tests to verify that HMAC is correct. + **************************************************************************/ +static int HMAC_test(BI_CTX *bi_ctx) +{ + uint8_t key[SHA256_SIZE]; + uint8_t ct[SHA256_SIZE]; + uint8_t dgst[SHA256_SIZE]; + int res = 1; + const char *key_str; + + const char *data_str = "Hi There"; + bigint *key_bi = bi_str_import(bi_ctx, "0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B"); + bigint *ct_bi = bi_str_import(bi_ctx, "9294727A3638BB1C13F48EF8158BFC9D"); + bi_export(bi_ctx, key_bi, key, MD5_SIZE); + bi_export(bi_ctx, ct_bi, ct, MD5_SIZE); + hmac_md5((const uint8_t *)data_str, 8, key, MD5_SIZE, dgst); + if (memcmp(dgst, ct, MD5_SIZE)) + { + printf("HMAC MD5 #1 failed\n"); + goto end; + } + + data_str = "what do ya want for nothing?"; + key_str = "Jefe"; + ct_bi = bi_str_import(bi_ctx, "750C783E6AB0B503EAA86E310A5DB738"); + bi_export(bi_ctx, ct_bi, ct, MD5_SIZE); + hmac_md5((const uint8_t *)data_str, 28, (const uint8_t *)key_str, 4, dgst); + if (memcmp(dgst, ct, MD5_SIZE)) + { + printf("HMAC MD5 #2 failed\n"); + goto end; + } + + data_str = "Hi There"; + key_bi = bi_str_import(bi_ctx, "0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B"); + ct_bi = bi_str_import(bi_ctx, "B617318655057264E28BC0B6FB378C8EF146BE00"); + bi_export(bi_ctx, key_bi, key, SHA1_SIZE); + bi_export(bi_ctx, ct_bi, ct, SHA1_SIZE); + + hmac_sha1((const uint8_t *)data_str, 8, + (const uint8_t *)key, SHA1_SIZE, dgst); + if (memcmp(dgst, ct, SHA1_SIZE)) + { + printf("HMAC SHA1 #1 failed\n"); + goto end; + } + + data_str = "what do ya want for nothing?"; + key_str = "Jefe"; + ct_bi = bi_str_import(bi_ctx, "EFFCDF6AE5EB2FA2D27416D5F184DF9C259A7C79"); + bi_export(bi_ctx, ct_bi, ct, SHA1_SIZE); + + hmac_sha1((const uint8_t *)data_str, 28, (const uint8_t *)key_str, 4, dgst); + if (memcmp(dgst, ct, SHA1_SIZE)) + { + printf("HMAC SHA1 #2 failed\n"); + goto end; + } + + data_str = "Hi There"; + key_bi = bi_str_import(bi_ctx, "0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B"); + ct_bi = bi_str_import(bi_ctx, + "B0344C61D8DB38535CA8AFCEAF0BF12B881DC200C9833DA726E9376C2E32CFF7"); + bi_export(bi_ctx, key_bi, key, 20); + bi_export(bi_ctx, ct_bi, ct, SHA256_SIZE); + + hmac_sha256((const uint8_t *)data_str, 8, + (const uint8_t *)key, 20, dgst); + + if (memcmp(dgst, ct, SHA256_SIZE)) + { + printf("HMAC SHA256 #1 failed\n"); + goto end; + } + + data_str = "what do ya want for nothing?"; + key_str = "Jefe"; + ct_bi = bi_str_import(bi_ctx, + "5BDCC146BF60754E6A042426089575C75A003F089D2739839DEC58B964EC3843"); + bi_export(bi_ctx, ct_bi, ct, SHA256_SIZE); + + hmac_sha256((const uint8_t *)data_str, 28, + (const uint8_t *)key_str, 4, dgst); + if (memcmp(dgst, ct, SHA256_SIZE)) + { + printf("HMAC SHA256 #2 failed\n"); + goto end; + } + + // other test + /*uint8_t secret[16]; + key_str = "9BBE436BA940F017B17652849A71DB35"; + ct_bi = bi_str_import(bi_ctx, key_str); + bi_export(bi_ctx, ct_bi, secret, 16); + + uint8_t random[26]; + data_str = "74657374206C6162656CA0BA9F936CDA311827A6F796FFD5198C"; + ct_bi = bi_str_import(bi_ctx, data_str); + bi_export(bi_ctx, ct_bi, random, 26); + + uint8_t output[256]; + p_hash_sha256(secret, 16, random, 26, output, 100); + ct_bi = bi_import(bi_ctx, output, 100); + bi_print("RESULT", ct_bi); + */ + + /*uint8_t secret[48]; + uint8_t random[256]; + uint8_t output[256]; + + key_str = + "8C6D256467157DAEC7BAEBC1371E6DABFF1AB686EFA7DCF6B65242AA6EEBFC0A7472A1E583C4F2B23F784F25A6DE05A6"; + ct_bi = bi_str_import(bi_ctx, key_str); + bi_export(bi_ctx, ct_bi, secret, 48); + + data_str = + "636C69656E742066696E697368656475F80B2E4375CFA44105D16694A5E2D232302FF27241BDF52BA681C13E2CDF9F"; + ct_bi = bi_str_import(bi_ctx, data_str); + bi_export(bi_ctx, ct_bi, random, 47); + + p_hash_sha256(secret, 48, random, 47, output, 12); + ct_bi = bi_import(bi_ctx, output, 12); + bi_print("RESULT1", ct_bi);*/ + + res = 0; + printf("All HMAC tests passed\n"); + +end: + return res; +} + +/************************************************************************** + * BIGINT tests + * + **************************************************************************/ +static int BIGINT_test(BI_CTX *ctx) +{ + int res = 1; + +#ifndef CONFIG_INTEGER_8BIT +#ifndef CONFIG_INTEGER_16BIT + bigint *bi_data, *bi_exp, *bi_res; + const char *expnt, *plaintext, *mod; + uint8_t compare[MAX_KEY_BYTE_SIZE]; + /** + * 512 bit key + */ + plaintext = /* 64 byte number */ + "01aaaaaaaaaabbbbbbbbbbbbbbbccccccccccccccdddddddddddddeeeeeeeeee"; + + mod = "C30773C8ABE09FCC279EE0E5343370DE" + "8B2FFDB6059271E3005A7CEEF0D35E0A" + "1F9915D95E63560836CC2EB2C289270D" + "BCAE8CAF6F5E907FC2759EE220071E1B"; + + expnt = "A1E556CD1738E10DF539E35101334E97" + "BE8D391C57A5C89A7AD9A2EA2ACA1B3D" + "F3140F5091CC535CBAA47CEC4159EE1F" + "B6A3661AFF1AB758426EAB158452A9B9"; + + bi_data = bi_import(ctx, (uint8_t *)plaintext, strlen(plaintext)); + bi_exp = int_to_bi(ctx, 0x10001); + bi_set_mod(ctx, bi_str_import(ctx, mod), 0); + bi_res = bi_mod_power(ctx, bi_data, bi_exp); + + bi_data = bi_res; /* resuse again - see if we get the original */ + + bi_exp = bi_str_import(ctx, expnt); + bi_res = bi_mod_power(ctx, bi_data, bi_exp); + bi_free_mod(ctx, 0); + + bi_export(ctx, bi_res, compare, 64); + if (memcmp(plaintext, compare, 64) != 0) + goto end; +#endif +#endif + + /* + * Multiply with psssible carry issue (8 bit) + */ + { + bigint *bi_x = bi_str_import(ctx, + "AFD5060E224B70DA99EFB385BA5C0D2BEA0AD1DAAA52686E1A02D677BC65C1DA7A496BBDCC02999E8814F10AFC4B8E0DD4E6687E0762CE717A5EA1E452B5C56065C8431F0FB9D23CFF3A4B4149798C0670AF7F9565A0EAE5CF1AB16A1F0C3DD5E485DC5ABB96EBE0B6778A15B7302CBCE358E4BF2E2E30932758AC6EFA9F5828"); + bigint *arg2 = bi_clone(ctx, bi_x); + bigint *arg3 = bi_clone(ctx, bi_x); + bigint *sqr_result = bi_square(ctx, bi_x); + bigint *mlt_result = bi_multiply(ctx, arg2, arg3); + + if (bi_compare(sqr_result, mlt_result) != 0) + { + bi_print("SQR_RESULT", sqr_result); + bi_print("MLT_RESULT", mlt_result); + bi_free(ctx, sqr_result); + bi_free(ctx, mlt_result); + goto end; + } + + bi_free(ctx, sqr_result); + bi_free(ctx, mlt_result); + } + + printf("All BIGINT tests passed\n"); + res = 0; + +end: + return res; +} + +/************************************************************************** + * RSA tests + * + * Use the results from openssl to verify PKCS1 etc + **************************************************************************/ +static int RSA_test(void) +{ + int res = 1; + const char *plaintext = /* 128 byte hex number */ + "1aaaaaaaaaabbbbbbbbbbbbbbbccccccccccccccdddddddddddddeeeeeeeeee2" + "1aaaaaaaaaabbbbbbbbbbbbbbbccccccccccccccdddddddddddddeeeeeeeee2\012"; + uint8_t enc_data[128], dec_data[128]; + RSA_CTX *rsa_ctx = NULL; + BI_CTX *bi_ctx; + bigint *plaintext_bi; + bigint *enc_data_bi, *dec_data_bi; + uint8_t enc_data2[128], dec_data2[128]; + int len; + uint8_t *buf; + + RNG_initialize(); + + /* extract the private key elements */ + len = get_file("../ssl/test/axTLS.key_1024", &buf); + if (asn1_get_private_key(buf, len, &rsa_ctx) < 0) + { + goto end; + } + + free(buf); + bi_ctx = rsa_ctx->bi_ctx; + plaintext_bi = bi_import(bi_ctx, + (const uint8_t *)plaintext, strlen(plaintext)); + + /* basic rsa encrypt */ + enc_data_bi = RSA_public(rsa_ctx, plaintext_bi); + bi_export(bi_ctx, bi_copy(enc_data_bi), enc_data, sizeof(enc_data)); + + /* basic rsa decrypt */ + dec_data_bi = RSA_private(rsa_ctx, enc_data_bi); + bi_export(bi_ctx, dec_data_bi, dec_data, sizeof(dec_data)); + + if (memcmp(dec_data, plaintext, strlen(plaintext))) + { + printf("Error: DECRYPT #1 failed\n"); + goto end; + } + + if (RSA_encrypt(rsa_ctx, (const uint8_t *)"abc", 3, enc_data2, 0) < 0) + { + printf("Error: ENCRYPT #2 failed\n"); + goto end; + } + + RSA_decrypt(rsa_ctx, enc_data2, dec_data2, sizeof(dec_data2), 1); + if (memcmp("abc", dec_data2, 3)) + { + printf("Error: DECRYPT #2 failed\n"); + goto end; + } + + RSA_free(rsa_ctx); + res = 0; + printf("All RSA tests passed\n"); + +end: + RNG_terminate(); + return res; +} + +/************************************************************************** + * Cert Testing + * + **************************************************************************/ +static int cert_tests(void) +{ + int res = -1, len; + X509_CTX *x509_ctx; + SSL_CTX *ssl_ctx; + uint8_t *buf; + + /* check a bunch of 3rd party certificates */ + ssl_ctx = ssl_ctx_new(0, 0); + len = get_file("../ssl/test/microsoft.x509_ca", &buf); + if ((res = add_cert_auth(ssl_ctx, buf, len)) < 0) + { + printf("Cert #1\n"); + ssl_display_error(res); + goto bad_cert; + } + + ssl_ctx_free(ssl_ctx); + free(buf); + + ssl_ctx = ssl_ctx_new(0, 0); + len = get_file("../ssl/test/thawte.x509_ca", &buf); + if ((res = add_cert_auth(ssl_ctx, buf, len)) < 0) + { + printf("Cert #2\n"); + ssl_display_error(res); + goto bad_cert; + } + + ssl_ctx_free(ssl_ctx); + free(buf); + + ssl_ctx = ssl_ctx_new(0, 0); + len = get_file("../ssl/test/deutsche_telecom.x509_ca", &buf); + if ((res = add_cert_auth(ssl_ctx, buf, len)) < 0) + { + printf("Cert #3\n"); + ssl_display_error(res); + goto bad_cert; + } + + ssl_ctx_free(ssl_ctx); + free(buf); + + ssl_ctx = ssl_ctx_new(0, 0); + len = get_file("../ssl/test/equifax.x509_ca", &buf); + if ((res = add_cert_auth(ssl_ctx, buf, len)) < 0) + { + printf("Cert #4\n"); + ssl_display_error(res); + goto bad_cert; + } + + ssl_ctx_free(ssl_ctx); + free(buf); + + ssl_ctx = ssl_ctx_new(0, 0); + len = get_file("../ssl/test/gnutls.cer", &buf); + if ((res = add_cert(ssl_ctx, buf, len)) < 0) + { + printf("Cert #5\n"); + ssl_display_error(res); + goto bad_cert; + } + + ssl_ctx_free(ssl_ctx); + free(buf); + + ssl_ctx = ssl_ctx_new(0, 0); + len = get_file("../ssl/test/socgen.cer", &buf); + if ((res = add_cert(ssl_ctx, buf, len)) < 0) + { + printf("Cert #6\n"); + ssl_display_error(res); + goto bad_cert; + } + + ssl_ctx_free(ssl_ctx); + free(buf); + + ssl_ctx = ssl_ctx_new(0, 0); + if ((res = ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CERT, + "../ssl/test/camster_duckdns_org.crt", NULL)) != SSL_OK) + { + printf("Cert #7\n"); + ssl_display_error(res); + goto bad_cert; + } + + ssl_ctx_free(ssl_ctx); + + ssl_ctx = ssl_ctx_new(0, 0); + if ((res = ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CERT, + "../ssl/test/comodo.sha384.cer", NULL)) != SSL_OK) + { + printf("Cert #8\n"); + ssl_display_error(res); + goto bad_cert; + } + + ssl_ctx_free(ssl_ctx); + + ssl_ctx = ssl_ctx_new(0, 0); + if ((res = ssl_obj_load(ssl_ctx, + SSL_OBJ_X509_CERT, "../ssl/test/ms_iis.cer", NULL)) != SSL_OK) + { + printf("Cert #9\n"); + ssl_display_error(res); + goto bad_cert; + } + + ssl_ctx_free(ssl_ctx); + + if (get_file("../ssl/test/qualityssl.com.der", &buf) < 0 || + x509_new(buf, &len, &x509_ctx)) + { + printf("Cert #10\n"); + res = -1; + goto bad_cert; + } + + if (strcmp(x509_ctx->subject_alt_dnsnames[1], "qualityssl.com")) + { + printf("Cert #11\n"); + res = -1; + goto bad_cert; + } + x509_free(x509_ctx); + free(buf); + + // this bundle has two DSA (1.2.840.10040.4.3 invalid) certificates + ssl_ctx = ssl_ctx_new(0, 0); + if (ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CACERT, + "../ssl/test/ca-bundle.crt", NULL)) + { + goto bad_cert; + } + + ssl_ctx_free(ssl_ctx); + res = 0; /* all ok */ + printf("All Certificate tests passed\n"); + +bad_cert: + if (res) + printf("Error: A certificate test failed\n"); + + return res; +} + +/** + * init a server socket. + */ +static int server_socket_init(int *port) +{ + struct sockaddr_in serv_addr; + int server_fd; + char yes = 1; + + /* Create socket for incoming connections */ + if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) + { + return -1; + } + + setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); + +go_again: + /* Construct local address structure */ + memset(&serv_addr, 0, sizeof(serv_addr)); /* Zero out structure */ + serv_addr.sin_family = AF_INET; /* Internet address family */ + serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ + serv_addr.sin_port = htons(*port); /* Local port */ + + /* Bind to the local address */ + if (bind(server_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) + { + (*port)++; + goto go_again; + } + /* Mark the socket so it will listen for incoming connections */ + if (listen(server_fd, 3000) < 0) + { + return -1; + } + + return server_fd; +} + +/** + * init a client socket. + */ +static int client_socket_init(uint16_t port) +{ + struct sockaddr_in address; + int client_fd; + + address.sin_family = AF_INET; + address.sin_port = htons(port); + address.sin_addr.s_addr = inet_addr("127.0.0.1"); + client_fd = socket(AF_INET, SOCK_STREAM, 0); + if (connect(client_fd, (struct sockaddr *)&address, sizeof(address)) < 0) + { + perror("socket"); + SOCKET_CLOSE(client_fd); + client_fd = -1; + } + + return client_fd; +} + +/************************************************************************** + * SSL Server Testing + * + **************************************************************************/ +typedef struct +{ + /* not used as yet */ + int dummy; +} SVR_CTX; + +typedef struct +{ + const char *testname; + const char *openssl_option; +} client_t; + +static void do_client(client_t *clnt) +{ + char openssl_buf[2048]; + usleep(200000); /* allow server to start */ + + /* show the session ids in the reconnect test */ + if (strcmp(clnt->testname, "Session Reuse") == 0) + { + sprintf(openssl_buf, "echo \"hello client\" | openssl s_client " + "-connect localhost:%d %s 2>&1 | grep \"Session-ID:\"", + g_port, clnt->openssl_option); + } + else if (strstr(clnt->testname, "GNUTLS") == NULL) + { + sprintf(openssl_buf, "echo \"hello client\" | openssl s_client " +#ifdef WIN32 + "-connect localhost:%d -quiet %s", +#else + "-connect localhost:%d -quiet %s > /dev/null 2>&1", +#endif + g_port, clnt->openssl_option); + } + else /* gnutls */ + { + sprintf(openssl_buf, "echo \"hello client\" | gnutls-cli " +#ifdef WIN32 + "-p %d %s localhost", +#else + "-p %d %s localhost > /dev/null 2>&1", +#endif + g_port, clnt->openssl_option); + } + +//printf("CLIENT %s\n", openssl_buf); + SYSTEM(openssl_buf); +} + +static int SSL_server_test( + const char *testname, + const char *openssl_option, + const char *device_cert, + const char *product_cert, + const char *private_key, + const char *ca_cert, + const char *password, + int axtls_option) +{ + int server_fd, ret = 0; + SSL_CTX *ssl_ctx = NULL; + struct sockaddr_in client_addr; + uint8_t *read_buf; + socklen_t clnt_len = sizeof(client_addr); + client_t client_data; +#ifndef WIN32 + pthread_t thread; +#endif + g_port++; + + client_data.testname = testname; + client_data.openssl_option = openssl_option; + + if ((server_fd = server_socket_init(&g_port)) < 0) + goto error; + + if (private_key) + { + axtls_option |= SSL_NO_DEFAULT_KEY; + } + + if ((ssl_ctx = ssl_ctx_new(axtls_option, SSL_DEFAULT_SVR_SESS)) == NULL) + { + ret = SSL_ERROR_INVALID_KEY; + goto error; + } + + if (private_key) + { + int obj_type = SSL_OBJ_RSA_KEY; + + if (strstr(private_key, ".p8")) + obj_type = SSL_OBJ_PKCS8; + else if (strstr(private_key, ".p12")) + obj_type = SSL_OBJ_PKCS12; + + if (ssl_obj_load(ssl_ctx, obj_type, private_key, password)) + { + ret = SSL_ERROR_INVALID_KEY; + goto error; + } + } + + if (device_cert) /* test chaining */ + { + if ((ret = ssl_obj_load(ssl_ctx, + SSL_OBJ_X509_CERT, device_cert, NULL)) != SSL_OK) + goto error; + } + + if (product_cert) /* test chaining */ + { + if ((ret = ssl_obj_load(ssl_ctx, + SSL_OBJ_X509_CERT, product_cert, NULL)) != SSL_OK) + goto error; + } + + if (ca_cert) /* test adding certificate authorities */ + { + if ((ret = ssl_obj_load(ssl_ctx, + SSL_OBJ_X509_CACERT, ca_cert, NULL)) != SSL_OK) + goto error; + } + +#ifndef WIN32 + pthread_create(&thread, NULL, + (void *(*)(void *))do_client, (void *)&client_data); + pthread_detach(thread); +#else + CreateThread(NULL, 1024, (LPTHREAD_START_ROUTINE)do_client, + (LPVOID)&client_data, 0, NULL); +#endif + + for (;;) + { + int client_fd, size = 0; + SSL *ssl; + + /* Wait for a client to connect */ + if ((client_fd = accept(server_fd, + (struct sockaddr *)&client_addr, &clnt_len)) < 0) + { + ret = SSL_ERROR_SOCK_SETUP_FAILURE; + goto error; + } + + /* we are ready to go */ + ssl = ssl_server_new(ssl_ctx, client_fd); + while ((size = ssl_read(ssl, &read_buf)) == SSL_OK); + SOCKET_CLOSE(client_fd); + + if (size == SSL_CLOSE_NOTIFY) + { + /* do nothing */ + } + else if (size < SSL_OK) /* got some alert or something nasty */ + { + ret = size; + + if (ret == SSL_ERROR_CONN_LOST) + continue; + + break; /* we've got a problem */ + } + else /* looks more promising */ + { + if (strstr("hello client", (char *)read_buf) == NULL) + { + printf("SSL server test \"%s\" passed\n", testname); + TTY_FLUSH(); + ret = 0; + break; + } + } + + ssl_free(ssl); + } + + SOCKET_CLOSE(server_fd); + +error: + ssl_ctx_free(ssl_ctx); + return ret; +} + +int SSL_server_tests(void) +{ + int ret = -1; + struct stat stat_buf; + SVR_CTX svr_test_ctx; + memset(&svr_test_ctx, 0, sizeof(SVR_CTX)); + + printf("### starting server tests\n"); TTY_FLUSH(); + + /* Go through the algorithms */ + + /* + * TLS client hello + */ + + /* + * AES128-SHA TLS1.2 + */ + if ((ret = SSL_server_test("AES128-SHA TLS1.2", + "-cipher AES128-SHA -tls1_2", + DEFAULT_CERT, NULL, DEFAULT_KEY, NULL, NULL, + DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * AES256-SHA TLS1.2 + */ + if ((ret = SSL_server_test("AES256-SHA TLS1.2", + "-cipher AES256-SHA -tls1_2", + DEFAULT_CERT, NULL, DEFAULT_KEY, NULL, NULL, + DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * AES128-SHA256 TLS1.2 + */ + if ((ret = SSL_server_test("AES128-SHA256 TLS1.2", + "-cipher AES128-SHA256 -tls1_2", + DEFAULT_CERT, NULL, DEFAULT_KEY, NULL, NULL, + DEFAULT_SVR_OPTION))) + goto cleanup; + + + /* + * AES256-SHA256 TLS1.2 + */ + if ((ret = SSL_server_test("AES256-SHA256 TLS1.2", + "-cipher AES256-SHA256 -tls1_2", + DEFAULT_CERT, NULL, DEFAULT_KEY, NULL, NULL, + DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * AES128-SHA TLS1.1 + */ + if ((ret = SSL_server_test("AES128-SHA TLS1.1", + "-cipher AES128-SHA -tls1_1", + DEFAULT_CERT, NULL, DEFAULT_KEY, NULL, NULL, + DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * AES128-SHA TLS1.0 + */ + if ((ret = SSL_server_test("AES128-SHA TLS1.0", + "-cipher AES128-SHA -tls1", + DEFAULT_CERT, NULL, DEFAULT_KEY, NULL, NULL, + DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * Session Reuse + * all the session id's should match for session resumption. + */ + if ((ret = SSL_server_test("Session Reuse", + "-cipher AES128-SHA -reconnect -tls1_2", + DEFAULT_CERT, NULL, DEFAULT_KEY, NULL, NULL, + DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * 1024 bit RSA key (check certificate chaining) + */ + if ((ret = SSL_server_test("1024 bit key", + "-cipher AES128-SHA -tls1_2", + "../ssl/test/axTLS.x509_1024.cer", NULL, + "../ssl/test/axTLS.key_1024", + NULL, NULL, DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * 2048 bit RSA key + */ + if ((ret = SSL_server_test("2048 bit key", + "-cipher AES128-SHA -tls1_2", + "../ssl/test/axTLS.x509_2048.cer", NULL, + "../ssl/test/axTLS.key_2048", + NULL, NULL, DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * 4096 bit RSA key + */ + if ((ret = SSL_server_test("4096 bit key", + "-cipher AES128-SHA -tls1_2", + "../ssl/test/axTLS.x509_4096.cer", NULL, + "../ssl/test/axTLS.key_4096", + NULL, NULL, DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * RSA1024/SHA256 + */ + if ((ret = SSL_server_test("RSA1024/SHA256", + "-tls1_2", + "../ssl/test/axTLS.x509_1024_sha256.pem" , NULL, + "../ssl/test/axTLS.key_1024", + NULL, NULL, DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * RSA1024/SHA384 + */ + if ((ret = SSL_server_test("RSA1024/SHA384", + "-tls1_2", + "../ssl/test/axTLS.x509_1024_sha384.pem" , NULL, + "../ssl/test/axTLS.key_1024", + NULL, NULL, DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * RSA1024/SHA512 + */ + if ((ret = SSL_server_test("RSA1024/SHA512", + "-tls1_2", + "../ssl/test/axTLS.x509_1024_sha512.pem" , NULL, + "../ssl/test/axTLS.key_1024", + NULL, NULL, DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * Client Verification + */ + if ((ret = SSL_server_test("Client Verification TLS1.2", + "-cipher AES128-SHA -tls1_2 " + "-cert ../ssl/test/axTLS.x509_2048.pem " + "-key ../ssl/test/axTLS.key_2048.pem ", + NULL, + "../ssl/test/axTLS.x509_1024.pem", + "../ssl/test/axTLS.key_1024.pem", + "../ssl/test/axTLS.ca_x509.cer", NULL, + DEFAULT_SVR_OPTION|SSL_CLIENT_AUTHENTICATION))) + goto cleanup; + + if ((ret = SSL_server_test("Client Verification TLS1.1", + "-cipher AES128-SHA -tls1_1 " + "-cert ../ssl/test/axTLS.x509_2048.pem " + "-key ../ssl/test/axTLS.key_2048.pem ", + NULL, + "../ssl/test/axTLS.x509_1024.pem", + "../ssl/test/axTLS.key_1024.pem", + "../ssl/test/axTLS.ca_x509.cer", NULL, + DEFAULT_SVR_OPTION|SSL_CLIENT_AUTHENTICATION))) + goto cleanup; + + /* this test should fail */ + if (stat("../ssl/test/axTLS.x509_bad_before.pem", &stat_buf) >= 0) + { + if ((ret = SSL_server_test("Error: Bad Before Cert", + "-cipher AES128-SHA -tls1_2 " + "-cert ../ssl/test/axTLS.x509_bad_before.pem " + "-key ../ssl/test/axTLS.key_1024.pem ", + NULL, + "../ssl/test/axTLS.x509_1024.pem", + "../ssl/test/axTLS.key_1024.pem", + "../ssl/test/axTLS.ca_x509.cer", NULL, + DEFAULT_SVR_OPTION|SSL_CLIENT_AUTHENTICATION)) != + SSL_X509_ERROR(X509_VFY_ERROR_NOT_YET_VALID)) + goto cleanup; + + printf("SSL server test \"%s\" passed\n", "Bad Before Cert"); + TTY_FLUSH(); + } + + /* this test should fail */ + if ((ret = SSL_server_test("Error: Bad After Cert", + "-cipher AES128-SHA -tls1_2 " + "-cert ../ssl/test/axTLS.x509_bad_after.pem " + "-key ../ssl/test/axTLS.key_1024.pem ", + NULL, + "../ssl/test/axTLS.x509_1024.pem", + "../ssl/test/axTLS.key_1024.pem", + "../ssl/test/axTLS.ca_x509.cer", NULL, + DEFAULT_SVR_OPTION|SSL_CLIENT_AUTHENTICATION)) != + SSL_X509_ERROR(X509_VFY_ERROR_EXPIRED)) + goto cleanup; + + printf("SSL server test \"%s\" passed\n", "Bad After Cert"); + TTY_FLUSH(); + + /* + * No trusted cert + */ + if ((ret = SSL_server_test("Error: No trusted certificate", + "-cipher AES128-SHA -tls1_2 " + "-cert ../ssl/test/axTLS.x509_1024.pem " + "-key ../ssl/test/axTLS.key_1024.pem ", + NULL, + "../ssl/test/axTLS.x509_1024.pem", + "../ssl/test/axTLS.key_1024.pem", + NULL, NULL, + DEFAULT_SVR_OPTION|SSL_CLIENT_AUTHENTICATION)) != + SSL_X509_ERROR(X509_VFY_ERROR_NO_TRUSTED_CERT)) + goto cleanup; + + printf("SSL server test \"%s\" passed\n", "No trusted certificate"); + TTY_FLUSH(); + + /* + * Self-signed (from the server) + */ + if ((ret = SSL_server_test("Error: Self-signed certificate (from server)", + "-cipher AES128-SHA -tls1_2 " + "-cert ../ssl/test/axTLS.x509_1024.pem " + "-key ../ssl/test/axTLS.key_1024.pem " + "-CAfile ../ssl/test/axTLS.ca_x509.pem ", + NULL, + "../ssl/test/axTLS.x509_1024.pem", + "../ssl/test/axTLS.key_1024.pem", + NULL, NULL, + DEFAULT_SVR_OPTION|SSL_CLIENT_AUTHENTICATION)) != + SSL_X509_ERROR(X509_VFY_ERROR_SELF_SIGNED)) + goto cleanup; + + printf("SSL server test \"%s\" passed\n", + "Self-signed certificate (from server)"); + TTY_FLUSH(); + + /* + * Self-signed (from the client) + */ + if ((ret = SSL_server_test("Self-signed certificate (from client)", + "-cipher AES128-SHA -tls1_2 " + "-cert ../ssl/test/axTLS.x509_1024.pem " + "-key ../ssl/test/axTLS.key_1024.pem ", + NULL, + "../ssl/test/axTLS.x509_1024.pem", + "../ssl/test/axTLS.key_1024.pem", + "../ssl/test/axTLS.ca_x509.cer", + NULL, + DEFAULT_SVR_OPTION|SSL_CLIENT_AUTHENTICATION))) + goto cleanup; + + /* + * Key in PEM format + */ + if ((ret = SSL_server_test("Key in PEM format", + "-cipher AES128-SHA -tls1_2", + "../ssl/test/axTLS.x509_1024.cer", NULL, + "../ssl/test/axTLS.key_1024.pem", NULL, + NULL, DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * Cert in PEM format + */ + if ((ret = SSL_server_test("Cert in PEM format", + "-cipher AES128-SHA -tls1_2", + "../ssl/test/axTLS.x509_1024.pem", NULL, + "../ssl/test/axTLS.key_1024.pem", NULL, + NULL, DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * Cert chain in PEM format + */ + if ((ret = SSL_server_test("Cert chain in PEM format", + "-cipher AES128-SHA -tls1_2", + "../ssl/test/axTLS.x509_device.pem", + NULL, "../ssl/test/axTLS.key_device.pem", + "../ssl/test/axTLS.ca_x509.pem", NULL, DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * AES128 Encrypted key + */ + if ((ret = SSL_server_test("AES128 encrypted key", + "-cipher AES128-SHA -tls1_2", + "../ssl/test/axTLS.x509_aes128.pem", NULL, + "../ssl/test/axTLS.key_aes128.pem", + NULL, "abcd", DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * AES256 Encrypted key + */ + if ((ret = SSL_server_test("AES256 encrypted key", + "-cipher AES128-SHA -tls1_2", + "../ssl/test/axTLS.x509_aes256.pem", NULL, + "../ssl/test/axTLS.key_aes256.pem", + NULL, "abcd", DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * AES128 Encrypted invalid key + */ + if ((ret = SSL_server_test("AES128 encrypted invalid key", + "-cipher AES128-SHA -tls1_2", + "../ssl/test/axTLS.x509_aes128.pem", NULL, + "../ssl/test/axTLS.key_aes128.pem", + NULL, "xyz", DEFAULT_SVR_OPTION)) != SSL_ERROR_INVALID_KEY) + goto cleanup; + + printf("SSL server test \"%s\" passed\n", "AES128 encrypted invalid key"); + TTY_FLUSH(); + + /* + * PKCS#8 key (encrypted) + */ + if ((ret = SSL_server_test("pkcs#8 encrypted", + "-cipher AES128-SHA -tls1_2", + DEFAULT_CERT, NULL, "../ssl/test/axTLS.encrypted.p8", + NULL, "abcd", DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * PKCS#8 key (unencrypted DER format) + */ + if ((ret = SSL_server_test("pkcs#8 DER unencrypted", + "-cipher AES128-SHA -tls1_2", + DEFAULT_CERT, NULL, "../ssl/test/axTLS.unencrypted.p8", + NULL, NULL, DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * PKCS#8 key (unencrypted PEM format) + */ + if ((ret = SSL_server_test("pkcs#8 PEM unencrypted", + "-cipher AES128-SHA -tls1_2", + DEFAULT_CERT, NULL, "../ssl/test/axTLS.unencrypted_pem.p8", + NULL, NULL, DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * PKCS#12 key/certificate + */ + if ((ret = SSL_server_test("pkcs#12 with CA", "-cipher AES128-SHA", + NULL, NULL, "../ssl/test/axTLS.withCA.p12", + NULL, "abcd", DEFAULT_SVR_OPTION))) + goto cleanup; + + if ((ret = SSL_server_test("pkcs#12 no CA", "-cipher AES128-SHA", + DEFAULT_CERT, NULL, "../ssl/test/axTLS.withoutCA.p12", + NULL, "abcd", DEFAULT_SVR_OPTION))) + goto cleanup; + + /* + * GNUTLS + */ + if ((ret = SSL_server_test("GNUTLS client", + "", + "../ssl/test/axTLS.x509_1024.cer", NULL, + "../ssl/test/axTLS.key_1024", + NULL, NULL, DEFAULT_SVR_OPTION))) + goto cleanup; + + if ((ret = SSL_server_test("GNUTLS client with verify", + "--x509certfile ../ssl/test/axTLS.x509_1024.pem " + "--x509keyfile ../ssl/test/axTLS.key_1024.pem", + "../ssl/test/axTLS.x509_1024.cer", NULL, + "../ssl/test/axTLS.key_1024", + "../ssl/test/axTLS.ca_x509.cer", NULL, + DEFAULT_SVR_OPTION|SSL_CLIENT_AUTHENTICATION))) + goto cleanup; + ret = 0; + +cleanup: + if (ret) + { + printf("Error: A server test failed\n"); + ssl_display_error(ret); + exit(1); + } + else + { + printf("All server tests passed\n"); TTY_FLUSH(); + } + + return ret; +} + +/************************************************************************** + * SSL Client Testing + * + **************************************************************************/ +typedef struct +{ + uint8_t session_id[SSL_SESSION_ID_SIZE]; +#ifndef WIN32 + pthread_t server_thread; +#endif + int start_server; + int stop_server; + int do_reneg; +} CLNT_SESSION_RESUME_CTX; + +typedef struct +{ + const char *testname; + const char *openssl_option; + int do_gnutls; +} server_t; + +static void do_server(server_t *svr) +{ + char openssl_buf[2048]; +#ifndef WIN32 + pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); +#endif + if (svr->do_gnutls) + { + sprintf(openssl_buf, "gnutls-serv " + "-p %d --quiet %s ", g_port, svr->openssl_option); + } + else + { + sprintf(openssl_buf, "openssl s_server " +#ifdef WIN32 + "-accept %d -quiet %s", +#else + "-accept %d -quiet %s > /dev/null", +#endif + g_port, svr->openssl_option); + } +//printf("SERVER %s\n", openssl_buf); + SYSTEM(openssl_buf); +} + +static int SSL_client_test( + const char *test, + SSL_CTX **ssl_ctx, + const char *openssl_option, + CLNT_SESSION_RESUME_CTX *sess_resume, + uint32_t client_options, + const char *private_key, + const char *password, + const char *cert) +{ + server_t server_data; + SSL *ssl = NULL; + int client_fd = -1; + uint8_t *session_id = NULL; + int ret = 1; +#ifndef WIN32 + pthread_t thread; +#endif + + server_data.do_gnutls = strstr(test, "GNUTLS") != NULL; + + if (sess_resume == NULL || sess_resume->start_server) + { + g_port++; + server_data.openssl_option = openssl_option; + +#ifndef WIN32 + pthread_create(&thread, NULL, + (void *(*)(void *))do_server, (void *)&server_data); + pthread_detach(thread); +#else + CreateThread(NULL, 1024, (LPTHREAD_START_ROUTINE)do_server, + (LPVOID)&server_data, 0, NULL); +#endif + } + + usleep(200000); /* allow server to start */ + + if (*ssl_ctx == NULL) + { + if (private_key) + { + client_options |= SSL_NO_DEFAULT_KEY; + } + + if ((*ssl_ctx = ssl_ctx_new( + client_options, SSL_DEFAULT_CLNT_SESS)) == NULL) + { + ret = SSL_ERROR_INVALID_KEY; + goto client_test_exit; + } + + if (private_key) + { + int obj_type = SSL_OBJ_RSA_KEY; + + if (strstr(private_key, ".p8")) + obj_type = SSL_OBJ_PKCS8; + else if (strstr(private_key, ".p12")) + obj_type = SSL_OBJ_PKCS12; + + if (ssl_obj_load(*ssl_ctx, obj_type, private_key, password)) + { + ret = SSL_ERROR_INVALID_KEY; + goto client_test_exit; + } + } + + if (cert) + { + if ((ret = ssl_obj_load(*ssl_ctx, + SSL_OBJ_X509_CERT, cert, NULL)) != SSL_OK) + { + printf("could not add cert %s (%d)\n", cert, ret); + TTY_FLUSH(); + goto client_test_exit; + } + } + + if (ssl_obj_load(*ssl_ctx, SSL_OBJ_X509_CACERT, + "../ssl/test/axTLS.ca_x509.cer", NULL)) + { + printf("could not add cert auth\n"); TTY_FLUSH(); + goto client_test_exit; + } + } + + if (sess_resume && !sess_resume->start_server) + { + session_id = sess_resume->session_id; + } + + if ((client_fd = client_socket_init(g_port)) < 0) + { + printf("could not start socket on %d\n", g_port); TTY_FLUSH(); + goto client_test_exit; + } + + ssl = ssl_client_new(*ssl_ctx, client_fd, + session_id, sizeof(session_id), NULL); + + /* check the return status */ + if ((ret = ssl_handshake_status(ssl))) + goto client_test_exit; + + /* renegotiate client */ + if (sess_resume && sess_resume->do_reneg) + { + if (ssl_renegotiate(ssl) == -SSL_ALERT_NO_RENEGOTIATION) + ret = 0; + else + ret = -SSL_ALERT_NO_RENEGOTIATION; + + goto client_test_exit; + } + + if (sess_resume) + { + memcpy(sess_resume->session_id, + ssl_get_session_id(ssl), SSL_SESSION_ID_SIZE); + } + + if (IS_SET_SSL_FLAG(SSL_SERVER_VERIFY_LATER) && + (ret = ssl_verify_cert(ssl))) + { + goto client_test_exit; + } + + ssl_write(ssl, (uint8_t *)"hello world\n", 13); + if (sess_resume) + { + const uint8_t *sess_id = ssl_get_session_id(ssl); + int i; + + printf(" Session-ID: "); + for (i = 0; i < SSL_SESSION_ID_SIZE; i++) + { + printf("%02X", sess_id[i]); + } + printf("\n"); + TTY_FLUSH(); + } + + ret = 0; + +client_test_exit: + ssl_free(ssl); + SOCKET_CLOSE(client_fd); + usleep(200000); /* allow openssl to say something */ + + if (sess_resume) + { + if (sess_resume->stop_server) + { + ssl_ctx_free(*ssl_ctx); + *ssl_ctx = NULL; + } + else if (sess_resume->start_server) + { +#ifndef WIN32 + sess_resume->server_thread = thread; +#endif + } + } + else + { + ssl_ctx_free(*ssl_ctx); + *ssl_ctx = NULL; + } + + if (ret == 0) + { + printf("SSL client test \"%s\" passed\n", test); + TTY_FLUSH(); + } + + return ret; +} + +int SSL_client_tests(void) +{ + int ret = -1; + SSL_CTX *ssl_ctx = NULL; + CLNT_SESSION_RESUME_CTX sess_resume; + memset(&sess_resume, 0, sizeof(CLNT_SESSION_RESUME_CTX)); + + sess_resume.start_server = 1; + printf("### starting client tests\n"); + + if ((ret = SSL_client_test("1024 bit key", + &ssl_ctx, + "-cert ../ssl/test/axTLS.x509_1024.pem " + "-key ../ssl/test/axTLS.key_1024.pem", + &sess_resume, + DEFAULT_CLNT_OPTION, NULL, NULL, NULL))) + goto cleanup; + + /* all the session id's should match for session resumption */ + sess_resume.start_server = 0; + if ((ret = SSL_client_test("Client session resumption #1", + &ssl_ctx, NULL, &sess_resume, + DEFAULT_CLNT_OPTION, NULL, NULL, NULL))) + goto cleanup; + + // no client renegotiation + sess_resume.do_reneg = 1; + // test relies on openssl killing the call + if ((ret = SSL_client_test("Client renegotiation", + &ssl_ctx, NULL, &sess_resume, + DEFAULT_CLNT_OPTION, NULL, NULL, NULL))) + goto cleanup; + sess_resume.do_reneg = 0; + + sess_resume.stop_server = 1; + if ((ret = SSL_client_test("Client session resumption #2", + &ssl_ctx, NULL, &sess_resume, + DEFAULT_CLNT_OPTION, NULL, NULL, NULL))) + goto cleanup; + + if ((ret = SSL_client_test("1024 bit key", + &ssl_ctx, + "-cert ../ssl/test/axTLS.x509_1024.pem " + "-key ../ssl/test/axTLS.key_1024.pem", NULL, + DEFAULT_CLNT_OPTION, NULL, NULL, NULL))) + goto cleanup; + + if ((ret = SSL_client_test("2048 bit key", + &ssl_ctx, + "-cert ../ssl/test/axTLS.x509_2048.pem " + "-key ../ssl/test/axTLS.key_2048.pem", NULL, + DEFAULT_CLNT_OPTION, NULL, NULL, NULL))) + goto cleanup; + + if ((ret = SSL_client_test("4096 bit key", + &ssl_ctx, + "-cert ../ssl/test/axTLS.x509_4096.pem " + "-key ../ssl/test/axTLS.key_4096.pem", NULL, + DEFAULT_CLNT_OPTION, NULL, NULL, NULL))) + goto cleanup; + + if ((ret = SSL_client_test("TLS 1.1", + &ssl_ctx, + "-cert ../ssl/test/axTLS.x509_1024.pem " + "-key ../ssl/test/axTLS.key_1024.pem -tls1_1", NULL, + DEFAULT_CLNT_OPTION, NULL, NULL, NULL))) + goto cleanup; + + if ((ret = SSL_client_test("TLS 1.0", + &ssl_ctx, + "-cert ../ssl/test/axTLS.x509_1024.pem " + "-key ../ssl/test/axTLS.key_1024.pem -tls1", NULL, + DEFAULT_CLNT_OPTION, NULL, NULL, NULL))) + goto cleanup; + + if ((ret = SSL_client_test("Basic Constraint - len OK", + &ssl_ctx, + "-cert ../ssl/test/axTLS.x509_end_chain.pem -key " + "../ssl/test/axTLS.key_end_chain.pem -CAfile " + "../ssl/test/axTLS.x509_intermediate_ca.pem", + NULL, + DEFAULT_CLNT_OPTION, NULL, NULL, NULL))) + goto cleanup; + + if ((ret = SSL_client_test("Basic Constraint - len NOT OK", + &ssl_ctx, + "-cert ../ssl/test/axTLS.x509_end_chain_bad.pem -key " + "../ssl/test/axTLS.key_end_chain.pem -CAfile " + "../ssl/test/axTLS.x509_intermediate_ca2.pem", + NULL, + DEFAULT_CLNT_OPTION, NULL, NULL, NULL)) + != SSL_X509_ERROR(X509_VFY_ERROR_BASIC_CONSTRAINT)) + { + printf("*** Error: %d\n", ret); + if (ret == 0) + ret = SSL_NOT_OK; + + goto cleanup; + } + + printf("SSL server test \"%s\" passed\n", "Basic Constraint - len NOT OK"); + + if ((ret = SSL_client_test("Server cert chaining", + &ssl_ctx, + "-cert ../ssl/test/axTLS.x509_device.pem " + "-key ../ssl/test/axTLS.key_device.pem " + "-CAfile ../ssl/test/axTLS.x509_1024.pem ", NULL, + DEFAULT_CLNT_OPTION, NULL, NULL, NULL))) + goto cleanup; + + /* Check the server can verify the client */ + if ((ret = SSL_client_test("Client peer authentication", + &ssl_ctx, + "-cert ../ssl/test/axTLS.x509_2048.pem " + "-key ../ssl/test/axTLS.key_2048.pem " + "-CAfile ../ssl/test/axTLS.ca_x509.pem " + "-verify 1 ", NULL, DEFAULT_CLNT_OPTION, + "../ssl/test/axTLS.key_1024", NULL, + "../ssl/test/axTLS.x509_1024.cer"))) + goto cleanup; + + /* Check the server can verify the client */ + if ((ret = SSL_client_test("Client peer authentication TLS1.1", + &ssl_ctx, + "-cert ../ssl/test/axTLS.x509_2048.pem " + "-key ../ssl/test/axTLS.key_2048.pem " + "-CAfile ../ssl/test/axTLS.ca_x509.pem " + "-verify 1 -tls1_1", NULL, DEFAULT_CLNT_OPTION, + "../ssl/test/axTLS.key_1024", NULL, + "../ssl/test/axTLS.x509_1024.cer"))) + goto cleanup; + + /* Should get an "ERROR" from openssl (as the handshake fails as soon as + * the certificate verification fails) */ + if ((ret = SSL_client_test("Error: Expired cert (verify now)", + &ssl_ctx, + "-cert ../ssl/test/axTLS.x509_bad_after.pem " + "-key ../ssl/test/axTLS.key_1024.pem", NULL, + DEFAULT_CLNT_OPTION, NULL, NULL, NULL)) != + SSL_X509_ERROR(X509_VFY_ERROR_EXPIRED)) + { + printf("*** Error: %d\n", ret); + goto cleanup; + } + + printf("SSL client test \"Expired cert (verify now)\" passed\n"); + + /* There is no "ERROR" from openssl */ + if ((ret = SSL_client_test("Error: Expired cert (verify later)", + &ssl_ctx, + "-cert ../ssl/test/axTLS.x509_bad_after.pem " + "-key ../ssl/test/axTLS.key_1024.pem", NULL, + DEFAULT_CLNT_OPTION|SSL_SERVER_VERIFY_LATER, NULL, + NULL, NULL)) != SSL_X509_ERROR(X509_VFY_ERROR_EXPIRED)) + { + printf("*** Error: %d\n", ret); TTY_FLUSH(); + goto cleanup; + } + + printf("SSL client test \"Expired cert (verify later)\" passed\n"); + + /* invalid cert type */ + /*if ((ret = SSL_client_test("Error: Invalid certificate type", + &ssl_ctx, + "-cert ../ssl/test/axTLS.x509_2048.pem " + "-key ../ssl/test/axTLS.key_2048.pem " + "-CAfile ../ssl/test/axTLS.ca_x509.pem " + "-verify 1 ", NULL, DEFAULT_CLNT_OPTION, + "../ssl/test/axTLS.key_1024.pem", NULL, + "../ssl/test/axTLS.x509_1024.pem")) + != SSL_ERROR_INVALID_KEY) + { + if (ret == 0) + ret = SSL_NOT_OK; + + printf("*** Error: %d\n", ret); TTY_FLUSH(); + goto cleanup; + } + + printf("SSL client test \"Invalid certificate type\" passed\n"); */ + + if ((ret = SSL_client_test("GNUTLS client", + &ssl_ctx, + "--x509certfile ../ssl/test/axTLS.x509_1024.pem " + "--x509keyfile ../ssl/test/axTLS.key_1024.pem -g", NULL, + DEFAULT_CLNT_OPTION, + "../ssl/test/axTLS.key_1024.pem", NULL, + "../ssl/test/axTLS.x509_1024.pem"))) + goto cleanup; + + ret = 0; + + if ((ret = SSL_client_test("GNUTLS client with verify", + &ssl_ctx, + "--x509certfile ../ssl/test/axTLS.x509_1024.pem " + "--x509keyfile ../ssl/test/axTLS.key_1024.pem -r -g", NULL, + DEFAULT_CLNT_OPTION|SSL_SERVER_VERIFY_LATER, + "../ssl/test/axTLS.key_1024.pem", NULL, + "../ssl/test/axTLS.x509_1024.pem"))) + goto cleanup; + + ret = 0; + +cleanup: + if (ret) + { + ssl_display_error(ret); + printf("Error: A client test failed\n"); + SYSTEM("sh ../ssl/test/killopenssl.sh"); + SYSTEM("sh ../ssl/test/killgnutls.sh"); + exit(1); + } + else + { + printf("All client tests passed\n"); TTY_FLUSH(); + } + + ssl_ctx_free(ssl_ctx); + return ret; +} + +/************************************************************************** + * SSL Basic Testing (test a big packet handshake) + * + **************************************************************************/ +static uint8_t basic_buf[256*1024]; + +static void do_basic(void) +{ + int client_fd; + SSL *ssl_clnt; + SSL_CTX *ssl_clnt_ctx = ssl_ctx_new( + DEFAULT_CLNT_OPTION, SSL_DEFAULT_CLNT_SESS); + usleep(200000); /* allow server to start */ + + if ((client_fd = client_socket_init(g_port)) < 0) + goto error; + + if (ssl_obj_load(ssl_clnt_ctx, SSL_OBJ_X509_CACERT, + "../ssl/test/axTLS.ca_x509.cer", NULL)) + goto error; + + ssl_clnt = ssl_client_new(ssl_clnt_ctx, client_fd, NULL, 0, NULL); + + /* check the return status */ + if (ssl_handshake_status(ssl_clnt) < 0) + { + ssl_display_error(ssl_handshake_status(ssl_clnt)); + goto error; + } + + ssl_write(ssl_clnt, basic_buf, sizeof(basic_buf)); + ssl_free(ssl_clnt); + +error: + ssl_ctx_free(ssl_clnt_ctx); + SOCKET_CLOSE(client_fd); + + /* exit this thread */ +} + +static int SSL_basic_test(void) +{ + int server_fd, client_fd, ret = 0, size = 0, offset = 0; + SSL_CTX *ssl_svr_ctx = NULL; + struct sockaddr_in client_addr; + uint8_t *read_buf; + socklen_t clnt_len = sizeof(client_addr); + SSL *ssl_svr; +#ifndef WIN32 + pthread_t thread; +#endif + memset(basic_buf, 0xA5, sizeof(basic_buf)/2); + memset(&basic_buf[sizeof(basic_buf)/2], 0x5A, sizeof(basic_buf)/2); + + if ((server_fd = server_socket_init(&g_port)) < 0) + goto error; + + ssl_svr_ctx = ssl_ctx_new(DEFAULT_SVR_OPTION, SSL_DEFAULT_SVR_SESS); + if ((ret = ssl_obj_load(ssl_svr_ctx, SSL_OBJ_X509_CERT, + "../ssl/test/axTLS.x509_1024.pem", NULL)) != SSL_OK) + goto error; + + if ((ret = ssl_obj_load(ssl_svr_ctx, SSL_OBJ_RSA_KEY, + "../ssl/test/axTLS.key_1024.pem", NULL)) != SSL_OK) + goto error; +#ifndef WIN32 + pthread_create(&thread, NULL, + (void *(*)(void *))do_basic, NULL); + pthread_detach(thread); +#else + CreateThread(NULL, 1024, (LPTHREAD_START_ROUTINE)do_basic, NULL, 0, NULL); +#endif + + /* Wait for a client to connect */ + if ((client_fd = accept(server_fd, + (struct sockaddr *) &client_addr, &clnt_len)) < 0) + { + ret = SSL_ERROR_SOCK_SETUP_FAILURE; + goto error; + } + + /* we are ready to go */ + ssl_svr = ssl_server_new(ssl_svr_ctx, client_fd); + + do + { + while ((size = ssl_read(ssl_svr, &read_buf)) == SSL_OK); + + if (size < SSL_OK) /* got some alert or something nasty */ + { + ssl_display_error(size); + ret = size; + break; + } + else /* looks more promising */ + { + if (memcmp(read_buf, &basic_buf[offset], size) != 0) + { + ret = SSL_NOT_OK; + break; + } + } + + offset += size; + } while (offset < sizeof(basic_buf)); + + printf(ret == SSL_OK && offset == sizeof(basic_buf) ? + "SSL basic test passed\n" : + "SSL basic test failed\n"); + TTY_FLUSH(); + + ssl_free(ssl_svr); + SOCKET_CLOSE(server_fd); + SOCKET_CLOSE(client_fd); + +error: + ssl_ctx_free(ssl_svr_ctx); + return ret; +} + +/************************************************************************** + * SSL unblocked case + * + **************************************************************************/ +static void do_unblocked(void) +{ + int client_fd; + SSL *ssl_clnt; + SSL_CTX *ssl_clnt_ctx = ssl_ctx_new( + DEFAULT_CLNT_OPTION, + SSL_DEFAULT_CLNT_SESS | + SSL_CONNECT_IN_PARTS); + usleep(200000); /* allow server to start */ + + if ((client_fd = client_socket_init(g_port)) < 0) + goto error; + + { +#ifdef WIN32 + u_long argp = 1; + ioctlsocket(client_fd, FIONBIO, &argp); +#else + int flags = fcntl(client_fd, F_GETFL, NULL); + fcntl(client_fd, F_SETFL, flags | O_NONBLOCK); +#endif + } + + if (ssl_obj_load(ssl_clnt_ctx, SSL_OBJ_X509_CACERT, + "../ssl/test/axTLS.ca_x509.cer", NULL)) + goto error; + + ssl_clnt = ssl_client_new(ssl_clnt_ctx, client_fd, NULL, 0, NULL); + + while (ssl_handshake_status(ssl_clnt) != SSL_OK) + { + if (ssl_read(ssl_clnt, NULL) < 0) + { + ssl_display_error(ssl_handshake_status(ssl_clnt)); + goto error; + } + } + + ssl_write(ssl_clnt, basic_buf, sizeof(basic_buf)); + ssl_free(ssl_clnt); + +error: + ssl_ctx_free(ssl_clnt_ctx); + SOCKET_CLOSE(client_fd); + + /* exit this thread */ +} + +static int SSL_unblocked_test(void) +{ + int server_fd, client_fd, ret = 0, size = 0, offset = 0; + SSL_CTX *ssl_svr_ctx = NULL; + struct sockaddr_in client_addr; + uint8_t *read_buf; + socklen_t clnt_len = sizeof(client_addr); + SSL *ssl_svr; +#ifndef WIN32 + pthread_t thread; +#endif + memset(basic_buf, 0xA5, sizeof(basic_buf)/2); + memset(&basic_buf[sizeof(basic_buf)/2], 0x5A, sizeof(basic_buf)/2); + + if ((server_fd = server_socket_init(&g_port)) < 0) + goto error; + + ssl_svr_ctx = ssl_ctx_new(DEFAULT_SVR_OPTION, SSL_DEFAULT_SVR_SESS); + if ((ret = ssl_obj_load(ssl_svr_ctx, SSL_OBJ_X509_CERT, + "../ssl/test/axTLS.x509_1024.pem", NULL)) != SSL_OK) + goto error; + + if ((ret = ssl_obj_load(ssl_svr_ctx, SSL_OBJ_RSA_KEY, + "../ssl/test/axTLS.key_1024.pem", NULL)) != SSL_OK) + goto error; + +#ifndef WIN32 + pthread_create(&thread, NULL, + (void *(*)(void *))do_unblocked, NULL); + pthread_detach(thread); +#else + CreateThread(NULL, 1024, (LPTHREAD_START_ROUTINE)do_unblocked, + NULL, 0, NULL); +#endif + + /* Wait for a client to connect */ + if ((client_fd = accept(server_fd, + (struct sockaddr *) &client_addr, &clnt_len)) < 0) + { + ret = SSL_ERROR_SOCK_SETUP_FAILURE; + goto error; + } + + /* we are ready to go */ + ssl_svr = ssl_server_new(ssl_svr_ctx, client_fd); + + do + { + while ((size = ssl_read(ssl_svr, &read_buf)) == SSL_OK); + + if (size < SSL_OK) /* got some alert or something nasty */ + { + ssl_display_error(size); + ret = size; + break; + } + else /* looks more promising */ + { + if (memcmp(read_buf, &basic_buf[offset], size) != 0) + { + ret = SSL_NOT_OK; + break; + } + } + + offset += size; + } while (offset < sizeof(basic_buf)); + + printf(ret == SSL_OK && offset == sizeof(basic_buf) ? + "SSL unblocked test passed\n" : + "SSL unblocked test failed\n"); + TTY_FLUSH(); + + ssl_free(ssl_svr); + SOCKET_CLOSE(server_fd); + SOCKET_CLOSE(client_fd); + +error: + ssl_ctx_free(ssl_svr_ctx); + return ret; +} + +#if !defined(WIN32) && defined(CONFIG_SSL_CTX_MUTEXING) +/************************************************************************** + * Multi-Threading Tests + * + **************************************************************************/ +#define NUM_THREADS 100 + +typedef struct +{ + SSL_CTX *ssl_clnt_ctx; + int port; + int thread_id; +} multi_t; + +void do_multi_clnt(multi_t *multi_data) +{ + int res = 1, client_fd, i; + SSL *ssl = NULL; + char tmp[5]; + + if ((client_fd = client_socket_init(multi_data->port)) < 0) + goto client_test_exit; + + usleep(200000); + ssl = ssl_client_new(multi_data->ssl_clnt_ctx, client_fd, NULL, 0, NULL); + + if ((res = ssl_handshake_status(ssl))) + { + printf("Client "); + ssl_display_error(res); + goto client_test_exit; + } + + sprintf(tmp, "%d\n", multi_data->thread_id); + for (i = 0; i < 10; i++) + ssl_write(ssl, (uint8_t *)tmp, strlen(tmp)+1); + +client_test_exit: + ssl_free(ssl); + SOCKET_CLOSE(client_fd); + free(multi_data); +} + +void do_multi_svr(SSL *ssl) +{ + uint8_t *read_buf; + int *res_ptr = malloc(sizeof(int)); + int res; + + for (;;) + { + res = ssl_read(ssl, &read_buf); + + /* kill the client */ + if (res != SSL_OK) + { + if (res == SSL_ERROR_CONN_LOST) + { + SOCKET_CLOSE(ssl->client_fd); + ssl_free(ssl); + break; + } + else if (res > 0) + { + /* do nothing */ + } + else /* some problem */ + { + printf("Server "); + ssl_display_error(res); + goto error; + } + } + } + + res = SSL_OK; +error: + *res_ptr = res; + pthread_exit(res_ptr); +} + +int multi_thread_test(void) +{ + int server_fd = -1; + SSL_CTX *ssl_server_ctx; + SSL_CTX *ssl_clnt_ctx; + pthread_t clnt_threads[NUM_THREADS]; + pthread_t svr_threads[NUM_THREADS]; + int i, res = 0; + struct sockaddr_in client_addr; + socklen_t clnt_len = sizeof(client_addr); + + printf("Do multi-threading test (takes a minute)\n"); + + ssl_svr_ctx = ssl_ctx_new(DEFAULT_SVR_OPTION, SSL_DEFAULT_SVR_SESS); + if ((ret = ssl_obj_load(ssl_svr_ctx, SSL_OBJ_X509_CERT, + "../ssl/test/axTLS.x509_1024.pem", NULL)) != SSL_OK) + goto error; + + if ((ret = ssl_obj_load(ssl_svr_ctx, SSL_OBJ_RSA_KEY, + "../ssl/test/axTLS.key_1024.pem", NULL)) != SSL_OK) + goto error; + ssl_clnt_ctx = ssl_ctx_new(DEFAULT_CLNT_OPTION, SSL_DEFAULT_CLNT_SESS); + + if (ssl_obj_load(ssl_clnt_ctx, SSL_OBJ_X509_CACERT, + "../ssl/test/axTLS.ca_x509.cer", NULL)) + goto error; + + if ((server_fd = server_socket_init(&g_port)) < 0) + goto error; + + for (i = 0; i < NUM_THREADS; i++) + { + multi_t *multi_data = (multi_t *)malloc(sizeof(multi_t)); + multi_data->ssl_clnt_ctx = ssl_clnt_ctx; + multi_data->port = g_port; + multi_data->thread_id = i+1; + pthread_create(&clnt_threads[i], NULL, + (void *(*)(void *))do_multi_clnt, (void *)multi_data); + pthread_detach(clnt_threads[i]); + } + + for (i = 0; i < NUM_THREADS; i++) + { + SSL *ssl_svr; + int client_fd = accept(server_fd, + (struct sockaddr *)&client_addr, &clnt_len); + + if (client_fd < 0) + goto error; + + ssl_svr = ssl_server_new(ssl_server_ctx, client_fd); + + pthread_create(&svr_threads[i], NULL, + (void *(*)(void *))do_multi_svr, (void *)ssl_svr); + } + + /* make sure we've run all of the threads */ + for (i = 0; i < NUM_THREADS; i++) + { + void *thread_res; + pthread_join(svr_threads[i], &thread_res); + + if (*((int *)thread_res) != 0) + res = 1; + + free(thread_res); + } + + if (res) + goto error; + + printf("Multi-thread test passed (%d)\n", NUM_THREADS); +error: + ssl_ctx_free(ssl_svr_ctx); + ssl_ctx_free(ssl_clnt_ctx); + SOCKET_CLOSE(server_fd); + return res; +} +#endif /* !defined(WIN32) && defined(CONFIG_SSL_CTX_MUTEXING) */ + +/************************************************************************** + * Header issue + * + **************************************************************************/ +//static void do_header_issue(void) +//{ +// char axtls_buf[2048]; +//#ifndef WIN32 +// pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); +//#endif +// sprintf(axtls_buf, "./axssl s_client -connect localhost:%d", g_port); +// SYSTEM(axtls_buf); +//} +// +//static int header_issue(void) +//{ +// FILE *f = fopen("../ssl/test/header_issue.dat", "r"); +// int server_fd = -1, client_fd = -1, ret = 1; +// uint8_t buf[2048]; +// int size = 0; +// struct sockaddr_in client_addr; +// socklen_t clnt_len = sizeof(client_addr); +//#ifndef WIN32 +// pthread_t thread; +//#endif +// +// if (f == NULL || (server_fd = server_socket_init(&g_port)) < 0) +// goto error; +// +//#ifndef WIN32 +// pthread_create(&thread, NULL, +// (void *(*)(void *))do_header_issue, NULL); +// pthread_detach(thread); +//#else +// CreateThread(NULL, 1024, (LPTHREAD_START_ROUTINE)do_header_issue, +// NULL, 0, NULL); +//#endif +// if ((client_fd = accept(server_fd, +// (struct sockaddr *) &client_addr, &clnt_len)) < 0) +// { +// ret = SSL_ERROR_SOCK_SETUP_FAILURE; +// goto error; +// } +// +// size = fread(buf, 1, sizeof(buf), f); +// if (SOCKET_WRITE(client_fd, buf, size) < 0) +// { +// ret = SSL_ERROR_SOCK_SETUP_FAILURE; +// goto error; +// } +// +// usleep(200000); +// +// ret = 0; +//error: +// fclose(f); +// SOCKET_CLOSE(client_fd); +// SOCKET_CLOSE(server_fd); +// TTY_FLUSH(); +// SYSTEM("killall axssl"); +// return ret; +//} + +/************************************************************************** + * main() + * + **************************************************************************/ +int main(int argc, char *argv[]) +{ + int ret = 1; + BI_CTX *bi_ctx; + int fd; + +#ifdef WIN32 + WSADATA wsaData; + WORD wVersionRequested = MAKEWORD(2, 2); + WSAStartup(wVersionRequested, &wsaData); + fd = _open("test_result.txt", O_WRONLY|O_TEMPORARY|O_CREAT, _S_IWRITE); + dup2(fd, 2); /* write stderr to this file */ +#else + fd = open("/dev/null", O_WRONLY); /* write stderr to /dev/null */ + signal(SIGPIPE, SIG_IGN); /* ignore pipe errors */ + dup2(fd, 2); +#endif + + /* can't do testing in this mode */ +#if defined CONFIG_SSL_GENERATE_X509_CERT + printf("Error: Must compile with default key/certificates\n"); + exit(1); +#endif + + bi_ctx = bi_initialize(); + + if (AES_test(bi_ctx)) + { + printf("AES tests failed\n"); + goto cleanup; + } + TTY_FLUSH(); + + if (MD5_test(bi_ctx)) + { + printf("MD5 tests failed\n"); + goto cleanup; + } + TTY_FLUSH(); + + if (SHA1_test(bi_ctx)) + { + printf("SHA1 tests failed\n"); + goto cleanup; + } + TTY_FLUSH(); + + if (SHA256_test(bi_ctx)) + { + printf("SHA256 tests failed\n"); + goto cleanup; + } + TTY_FLUSH(); + + if (SHA384_test(bi_ctx)) + { + printf("SHA384 tests failed\n"); + goto cleanup; + } + TTY_FLUSH(); + + if (SHA512_test(bi_ctx)) + { + printf("SHA512 tests failed\n"); + goto cleanup; + } + TTY_FLUSH(); + + if (HMAC_test(bi_ctx)) + { + printf("HMAC tests failed\n"); + goto cleanup; + } + TTY_FLUSH(); + + if (BIGINT_test(bi_ctx)) + { + printf("BigInt tests failed!\n"); + goto cleanup; + } + TTY_FLUSH(); + + bi_terminate(bi_ctx); + + if (RSA_test()) + { + printf("RSA tests failed\n"); + goto cleanup; + } + TTY_FLUSH(); + + if (cert_tests()) + { + printf("CERT tests failed\n"); + goto cleanup; + } + TTY_FLUSH(); + +#if !defined(WIN32) && defined(CONFIG_SSL_CTX_MUTEXING) + if (multi_thread_test()) + goto cleanup; +#endif + + if (SSL_basic_test()) + goto cleanup; + + SYSTEM("sh ../ssl/test/killopenssl.sh"); + + if (SSL_unblocked_test()) + goto cleanup; + + SYSTEM("sh ../ssl/test/killopenssl.sh"); + + if (SSL_client_tests()) + goto cleanup; + + SYSTEM("sh ../ssl/test/killopenssl.sh"); + SYSTEM("sh ../ssl/test/killgnutls.sh"); + + if (SSL_server_tests()) + goto cleanup; + + SYSTEM("sh ../ssl/test/killopenssl.sh"); + +// if (header_issue()) +// { +// printf("Header tests failed\n"); TTY_FLUSH(); +// goto cleanup; +// } + + ret = 0; /* all ok */ + printf("**** ALL TESTS PASSED ****\n"); TTY_FLUSH(); +cleanup: + + if (ret) + printf("Error: Some tests failed!\n"); + + close(fd); + return ret; +} diff --git a/tools/sdk/axtls/ssl/tls1.c b/tools/sdk/axtls/ssl/tls1.c new file mode 100644 index 0000000000..ac347d261a --- /dev/null +++ b/tools/sdk/axtls/ssl/tls1.c @@ -0,0 +1,2603 @@ +/* + * Copyright (c) 2007-2016, 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. + */ + +/** + * Common ssl/tlsv1 code to both the client and server implementations. + */ + +#include +#include +#include +#include +#include "os_port.h" +#include "ssl.h" + +/* The session expiry time */ +#define SSL_EXPIRY_TIME (CONFIG_SSL_EXPIRY_TIME*3600) + +static const uint8_t g_hello_request[] = { HS_HELLO_REQUEST, 0, 0, 0 }; +static const uint8_t g_chg_cipher_spec_pkt[] = { 1 }; +static const char * server_finished = "server finished"; +static const char * client_finished = "client finished"; + +static int do_handshake(SSL *ssl, uint8_t *buf, int read_len); +static int set_key_block(SSL *ssl, int is_write); +static int verify_digest(SSL *ssl, int mode, const uint8_t *buf, int read_len); +static void *crypt_new(SSL *ssl, uint8_t *key, uint8_t *iv, int is_decrypt, void* cached); +static int send_raw_packet(SSL *ssl, uint8_t protocol); +static void certificate_free(SSL* ssl); +static int increase_bm_data_size(SSL *ssl, size_t size); +static int check_certificate_chain(SSL *ssl); + +/** + * The server will pick the cipher based on the order that the order that the + * ciphers are listed. This order is defined at compile time. + */ +#ifndef CONFIG_SSL_SKELETON_MODE +static void session_free(SSL_SESSION *ssl_sessions[], int sess_index); +#endif + +const uint8_t ssl_prot_prefs[NUM_PROTOCOLS] = +#ifdef CONFIG_SSL_PROT_LOW /* low security, fast speed */ +{ SSL_AES128_SHA, SSL_AES128_SHA256, SSL_AES256_SHA, SSL_AES256_SHA256 }; +#elif CONFIG_SSL_PROT_MEDIUM /* medium security, medium speed */ +{ SSL_AES128_SHA256, SSL_AES256_SHA256, SSL_AES256_SHA, SSL_AES128_SHA }; +#else /* CONFIG_SSL_PROT_HIGH */ /* high security, low speed */ +{ SSL_AES256_SHA256, SSL_AES128_SHA256, SSL_AES256_SHA, SSL_AES128_SHA }; +#endif + +/** + * The cipher map containing all the essentials for each cipher. + */ +static const cipher_info_t cipher_info[NUM_PROTOCOLS] = +{ + { /* AES128-SHA */ + SSL_AES128_SHA, /* AES128-SHA */ + 16, /* key size */ + 16, /* iv size */ + 16, /* block padding size */ + SHA1_SIZE, /* digest size */ + 2*(SHA1_SIZE+16+16), /* key block size */ + hmac_sha1_v, /* hmac algorithm */ + (crypt_func)AES_cbc_encrypt, /* encrypt */ + (crypt_func)AES_cbc_decrypt /* decrypt */ + }, + { /* AES256-SHA */ + SSL_AES256_SHA, /* AES256-SHA */ + 32, /* key size */ + 16, /* iv size */ + 16, /* block padding size */ + SHA1_SIZE, /* digest size */ + 2*(SHA1_SIZE+32+16), /* key block size */ + hmac_sha1_v, /* hmac algorithm */ + (crypt_func)AES_cbc_encrypt, /* encrypt */ + (crypt_func)AES_cbc_decrypt /* decrypt */ + }, + { /* AES128-SHA256 */ + SSL_AES128_SHA256, /* AES128-SHA256 */ + 16, /* key size */ + 16, /* iv size */ + 16, /* block padding size */ + SHA256_SIZE, /* digest size */ + 2*(SHA256_SIZE+32+16), /* key block size */ + hmac_sha256_v, /* hmac algorithm */ + (crypt_func)AES_cbc_encrypt, /* encrypt */ + (crypt_func)AES_cbc_decrypt /* decrypt */ + }, + { /* AES256-SHA256 */ + SSL_AES256_SHA256, /* AES256-SHA256 */ + 32, /* key size */ + 16, /* iv size */ + 16, /* block padding size */ + SHA256_SIZE, /* digest size */ + 2*(SHA256_SIZE+32+16), /* key block size */ + hmac_sha256_v, /* hmac algorithm */ + (crypt_func)AES_cbc_encrypt, /* encrypt */ + (crypt_func)AES_cbc_decrypt /* decrypt */ + } +}; + +static void prf(SSL *ssl, const uint8_t *sec, int sec_len, + uint8_t *seed, int seed_len, + uint8_t *out, int olen); +static const cipher_info_t *get_cipher_info(uint8_t cipher); +static void increment_read_sequence(SSL *ssl); +static void increment_write_sequence(SSL *ssl); +static void add_hmac_digest(SSL *ssl, int snd, uint8_t *hmac_header, + const uint8_t *buf, int buf_len, uint8_t *hmac_buf); + +/* win32 VC6.0 doesn't have variadic macros */ +#if defined(WIN32) && !defined(CONFIG_SSL_FULL_MODE) +void DISPLAY_BYTES(SSL *ssl, const char *format, + const uint8_t *data, int size, ...) {} +#endif + +/** + * Allocate new SSL extensions structure and return pointer to it + * + */ +EXP_FUNC SSL_EXTENSIONS * STDCALL ssl_ext_new() +{ + return (SSL_EXTENSIONS *)calloc(1, sizeof(SSL_EXTENSIONS)); +} + +/** + * Free SSL extensions structure + * + */ +EXP_FUNC void STDCALL ssl_ext_free(SSL_EXTENSIONS *ssl_ext) +{ + if (ssl_ext == NULL ) + { + return; + } + + free(ssl_ext); +} + +EXP_FUNC void STDCALL ssl_ext_set_host_name(SSL_EXTENSIONS * ext, const char* host_name) +{ + free(ext->host_name); + ext->host_name = NULL; + if (host_name) { + ext->host_name = strdup(host_name); + } +} + +/** + * Set the maximum fragment size for the fragment size negotiation extension + */ +EXP_FUNC void STDCALL ssl_ext_set_max_fragment_size(SSL_EXTENSIONS * ext, unsigned fragment_size) +{ + ext->max_fragment_size = fragment_size; +} + +/** + * Establish a new client/server context. + */ +EXP_FUNC SSL_CTX *STDCALL ssl_ctx_new(uint32_t options, int num_sessions) +{ + SSL_CTX *ssl_ctx = (SSL_CTX *)calloc(1, sizeof (SSL_CTX)); + ssl_ctx->options = options; + RNG_initialize(); + + if (load_key_certs(ssl_ctx) < 0) + { + free(ssl_ctx); /* can't load our key/certificate pair, so die */ + return NULL; + } + +#ifndef CONFIG_SSL_SKELETON_MODE + ssl_ctx->num_sessions = num_sessions; +#endif + + SSL_CTX_MUTEX_INIT(ssl_ctx->mutex); + +#ifndef CONFIG_SSL_SKELETON_MODE + if (num_sessions) + { + ssl_ctx->ssl_sessions = (SSL_SESSION **) + calloc(1, num_sessions*sizeof(SSL_SESSION *)); + } +#endif + + return ssl_ctx; +} + +/* + * Remove a client/server context. + */ +EXP_FUNC void STDCALL ssl_ctx_free(SSL_CTX *ssl_ctx) +{ + SSL *ssl; + int i; + + if (ssl_ctx == NULL) + return; + + ssl = ssl_ctx->head; + + /* clear out all the ssl entries */ + while (ssl) + { + SSL *next = ssl->next; + ssl_free(ssl); + ssl = next; + } + +#ifndef CONFIG_SSL_SKELETON_MODE + /* clear out all the sessions */ + for (i = 0; i < ssl_ctx->num_sessions; i++) + session_free(ssl_ctx->ssl_sessions, i); + + free(ssl_ctx->ssl_sessions); +#endif + + i = 0; + while (i < CONFIG_SSL_MAX_CERTS && ssl_ctx->certs[i].buf) + { + free(ssl_ctx->certs[i].buf); + ssl_ctx->certs[i++].buf = NULL; + } + +#ifdef CONFIG_SSL_CERT_VERIFICATION + remove_ca_certs(ssl_ctx->ca_cert_ctx); +#endif + ssl_ctx->chain_length = 0; + SSL_CTX_MUTEX_DESTROY(ssl_ctx->mutex); + RSA_free(ssl_ctx->rsa_ctx); + RNG_terminate(); + free(ssl_ctx); +} + +/* + * Free any used resources used by this connection. + */ +EXP_FUNC void STDCALL ssl_free(SSL *ssl) +{ + SSL_CTX *ssl_ctx; + + if (ssl == NULL) /* just ignore null pointers */ + return; + + /* only notify if we weren't notified first */ + /* spec says we must notify when we are dying */ + if (!IS_SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY)) + send_alert(ssl, SSL_ALERT_CLOSE_NOTIFY); + + ssl_ctx = ssl->ssl_ctx; + + SSL_CTX_LOCK(ssl_ctx->mutex); + + /* adjust the server SSL list */ + if (ssl->prev) + ssl->prev->next = ssl->next; + else + ssl_ctx->head = ssl->next; + + if (ssl->next) + ssl->next->prev = ssl->prev; + else + ssl_ctx->tail = ssl->prev; + + SSL_CTX_UNLOCK(ssl_ctx->mutex); + + /* may already be free - but be sure */ + free(ssl->encrypt_ctx); + ssl->encrypt_ctx = NULL; + free(ssl->decrypt_ctx); + ssl->decrypt_ctx = NULL; + disposable_free(ssl); + certificate_free(ssl); + free(ssl->bm_all_data); + ssl_ext_free(ssl->extensions); + ssl->extensions = NULL; + free(ssl); +} + +/* + * Read the SSL connection and send any alerts for various errors. + */ +EXP_FUNC int STDCALL ssl_read(SSL *ssl, uint8_t **in_data) +{ + int ret = SSL_OK; + do { + ret= basic_read(ssl, in_data); + + /* check for return code so we can send an alert */ + if (ret < SSL_OK && ret != SSL_CLOSE_NOTIFY) + { + if (ret != SSL_ERROR_CONN_LOST) + { + send_alert(ssl, ret); + #ifndef CONFIG_SSL_SKELETON_MODE + /* something nasty happened, so get rid of this session */ + kill_ssl_session(ssl->ssl_ctx->ssl_sessions, ssl); + #endif + } + } + } while (IS_SET_SSL_FLAG(SSL_READ_BLOCKING) && (ssl->got_bytes < ssl->need_bytes) && ret == 0 && !IS_SET_SSL_FLAG(SSL_NEED_RECORD)); + return ret; +} + +/* + * Write application data to the client + */ +EXP_FUNC int STDCALL ssl_write(SSL *ssl, const uint8_t *out_data, int out_len) +{ + int n = out_len, nw, i, tot = 0; + /* maximum size of a TLS packet is around 16kB, so fragment */ + + do + { + nw = n; + + if (nw > ssl->max_plain_length) /* fragment if necessary */ + nw = ssl->max_plain_length; + + if ((i = send_packet(ssl, PT_APP_PROTOCOL_DATA, + &out_data[tot], nw)) <= 0) + { + out_len = i; /* an error */ + break; + } + + tot += i; + n -= i; + } while (n > 0); + + return out_len; +} + +EXP_FUNC int STDCALL ssl_calculate_write_length(SSL *ssl, int length) +{ + int msg_length = 0; + if (ssl->hs_status == SSL_ERROR_DEAD) + return SSL_ERROR_CONN_LOST; + + if (ssl->flag & SSL_SENT_CLOSE_NOTIFY) + return SSL_CLOSE_NOTIFY; + + msg_length += length; + + if (ssl->flag & SSL_TX_ENCRYPTED) + { + msg_length += ssl->cipher_info->digest_size; + { + int last_blk_size = msg_length%ssl->cipher_info->padding_size; + int pad_bytes = ssl->cipher_info->padding_size - last_blk_size; + if (pad_bytes == 0) + pad_bytes += ssl->cipher_info->padding_size; + msg_length += pad_bytes; + } + if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_1) + { + msg_length += ssl->cipher_info->iv_size; + } + } + return SSL_RECORD_SIZE+msg_length; +} + +/** + * Add a certificate to the certificate chain. + */ +int add_cert(SSL_CTX *ssl_ctx, const uint8_t *buf, int len) +{ + int ret = SSL_ERROR_NO_CERT_DEFINED, i = 0; + SSL_CERT *ssl_cert; + X509_CTX *cert = NULL; + int offset; + + while (i < CONFIG_SSL_MAX_CERTS && ssl_ctx->certs[i].buf) + i++; + + if (i == CONFIG_SSL_MAX_CERTS) /* too many certs */ + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: maximum number of certs added (%d) - change of " + "compile-time configuration required\n", + CONFIG_SSL_MAX_CERTS); +#endif + goto error; + } + + if ((ret = x509_new(buf, &offset, &cert))) + goto error; + +#if defined (CONFIG_SSL_FULL_MODE) + if (ssl_ctx->options & SSL_DISPLAY_CERTS) + x509_print(cert, NULL); +#endif + + ssl_cert = &ssl_ctx->certs[i]; + ssl_cert->size = len; + ssl_cert->buf = (uint8_t *)malloc(len); + + switch (cert->sig_type) + { + case SIG_TYPE_SHA1: + ssl_cert->hash_alg = SIG_ALG_SHA1; + break; + + case SIG_TYPE_SHA256: + ssl_cert->hash_alg = SIG_ALG_SHA256; + break; + + case SIG_TYPE_SHA384: + ssl_cert->hash_alg = SIG_ALG_SHA384; + break; + + case SIG_TYPE_SHA512: + ssl_cert->hash_alg = SIG_ALG_SHA512; + break; + } + + memcpy(ssl_cert->buf, buf, len); + ssl_ctx->chain_length++; + len -= offset; + ret = SSL_OK; /* ok so far */ + + /* recurse? */ + if (len > 0) + { + ret = add_cert(ssl_ctx, &buf[offset], len); + } + +error: + x509_free(cert); /* don't need anymore */ + return ret; +} + +#ifdef CONFIG_SSL_CERT_VERIFICATION +/** + * Add a certificate authority. + */ +int add_cert_auth(SSL_CTX *ssl_ctx, const uint8_t *buf, int len) +{ + int ret = X509_OK; /* ignore errors for now */ + int i = 0; + CA_CERT_CTX *ca_cert_ctx; + + if (ssl_ctx->ca_cert_ctx == NULL) + ssl_ctx->ca_cert_ctx = (CA_CERT_CTX *)calloc(1, sizeof(CA_CERT_CTX)); + + ca_cert_ctx = ssl_ctx->ca_cert_ctx; + + while (i < CONFIG_X509_MAX_CA_CERTS && ca_cert_ctx->cert[i]) + i++; + + while (len > 0) + { + int offset; + if (i >= CONFIG_X509_MAX_CA_CERTS) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: maximum number of CA certs added (%d) - change of " + "compile-time configuration required\n", + CONFIG_X509_MAX_CA_CERTS); +#endif + ret = X509_MAX_CERTS; + break; + } + + /* ignore the return code */ + if (x509_new(buf, &offset, &ca_cert_ctx->cert[i]) == X509_OK) + { +#if defined (CONFIG_SSL_FULL_MODE) + if (ssl_ctx->options & SSL_DISPLAY_CERTS) + x509_print(ca_cert_ctx->cert[i], NULL); +#endif + } + + i++; + len -= offset; + } + + return ret; +} + +/* + * Retrieve an X.509 distinguished name component + */ +EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component) +{ + if (ssl->x509_ctx == NULL) + return NULL; + + switch (component) + { + case SSL_X509_CERT_COMMON_NAME: + return ssl->x509_ctx->cert_dn[X509_COMMON_NAME]; + + case SSL_X509_CERT_ORGANIZATION: + return ssl->x509_ctx->cert_dn[X509_ORGANIZATION]; + + case SSL_X509_CERT_ORGANIZATIONAL_NAME: + return ssl->x509_ctx->cert_dn[X509_ORGANIZATIONAL_UNIT]; + + case SSL_X509_CERT_LOCATION: + return ssl->x509_ctx->cert_dn[X509_LOCATION]; + + case SSL_X509_CERT_COUNTRY: + return ssl->x509_ctx->cert_dn[X509_COUNTRY]; + + case SSL_X509_CERT_STATE: + return ssl->x509_ctx->cert_dn[X509_STATE]; + + case SSL_X509_CA_CERT_COMMON_NAME: + return ssl->x509_ctx->ca_cert_dn[X509_COMMON_NAME]; + + case SSL_X509_CA_CERT_ORGANIZATION: + return ssl->x509_ctx->ca_cert_dn[X509_ORGANIZATION]; + + case SSL_X509_CA_CERT_ORGANIZATIONAL_NAME: + return ssl->x509_ctx->ca_cert_dn[X509_ORGANIZATIONAL_UNIT]; + + case SSL_X509_CA_CERT_LOCATION: + return ssl->x509_ctx->ca_cert_dn[X509_LOCATION]; + + case SSL_X509_CA_CERT_COUNTRY: + return ssl->x509_ctx->ca_cert_dn[X509_COUNTRY]; + + case SSL_X509_CA_CERT_STATE: + return ssl->x509_ctx->ca_cert_dn[X509_STATE]; + + default: + return NULL; + } +} + +/* + * Retrieve a "Subject Alternative Name" from a v3 certificate + */ +EXP_FUNC const char * STDCALL ssl_get_cert_subject_alt_dnsname(const SSL *ssl, + int dnsindex) +{ + int i; + + if (ssl->x509_ctx == NULL || ssl->x509_ctx->subject_alt_dnsnames == NULL) + return NULL; + + for (i = 0; i < dnsindex; ++i) + { + if (ssl->x509_ctx->subject_alt_dnsnames[i] == NULL) + return NULL; + } + + return ssl->x509_ctx->subject_alt_dnsnames[dnsindex]; +} + +#endif /* CONFIG_SSL_CERT_VERIFICATION */ + +/* + * Find an ssl object based on the client's file descriptor. + */ +EXP_FUNC SSL * STDCALL ssl_find(SSL_CTX *ssl_ctx, int client_fd) +{ + SSL *ssl; + + SSL_CTX_LOCK(ssl_ctx->mutex); + ssl = ssl_ctx->head; + + /* search through all the ssl entries */ + while (ssl) + { + if (ssl->client_fd == client_fd) + { + SSL_CTX_UNLOCK(ssl_ctx->mutex); + return ssl; + } + + ssl = ssl->next; + } + + SSL_CTX_UNLOCK(ssl_ctx->mutex); + return NULL; +} + +/* + * Force the client to perform its handshake again. + */ +EXP_FUNC int STDCALL ssl_renegotiate(SSL *ssl) +{ + int ret = SSL_OK; + + disposable_new(ssl); +#ifdef CONFIG_SSL_ENABLE_CLIENT + if (IS_SET_SSL_FLAG(SSL_IS_CLIENT)) + { + ret = do_client_connect(ssl); + } + else +#endif + { + send_packet(ssl, PT_HANDSHAKE_PROTOCOL, + g_hello_request, sizeof(g_hello_request)); + SET_SSL_FLAG(SSL_NEED_RECORD); + } + + return ret; +} + +/** + * @brief Get what we need for key info. + * @param cipher [in] The cipher information we are after + * @param key_size [out] The key size for the cipher + * @param iv_size [out] The iv size for the cipher + * @return The amount of key information we need. + */ +static const cipher_info_t *get_cipher_info(uint8_t cipher) +{ + int i; + + for (i = 0; i < NUM_PROTOCOLS; i++) + { + if (cipher_info[i].cipher == cipher) + { + return &cipher_info[i]; + } + } + + return NULL; /* error */ +} + +/* + * Get a new ssl context for a new connection. + */ +SSL *ssl_new(SSL_CTX *ssl_ctx, int client_fd) +{ + SSL *ssl = (SSL *)calloc(1, sizeof(SSL)); + ssl->ssl_ctx = ssl_ctx; + ssl->max_plain_length = 1460*4; + ssl->bm_all_data = (uint8_t*) calloc(1, ssl->max_plain_length + RT_EXTRA); + ssl->need_bytes = SSL_RECORD_SIZE; /* need a record */ + ssl->client_fd = client_fd; + ssl->flag = SSL_NEED_RECORD; + ssl->bm_data = ssl->bm_all_data + BM_RECORD_OFFSET; /* space at the start */ + ssl->hs_status = SSL_NOT_OK; /* not connected */ +#ifdef CONFIG_ENABLE_VERIFICATION + ssl->ca_cert_ctx = ssl_ctx->ca_cert_ctx; + ssl->can_free_certificates = false; +#endif + disposable_new(ssl); + + /* a bit hacky but saves a few bytes of memory */ + ssl->flag |= ssl_ctx->options; + if (IS_SET_SSL_FLAG(SSL_CONNECT_IN_PARTS) && IS_SET_SSL_FLAG(SSL_READ_BLOCKING)) { + CLR_SSL_FLAG(SSL_READ_BLOCKING); + } + SSL_CTX_LOCK(ssl_ctx->mutex); + + if (ssl_ctx->head == NULL) + { + ssl_ctx->head = ssl; + ssl_ctx->tail = ssl; + } + else + { + ssl->prev = ssl_ctx->tail; + ssl_ctx->tail->next = ssl; + ssl_ctx->tail = ssl; + } + + ssl->encrypt_ctx = malloc(sizeof(AES_CTX)); + ssl->decrypt_ctx = malloc(sizeof(AES_CTX)); + + SSL_CTX_UNLOCK(ssl_ctx->mutex); + return ssl; +} + +/* + * Add a private key to a context. + */ +int add_private_key(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj) +{ + int ret = SSL_OK; + + /* get the private key details */ + if (asn1_get_private_key(ssl_obj->buf, ssl_obj->len, &ssl_ctx->rsa_ctx)) + { + ret = SSL_ERROR_INVALID_KEY; + goto error; + } + +error: + return ret; +} + +/** + * Increment the read sequence number (as a 64 bit endian indepenent #) + */ +static void increment_read_sequence(SSL *ssl) +{ + int i; + + for (i = 7; i >= 0; i--) + { + if (++ssl->read_sequence[i]) + break; + } +} + +/** + * Increment the read sequence number (as a 64 bit endian indepenent #) + */ +static void increment_write_sequence(SSL *ssl) +{ + int i; + + for (i = 7; i >= 0; i--) + { + if (++ssl->write_sequence[i]) + break; + } +} + +/** + * Work out the HMAC digest in a packet. + */ +static void add_hmac_digest(SSL *ssl, int mode, uint8_t *hmac_header, + const uint8_t *buf, int buf_len, uint8_t *hmac_buf) +{ + const uint8_t* bufs[] = { + (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_WRITE) ? + ssl->write_sequence : ssl->read_sequence, + hmac_header, + buf + }; + + int lengths[] = { + 8, + SSL_RECORD_SIZE, + buf_len + }; + + ssl->cipher_info->hmac_v(bufs, lengths, 3, + (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_READ) ? + ssl->server_mac : ssl->client_mac, + ssl->cipher_info->digest_size, hmac_buf); + +#if 0 + print_blob("record", hmac_header, SSL_RECORD_SIZE); + print_blob("buf", buf, buf_len); + if (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_WRITE) + { + print_blob("write seq", ssl->write_sequence, 8); + } + else + { + print_blob("read seq", ssl->read_sequence, 8); + } + + if (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_READ) + { + print_blob("server mac", + ssl->server_mac, ssl->cipher_info->digest_size); + } + else + { + print_blob("client mac", + ssl->client_mac, ssl->cipher_info->digest_size); + } + print_blob("hmac", hmac_buf, ssl->cipher_info->digest_size); +#endif +} + +/** + * Verify that the digest of a packet is correct. + */ +static int verify_digest(SSL *ssl, int mode, const uint8_t *buf, int read_len) +{ + uint8_t hmac_buf[SHA256_SIZE]; // size of largest digest + int hmac_offset; + + int last_blk_size = buf[read_len-1], i; + hmac_offset = read_len-last_blk_size-ssl->cipher_info->digest_size-1; + + /* guard against a timing attack - make sure we do the digest */ + if (hmac_offset < 0) + { + hmac_offset = 0; + } + else + { + /* already looked at last byte */ + for (i = 1; i < last_blk_size; i++) + { + if (buf[read_len-i] != last_blk_size) + { + hmac_offset = 0; + break; + } + } + } + + /* sanity check the offset */ + ssl->hmac_header[3] = hmac_offset >> 8; /* insert size */ + ssl->hmac_header[4] = hmac_offset & 0xff; + add_hmac_digest(ssl, mode, ssl->hmac_header, buf, hmac_offset, hmac_buf); + + if (memcmp(hmac_buf, &buf[hmac_offset], ssl->cipher_info->digest_size)) + { + return SSL_ERROR_INVALID_HMAC; + } + + return hmac_offset; +} + +/** + * Add a packet to the end of our sent and received packets, so that we may use + * it to calculate the hash at the end. + */ +void add_packet(SSL *ssl, const uint8_t *pkt, int len) +{ + // TLS1.2+ + if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_2 || ssl->version == 0) + { + SHA256_Update(&ssl->dc->sha256_ctx, pkt, len); + } + + if (ssl->version < SSL_PROTOCOL_VERSION_TLS1_2 || + ssl->next_state == HS_SERVER_HELLO || + ssl->next_state == 0) + { + MD5_Update(&ssl->dc->md5_ctx, pkt, len); + SHA1_Update(&ssl->dc->sha1_ctx, pkt, len); + } +} + +/** + * Work out the MD5 PRF. + */ +static void p_hash_md5(const uint8_t *sec, int sec_len, + uint8_t *seed, int seed_len, uint8_t *out, int olen) +{ + uint8_t a1[MD5_SIZE+77]; + + /* A(1) */ + hmac_md5(seed, seed_len, sec, sec_len, a1); + memcpy(&a1[MD5_SIZE], seed, seed_len); + hmac_md5(a1, MD5_SIZE+seed_len, sec, sec_len, out); + + while (olen > MD5_SIZE) + { + uint8_t a2[MD5_SIZE]; + out += MD5_SIZE; + olen -= MD5_SIZE; + + /* A(N) */ + hmac_md5(a1, MD5_SIZE, sec, sec_len, a2); + memcpy(a1, a2, MD5_SIZE); + + /* work out the actual hash */ + hmac_md5(a1, MD5_SIZE+seed_len, sec, sec_len, out); + } +} + +/** + * Work out the SHA1 PRF. + */ +static void p_hash_sha1(const uint8_t *sec, int sec_len, + uint8_t *seed, int seed_len, uint8_t *out, int olen) +{ + uint8_t a1[SHA1_SIZE+77]; + + /* A(1) */ + hmac_sha1(seed, seed_len, sec, sec_len, a1); + memcpy(&a1[SHA1_SIZE], seed, seed_len); + hmac_sha1(a1, SHA1_SIZE+seed_len, sec, sec_len, out); + + while (olen > SHA1_SIZE) + { + uint8_t a2[SHA1_SIZE]; + out += SHA1_SIZE; + olen -= SHA1_SIZE; + + /* A(N) */ + hmac_sha1(a1, SHA1_SIZE, sec, sec_len, a2); + memcpy(a1, a2, SHA1_SIZE); + + /* work out the actual hash */ + hmac_sha1(a1, SHA1_SIZE+seed_len, sec, sec_len, out); + } +} + +/** + * Work out the SHA256 PRF. + */ +static void p_hash_sha256(const uint8_t *sec, int sec_len, + uint8_t *seed, int seed_len, uint8_t *out, int olen) +{ + uint8_t a1[SHA256_SIZE+77]; + + /* A(1) */ + hmac_sha256(seed, seed_len, sec, sec_len, a1); + memcpy(&a1[SHA256_SIZE], seed, seed_len); + hmac_sha256(a1, SHA256_SIZE+seed_len, sec, sec_len, out); + + while (olen > SHA256_SIZE) + { + uint8_t a2[SHA256_SIZE]; + out += SHA256_SIZE; + olen -= SHA256_SIZE; + + // A(N) + hmac_sha256(a1, SHA256_SIZE, sec, sec_len, a2); + memcpy(a1, a2, SHA256_SIZE); + + // work out the actual hash + hmac_sha256(a1, SHA256_SIZE+seed_len, sec, sec_len, out); + } +} + +/** + * Work out the PRF. + */ +static void prf(SSL *ssl, const uint8_t *sec, int sec_len, + uint8_t *seed, int seed_len, + uint8_t *out, int olen) +{ + if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_2) // TLS1.2+ + { + p_hash_sha256(sec, sec_len, seed, seed_len, out, olen); + } + else // TLS1.0/1.1 + { + int len, i; + const uint8_t *S1, *S2; + uint8_t xbuf[2*(SHA256_SIZE+32+16) + MD5_SIZE]; /* max keyblock */ + uint8_t ybuf[2*(SHA256_SIZE+32+16) + SHA1_SIZE]; /* max keyblock */ + + len = sec_len/2; + S1 = sec; + S2 = &sec[len]; + len += (sec_len & 1); /* add for odd, make longer */ + + p_hash_md5(S1, len, seed, seed_len, xbuf, olen); + p_hash_sha1(S2, len, seed, seed_len, ybuf, olen); + + for (i = 0; i < olen; i++) + out[i] = xbuf[i] ^ ybuf[i]; + } +} + +/** + * Generate a master secret based on the client/server random data and the + * premaster secret. + */ +void generate_master_secret(SSL *ssl, const uint8_t *premaster_secret) +{ + uint8_t buf[77]; +//print_blob("premaster secret", premaster_secret, 48); + strcpy((char *)buf, "master secret"); + memcpy(&buf[13], ssl->dc->client_random, SSL_RANDOM_SIZE); + memcpy(&buf[45], ssl->dc->server_random, SSL_RANDOM_SIZE); + prf(ssl, premaster_secret, SSL_SECRET_SIZE, buf, 77, ssl->dc->master_secret, + SSL_SECRET_SIZE); +#if 0 + print_blob("client random", ssl->dc->client_random, 32); + print_blob("server random", ssl->dc->server_random, 32); + print_blob("master secret", ssl->dc->master_secret, 48); +#endif +} + +/** + * Generate a 'random' blob of data used for the generation of keys. + */ +static void generate_key_block(SSL *ssl, + uint8_t *client_random, uint8_t *server_random, + uint8_t *master_secret, uint8_t *key_block, int key_block_size) +{ + uint8_t buf[77]; + strcpy((char *)buf, "key expansion"); + memcpy(&buf[13], server_random, SSL_RANDOM_SIZE); + memcpy(&buf[45], client_random, SSL_RANDOM_SIZE); + prf(ssl, master_secret, SSL_SECRET_SIZE, buf, 77, + key_block, key_block_size); +} + +/** + * Calculate the digest used in the finished message. This function also + * doubles up as a certificate verify function. + */ +int finished_digest(SSL *ssl, const char *label, uint8_t *digest) +{ + uint8_t mac_buf[SHA1_SIZE+MD5_SIZE+15]; + uint8_t *q = mac_buf; + int dgst_len; + + if (label) + { + strcpy((char *)q, label); + q += strlen(label); + } + + if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_2) // TLS1.2+ + { + SHA256_CTX sha256_ctx = ssl->dc->sha256_ctx; // interim copy + SHA256_Final(q, &sha256_ctx); + q += SHA256_SIZE; + dgst_len = (int)(q-mac_buf); + } + else // TLS1.0/1.1 + { + MD5_CTX md5_ctx = ssl->dc->md5_ctx; // interim copy + SHA1_CTX sha1_ctx = ssl->dc->sha1_ctx; + + MD5_Final(q, &md5_ctx); + q += MD5_SIZE; + + SHA1_Final(q, &sha1_ctx); + q += SHA1_SIZE; + dgst_len = (int)(q-mac_buf); + } + + if (label) + { + prf(ssl, ssl->dc->master_secret, SSL_SECRET_SIZE, + mac_buf, dgst_len, digest, SSL_FINISHED_HASH_SIZE); + } + else /* for use in a certificate verify */ + { + memcpy(digest, mac_buf, dgst_len); + } + +#if 0 + printf("label: %s\n", label); + print_blob("mac_buf", mac_buf, dgst_len); + print_blob("finished digest", digest, SSL_FINISHED_HASH_SIZE); +#endif + + return dgst_len; +} + +/** + * Retrieve (and initialise) the context of a cipher. + */ +static void *crypt_new(SSL *ssl, uint8_t *key, uint8_t *iv, int is_decrypt, void* cached) +{ + switch (ssl->cipher) + { + case SSL_AES128_SHA: + case SSL_AES128_SHA256: + { + AES_CTX *aes_ctx; + if (cached) + aes_ctx = (AES_CTX*) cached; + else + aes_ctx = (AES_CTX*) malloc(sizeof(AES_CTX)); + AES_set_key(aes_ctx, key, iv, AES_MODE_128); + + if (is_decrypt) + { + AES_convert_key(aes_ctx); + } + + return (void *)aes_ctx; + } + + case SSL_AES256_SHA: + case SSL_AES256_SHA256: + { + AES_CTX *aes_ctx; + if (cached) + aes_ctx = (AES_CTX*) cached; + else + aes_ctx = (AES_CTX*) malloc(sizeof(AES_CTX)); + + AES_set_key(aes_ctx, key, iv, AES_MODE_256); + + if (is_decrypt) + { + AES_convert_key(aes_ctx); + } + + return (void *)aes_ctx; + } + + } + + return NULL; /* its all gone wrong */ +} + +/** + * Send a packet over the socket. + */ +static int send_raw_packet(SSL *ssl, uint8_t protocol) +{ + uint8_t *rec_buf = ssl->bm_all_data; + int pkt_size = SSL_RECORD_SIZE+ssl->bm_index; + int sent = 0; + int ret = SSL_OK; + + rec_buf[0] = protocol; + rec_buf[1] = 0x03; /* version = 3.1 or higher */ + rec_buf[2] = ssl->version & 0x0f; + rec_buf[3] = ssl->bm_index >> 8; + rec_buf[4] = ssl->bm_index & 0xff; + + DISPLAY_BYTES(ssl, "sending %d bytes", ssl->bm_all_data, + pkt_size, pkt_size); + + while (sent < pkt_size) + { + ret = SOCKET_WRITE(ssl->client_fd, + &ssl->bm_all_data[sent], pkt_size-sent); + + if (ret >= 0) + sent += ret; + else + { + +#ifdef WIN32 + if (GetLastError() != WSAEWOULDBLOCK) +#else + if (errno != EAGAIN && errno != EWOULDBLOCK) +#endif + return SSL_ERROR_CONN_LOST; + } +#ifndef ESP8266 + /* keep going until the write buffer has some space */ + if (sent != pkt_size) + { + fd_set wfds; + FD_ZERO(&wfds); + FD_SET(ssl->client_fd, &wfds); + + /* block and wait for it */ + if (select(ssl->client_fd + 1, NULL, &wfds, NULL, NULL) < 0) + return SSL_ERROR_CONN_LOST; + } +#endif + } + + SET_SSL_FLAG(SSL_NEED_RECORD); /* reset for next time */ + ssl->bm_index = 0; + + if (protocol != PT_APP_PROTOCOL_DATA) + { + /* always return SSL_OK during handshake */ + ret = SSL_OK; + } + + return ret; +} + +/** + * Send an encrypted packet with padding bytes if necessary. + */ +int send_packet(SSL *ssl, uint8_t protocol, const uint8_t *in, int length) +{ + int ret, msg_length = 0; + + /* if our state is bad, don't bother */ + if (ssl->hs_status == SSL_ERROR_DEAD) + return SSL_ERROR_CONN_LOST; + + if (IS_SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY)) + return SSL_CLOSE_NOTIFY; + + if (in) /* has the buffer already been initialised? */ + { + memcpy(ssl->bm_data, in, length); + } + + msg_length += length; + + if (IS_SET_SSL_FLAG(SSL_TX_ENCRYPTED)) + { + int mode = IS_SET_SSL_FLAG(SSL_IS_CLIENT) ? + SSL_CLIENT_WRITE : SSL_SERVER_WRITE; + uint8_t hmac_header[SSL_RECORD_SIZE] = + { + protocol, + 0x03, /* version = 3.1 or higher */ + ssl->version & 0x0f, + msg_length >> 8, + msg_length & 0xff + }; + + if (protocol == PT_HANDSHAKE_PROTOCOL) + { + DISPLAY_STATE(ssl, 1, ssl->bm_data[0], 0); + + if (ssl->bm_data[0] != HS_HELLO_REQUEST) + { + add_packet(ssl, ssl->bm_data, msg_length); + } + } + + /* add the packet digest */ + add_hmac_digest(ssl, mode, hmac_header, ssl->bm_data, msg_length, + &ssl->bm_data[msg_length]); + msg_length += ssl->cipher_info->digest_size; + + /* add padding */ + { + int last_blk_size = msg_length%ssl->cipher_info->padding_size; + int pad_bytes = ssl->cipher_info->padding_size - last_blk_size; + + /* ensure we always have at least 1 padding byte */ + if (pad_bytes == 0) + pad_bytes += ssl->cipher_info->padding_size; + + memset(&ssl->bm_data[msg_length], pad_bytes-1, pad_bytes); + msg_length += pad_bytes; + } + + DISPLAY_BYTES(ssl, "unencrypted write", ssl->bm_data, msg_length); + increment_write_sequence(ssl); + + /* add the explicit IV for TLS1.1 */ + if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_1) + { + uint8_t iv_size = ssl->cipher_info->iv_size; + uint8_t *t_buf = malloc(msg_length + iv_size); + memcpy(t_buf + iv_size, ssl->bm_data, msg_length); + if (get_random(iv_size, t_buf) < 0) + return SSL_NOT_OK; + + msg_length += iv_size; + memcpy(ssl->bm_data, t_buf, msg_length); + free(t_buf); + } + + /* now encrypt the packet */ + ssl->cipher_info->encrypt(ssl->encrypt_ctx, ssl->bm_data, + ssl->bm_data, msg_length); + } + else if (protocol == PT_HANDSHAKE_PROTOCOL) + { + DISPLAY_STATE(ssl, 1, ssl->bm_data[0], 0); + + if (ssl->bm_data[0] != HS_HELLO_REQUEST) + { + add_packet(ssl, ssl->bm_data, length); + } + } + + ssl->bm_index = msg_length; + if ((ret = send_raw_packet(ssl, protocol)) <= 0) + return ret; + + return length; /* just return what we wanted to send */ +} + +/** + * Work out the cipher keys we are going to use for this session based on the + * master secret. + */ +static int set_key_block(SSL *ssl, int is_write) +{ + const cipher_info_t *ciph_info = get_cipher_info(ssl->cipher); + uint8_t *q; + uint8_t client_key[32], server_key[32]; /* big enough for AES256 */ + uint8_t client_iv[16], server_iv[16]; /* big enough for AES128/256 */ + int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT); + + if (ciph_info == NULL) + return -1; + + /* only do once in a handshake */ + if (!ssl->dc->key_block_generated) + { + generate_key_block(ssl, ssl->dc->client_random, ssl->dc->server_random, + ssl->dc->master_secret, ssl->dc->key_block, + ciph_info->key_block_size); +#if 0 + print_blob("master", ssl->dc->master_secret, SSL_SECRET_SIZE); + print_blob("keyblock", ssl->dc->key_block, ciph_info->key_block_size); + print_blob("client random", ssl->dc->client_random, 32); + print_blob("server random", ssl->dc->server_random, 32); +#endif + ssl->dc->key_block_generated = 1; + } + + q = ssl->dc->key_block; + + if ((is_client && is_write) || (!is_client && !is_write)) + { + memcpy(ssl->client_mac, q, ciph_info->digest_size); + } + + q += ciph_info->digest_size; + + if ((!is_client && is_write) || (is_client && !is_write)) + { + memcpy(ssl->server_mac, q, ciph_info->digest_size); + } + + q += ciph_info->digest_size; + memcpy(client_key, q, ciph_info->key_size); + q += ciph_info->key_size; + memcpy(server_key, q, ciph_info->key_size); + q += ciph_info->key_size; + + memcpy(client_iv, q, ciph_info->iv_size); + q += ciph_info->iv_size; + memcpy(server_iv, q, ciph_info->iv_size); + q += ciph_info->iv_size; +#if 0 + print_blob("client key", client_key, ciph_info->key_size); + print_blob("server key", server_key, ciph_info->key_size); + print_blob("client iv", client_iv, ciph_info->iv_size); + print_blob("server iv", server_iv, ciph_info->iv_size); +#endif + + // free(is_write ? ssl->encrypt_ctx : ssl->decrypt_ctx); + + /* now initialise the ciphers */ + if (is_client) + { + finished_digest(ssl, server_finished, ssl->dc->final_finish_mac); + + if (is_write) + ssl->encrypt_ctx = crypt_new(ssl, client_key, client_iv, 0, ssl->encrypt_ctx); + else + ssl->decrypt_ctx = crypt_new(ssl, server_key, server_iv, 1, ssl->decrypt_ctx); + } + else + { + finished_digest(ssl, client_finished, ssl->dc->final_finish_mac); + + if (is_write) + ssl->encrypt_ctx = crypt_new(ssl, server_key, server_iv, 0, ssl->encrypt_ctx); + else + ssl->decrypt_ctx = crypt_new(ssl, client_key, client_iv, 1, ssl->decrypt_ctx); + } + + ssl->cipher_info = ciph_info; + return 0; +} + +/** + * Read the SSL connection. + */ +int basic_read(SSL *ssl, uint8_t **in_data) +{ + int ret = SSL_OK; + int read_len, is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT); + uint8_t *buf = ssl->bm_data; + + if (IS_SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY)) + return SSL_CLOSE_NOTIFY; + + read_len = SOCKET_READ(ssl->client_fd, &buf[ssl->bm_read_index], + ssl->need_bytes-ssl->got_bytes); + + if (read_len < 0) + { +#ifdef WIN32 + if (GetLastError() == WSAEWOULDBLOCK) +#else + if (errno == EAGAIN || errno == EWOULDBLOCK) +#endif + return 0; + } + + /* connection has gone, so die */ + if (read_len <= 0) + { + ret = SSL_ERROR_CONN_LOST; + ssl->hs_status = SSL_ERROR_DEAD; /* make sure it stays dead */ + goto error; + } + + DISPLAY_BYTES(ssl, "received %d bytes", + &ssl->bm_data[ssl->bm_read_index], read_len, read_len); + + ssl->got_bytes += read_len; + ssl->bm_read_index += read_len; + + /* haven't quite got what we want, so try again later */ + if (ssl->got_bytes < ssl->need_bytes) + return SSL_OK; + + read_len = ssl->got_bytes; + ssl->got_bytes = 0; + + if (IS_SET_SSL_FLAG(SSL_NEED_RECORD)) + { + /* check for sslv2 "client hello" */ + if ((buf[0] & 0x80) && buf[2] == 1) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: no SSLv23 handshaking allowed\n"); +#endif + ret = SSL_ERROR_NOT_SUPPORTED; + goto error; /* not an error - just get out of here */ + } + + ssl->need_bytes = (buf[3] << 8) + buf[4]; + + /* do we violate the spec with the message size? */ + if (ssl->need_bytes > RT_MAX_PLAIN_LENGTH+RT_EXTRA-BM_RECORD_OFFSET) + { + ret = SSL_ERROR_RECORD_OVERFLOW; + goto error; + } + + /* is the allocated buffer large enough to handle all the data? if not, increase its size*/ + if (ssl->need_bytes > ssl->max_plain_length+RT_EXTRA-BM_RECORD_OFFSET) + { + printf("ssl->need_bytes=%d > %d\r\n", ssl->need_bytes, ssl->max_plain_length+RT_EXTRA-BM_RECORD_OFFSET); + ret = increase_bm_data_size(ssl, ssl->need_bytes + BM_RECORD_OFFSET - RT_EXTRA); + if (ret != SSL_OK) + { + ret = SSL_ERROR_INVALID_PROT_MSG; + goto error; + } + } + + CLR_SSL_FLAG(SSL_NEED_RECORD); + memcpy(ssl->hmac_header, buf, 3); /* store for hmac */ + ssl->record_type = buf[0]; + goto error; /* no error, we're done */ + } + + /* for next time - just do it now in case of an error */ + SET_SSL_FLAG(SSL_NEED_RECORD); + ssl->need_bytes = SSL_RECORD_SIZE; + + /* decrypt if we need to */ + if (IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED)) + { + ssl->cipher_info->decrypt(ssl->decrypt_ctx, buf, buf, read_len); + + if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_1) + { + buf += ssl->cipher_info->iv_size; + read_len -= ssl->cipher_info->iv_size; + } + + read_len = verify_digest(ssl, + is_client ? SSL_CLIENT_READ : SSL_SERVER_READ, buf, read_len); + + /* does the hmac work? */ + if (read_len < 0) + { + ret = read_len; + goto error; + } + + DISPLAY_BYTES(ssl, "decrypted", buf, read_len); + increment_read_sequence(ssl); + } + + /* The main part of the SSL packet */ + switch (ssl->record_type) + { + case PT_HANDSHAKE_PROTOCOL: + if (ssl->dc != NULL) + { + ssl->dc->bm_proc_index = 0; + ret = do_handshake(ssl, buf, read_len); + } + else /* no client renegotiation allowed */ + { + ret = SSL_ERROR_NO_CLIENT_RENOG; + goto error; + } + break; + + case PT_CHANGE_CIPHER_SPEC: + if (ssl->next_state != HS_FINISHED) + { + ret = SSL_ERROR_INVALID_HANDSHAKE; + goto error; + } + + if (set_key_block(ssl, 0) < 0) + { + ret = SSL_ERROR_INVALID_HANDSHAKE; + goto error; + } + + /* all encrypted from now on */ + SET_SSL_FLAG(SSL_RX_ENCRYPTED); + memset(ssl->read_sequence, 0, 8); + break; + + case PT_APP_PROTOCOL_DATA: + if (in_data && ssl->hs_status == SSL_OK) + { + *in_data = buf; /* point to the work buffer */ + (*in_data)[read_len] = 0; /* null terminate just in case */ + ret = read_len; + } + else + ret = SSL_ERROR_INVALID_PROT_MSG; + break; + + case PT_ALERT_PROTOCOL: + /* return the alert # with alert bit set */ + if (buf[0] == SSL_ALERT_TYPE_WARNING && + buf[1] == SSL_ALERT_CLOSE_NOTIFY) + { + ret = SSL_CLOSE_NOTIFY; + send_alert(ssl, SSL_ALERT_CLOSE_NOTIFY); + SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY); + } + else + { + ret = -buf[1]; + DISPLAY_ALERT(ssl, buf[1]); + } + + break; + + default: + ret = SSL_ERROR_INVALID_PROT_MSG; + break; + } + +error: + ssl->bm_read_index = 0; /* reset to go again */ + + if (ret < SSL_OK && in_data)/* if all wrong, then clear this buffer ptr */ + *in_data = NULL; + + return ret; +} + +int increase_bm_data_size(SSL *ssl, size_t size) +{ + if (ssl->max_plain_length == RT_MAX_PLAIN_LENGTH) { + return SSL_OK; + } + if (ssl->can_free_certificates) { + certificate_free(ssl); + } + size_t required = (size + 1023) & ~(1023); // round up to 1k + required = (required < RT_MAX_PLAIN_LENGTH) ? required : RT_MAX_PLAIN_LENGTH; + uint8_t* new_bm_all_data = (uint8_t*) realloc(ssl->bm_all_data, required + RT_EXTRA); + if (!new_bm_all_data) { + printf("failed to grow plain buffer\r\n"); + ssl->hs_status = SSL_ERROR_DEAD; + return SSL_ERROR_CONN_LOST; + } + ssl->bm_all_data = new_bm_all_data; + ssl->bm_data = ssl->bm_all_data + BM_RECORD_OFFSET; + ssl->max_plain_length = required; + return SSL_OK; +} + +/** + * Do some basic checking of data and then perform the appropriate handshaking. + */ +static int do_handshake(SSL *ssl, uint8_t *buf, int read_len) +{ + int hs_len = (buf[2]<<8) + buf[3]; + uint8_t handshake_type = buf[0]; + int ret = SSL_OK; + int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT); + + /* some integrity checking on the handshake */ + PARANOIA_CHECK(read_len-SSL_HS_HDR_SIZE, hs_len); + + if (handshake_type != ssl->next_state) + { + /* handle a special case on the client */ + if (!is_client || handshake_type != HS_CERT_REQ || + ssl->next_state != HS_SERVER_HELLO_DONE) + { + ret = SSL_ERROR_INVALID_HANDSHAKE; + goto error; + } + } + + hs_len += SSL_HS_HDR_SIZE; /* adjust for when adding packets */ + ssl->bm_index = hs_len; /* store the size and check later */ + DISPLAY_STATE(ssl, 0, handshake_type, 0); + + if (handshake_type != HS_CERT_VERIFY && handshake_type != HS_HELLO_REQUEST) + add_packet(ssl, buf, hs_len); + +#if defined(CONFIG_SSL_ENABLE_CLIENT) + ret = is_client ? + do_clnt_handshake(ssl, handshake_type, buf, hs_len) : + do_svr_handshake(ssl, handshake_type, buf, hs_len); +#else + ret = do_svr_handshake(ssl, handshake_type, buf, hs_len); +#endif + + /* just use recursion to get the rest */ + if (hs_len < read_len && ret == SSL_OK) + ret = do_handshake(ssl, &buf[hs_len], read_len-hs_len); + +error: + return ret; +} + +/** + * Sends the change cipher spec message. We have just read a finished message + * from the client. + */ +int send_change_cipher_spec(SSL *ssl) +{ + int ret = send_packet(ssl, PT_CHANGE_CIPHER_SPEC, + g_chg_cipher_spec_pkt, sizeof(g_chg_cipher_spec_pkt)); + + if (ret >= 0 && set_key_block(ssl, 1) < 0) + ret = SSL_ERROR_INVALID_HANDSHAKE; + + if (ssl->cipher_info) + SET_SSL_FLAG(SSL_TX_ENCRYPTED); + + memset(ssl->write_sequence, 0, 8); + return ret; +} + +/** + * Send a "finished" message + */ +int send_finished(SSL *ssl) +{ + uint8_t buf[SHA1_SIZE+MD5_SIZE+15+4] = { + HS_FINISHED, 0, 0, SSL_FINISHED_HASH_SIZE }; + + /* now add the finished digest mac (12 bytes) */ + finished_digest(ssl, + IS_SET_SSL_FLAG(SSL_IS_CLIENT) ? + client_finished : server_finished, &buf[4]); + +#ifndef CONFIG_SSL_SKELETON_MODE + /* store in the session cache */ + if (!IS_SET_SSL_FLAG(SSL_SESSION_RESUME) && ssl->ssl_ctx->num_sessions) + { + memcpy(ssl->session->master_secret, + ssl->dc->master_secret, SSL_SECRET_SIZE); + } +#endif + + return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, + buf, SSL_FINISHED_HASH_SIZE+4); +} + +/** + * Send an alert message. + * Return 1 if the alert was an "error". + */ +int send_alert(SSL *ssl, int error_code) +{ + int alert_num = 0; + int is_warning = 0; + uint8_t buf[2]; + + /* Don't bother, we're already dead */ + if (ssl->hs_status == SSL_ERROR_DEAD) + { + return SSL_ERROR_CONN_LOST; + } + +#ifdef CONFIG_SSL_FULL_MODE + if (IS_SET_SSL_FLAG(SSL_DISPLAY_STATES)) + ssl_display_error(error_code); +#endif + + switch (error_code) + { + case SSL_ALERT_CLOSE_NOTIFY: + is_warning = 1; + alert_num = SSL_ALERT_CLOSE_NOTIFY; + break; + + case SSL_ERROR_CONN_LOST: /* don't send alert just yet */ + is_warning = 1; + break; + + case SSL_ERROR_NO_CIPHER: + alert_num = SSL_ALERT_HANDSHAKE_FAILURE; + break; + + case SSL_ERROR_INVALID_HMAC: + alert_num = SSL_ALERT_BAD_RECORD_MAC; + break; + + case SSL_ERROR_FINISHED_INVALID: + case SSL_ERROR_INVALID_KEY: + alert_num = SSL_ALERT_DECRYPT_ERROR; + break; + + case SSL_ERROR_INVALID_VERSION: + alert_num = SSL_ALERT_INVALID_VERSION; + break; + + case SSL_ERROR_INVALID_SESSION: + alert_num = SSL_ALERT_ILLEGAL_PARAMETER; + break; + + case SSL_ERROR_NO_CLIENT_RENOG: + alert_num = SSL_ALERT_NO_RENEGOTIATION; + break; + + case SSL_ERROR_RECORD_OVERFLOW: + alert_num = SSL_ALERT_RECORD_OVERFLOW; + break; + + case SSL_X509_ERROR(X509_VFY_ERROR_EXPIRED): + case SSL_X509_ERROR(X509_VFY_ERROR_NOT_YET_VALID): + alert_num = SSL_ALERT_CERTIFICATE_EXPIRED; + break; + + case SSL_X509_ERROR(X509_VFY_ERROR_NO_TRUSTED_CERT): + alert_num = SSL_ALERT_UNKNOWN_CA; + break; + + case SSL_X509_ERROR(X509_VFY_ERROR_UNSUPPORTED_DIGEST): + case SSL_ERROR_INVALID_CERT_HASH_ALG: + alert_num = SSL_ALERT_UNSUPPORTED_CERTIFICATE; + break; + + case SSL_ERROR_BAD_CERTIFICATE: + case SSL_X509_ERROR(X509_VFY_ERROR_BAD_SIGNATURE): + alert_num = SSL_ALERT_BAD_CERTIFICATE; + break; + + case SSL_ERROR_INVALID_HANDSHAKE: + case SSL_ERROR_INVALID_PROT_MSG: + default: + /* a catch-all for anything bad */ + alert_num = (error_code <= SSL_X509_OFFSET) ? + SSL_ALERT_CERTIFICATE_UNKNOWN: SSL_ALERT_UNEXPECTED_MESSAGE; + break; + } + + buf[0] = is_warning ? 1 : 2; + buf[1] = alert_num; + send_packet(ssl, PT_ALERT_PROTOCOL, buf, sizeof(buf)); + DISPLAY_ALERT(ssl, alert_num); + return is_warning ? 0 : 1; +} + +/** + * Process a client finished message. + */ +int process_finished(SSL *ssl, uint8_t *buf, int hs_len) +{ + int ret = SSL_OK; + int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT); + int resume = IS_SET_SSL_FLAG(SSL_SESSION_RESUME); + + PARANOIA_CHECK(ssl->bm_index, SSL_FINISHED_HASH_SIZE+4); + + /* check that we all work before we continue */ + if (memcmp(ssl->dc->final_finish_mac, &buf[4], SSL_FINISHED_HASH_SIZE)) + return SSL_ERROR_FINISHED_INVALID; + + if ((!is_client && !resume) || (is_client && resume)) + { + if ((ret = send_change_cipher_spec(ssl)) == SSL_OK) + ret = send_finished(ssl); + } + + /* if we ever renegotiate */ + ssl->next_state = is_client ? HS_HELLO_REQUEST : HS_CLIENT_HELLO; + ssl->hs_status = ret; /* set the final handshake status */ + +error: + return ret; +} + +/** + * Send a certificate. + */ +int send_certificate(SSL *ssl) +{ + int ret = SSL_OK; + int i = 0; + uint8_t *buf = ssl->bm_data; + int offset = 7; + int chain_length; + + buf[0] = HS_CERTIFICATE; + buf[1] = 0; + buf[4] = 0; + + /* spec says we must check if the hash/sig algorithm is OK */ + if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_2 && + ((ret = check_certificate_chain(ssl)) != SSL_OK)) + { + ret = SSL_ERROR_INVALID_CERT_HASH_ALG; + goto error; + } + + while (i < ssl->ssl_ctx->chain_length) + { + SSL_CERT *cert = &ssl->ssl_ctx->certs[i]; + buf[offset++] = 0; + buf[offset++] = cert->size >> 8; /* cert 1 length */ + buf[offset++] = cert->size & 0xff; + memcpy(&buf[offset], cert->buf, cert->size); + offset += cert->size; + i++; + } + + chain_length = offset - 7; + buf[5] = chain_length >> 8; /* cert chain length */ + buf[6] = chain_length & 0xff; + chain_length += 3; + buf[2] = chain_length >> 8; /* handshake length */ + buf[3] = chain_length & 0xff; + ssl->bm_index = offset; + ret = send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, offset); + +error: + return ret; +} + +/** + * Create a blob of memory that we'll get rid of once the handshake is + * complete. + */ +void disposable_new(SSL *ssl) +{ + if (ssl->dc == NULL) + { + ssl->dc = (DISPOSABLE_CTX *)calloc(1, sizeof(DISPOSABLE_CTX)); + SHA256_Init(&ssl->dc->sha256_ctx); + MD5_Init(&ssl->dc->md5_ctx); + SHA1_Init(&ssl->dc->sha1_ctx); + } +} + +/** + * Remove the temporary blob of memory. + */ +void disposable_free(SSL *ssl) +{ + if (ssl->dc) + { + memset(ssl->dc, 0, sizeof(DISPOSABLE_CTX)); + free(ssl->dc); + ssl->dc = NULL; + } + ssl->can_free_certificates = true; +} + +static void certificate_free(SSL* ssl) +{ +#ifdef CONFIG_SSL_CERT_VERIFICATION + if (ssl->x509_ctx) { + x509_free(ssl->x509_ctx); + ssl->x509_ctx = 0; + } + ssl->can_free_certificates = false; +#endif +} + +#ifndef CONFIG_SSL_SKELETON_MODE /* no session resumption in this mode */ +/** + * Find if an existing session has the same session id. If so, use the + * master secret from this session for session resumption. + */ +SSL_SESSION *ssl_session_update(int max_sessions, SSL_SESSION *ssl_sessions[], + SSL *ssl, const uint8_t *session_id) +{ + time_t tm = time(NULL); + time_t oldest_sess_time = tm; + SSL_SESSION *oldest_sess = NULL; + int i; + + /* no sessions? Then bail */ + if (max_sessions == 0) + return NULL; + + SSL_CTX_LOCK(ssl->ssl_ctx->mutex); + if (session_id) + { + for (i = 0; i < max_sessions; i++) + { + if (ssl_sessions[i]) + { + /* kill off any expired sessions (including those in + the future) */ + if ((tm > ssl_sessions[i]->conn_time + SSL_EXPIRY_TIME) || + (tm < ssl_sessions[i]->conn_time)) + { + session_free(ssl_sessions, i); + continue; + } + + /* if the session id matches, it must still be less than + the expiry time */ + if (memcmp(ssl_sessions[i]->session_id, session_id, + SSL_SESSION_ID_SIZE) == 0) + { + ssl->session_index = i; + memcpy(ssl->dc->master_secret, + ssl_sessions[i]->master_secret, SSL_SECRET_SIZE); + SET_SSL_FLAG(SSL_SESSION_RESUME); + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + return ssl_sessions[i]; /* a session was found */ + } + } + } + } + + /* If we've got here, no matching session was found - so create one */ + for (i = 0; i < max_sessions; i++) + { + if (ssl_sessions[i] == NULL) + { + /* perfect, this will do */ + ssl_sessions[i] = (SSL_SESSION *)calloc(1, sizeof(SSL_SESSION)); + ssl_sessions[i]->conn_time = tm; + ssl->session_index = i; + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + return ssl_sessions[i]; /* return the session object */ + } + else if (ssl_sessions[i]->conn_time <= oldest_sess_time) + { + /* find the oldest session */ + oldest_sess_time = ssl_sessions[i]->conn_time; + oldest_sess = ssl_sessions[i]; + ssl->session_index = i; + } + } + + /* ok, we've used up all of our sessions. So blow the oldest session away */ + oldest_sess->conn_time = tm; + memset(oldest_sess->session_id, 0, SSL_SESSION_ID_SIZE); + memset(oldest_sess->master_secret, 0, SSL_SECRET_SIZE); + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + return oldest_sess; +} + +/** + * Free an existing session. + */ +static void session_free(SSL_SESSION *ssl_sessions[], int sess_index) +{ + if (ssl_sessions[sess_index]) + { + free(ssl_sessions[sess_index]); + ssl_sessions[sess_index] = NULL; + } +} + +/** + * This ssl object doesn't want this session anymore. + */ +void kill_ssl_session(SSL_SESSION **ssl_sessions, SSL *ssl) +{ + SSL_CTX_LOCK(ssl->ssl_ctx->mutex); + + if (ssl->ssl_ctx->num_sessions) + { + session_free(ssl_sessions, ssl->session_index); + ssl->session = NULL; + } + + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); +} +#endif /* CONFIG_SSL_SKELETON_MODE */ + +/* + * Get the session id for a handshake. This will be a 32 byte sequence. + */ +EXP_FUNC const uint8_t * STDCALL ssl_get_session_id(const SSL *ssl) +{ + return ssl->session_id; +} + +/* + * Get the session id size for a handshake. + */ +EXP_FUNC uint8_t STDCALL ssl_get_session_id_size(const SSL *ssl) +{ + return ssl->sess_id_size; +} + +/* + * Return the cipher id (in the SSL form). + */ +EXP_FUNC uint8_t STDCALL ssl_get_cipher_id(const SSL *ssl) +{ + return ssl->cipher; +} + +/* + * Return the status of the handshake. + */ +EXP_FUNC int STDCALL ssl_handshake_status(const SSL *ssl) +{ + return ssl->hs_status; +} + +/* + * Retrieve various parameters about the SSL engine. + */ +EXP_FUNC int STDCALL ssl_get_config(int offset) +{ + switch (offset) + { + /* return the appropriate build mode */ + case SSL_BUILD_MODE: +#if defined(CONFIG_SSL_FULL_MODE) + return SSL_BUILD_FULL_MODE; +#elif defined(CONFIG_SSL_ENABLE_CLIENT) + return SSL_BUILD_ENABLE_CLIENT; +#elif defined(CONFIG_ENABLE_VERIFICATION) + return SSL_BUILD_ENABLE_VERIFICATION; +#elif defined(CONFIG_SSL_SERVER_ONLY ) + return SSL_BUILD_SERVER_ONLY; +#else + return SSL_BUILD_SKELETON_MODE; +#endif + + case SSL_MAX_CERT_CFG_OFFSET: + return CONFIG_SSL_MAX_CERTS; + +#ifdef CONFIG_SSL_CERT_VERIFICATION + case SSL_MAX_CA_CERT_CFG_OFFSET: + return CONFIG_X509_MAX_CA_CERTS; +#endif +#ifdef CONFIG_SSL_HAS_PEM + case SSL_HAS_PEM: + return 1; +#endif + default: + return 0; + } +} + +/** + * Check the certificate chain to see if the certs are supported + */ +static int check_certificate_chain(SSL *ssl) +{ + int i = 0; + int ret = SSL_OK; + + while (i < ssl->ssl_ctx->chain_length) + { + int j = 0; + uint8_t found = 0; + SSL_CERT *cert = &ssl->ssl_ctx->certs[i]; + + while (j < ssl->num_sig_algs) + { + if (ssl->sig_algs[j++] == cert->hash_alg) + { + found = 1; + break; + } + } + + if (!found) + { + + ret = SSL_ERROR_INVALID_CERT_HASH_ALG; + goto error; + } + + i++; + } + +error: + return ret; +} + +#ifdef CONFIG_SSL_CERT_VERIFICATION +/** + * Authenticate a received certificate. + */ +EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl) +{ + int ret; + int pathLenConstraint = 0; + + SSL_CTX_LOCK(ssl->ssl_ctx->mutex); + ret = x509_verify(ssl->ssl_ctx->ca_cert_ctx, ssl->x509_ctx, + &pathLenConstraint); + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + + if (ret) /* modify into an SSL error type */ + { + ret = SSL_X509_ERROR(ret); + } + + return ret; +} + +/** + * Process a certificate message. + */ +int process_certificate(SSL *ssl, X509_CTX **x509_ctx) +{ + int ret = SSL_OK; + uint8_t *buf = &ssl->bm_data[ssl->dc->bm_proc_index]; + int pkt_size = ssl->bm_index; + int cert_size, offset = 5, offset_start; + int total_cert_len = (buf[offset]<<8) + buf[offset+1]; + int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT); + X509_CTX *chain = 0; + X509_CTX **certs = 0; + int *cert_used = 0; + int num_certs = 0; + int i = 0; + offset += 2; + + ax_wdt_feed(); + + PARANOIA_CHECK(pkt_size, total_cert_len + offset); + + // record the start point for the second pass + offset_start = offset; + + // first pass - count the certificates + while (offset < total_cert_len) + { + offset++; /* skip empty char */ + cert_size = (buf[offset]<<8) + buf[offset+1]; + offset += 2; + offset += cert_size; + num_certs++; + } + + PARANOIA_CHECK(pkt_size, offset); + + certs = (X509_CTX**) calloc(num_certs, sizeof(void*)); + cert_used = (int*) calloc(num_certs, sizeof(int)); + num_certs = 0; + + // restore the offset from the saved value + offset = offset_start; + + // second pass - load the certificates + while (offset < total_cert_len) + { + offset++; /* skip empty char */ + cert_size = (buf[offset]<<8) + buf[offset+1]; + offset += 2; + ax_wdt_feed(); + if (x509_new(&buf[offset], NULL, certs+num_certs)) + { + ret = SSL_ERROR_BAD_CERTIFICATE; + goto error; + } + +#if defined (CONFIG_SSL_FULL_MODE) + if (ssl->ssl_ctx->options & SSL_DISPLAY_CERTS) + x509_print(certs[num_certs], NULL); +#endif + num_certs++; + offset += cert_size; + } + + PARANOIA_CHECK(pkt_size, offset); + + // third pass - link certs together, assume server cert is the first + *x509_ctx = certs[0]; + chain = certs[0]; + cert_used[0] = 1; + + // repeat until the end of the chain is found + while (1) + { + // look for CA cert + for( i = 1; i < num_certs; i++ ) + { + if (certs[i] == chain) + continue; + + if (cert_used[i]) + continue; // don't allow loops + + if (asn1_compare_dn(chain->ca_cert_dn, certs[i]->cert_dn) == 0) + { + // CA cert found, add it to the chain + cert_used[i] = 1; + chain->next = certs[i]; + chain = certs[i]; + break; + } + } + + // no CA cert found, reached the end of the chain + if (i >= num_certs) + break; + } + + // clean up any certs that aren't part of the chain + for (i = 1; i < num_certs; i++) + { + if (cert_used[i] == 0) + x509_free(certs[i]); + } + + /* if we are client we can do the verify now or later */ + if (is_client && !IS_SET_SSL_FLAG(SSL_SERVER_VERIFY_LATER)) + { + ret = ssl_verify_cert(ssl); + } + + ssl->next_state = is_client ? HS_SERVER_HELLO_DONE : HS_CLIENT_KEY_XCHG; + ssl->dc->bm_proc_index += offset; +error: + // clean up arrays + if (certs) + free(certs); + + if (cert_used) + free(cert_used); + + return ret; +} + +EXP_FUNC int STDCALL ssl_match_fingerprint(const SSL *ssl, const uint8_t* fp) +{ + if (ssl->x509_ctx == NULL || ssl->x509_ctx->fingerprint == NULL) + return 1; + int res = memcmp(ssl->x509_ctx->fingerprint, fp, SHA1_SIZE); + if (res != 0) { + printf("cert FP: "); + for (int i = 0; i < SHA1_SIZE; ++i) { + printf("%02X ", ssl->x509_ctx->fingerprint[i]); + } + printf("\r\ntest FP: "); + for (int i = 0; i < SHA1_SIZE; ++i) { + printf("%02X ", fp[i]); + } + printf("\r\n"); + } + return res; +} + +EXP_FUNC int STDCALL ssl_match_spki_sha256(const SSL *ssl, const uint8_t* hash) +{ + if (ssl->x509_ctx == NULL || ssl->x509_ctx->spki_sha256 == NULL) + return 1; + int res = memcmp(ssl->x509_ctx->spki_sha256, hash, SHA256_SIZE); + if (res != 0) { + printf("cert SPKI SHA-256 hash: "); + for (int i = 0; i < SHA256_SIZE; ++i) { + printf("%02X ", ssl->x509_ctx->spki_sha256[i]); + } + printf("\r\ntest hash: "); + for (int i = 0; i < SHA256_SIZE; ++i) { + printf("%02X ", hash[i]); + } + printf("\r\n"); + } + return res; +} + +#endif /* CONFIG_SSL_CERT_VERIFICATION */ + +/** + * Debugging routine to display SSL handshaking stuff. + */ +#ifdef CONFIG_SSL_FULL_MODE +/** + * Debugging routine to display SSL states. + */ +void DISPLAY_STATE(SSL *ssl, int is_send, uint8_t state, int not_ok) +{ + const char *str; + + if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES)) + return; + + if (not_ok) printf("Error - invalid State:\t"); + else printf("State:\t"); + if (is_send) printf("sending "); + else printf("receiving "); + + switch (state) + { + case HS_HELLO_REQUEST: + printf("Hello Request (0)\n"); + break; + + case HS_CLIENT_HELLO: + printf("Client Hello (1)\n"); + break; + + case HS_SERVER_HELLO: + printf("Server Hello (2)\n"); + break; + + case HS_CERTIFICATE: + printf("Certificate (11)\n"); + break; + + case HS_SERVER_KEY_XCHG: + printf("Certificate Request (12)\n"); + break; + + case HS_CERT_REQ: + printf("Certificate Request (13)\n"); + break; + + case HS_SERVER_HELLO_DONE: + printf("Server Hello Done (14)\n"); + break; + + case HS_CERT_VERIFY: + printf("Certificate Verify (15)\n"); + break; + + case HS_CLIENT_KEY_XCHG: + printf("Client Key Exchange (16)\n"); + break; + + case HS_FINISHED: + printf("Finished (16)\n"); + break; + + default: + printf("Error (Unknown)\n"); + break; + } +} + +/** + * Debugging routine to display RSA objects + */ +void DISPLAY_RSA(SSL *ssl, const RSA_CTX *rsa_ctx) +{ + if (!IS_SET_SSL_FLAG(SSL_DISPLAY_RSA)) + return; + + RSA_print(rsa_ctx); + TTY_FLUSH(); +} + +/** + * Debugging routine to display SSL handshaking bytes. + */ +void DISPLAY_BYTES(SSL *ssl, const char *format, + const uint8_t *data, int size, ...) +{ + va_list(ap); + + if (!IS_SET_SSL_FLAG(SSL_DISPLAY_BYTES)) + return; + + va_start(ap, size); + print_blob(format, data, size, va_arg(ap, char *)); + va_end(ap); + TTY_FLUSH(); +} + +/** + * Debugging routine to display SSL handshaking errors. + */ +EXP_FUNC void STDCALL ssl_display_error(int error_code) +{ + if (error_code == SSL_OK) + return; + + printf("Error: "); + + /* X509 error? */ + if (error_code < SSL_X509_OFFSET) + { + char buff[64]; + printf("%s\n", x509_display_error(error_code - SSL_X509_OFFSET, buff)); + return; + } + + /* SSL alert error code */ + if (error_code > SSL_ERROR_CONN_LOST) + { + printf("SSL error %d\n", -error_code); + return; + } + + switch (error_code) + { + case SSL_ERROR_DEAD: + printf("connection dead"); + break; + + case SSL_ERROR_RECORD_OVERFLOW: + printf("record overflow"); + break; + + case SSL_ERROR_INVALID_HANDSHAKE: + printf("invalid handshake"); + break; + + case SSL_ERROR_INVALID_PROT_MSG: + printf("invalid protocol message"); + break; + + case SSL_ERROR_INVALID_HMAC: + printf("invalid mac"); + break; + + case SSL_ERROR_INVALID_VERSION: + printf("invalid version"); + break; + + case SSL_ERROR_INVALID_SESSION: + printf("invalid session"); + break; + + case SSL_ERROR_NO_CIPHER: + printf("no cipher"); + break; + + case SSL_ERROR_INVALID_CERT_HASH_ALG: + printf("invalid cert hash algorithm"); + break; + + case SSL_ERROR_CONN_LOST: + printf("connection lost"); + break; + + case SSL_ERROR_BAD_CERTIFICATE: + printf("bad certificate"); + break; + + case SSL_ERROR_INVALID_KEY: + printf("invalid key"); + break; + + case SSL_ERROR_FINISHED_INVALID: + printf("finished invalid"); + break; + + case SSL_ERROR_NO_CERT_DEFINED: + printf("no certificate defined"); + break; + + case SSL_ERROR_NO_CLIENT_RENOG: + printf("client renegotiation not supported"); + break; + + case SSL_ERROR_NOT_SUPPORTED: + printf("Option not supported"); + break; + + default: + printf("undefined as yet - %d", error_code); + break; + } + + printf("\n"); +} + +/** + * Debugging routine to display alerts. + */ +void DISPLAY_ALERT(SSL *ssl, int alert) +{ + if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES)) + return; + + printf("Alert: "); + + switch (alert) + { + case SSL_ALERT_CLOSE_NOTIFY: + printf("close notify"); + break; + + case SSL_ALERT_UNEXPECTED_MESSAGE: + printf("unexpected message"); + break; + + case SSL_ALERT_BAD_RECORD_MAC: + printf("bad record mac"); + break; + + case SSL_ERROR_RECORD_OVERFLOW: + printf("record overlow"); + break; + + case SSL_ALERT_HANDSHAKE_FAILURE: + printf("handshake failure"); + break; + + case SSL_ALERT_BAD_CERTIFICATE: + printf("bad certificate"); + break; + + case SSL_ALERT_UNSUPPORTED_CERTIFICATE: + printf("unsupported certificate"); + break; + + case SSL_ALERT_CERTIFICATE_EXPIRED: + printf("certificate expired"); + break; + + case SSL_ALERT_CERTIFICATE_UNKNOWN: + printf("certificate unknown"); + break; + + case SSL_ALERT_ILLEGAL_PARAMETER: + printf("illegal parameter"); + break; + + case SSL_ALERT_UNKNOWN_CA: + printf("unknown ca"); + break; + + case SSL_ALERT_DECODE_ERROR: + printf("decode error"); + break; + + case SSL_ALERT_DECRYPT_ERROR: + printf("decrypt error"); + break; + + case SSL_ALERT_INVALID_VERSION: + printf("invalid version"); + break; + + case SSL_ALERT_NO_RENEGOTIATION: + printf("no renegotiation"); + break; + + default: + printf("alert - (unknown %d)", alert); + break; + } + + printf("\n"); +} + +#endif /* CONFIG_SSL_FULL_MODE */ + +/** + * Return the version of this library. + */ +EXP_FUNC const char * STDCALL ssl_version() +{ + static const char * axtls_version = AXTLS_VERSION; + return axtls_version; +} + +/** + * Enable the various language bindings to work regardless of the + * configuration - they just return an error statement and a bad return code. + */ +#if !defined(CONFIG_SSL_FULL_MODE) +EXP_FUNC void STDCALL ssl_display_error(int error_code) {} +#endif + +#ifdef CONFIG_BINDINGS +#if !defined(CONFIG_SSL_ENABLE_CLIENT) +EXP_FUNC SSL * STDCALL ssl_client_new(SSL_CTX *ssl_ctx, int client_fd, const + uint8_t *session_id, uint8_t sess_id_size) +{ + printf("%s", unsupported_str); + return NULL; +} +#endif + +#if !defined(CONFIG_SSL_CERT_VERIFICATION) +EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl) +{ + printf("%s", unsupported_str); + return -1; +} + + +EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component) +{ + printf("%s", unsupported_str); + return NULL; +} + +EXP_FUNC const char * STDCALL ssl_get_cert_subject_alt_dnsname(const SSL *ssl, int index) +{ + printf("%s", unsupported_str); + return NULL; +} + +#endif /* CONFIG_SSL_CERT_VERIFICATION */ + +#endif /* CONFIG_BINDINGS */ + diff --git a/tools/sdk/axtls/ssl/tls1.h b/tools/sdk/axtls/ssl/tls1.h new file mode 100644 index 0000000000..d9b52297d1 --- /dev/null +++ b/tools/sdk/axtls/ssl/tls1.h @@ -0,0 +1,324 @@ +/* + * Copyright (c) 2007-2016, 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 tls1.h + * + * @brief The definitions for the TLS library. + */ +#ifndef HEADER_SSL_LIB_H +#define HEADER_SSL_LIB_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "version.h" +#include "config.h" +#include "os_int.h" +#include "os_port.h" +#include "../crypto/crypto.h" +#include "crypto_misc.h" + +#define SSL_PROTOCOL_MIN_VERSION 0x31 /* TLS v1.0 */ +#define SSL_PROTOCOL_VERSION_MAX 0x33 /* TLS v1.3 */ +#define SSL_PROTOCOL_VERSION_TLS1_1 0x32 /* TLS v1.1 */ +#define SSL_PROTOCOL_VERSION_TLS1_2 0x33 /* TLS v1.2 */ +#define SSL_RANDOM_SIZE 32 +#define SSL_SECRET_SIZE 48 +#define SSL_FINISHED_HASH_SIZE 12 +#define SSL_RECORD_SIZE 5 +#define SSL_SERVER_READ 0 +#define SSL_SERVER_WRITE 1 +#define SSL_CLIENT_READ 2 +#define SSL_CLIENT_WRITE 3 +#define SSL_HS_HDR_SIZE 4 + +/* the flags we use while establishing a connection */ +#define SSL_NEED_RECORD 0x0001 +#define SSL_TX_ENCRYPTED 0x0002 +#define SSL_RX_ENCRYPTED 0x0004 +#define SSL_SESSION_RESUME 0x0008 +#define SSL_IS_CLIENT 0x0010 +#define SSL_HAS_CERT_REQ 0x0020 +#define SSL_SENT_CLOSE_NOTIFY 0x0040 + +/* some macros to muck around with flag bits */ +#define SET_SSL_FLAG(A) (ssl->flag |= A) +#define CLR_SSL_FLAG(A) (ssl->flag &= ~A) +#define IS_SET_SSL_FLAG(A) (ssl->flag & A) + +#define MAX_KEY_BYTE_SIZE 512 /* for a 4096 bit key */ +#define RT_MAX_PLAIN_LENGTH 16384 +#define RT_EXTRA 1024 +#define BM_RECORD_OFFSET 5 + +#define NUM_PROTOCOLS 4 + +#define MAX_SIG_ALGORITHMS 4 +#define SIG_ALG_SHA1 2 +#define SIG_ALG_SHA256 4 +#define SIG_ALG_SHA384 5 +#define SIG_ALG_SHA512 6 +#define SIG_ALG_RSA 1 + +#define PARANOIA_CHECK(A, B) if (A < B) { \ + ret = SSL_ERROR_INVALID_HANDSHAKE; goto error; } + +/* protocol types */ +enum +{ + PT_CHANGE_CIPHER_SPEC = 20, + PT_ALERT_PROTOCOL, + PT_HANDSHAKE_PROTOCOL, + PT_APP_PROTOCOL_DATA +}; + +/* handshaking types */ +enum +{ + HS_HELLO_REQUEST, + HS_CLIENT_HELLO, + HS_SERVER_HELLO, + HS_CERTIFICATE = 11, + HS_SERVER_KEY_XCHG, + HS_CERT_REQ, + HS_SERVER_HELLO_DONE, + HS_CERT_VERIFY, + HS_CLIENT_KEY_XCHG, + HS_FINISHED = 20 +}; + +/* SSL extension types */ +enum +{ + SSL_EXT_SERVER_NAME = 0, + SSL_EXT_MAX_FRAGMENT_SIZE, + SSL_EXT_SIG_ALG = 0x0d, +}; + +typedef struct +{ + uint8_t cipher; + uint8_t key_size; + uint8_t iv_size; + uint8_t padding_size; + uint8_t digest_size; + uint8_t key_block_size; + hmac_func_v hmac_v; + crypt_func encrypt; + crypt_func decrypt; +} cipher_info_t; + +struct _SSLObjLoader +{ + uint8_t *buf; + int len; +}; + +typedef struct _SSLObjLoader SSLObjLoader; + +typedef struct +{ + time_t conn_time; + uint8_t session_id[SSL_SESSION_ID_SIZE]; + uint8_t master_secret[SSL_SECRET_SIZE]; +} SSL_SESSION; + +typedef struct +{ + uint8_t *buf; + int size; + uint8_t hash_alg; +} SSL_CERT; + +typedef struct +{ + MD5_CTX md5_ctx; + SHA1_CTX sha1_ctx; + SHA256_CTX sha256_ctx; + uint8_t client_random[SSL_RANDOM_SIZE]; /* client's random sequence */ + uint8_t server_random[SSL_RANDOM_SIZE]; /* server's random sequence */ + uint8_t final_finish_mac[128]; + uint8_t master_secret[SSL_SECRET_SIZE]; + uint8_t key_block[256]; + uint16_t bm_proc_index; + uint8_t key_block_generated; +} DISPOSABLE_CTX; + +typedef struct +{ + char *host_name; /* Needed for the SNI support */ + /* Needed for the Max Fragment Size Extension. + Allowed values: 2^9, 2^10 .. 2^14 */ + uint16_t max_fragment_size; +} SSL_EXTENSIONS; + +struct _SSL +{ + uint32_t flag; + uint16_t need_bytes; + uint16_t got_bytes; + uint8_t record_type; + uint8_t cipher; + uint8_t sess_id_size; + uint8_t version; + uint8_t client_version; + int16_t next_state; + int16_t hs_status; + DISPOSABLE_CTX *dc; /* temporary data which we'll get rid of soon */ + int client_fd; + const cipher_info_t *cipher_info; + void *encrypt_ctx; + void *decrypt_ctx; + uint8_t *bm_all_data; + uint8_t *bm_data; + uint16_t bm_index; + uint16_t bm_read_index; + size_t max_plain_length; + uint8_t sig_algs[MAX_SIG_ALGORITHMS]; + uint8_t num_sig_algs; + struct _SSL *next; /* doubly linked list */ + struct _SSL *prev; + struct _SSL_CTX *ssl_ctx; /* back reference to a clnt/svr ctx */ +#ifndef CONFIG_SSL_SKELETON_MODE + uint16_t session_index; + SSL_SESSION *session; +#endif +#ifdef CONFIG_SSL_CERT_VERIFICATION + X509_CTX *x509_ctx; + bool can_free_certificates; +#endif + uint8_t session_id[SSL_SESSION_ID_SIZE]; + uint8_t client_mac[SHA256_SIZE]; /* for HMAC verification */ + uint8_t server_mac[SHA256_SIZE]; /* for HMAC verification */ + uint8_t read_sequence[8]; /* 64 bit sequence number */ + uint8_t write_sequence[8]; /* 64 bit sequence number */ + uint8_t hmac_header[SSL_RECORD_SIZE]; /* rx hmac */ + SSL_EXTENSIONS *extensions; /* Contains the SSL (client) extensions */ +}; + +typedef struct _SSL SSL; + +struct _SSL_CTX +{ + uint32_t options; + uint8_t chain_length; + RSA_CTX *rsa_ctx; +#ifdef CONFIG_SSL_CERT_VERIFICATION + CA_CERT_CTX *ca_cert_ctx; +#endif + SSL *head; + SSL *tail; + SSL_CERT certs[CONFIG_SSL_MAX_CERTS]; +#ifndef CONFIG_SSL_SKELETON_MODE + uint16_t num_sessions; + SSL_SESSION **ssl_sessions; +#endif +#ifdef CONFIG_SSL_CTX_MUTEXING + SSL_CTX_MUTEX_TYPE mutex; +#endif +#ifdef CONFIG_OPENSSL_COMPATIBLE + void *bonus_attr; +#endif +}; + +typedef struct _SSL_CTX SSL_CTX; + +/* backwards compatibility */ +typedef struct _SSL_CTX SSLCTX; + +extern const uint8_t ssl_prot_prefs[NUM_PROTOCOLS]; + +SSL *ssl_new(SSL_CTX *ssl_ctx, int client_fd); +void disposable_new(SSL *ssl); +void disposable_free(SSL *ssl); +int send_packet(SSL *ssl, uint8_t protocol, + const uint8_t *in, int length); +int do_svr_handshake(SSL *ssl, int handshake_type, uint8_t *buf, int hs_len); +int do_clnt_handshake(SSL *ssl, int handshake_type, uint8_t *buf, int hs_len); +int process_finished(SSL *ssl, uint8_t *buf, int hs_len); +int process_sslv23_client_hello(SSL *ssl); +int send_alert(SSL *ssl, int error_code); +int send_finished(SSL *ssl); +int send_certificate(SSL *ssl); +int basic_read(SSL *ssl, uint8_t **in_data); +int send_change_cipher_spec(SSL *ssl); +int finished_digest(SSL *ssl, const char *label, uint8_t *digest); +void generate_master_secret(SSL *ssl, const uint8_t *premaster_secret); +void add_packet(SSL *ssl, const uint8_t *pkt, int len); +int add_cert(SSL_CTX *ssl_ctx, const uint8_t *buf, int len); +int add_private_key(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj); +void ssl_obj_free(SSLObjLoader *ssl_obj); +int pkcs8_decode(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj, const char *password); +int pkcs12_decode(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj, const char *password); +int load_key_certs(SSL_CTX *ssl_ctx); +#ifdef CONFIG_SSL_CERT_VERIFICATION +int add_cert_auth(SSL_CTX *ssl_ctx, const uint8_t *buf, int len); +void remove_ca_certs(CA_CERT_CTX *ca_cert_ctx); +#endif +#ifdef CONFIG_SSL_ENABLE_CLIENT +int do_client_connect(SSL *ssl); +#endif + +#ifdef CONFIG_SSL_FULL_MODE +void DISPLAY_STATE(SSL *ssl, int is_send, uint8_t state, int not_ok); +void DISPLAY_BYTES(SSL *ssl, const char *format, + const uint8_t *data, int size, ...); +void DISPLAY_CERT(SSL *ssl, const X509_CTX *x509_ctx); +void DISPLAY_RSA(SSL *ssl, const RSA_CTX *rsa_ctx); +void DISPLAY_ALERT(SSL *ssl, int alert); +#else +#define DISPLAY_STATE(A,B,C,D) +#define DISPLAY_CERT(A,B) +#define DISPLAY_RSA(A,B) +#define DISPLAY_ALERT(A, B) +#ifdef WIN32 +void DISPLAY_BYTES(SSL *ssl, const char *format,/* win32 has no variadic macros */ + const uint8_t *data, int size, ...); +#else +#define DISPLAY_BYTES(A,B,C,D,...) +#endif +#endif + +#ifdef CONFIG_SSL_CERT_VERIFICATION +int process_certificate(SSL *ssl, X509_CTX **x509_ctx); +#endif + +SSL_SESSION *ssl_session_update(int max_sessions, + SSL_SESSION *ssl_sessions[], SSL *ssl, + const uint8_t *session_id); +void kill_ssl_session(SSL_SESSION **ssl_sessions, SSL *ssl); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/axtls/ssl/tls1_clnt.c b/tools/sdk/axtls/ssl/tls1_clnt.c new file mode 100644 index 0000000000..f670e704f6 --- /dev/null +++ b/tools/sdk/axtls/ssl/tls1_clnt.c @@ -0,0 +1,541 @@ +/* + * Copyright (c) 2007-2016, 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. + */ + +#include +#include +#include +#include +#include "os_port.h" +#include "ssl.h" + +#ifdef CONFIG_SSL_ENABLE_CLIENT /* all commented out if no client */ + +/* support sha512/384/256/1 RSA */ +static const uint8_t g_sig_alg[] = { + 0x00, SSL_EXT_SIG_ALG, + 0x00, 0x0a, 0x00, 0x08, + SIG_ALG_SHA512, SIG_ALG_RSA, + SIG_ALG_SHA384, SIG_ALG_RSA, + SIG_ALG_SHA256, SIG_ALG_RSA, + SIG_ALG_SHA1, SIG_ALG_RSA +}; + +static const uint8_t g_asn1_sha256[] = +{ + 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, + 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20 +}; + +static int send_client_hello(SSL *ssl); +static int process_server_hello(SSL *ssl); +static int process_server_hello_done(SSL *ssl); +static int send_client_key_xchg(SSL *ssl); +static int process_cert_req(SSL *ssl); +static int send_cert_verify(SSL *ssl); + +/* + * Establish a new SSL connection to an SSL server. + */ +EXP_FUNC SSL * STDCALL ssl_client_new(SSL_CTX *ssl_ctx, int client_fd, const + uint8_t *session_id, uint8_t sess_id_size, SSL_EXTENSIONS* ssl_ext) +{ + SSL *ssl = ssl_new(ssl_ctx, client_fd); + ssl->version = SSL_PROTOCOL_VERSION_MAX; /* try top version first */ + + if (session_id && ssl_ctx->num_sessions) + { + if (sess_id_size > SSL_SESSION_ID_SIZE) /* validity check */ + { + ssl_free(ssl); + return NULL; + } + + memcpy(ssl->session_id, session_id, sess_id_size); + ssl->sess_id_size = sess_id_size; + SET_SSL_FLAG(SSL_SESSION_RESUME); /* just flag for later */ + } + + ssl->extensions = ssl_ext; + + SET_SSL_FLAG(SSL_IS_CLIENT); + do_client_connect(ssl); + return ssl; +} + +/* + * Process the handshake record. + */ +int do_clnt_handshake(SSL *ssl, int handshake_type, uint8_t *buf, int hs_len) +{ + int ret; + + /* To get here the state must be valid */ + switch (handshake_type) + { + case HS_SERVER_HELLO: + ret = process_server_hello(ssl); + break; + + case HS_CERTIFICATE: + ret = process_certificate(ssl, &ssl->x509_ctx); + break; + + case HS_SERVER_HELLO_DONE: + if ((ret = process_server_hello_done(ssl)) == SSL_OK) + { + if (IS_SET_SSL_FLAG(SSL_HAS_CERT_REQ)) + { + if ((ret = send_certificate(ssl)) == SSL_OK && + (ret = send_client_key_xchg(ssl)) == SSL_OK) + { + send_cert_verify(ssl); + } + } + else + { + ret = send_client_key_xchg(ssl); + } + + if (ret == SSL_OK && + (ret = send_change_cipher_spec(ssl)) == SSL_OK) + { + ret = send_finished(ssl); + } + } + break; + + case HS_CERT_REQ: + ret = process_cert_req(ssl); + break; + + case HS_FINISHED: + ret = process_finished(ssl, buf, hs_len); + disposable_free(ssl); + if (ssl->ssl_ctx->options & SSL_READ_BLOCKING) { + ssl->flag |= SSL_READ_BLOCKING; + } + /* note: client renegotiation is not allowed after this */ + break; + + case HS_HELLO_REQUEST: + disposable_new(ssl); + ret = do_client_connect(ssl); + break; + + default: + ret = SSL_ERROR_INVALID_HANDSHAKE; + break; + } + + return ret; +} + +/* + * Do the handshaking from the beginning. + */ +int do_client_connect(SSL *ssl) +{ + int ret = SSL_OK; + + send_client_hello(ssl); /* send the client hello */ + ssl->bm_read_index = 0; + ssl->next_state = HS_SERVER_HELLO; + ssl->hs_status = SSL_NOT_OK; /* not connected */ + + /* sit in a loop until it all looks good */ + if (!IS_SET_SSL_FLAG(SSL_CONNECT_IN_PARTS)) + { + while (ssl->hs_status != SSL_OK) + { + ret = ssl_read(ssl, NULL); + + if (ret < SSL_OK) + break; + } + + ssl->hs_status = ret; /* connected? */ + } + + return ret; +} + +/* + * Send the initial client hello. + */ +static int send_client_hello(SSL *ssl) +{ + uint8_t *buf = ssl->bm_data; + time_t tm = time(NULL); + uint8_t *tm_ptr = &buf[6]; /* time will go here */ + int i, offset, ext_offset; + int ext_len = 0; + + + buf[0] = HS_CLIENT_HELLO; + buf[1] = 0; + buf[2] = 0; + /* byte 3 is calculated later */ + buf[4] = 0x03; + buf[5] = ssl->version & 0x0f; + + /* client random value - spec says that 1st 4 bytes are big endian time */ + *tm_ptr++ = (uint8_t)(((long)tm & 0xff000000) >> 24); + *tm_ptr++ = (uint8_t)(((long)tm & 0x00ff0000) >> 16); + *tm_ptr++ = (uint8_t)(((long)tm & 0x0000ff00) >> 8); + *tm_ptr++ = (uint8_t)(((long)tm & 0x000000ff)); + if (get_random(SSL_RANDOM_SIZE-4, &buf[10]) < 0) + return SSL_NOT_OK; + + memcpy(ssl->dc->client_random, &buf[6], SSL_RANDOM_SIZE); + offset = 6 + SSL_RANDOM_SIZE; + + /* give session resumption a go */ + if (IS_SET_SSL_FLAG(SSL_SESSION_RESUME)) /* set initially by user */ + { + buf[offset++] = ssl->sess_id_size; + memcpy(&buf[offset], ssl->session_id, ssl->sess_id_size); + offset += ssl->sess_id_size; + CLR_SSL_FLAG(SSL_SESSION_RESUME); /* clear so we can set later */ + } + else + { + /* no session id - because no session resumption just yet */ + buf[offset++] = 0; + } + + buf[offset++] = 0; /* number of ciphers */ + buf[offset++] = NUM_PROTOCOLS*2;/* number of ciphers */ + + /* put all our supported protocols in our request */ + for (i = 0; i < NUM_PROTOCOLS; i++) + { + buf[offset++] = 0; /* cipher we are using */ + buf[offset++] = ssl_prot_prefs[i]; + } + + buf[offset++] = 1; /* no compression */ + buf[offset++] = 0; + + ext_offset = offset; + + buf[offset++] = 0; /* total length of extensions */ + buf[offset++] = 0; + + /* send the signature algorithm extension for TLS 1.2+ */ + if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_2) + { + memcpy(&buf[offset], g_sig_alg, sizeof(g_sig_alg)); + offset += sizeof(g_sig_alg); + ext_len += sizeof(g_sig_alg); + } + + if (ssl->extensions != NULL) + { + /* send the host name if specified */ + if (ssl->extensions->host_name != NULL) + { + size_t host_len = strlen(ssl->extensions->host_name); + buf[offset++] = 0; + buf[offset++] = SSL_EXT_SERVER_NAME; /* server_name(0) (65535) */ + buf[offset++] = 0; + buf[offset++] = host_len + 5; /* server_name length */ + buf[offset++] = 0; + buf[offset++] = host_len + 3; /* server_list length */ + buf[offset++] = 0; /* host_name(0) (255) */ + buf[offset++] = 0; + buf[offset++] = host_len; /* host_name length */ + strncpy((char*) &buf[offset], ssl->extensions->host_name, host_len); + offset += host_len; + ext_len += host_len + 9; + } + + if (ssl->extensions->max_fragment_size) + { + buf[offset++] = 0; + buf[offset++] = SSL_EXT_MAX_FRAGMENT_SIZE; + + buf[offset++] = 0; // size of data + buf[offset++] = 2; + + buf[offset++] = (uint8_t) + ((ssl->extensions->max_fragment_size >> 8) & 0xff); + buf[offset++] = (uint8_t) + (ssl->extensions->max_fragment_size & 0xff); + ext_len += 6; + } + } + + if (ext_len > 0) + { + // update the extensions length value + buf[ext_offset] = (uint8_t) ((ext_len >> 8) & 0xff); + buf[ext_offset + 1] = (uint8_t) (ext_len & 0xff); + } + + buf[3] = offset - 4; /* handshake size */ + return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, offset); +} + +/* + * Process the server hello. + */ +static int process_server_hello(SSL *ssl) +{ + uint8_t *buf = ssl->bm_data; + int pkt_size = ssl->bm_index; + int num_sessions = ssl->ssl_ctx->num_sessions; + uint8_t sess_id_size; + int offset, ret = SSL_OK; + + /* check that we are talking to a TLSv1 server */ + uint8_t version = (buf[4] << 4) + buf[5]; + if (version > SSL_PROTOCOL_VERSION_MAX) + { + version = SSL_PROTOCOL_VERSION_MAX; + } + else if (ssl->version < SSL_PROTOCOL_MIN_VERSION) + { + ret = SSL_ERROR_INVALID_VERSION; + ssl_display_error(ret); + goto error; + } + + ssl->version = version; + + /* get the server random value */ + memcpy(ssl->dc->server_random, &buf[6], SSL_RANDOM_SIZE); + offset = 6 + SSL_RANDOM_SIZE; /* skip of session id size */ + sess_id_size = buf[offset++]; + + if (sess_id_size > SSL_SESSION_ID_SIZE) + { + ret = SSL_ERROR_INVALID_SESSION; + goto error; + } + + if (num_sessions) + { + ssl->session = ssl_session_update(num_sessions, + ssl->ssl_ctx->ssl_sessions, ssl, &buf[offset]); + memcpy(ssl->session->session_id, &buf[offset], sess_id_size); + + /* pad the rest with 0's */ + if (sess_id_size < SSL_SESSION_ID_SIZE) + { + memset(&ssl->session->session_id[sess_id_size], 0, + SSL_SESSION_ID_SIZE-sess_id_size); + } + } + + memcpy(ssl->session_id, &buf[offset], sess_id_size); + ssl->sess_id_size = sess_id_size; + offset += sess_id_size; + + /* get the real cipher we are using - ignore MSB */ + ssl->cipher = buf[++offset]; + ssl->next_state = IS_SET_SSL_FLAG(SSL_SESSION_RESUME) ? + HS_FINISHED : HS_CERTIFICATE; + + offset += 2; // ignore compression + PARANOIA_CHECK(pkt_size, offset); + + ssl->dc->bm_proc_index = offset; + PARANOIA_CHECK(pkt_size, offset); + + // no extensions +error: + return ret; +} + +/** + * Process the server hello done message. + */ +static int process_server_hello_done(SSL *ssl) +{ + ssl->next_state = HS_FINISHED; + return SSL_OK; +} + +/* + * Send a client key exchange message. + */ +static int send_client_key_xchg(SSL *ssl) +{ + uint8_t *buf = ssl->bm_data; + uint8_t premaster_secret[SSL_SECRET_SIZE]; + int enc_secret_size = -1; + + buf[0] = HS_CLIENT_KEY_XCHG; + buf[1] = 0; + + // spec says client must use the what is initially negotiated - + // and this is our current version + premaster_secret[0] = 0x03; + premaster_secret[1] = SSL_PROTOCOL_VERSION_MAX & 0x0f; + if (get_random(SSL_SECRET_SIZE-2, &premaster_secret[2]) < 0) + return SSL_NOT_OK; + + DISPLAY_RSA(ssl, ssl->x509_ctx->rsa_ctx); + + /* rsa_ctx->bi_ctx is not thread-safe */ + SSL_CTX_LOCK(ssl->ssl_ctx->mutex); + enc_secret_size = RSA_encrypt(ssl->x509_ctx->rsa_ctx, premaster_secret, + SSL_SECRET_SIZE, &buf[6], 0); + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + + buf[2] = (enc_secret_size + 2) >> 8; + buf[3] = (enc_secret_size + 2) & 0xff; + buf[4] = enc_secret_size >> 8; + buf[5] = enc_secret_size & 0xff; + + generate_master_secret(ssl, premaster_secret); + return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, enc_secret_size+6); +} + +/* + * Process the certificate request. + */ +static int process_cert_req(SSL *ssl) +{ + uint8_t *buf = &ssl->bm_data[ssl->dc->bm_proc_index]; + int ret = SSL_OK; + int cert_req_size = (buf[2]<<8) + buf[3]; + int offset = 4; + int pkt_size = ssl->bm_index; + uint8_t cert_type_len, sig_alg_len; + + PARANOIA_CHECK(pkt_size, offset + cert_req_size); + ssl->dc->bm_proc_index = cert_req_size; + + /* don't do any processing - we will send back an RSA certificate anyway */ + ssl->next_state = HS_SERVER_HELLO_DONE; + SET_SSL_FLAG(SSL_HAS_CERT_REQ); + + if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_2) // TLS1.2+ + { + // supported certificate types + cert_type_len = buf[offset++]; + PARANOIA_CHECK(pkt_size, offset + cert_type_len); + offset += cert_type_len; + + // supported signature algorithms + sig_alg_len = buf[offset++] << 8; + sig_alg_len += buf[offset++]; + PARANOIA_CHECK(pkt_size, offset + sig_alg_len); + + while (sig_alg_len > 0) + { + uint8_t hash_alg = buf[offset++]; + uint8_t sig_alg = buf[offset++]; + sig_alg_len -= 2; + + if (sig_alg == SIG_ALG_RSA && + (hash_alg == SIG_ALG_SHA1 || + hash_alg == SIG_ALG_SHA256 || + hash_alg == SIG_ALG_SHA384 || + hash_alg == SIG_ALG_SHA512)) + { + ssl->sig_algs[ssl->num_sig_algs++] = hash_alg; + } + } + } + +error: + return ret; +} + +/* + * Send a certificate verify message. + */ +static int send_cert_verify(SSL *ssl) +{ + uint8_t *buf = ssl->bm_data; + uint8_t dgst[SHA1_SIZE+MD5_SIZE+15]; + RSA_CTX *rsa_ctx = ssl->ssl_ctx->rsa_ctx; + int n = 0, ret; + int offset = 0; + int dgst_len; + + if (rsa_ctx == NULL) + return SSL_OK; + + DISPLAY_RSA(ssl, rsa_ctx); + + buf[0] = HS_CERT_VERIFY; + buf[1] = 0; + + if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_2) // TLS1.2+ + { + buf[4] = SIG_ALG_SHA256; + buf[5] = SIG_ALG_RSA; + offset = 6; + memcpy(dgst, g_asn1_sha256, sizeof(g_asn1_sha256)); + dgst_len = finished_digest(ssl, NULL, &dgst[sizeof(g_asn1_sha256)]) + + sizeof(g_asn1_sha256); + } + else + { + offset = 4; + dgst_len = finished_digest(ssl, NULL, dgst); + } + + /* rsa_ctx->bi_ctx is not thread-safe */ + if (rsa_ctx) + { + SSL_CTX_LOCK(ssl->ssl_ctx->mutex); + n = RSA_encrypt(rsa_ctx, dgst, dgst_len, &buf[offset + 2], 1); + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + + if (n == 0) + { + ret = SSL_ERROR_INVALID_KEY; + goto error; + } + } + + buf[offset] = n >> 8; /* add the RSA size */ + buf[offset+1] = n & 0xff; + n += 2; + + if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_2) // TLS1.2+ + { + n += 2; // sig/alg + offset -= 2; + } + + buf[2] = n >> 8; + buf[3] = n & 0xff; + ret = send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, n + offset); + +error: + return ret; +} + +#endif /* CONFIG_SSL_ENABLE_CLIENT */ diff --git a/tools/sdk/axtls/ssl/tls1_svr.c b/tools/sdk/axtls/ssl/tls1_svr.c new file mode 100644 index 0000000000..abc044552d --- /dev/null +++ b/tools/sdk/axtls/ssl/tls1_svr.c @@ -0,0 +1,526 @@ +/* + * Copyright (c) 2007-2016, 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. + */ + +#include +#include +#include +#include "os_port.h" +#include "ssl.h" + +static const uint8_t g_hello_done[] = { HS_SERVER_HELLO_DONE, 0, 0, 0 }; +static const uint8_t g_asn1_sha256[] = +{ + 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, + 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20 +}; + +static int process_client_hello(SSL *ssl); +static int send_server_hello_sequence(SSL *ssl); +static int send_server_hello(SSL *ssl); +static int send_server_hello_done(SSL *ssl); +static int process_client_key_xchg(SSL *ssl); +#ifdef CONFIG_SSL_CERT_VERIFICATION +static int send_certificate_request(SSL *ssl); +static int process_cert_verify(SSL *ssl); +#endif + +/* + * Establish a new SSL connection to an SSL client. + */ +EXP_FUNC SSL * STDCALL ssl_server_new(SSL_CTX *ssl_ctx, int client_fd) +{ + SSL *ssl; + + ssl = ssl_new(ssl_ctx, client_fd); + ssl->next_state = HS_CLIENT_HELLO; + +#ifdef CONFIG_SSL_FULL_MODE + if (ssl_ctx->chain_length == 0) + printf("Warning - no server certificate defined\n"); TTY_FLUSH(); +#endif + + return ssl; +} + +/* + * Process the handshake record. + */ +int do_svr_handshake(SSL *ssl, int handshake_type, uint8_t *buf, int hs_len) +{ + int ret = SSL_OK; + ssl->hs_status = SSL_NOT_OK; /* not connected */ + + /* To get here the state must be valid */ + switch (handshake_type) + { + case HS_CLIENT_HELLO: + if ((ret = process_client_hello(ssl)) == SSL_OK) + ret = send_server_hello_sequence(ssl); + break; + +#ifdef CONFIG_SSL_CERT_VERIFICATION + case HS_CERTIFICATE:/* the client sends its cert */ + ret = process_certificate(ssl, &ssl->x509_ctx); + + if (ret == SSL_OK) /* verify the cert */ + { + int cert_res; + int pathLenConstraint = 0; + + cert_res = x509_verify(ssl->ssl_ctx->ca_cert_ctx, + ssl->x509_ctx, &pathLenConstraint); + ret = (cert_res == 0) ? SSL_OK : SSL_X509_ERROR(cert_res); + } + break; + + case HS_CERT_VERIFY: + ret = process_cert_verify(ssl); + add_packet(ssl, buf, hs_len); /* needs to be done after */ + break; +#endif + case HS_CLIENT_KEY_XCHG: + ret = process_client_key_xchg(ssl); + break; + + case HS_FINISHED: + ret = process_finished(ssl, buf, hs_len); + disposable_free(ssl); /* free up some memory */ + break; + } + + return ret; +} + +/* + * Process a client hello message. + */ +static int process_client_hello(SSL *ssl) +{ + uint8_t *buf = ssl->bm_data; + int pkt_size = ssl->bm_index; + int i, j, cs_len, id_len, offset = 6 + SSL_RANDOM_SIZE; + int ret = SSL_OK; + + uint8_t version = (buf[4] << 4) + buf[5]; + ssl->version = ssl->client_version = version; + + if (version > SSL_PROTOCOL_VERSION_MAX) + { + /* use client's version instead */ + ssl->version = SSL_PROTOCOL_VERSION_MAX; + } + else if (version < SSL_PROTOCOL_MIN_VERSION) /* old version supported? */ + { + ret = SSL_ERROR_INVALID_VERSION; + ssl_display_error(ret); + goto error; + } + + memcpy(ssl->dc->client_random, &buf[6], SSL_RANDOM_SIZE); + + /* process the session id */ + id_len = buf[offset++]; + if (id_len > SSL_SESSION_ID_SIZE) + { + return SSL_ERROR_INVALID_SESSION; + } + +#ifndef CONFIG_SSL_SKELETON_MODE + ssl->session = ssl_session_update(ssl->ssl_ctx->num_sessions, + ssl->ssl_ctx->ssl_sessions, ssl, id_len ? &buf[offset] : NULL); +#endif + + offset += id_len; + cs_len = (buf[offset]<<8) + buf[offset+1]; + offset += 3; /* add 1 due to all cipher suites being 8 bit */ + + PARANOIA_CHECK(pkt_size, offset + cs_len); + + /* work out what cipher suite we are going to use - client defines + the preference */ + for (i = 0; i < cs_len; i += 2) + { + for (j = 0; j < NUM_PROTOCOLS; j++) + { + if (ssl_prot_prefs[j] == buf[offset+i]) /* got a match? */ + { + ssl->cipher = ssl_prot_prefs[j]; + goto do_compression; + } + } + } + + /* ouch! protocol is not supported */ + return SSL_ERROR_NO_CIPHER; + + /* completely ignore compression */ +do_compression: + offset += cs_len; + id_len = buf[offset++]; + offset += id_len; + PARANOIA_CHECK(pkt_size, offset + id_len); + + if (offset == pkt_size) + { + /* no extensions */ + goto error; + } + + /* extension size */ + id_len = buf[offset++] << 8; + id_len += buf[offset++]; + PARANOIA_CHECK(pkt_size, offset + id_len); + + // Check for extensions from the client - only the signature algorithm + // is supported + while (offset < pkt_size) + { + int ext = buf[offset++] << 8; + ext += buf[offset++]; + int ext_len = buf[offset++] << 8; + ext_len += buf[offset++]; + PARANOIA_CHECK(pkt_size, offset + ext_len); + + if (ext == SSL_EXT_SIG_ALG) + { + while (ext_len > 0) + { + uint8_t hash_alg = buf[offset++]; + uint8_t sig_alg = buf[offset++]; + ext_len -= 2; + + if (sig_alg == SIG_ALG_RSA && + (hash_alg == SIG_ALG_SHA1 || + hash_alg == SIG_ALG_SHA256 || + hash_alg == SIG_ALG_SHA384 || + hash_alg == SIG_ALG_SHA512)) + { + ssl->sig_algs[ssl->num_sig_algs++] = hash_alg; + } + } + } + else + { + offset += ext_len; + } + } + + /* default is RSA/SHA1 */ + if (ssl->num_sig_algs == 0) + { + ssl->sig_algs[ssl->num_sig_algs++] = SIG_ALG_SHA1; + } + +error: + return ret; +} + +/* + * Send the entire server hello sequence + */ +static int send_server_hello_sequence(SSL *ssl) +{ + int ret; + + if ((ret = send_server_hello(ssl)) == SSL_OK) + { +#ifndef CONFIG_SSL_SKELETON_MODE + /* resume handshake? */ + if (IS_SET_SSL_FLAG(SSL_SESSION_RESUME)) + { + if ((ret = send_change_cipher_spec(ssl)) == SSL_OK) + { + ret = send_finished(ssl); + ssl->next_state = HS_FINISHED; + } + } + else +#endif + if ((ret = send_certificate(ssl)) == SSL_OK) + { +#ifdef CONFIG_SSL_CERT_VERIFICATION + /* ask the client for its certificate */ + if (IS_SET_SSL_FLAG(SSL_CLIENT_AUTHENTICATION)) + { + if ((ret = send_certificate_request(ssl)) == SSL_OK) + { + ret = send_server_hello_done(ssl); + ssl->next_state = HS_CERTIFICATE; + } + } + else +#endif + { + ret = send_server_hello_done(ssl); + ssl->next_state = HS_CLIENT_KEY_XCHG; + } + } + } + + return ret; +} + +/* + * Send a server hello message. + */ +static int send_server_hello(SSL *ssl) +{ + uint8_t *buf = ssl->bm_data; + int offset = 0; + + buf[0] = HS_SERVER_HELLO; + buf[1] = 0; + buf[2] = 0; + /* byte 3 is calculated later */ + buf[4] = 0x03; + buf[5] = ssl->version & 0x0f; + + /* server random value */ + if (get_random(SSL_RANDOM_SIZE, &buf[6]) < 0) + return SSL_NOT_OK; + + memcpy(ssl->dc->server_random, &buf[6], SSL_RANDOM_SIZE); + offset = 6 + SSL_RANDOM_SIZE; + +#ifndef CONFIG_SSL_SKELETON_MODE + if (IS_SET_SSL_FLAG(SSL_SESSION_RESUME)) + { + /* retrieve id from session cache */ + buf[offset++] = SSL_SESSION_ID_SIZE; + memcpy(&buf[offset], ssl->session->session_id, SSL_SESSION_ID_SIZE); + memcpy(ssl->session_id, ssl->session->session_id, SSL_SESSION_ID_SIZE); + ssl->sess_id_size = SSL_SESSION_ID_SIZE; + offset += SSL_SESSION_ID_SIZE; + } + else /* generate our own session id */ +#endif + { +#ifndef CONFIG_SSL_SKELETON_MODE + buf[offset++] = SSL_SESSION_ID_SIZE; + get_random(SSL_SESSION_ID_SIZE, &buf[offset]); + memcpy(ssl->session_id, &buf[offset], SSL_SESSION_ID_SIZE); + ssl->sess_id_size = SSL_SESSION_ID_SIZE; + + /* store id in session cache */ + if (ssl->ssl_ctx->num_sessions) + { + memcpy(ssl->session->session_id, + ssl->session_id, SSL_SESSION_ID_SIZE); + } + + offset += SSL_SESSION_ID_SIZE; +#else + buf[offset++] = 0; /* don't bother with session id in skelton mode */ +#endif + } + + buf[offset++] = 0; /* cipher we are using */ + buf[offset++] = ssl->cipher; + buf[offset++] = 0; /* no compression and no extensions supported */ + buf[3] = offset - 4; /* handshake size */ + return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, offset); +} + +/* + * Send the server hello done message. + */ +static int send_server_hello_done(SSL *ssl) +{ + return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, + g_hello_done, sizeof(g_hello_done)); +} + +/* + * Pull apart a client key exchange message. Decrypt the pre-master key (using + * our RSA private key) and then work out the master key. Initialise the + * ciphers. + */ +static int process_client_key_xchg(SSL *ssl) +{ + uint8_t *buf = &ssl->bm_data[ssl->dc->bm_proc_index]; + int pkt_size = ssl->bm_index; + int premaster_size, secret_length = (buf[2] << 8) + buf[3]; + uint8_t premaster_secret[MAX_KEY_BYTE_SIZE]; + RSA_CTX *rsa_ctx = ssl->ssl_ctx->rsa_ctx; + int offset = 4; + int ret = SSL_OK; + + if (rsa_ctx == NULL) + { + ret = SSL_ERROR_NO_CERT_DEFINED; + goto error; + } + + /* is there an extra size field? */ + if ((secret_length - 2) == rsa_ctx->num_octets) + offset += 2; + + PARANOIA_CHECK(pkt_size, rsa_ctx->num_octets+offset); + + /* rsa_ctx->bi_ctx is not thread-safe */ + SSL_CTX_LOCK(ssl->ssl_ctx->mutex); + premaster_size = RSA_decrypt(rsa_ctx, &buf[offset], premaster_secret, + sizeof(premaster_secret), 1); + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + + if (premaster_size != SSL_SECRET_SIZE || + premaster_secret[0] != 0x03 || /* must be the same as client + offered version */ + premaster_secret[1] != (ssl->client_version & 0x0f)) + { + /* guard against a Bleichenbacher attack */ + if (get_random(SSL_SECRET_SIZE, premaster_secret) < 0) + return SSL_NOT_OK; + + /* and continue - will die eventually when checking the mac */ + } + + generate_master_secret(ssl, premaster_secret); + +#ifdef CONFIG_SSL_CERT_VERIFICATION + ssl->next_state = IS_SET_SSL_FLAG(SSL_CLIENT_AUTHENTICATION) ? + HS_CERT_VERIFY : HS_FINISHED; +#else + ssl->next_state = HS_FINISHED; +#endif + + ssl->dc->bm_proc_index += rsa_ctx->num_octets+offset; +error: + return ret; +} + +#ifdef CONFIG_SSL_CERT_VERIFICATION +static const uint8_t g_cert_request[] = { HS_CERT_REQ, 0, + 0, 0x0e, + 1, 1, // rsa sign + 0x00, 0x08, + SIG_ALG_SHA256, SIG_ALG_RSA, + SIG_ALG_SHA512, SIG_ALG_RSA, + SIG_ALG_SHA384, SIG_ALG_RSA, + SIG_ALG_SHA1, SIG_ALG_RSA, + 0, 0 +}; + +static const uint8_t g_cert_request_v1[] = { HS_CERT_REQ, 0, 0, 4, 1, 0, 0, 0 }; + +/* + * Send the certificate request message. + */ +static int send_certificate_request(SSL *ssl) +{ + if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_2) // TLS1.2+ + { + return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, + g_cert_request, sizeof(g_cert_request)); + } + else + { + return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, + g_cert_request_v1, sizeof(g_cert_request_v1)); + } +} + +/* + * Ensure the client has the private key by first decrypting the packet and + * then checking the packet digests. + */ +static int process_cert_verify(SSL *ssl) +{ + uint8_t *buf = &ssl->bm_data[ssl->dc->bm_proc_index]; + int pkt_size = ssl->bm_index; + uint8_t dgst_buf[MAX_KEY_BYTE_SIZE]; + uint8_t dgst[MD5_SIZE + SHA1_SIZE]; + X509_CTX *x509_ctx = ssl->x509_ctx; + int ret = SSL_OK; + int offset = 6; + int rsa_len; + int n; + + DISPLAY_RSA(ssl, x509_ctx->rsa_ctx); + + if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_2) // TLS1.2+ + { + // TODO: should really need to be able to handle other algorihms. An + // assumption is made on RSA/SHA256 and appears to be OK. + //uint8_t hash_alg = buf[4]; + //uint8_t sig_alg = buf[5]; + offset = 8; + rsa_len = (buf[6] << 8) + buf[7]; + } + else + { + rsa_len = (buf[4] << 8) + buf[5]; + } + + PARANOIA_CHECK(pkt_size, offset + rsa_len); + + /* rsa_ctx->bi_ctx is not thread-safe */ + SSL_CTX_LOCK(ssl->ssl_ctx->mutex); + n = RSA_decrypt(x509_ctx->rsa_ctx, &buf[offset], dgst_buf, + sizeof(dgst_buf), 0); + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + + if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_2) // TLS1.2+ + { + if (memcmp(dgst_buf, g_asn1_sha256, sizeof(g_asn1_sha256))) + { + ret = SSL_ERROR_INVALID_KEY; + goto error; + } + + finished_digest(ssl, NULL, dgst); /* calculate the digest */ + if (memcmp(&dgst_buf[sizeof(g_asn1_sha256)], dgst, SHA256_SIZE)) + { + ret = SSL_ERROR_INVALID_KEY; + goto error; + } + } + else // TLS1.0/1.1 + { + if (n != SHA1_SIZE + MD5_SIZE) + { + ret = SSL_ERROR_INVALID_KEY; + goto end_cert_vfy; + } + + finished_digest(ssl, NULL, dgst); /* calculate the digest */ + if (memcmp(dgst_buf, dgst, MD5_SIZE + SHA1_SIZE)) + { + ret = SSL_ERROR_INVALID_KEY; + } + } + +end_cert_vfy: + ssl->next_state = HS_FINISHED; +error: + return ret; +} + +#endif diff --git a/tools/sdk/axtls/ssl/version.h b/tools/sdk/axtls/ssl/version.h new file mode 100644 index 0000000000..c9d6c252f2 --- /dev/null +++ b/tools/sdk/axtls/ssl/version.h @@ -0,0 +1 @@ +#define AXTLS_VERSION "2.1.2" diff --git a/tools/sdk/axtls/ssl/x509.c b/tools/sdk/axtls/ssl/x509.c new file mode 100644 index 0000000000..dbb9fd3dd3 --- /dev/null +++ b/tools/sdk/axtls/ssl/x509.c @@ -0,0 +1,899 @@ +/* + * Copyright (c) 2007-2016, 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 x509.c + * + * Certificate processing. + */ + +#include +#include +#include +#include +#include "os_port.h" +#include "crypto_misc.h" + +#ifdef CONFIG_SSL_CERT_VERIFICATION +static int x509_v3_subject_alt_name(const uint8_t *cert, int offset, + X509_CTX *x509_ctx); +static int x509_v3_basic_constraints(const uint8_t *cert, int offset, + X509_CTX *x509_ctx); +static int x509_v3_key_usage(const uint8_t *cert, int offset, + X509_CTX *x509_ctx); + +/** + * Retrieve the signature from a certificate. + */ +static const uint8_t *get_signature(const uint8_t *asn1_sig, int *len) +{ + int offset = 0; + const uint8_t *ptr = NULL; + + if (asn1_next_obj(asn1_sig, &offset, ASN1_SEQUENCE) < 0 || + asn1_skip_obj(asn1_sig, &offset, ASN1_SEQUENCE)) + goto end_get_sig; + + if (asn1_sig[offset++] != ASN1_OCTET_STRING) + goto end_get_sig; + *len = get_asn1_length(asn1_sig, &offset); + ptr = &asn1_sig[offset]; /* all ok */ + +end_get_sig: + return ptr; +} + +#endif + +/** + * Construct a new x509 object. + * @return 0 if ok. < 0 if there was a problem. + */ +int x509_new(const uint8_t *cert, int *len, X509_CTX **ctx) +{ + int begin_tbs, end_tbs, begin_spki, end_spki; + int ret = X509_NOT_OK, offset = 0, cert_size = 0; + int version = 0; + X509_CTX *x509_ctx; +#ifdef CONFIG_SSL_CERT_VERIFICATION /* only care if doing verification */ + BI_CTX *bi_ctx; +#endif + + *ctx = (X509_CTX *)calloc(1, sizeof(X509_CTX)); + x509_ctx = *ctx; + + /* get the certificate size */ + asn1_skip_obj(cert, &cert_size, ASN1_SEQUENCE); + + if (asn1_next_obj(cert, &offset, ASN1_SEQUENCE) < 0) + goto end_cert; + + begin_tbs = offset; /* start of the tbs */ + end_tbs = begin_tbs; /* work out the end of the tbs */ + asn1_skip_obj(cert, &end_tbs, ASN1_SEQUENCE); + + if (asn1_next_obj(cert, &offset, ASN1_SEQUENCE) < 0) + goto end_cert; + + /* optional version */ + if (cert[offset] == ASN1_EXPLICIT_TAG && + asn1_version(cert, &offset, &version) == X509_NOT_OK) + goto end_cert; + + if (asn1_skip_obj(cert, &offset, ASN1_INTEGER) || /* serial number */ + asn1_next_obj(cert, &offset, ASN1_SEQUENCE) < 0) + goto end_cert; + + /* make sure the signature is ok */ + if (asn1_signature_type(cert, &offset, x509_ctx)) + { + ret = X509_VFY_ERROR_UNSUPPORTED_DIGEST; + goto end_cert; + } + + if (asn1_name(cert, &offset, x509_ctx->ca_cert_dn) || + asn1_validity(cert, &offset, x509_ctx) || + asn1_name(cert, &offset, x509_ctx->cert_dn)) + { + goto end_cert; + } + begin_spki = offset; + if (asn1_public_key(cert, &offset, x509_ctx)) + goto end_cert; + end_spki = offset; + + x509_ctx->fingerprint = malloc(SHA1_SIZE); + SHA1_CTX sha_fp_ctx; + SHA1_Init(&sha_fp_ctx); + SHA1_Update(&sha_fp_ctx, &cert[0], cert_size); + SHA1_Final(x509_ctx->fingerprint, &sha_fp_ctx); + + x509_ctx->spki_sha256 = malloc(SHA256_SIZE); + SHA256_CTX spki_hash_ctx; + SHA256_Init(&spki_hash_ctx); + SHA256_Update(&spki_hash_ctx, &cert[begin_spki], end_spki-begin_spki); + SHA256_Final(x509_ctx->spki_sha256, &spki_hash_ctx); + +#ifdef CONFIG_SSL_CERT_VERIFICATION /* only care if doing verification */ + bi_ctx = x509_ctx->rsa_ctx->bi_ctx; + + /* use the appropriate signature algorithm */ + switch (x509_ctx->sig_type) + { + case SIG_TYPE_MD5: + { + MD5_CTX md5_ctx; + uint8_t md5_dgst[MD5_SIZE]; + MD5_Init(&md5_ctx); + MD5_Update(&md5_ctx, &cert[begin_tbs], end_tbs-begin_tbs); + MD5_Final(md5_dgst, &md5_ctx); + x509_ctx->digest = bi_import(bi_ctx, md5_dgst, MD5_SIZE); + } + break; + + case SIG_TYPE_SHA1: + { + SHA1_CTX sha_ctx; + uint8_t sha_dgst[SHA1_SIZE]; + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx, &cert[begin_tbs], end_tbs-begin_tbs); + SHA1_Final(sha_dgst, &sha_ctx); + x509_ctx->digest = bi_import(bi_ctx, sha_dgst, SHA1_SIZE); + } + break; + + case SIG_TYPE_SHA256: + { + SHA256_CTX sha256_ctx; + uint8_t sha256_dgst[SHA256_SIZE]; + SHA256_Init(&sha256_ctx); + SHA256_Update(&sha256_ctx, &cert[begin_tbs], end_tbs-begin_tbs); + SHA256_Final(sha256_dgst, &sha256_ctx); + x509_ctx->digest = bi_import(bi_ctx, sha256_dgst, SHA256_SIZE); + } + break; + + case SIG_TYPE_SHA384: + { + SHA384_CTX sha384_ctx; + uint8_t sha384_dgst[SHA384_SIZE]; + SHA384_Init(&sha384_ctx); + SHA384_Update(&sha384_ctx, &cert[begin_tbs], end_tbs-begin_tbs); + SHA384_Final(sha384_dgst, &sha384_ctx); + x509_ctx->digest = bi_import(bi_ctx, sha384_dgst, SHA384_SIZE); + } + break; + + case SIG_TYPE_SHA512: + { + SHA512_CTX sha512_ctx; + uint8_t sha512_dgst[SHA512_SIZE]; + SHA512_Init(&sha512_ctx); + SHA512_Update(&sha512_ctx, &cert[begin_tbs], end_tbs-begin_tbs); + SHA512_Final(sha512_dgst, &sha512_ctx); + x509_ctx->digest = bi_import(bi_ctx, sha512_dgst, SHA512_SIZE); + } + break; + } + + if (version == 2 && asn1_next_obj(cert, &offset, ASN1_V3_DATA) > 0) + { + x509_v3_subject_alt_name(cert, offset, x509_ctx); + x509_v3_basic_constraints(cert, offset, x509_ctx); + x509_v3_key_usage(cert, offset, x509_ctx); + } + + offset = end_tbs; /* skip the rest of v3 data */ + if (asn1_skip_obj(cert, &offset, ASN1_SEQUENCE) || + asn1_signature(cert, &offset, x509_ctx)) + goto end_cert; +#endif + ret = X509_OK; +end_cert: + if (len) + { + *len = cert_size; + } + + if (ret) + { +#ifdef CONFIG_SSL_FULL_MODE + char buff[64]; + printf("Error: Invalid X509 ASN.1 file (%s)\n", + x509_display_error(ret, buff)); +#endif + x509_free(x509_ctx); + *ctx = NULL; + } + + return ret; +} + +#ifdef CONFIG_SSL_CERT_VERIFICATION /* only care if doing verification */ +static int x509_v3_subject_alt_name(const uint8_t *cert, int offset, + X509_CTX *x509_ctx) +{ + if ((offset = asn1_is_subject_alt_name(cert, offset)) > 0) + { + x509_ctx->subject_alt_name_present = true; + x509_ctx->subject_alt_name_is_critical = + asn1_is_critical_ext(cert, &offset); + + if (asn1_next_obj(cert, &offset, ASN1_OCTET_STRING) > 0) + { + int altlen; + + if ((altlen = asn1_next_obj(cert, &offset, ASN1_SEQUENCE)) > 0) + { + int endalt = offset + altlen; + int totalnames = 0; + + while (offset < endalt) + { + int type = cert[offset++]; + int dnslen = get_asn1_length(cert, &offset); + + if (type == ASN1_CONTEXT_DNSNAME) + { + x509_ctx->subject_alt_dnsnames = (char**) + realloc(x509_ctx->subject_alt_dnsnames, + (totalnames + 2) * sizeof(char*)); + x509_ctx->subject_alt_dnsnames[totalnames] = + (char*)malloc(dnslen + 1); + x509_ctx->subject_alt_dnsnames[totalnames+1] = NULL; + memcpy(x509_ctx->subject_alt_dnsnames[totalnames], + cert + offset, dnslen); + x509_ctx->subject_alt_dnsnames[totalnames][dnslen] = 0; + totalnames++; + } + + offset += dnslen; + } + } + } + } + + return X509_OK; +} + +/** + * Basic constraints - see https://tools.ietf.org/html/rfc5280#page-39 + */ +static int x509_v3_basic_constraints(const uint8_t *cert, int offset, + X509_CTX *x509_ctx) +{ + int ret = X509_OK; + + if ((offset = asn1_is_basic_constraints(cert, offset)) == 0) + goto end_contraints; + + x509_ctx->basic_constraint_present = true; + x509_ctx->basic_constraint_is_critical = + asn1_is_critical_ext(cert, &offset); + + if (asn1_next_obj(cert, &offset, ASN1_OCTET_STRING) < 0 || + asn1_next_obj(cert, &offset, ASN1_SEQUENCE) < 0 || + asn1_get_bool(cert, &offset, &x509_ctx->basic_constraint_cA) < 0 || + asn1_get_int(cert, &offset, + &x509_ctx->basic_constraint_pathLenConstraint) < 0) + { + ret = X509_NOT_OK; + } + +end_contraints: + return ret; +} + +/* + * Key usage - see https://tools.ietf.org/html/rfc5280#section-4.2.1.3 + */ +static int x509_v3_key_usage(const uint8_t *cert, int offset, + X509_CTX *x509_ctx) +{ + int ret = X509_OK; + + if ((offset = asn1_is_key_usage(cert, offset)) == 0) + goto end_key_usage; + + x509_ctx->key_usage_present = true; + x509_ctx->key_usage_is_critical = asn1_is_critical_ext(cert, &offset); + + if (asn1_next_obj(cert, &offset, ASN1_OCTET_STRING) < 0 || + asn1_get_bit_string_as_int(cert, &offset, &x509_ctx->key_usage)) + { + ret = X509_NOT_OK; + } + +end_key_usage: + return ret; +} +#endif + +/** + * Free an X.509 object's resources. + */ +void x509_free(X509_CTX *x509_ctx) +{ + X509_CTX *next; + int i; + + if (x509_ctx == NULL) /* if already null, then don't bother */ + return; + + for (i = 0; i < X509_NUM_DN_TYPES; i++) + { + free(x509_ctx->ca_cert_dn[i]); + free(x509_ctx->cert_dn[i]); + } + + free(x509_ctx->signature); + +#ifdef CONFIG_SSL_CERT_VERIFICATION + if (x509_ctx->digest) + { + bi_free(x509_ctx->rsa_ctx->bi_ctx, x509_ctx->digest); + } + + if (x509_ctx->fingerprint) + { + free(x509_ctx->fingerprint); + } + + if (x509_ctx->spki_sha256) + { + free(x509_ctx->spki_sha256); + } + + if (x509_ctx->subject_alt_dnsnames) + { + for (i = 0; x509_ctx->subject_alt_dnsnames[i]; ++i) + free(x509_ctx->subject_alt_dnsnames[i]); + + free(x509_ctx->subject_alt_dnsnames); + } +#endif + + RSA_free(x509_ctx->rsa_ctx); + next = x509_ctx->next; + free(x509_ctx); + x509_free(next); /* clear the chain */ +} + +#ifdef CONFIG_SSL_CERT_VERIFICATION +/** + * Take a signature and decrypt it. + */ +static bigint *sig_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len, + bigint *modulus, bigint *pub_exp) +{ + int i, size; + bigint *decrypted_bi, *dat_bi; + bigint *bir = NULL; + uint8_t *block = (uint8_t *)malloc(sig_len); + + /* decrypt */ + dat_bi = bi_import(ctx, sig, sig_len); + ctx->mod_offset = BIGINT_M_OFFSET; + + /* convert to a normal block */ + decrypted_bi = bi_mod_power2(ctx, dat_bi, modulus, pub_exp); + + bi_export(ctx, decrypted_bi, block, sig_len); + ctx->mod_offset = BIGINT_M_OFFSET; + + i = 10; /* start at the first possible non-padded byte */ + while (block[i++] && i < sig_len); + size = sig_len - i; + + /* get only the bit we want */ + if (size > 0) + { + int len; + const uint8_t *sig_ptr = get_signature(&block[i], &len); + + if (sig_ptr) + { + bir = bi_import(ctx, sig_ptr, len); + } + } + free(block); + /* save a few bytes of memory */ + bi_clear_cache(ctx); + return bir; +} + +/** + * Do some basic checks on the certificate chain. + * + * Certificate verification consists of a number of checks: + * - The date of the certificate is after the start date. + * - The date of the certificate is before the finish date. + * - A root certificate exists in the certificate store. + * - That the certificate(s) are not self-signed. + * - The certificate chain is valid. + * - The signature of the certificate is valid. + * - Basic constraints + */ +int x509_verify(const CA_CERT_CTX *ca_cert_ctx, const X509_CTX *cert, + int *pathLenConstraint) +{ + int ret = X509_OK, i = 0; + bigint *cert_sig; + X509_CTX *next_cert = NULL; + BI_CTX *ctx = NULL; + bigint *mod = NULL, *expn = NULL; + int match_ca_cert = 0; + struct timeval tv; + uint8_t is_self_signed = 0; + + if (cert == NULL) + { + ret = X509_VFY_ERROR_NO_TRUSTED_CERT; + goto end_verify; + } + + /* a self-signed certificate that is not in the CA store - use this + to check the signature */ + if (asn1_compare_dn(cert->ca_cert_dn, cert->cert_dn) == 0) + { + is_self_signed = 1; + ctx = cert->rsa_ctx->bi_ctx; + mod = cert->rsa_ctx->m; + expn = cert->rsa_ctx->e; + } + + gettimeofday(&tv, NULL); + + /* check the not before date */ + if (tv.tv_sec < cert->not_before) + { + ret = X509_VFY_ERROR_NOT_YET_VALID; + goto end_verify; + } + + /* check the not after date */ + if (tv.tv_sec > cert->not_after) + { + ret = X509_VFY_ERROR_EXPIRED; + goto end_verify; + } + + if (cert->basic_constraint_present) + { + /* If the cA boolean is not asserted, + then the keyCertSign bit in the key usage extension MUST NOT be + asserted. */ + if (!cert->basic_constraint_cA && + IS_SET_KEY_USAGE_FLAG(cert, KEY_USAGE_KEY_CERT_SIGN)) + { + ret = X509_VFY_ERROR_BASIC_CONSTRAINT; + goto end_verify; + } + + /* The pathLenConstraint field is meaningful only if the cA boolean is + asserted and the key usage extension, if present, asserts the + keyCertSign bit. In this case, it gives the maximum number of + non-self-issued intermediate certificates that may follow this + certificate in a valid certification path. */ + if (cert->basic_constraint_cA && + (!cert->key_usage_present || + IS_SET_KEY_USAGE_FLAG(cert, KEY_USAGE_KEY_CERT_SIGN)) && + (cert->basic_constraint_pathLenConstraint+1) < *pathLenConstraint) + { + ret = X509_VFY_ERROR_BASIC_CONSTRAINT; + goto end_verify; + } + } + + next_cert = cert->next; + + /* last cert in the chain - look for a trusted cert */ + if (next_cert == NULL) + { + if (ca_cert_ctx != NULL) + { + /* go thru the CA store */ + while (i < CONFIG_X509_MAX_CA_CERTS && ca_cert_ctx->cert[i]) + { + /* the extension is present but the cA boolean is not + asserted, then the certified public key MUST NOT be used + to verify certificate signatures. */ + if (cert->basic_constraint_present && + !ca_cert_ctx->cert[i]->basic_constraint_cA) + continue; + + if (asn1_compare_dn(cert->ca_cert_dn, + ca_cert_ctx->cert[i]->cert_dn) == 0) + { + /* use this CA certificate for signature verification */ + match_ca_cert = true; + ctx = ca_cert_ctx->cert[i]->rsa_ctx->bi_ctx; + mod = ca_cert_ctx->cert[i]->rsa_ctx->m; + expn = ca_cert_ctx->cert[i]->rsa_ctx->e; + + + break; + } + + i++; + } + } + + /* couldn't find a trusted cert (& let self-signed errors + be returned) */ + if (!match_ca_cert && !is_self_signed) + { + ret = X509_VFY_ERROR_NO_TRUSTED_CERT; + goto end_verify; + } + } + else if (asn1_compare_dn(cert->ca_cert_dn, next_cert->cert_dn) != 0) + { + /* check the chain */ + ret = X509_VFY_ERROR_INVALID_CHAIN; + goto end_verify; + } + else /* use the next certificate in the chain for signature verify */ + { + ctx = next_cert->rsa_ctx->bi_ctx; + mod = next_cert->rsa_ctx->m; + expn = next_cert->rsa_ctx->e; + } + + /* cert is self signed */ + if (!match_ca_cert && is_self_signed) + { + ret = X509_VFY_ERROR_SELF_SIGNED; + goto end_verify; + } + + /* check the signature */ + cert_sig = sig_verify(ctx, cert->signature, cert->sig_len, + bi_clone(ctx, mod), bi_clone(ctx, expn)); + + if (cert_sig && cert->digest) + { + if (bi_compare(cert_sig, cert->digest) != 0) + ret = X509_VFY_ERROR_BAD_SIGNATURE; + + + bi_free(ctx, cert_sig); + } + else + { + ret = X509_VFY_ERROR_BAD_SIGNATURE; + } + + if (ret) + goto end_verify; + + /* go down the certificate chain using recursion. */ + if (next_cert != NULL) + { + (*pathLenConstraint)++; /* don't include last certificate */ + ret = x509_verify(ca_cert_ctx, next_cert, pathLenConstraint); + } + +end_verify: + return ret; +} +#endif + +#if defined (CONFIG_SSL_FULL_MODE) +/** + * Used for diagnostics. + */ +static const char *not_part_of_cert = ""; +void x509_print(const X509_CTX *cert, CA_CERT_CTX *ca_cert_ctx) +{ + if (cert == NULL) + return; + + printf("=== CERTIFICATE ISSUED TO ===\n"); + printf("Common Name (CN):\t\t"); + printf("%s\n", cert->cert_dn[X509_COMMON_NAME] ? + cert->cert_dn[X509_COMMON_NAME] : not_part_of_cert); + + printf("Organization (O):\t\t"); + printf("%s\n", cert->cert_dn[X509_ORGANIZATION] ? + cert->cert_dn[X509_ORGANIZATION] : not_part_of_cert); + + if (cert->cert_dn[X509_ORGANIZATIONAL_UNIT]) + { + printf("Organizational Unit (OU):\t"); + printf("%s\n", cert->cert_dn[X509_ORGANIZATIONAL_UNIT]); + } + + if (cert->cert_dn[X509_LOCATION]) + { + printf("Location (L):\t\t\t"); + printf("%s\n", cert->cert_dn[X509_LOCATION]); + } + + if (cert->cert_dn[X509_COUNTRY]) + { + printf("Country (C):\t\t\t"); + printf("%s\n", cert->cert_dn[X509_COUNTRY]); + } + + if (cert->cert_dn[X509_STATE]) + { + printf("State (ST):\t\t\t"); + printf("%s\n", cert->cert_dn[X509_STATE]); + } + + if (cert->basic_constraint_present) + { + printf("Basic Constraints:\t\t%sCA:%s, pathlen:%d\n", + cert->basic_constraint_is_critical ? + "critical, " : "", + cert->basic_constraint_cA? "TRUE" : "FALSE", + cert->basic_constraint_pathLenConstraint); + } + + if (cert->key_usage_present) + { + printf("Key Usage:\t\t\t%s", cert->key_usage_is_critical ? + "critical, " : ""); + bool has_started = false; + + if (IS_SET_KEY_USAGE_FLAG(cert, KEY_USAGE_DIGITAL_SIGNATURE)) + { + printf("Digital Signature"); + has_started = true; + } + + if (IS_SET_KEY_USAGE_FLAG(cert, KEY_USAGE_NON_REPUDIATION)) + { + if (has_started) + printf(", "); + + printf("Non Repudiation"); + has_started = true; + } + + if (IS_SET_KEY_USAGE_FLAG(cert, KEY_USAGE_KEY_ENCIPHERMENT)) + { + if (has_started) + printf(", "); + + printf("Key Encipherment"); + has_started = true; + } + + if (IS_SET_KEY_USAGE_FLAG(cert, KEY_USAGE_DATA_ENCIPHERMENT)) + { + if (has_started) + printf(", "); + + printf("Data Encipherment"); + has_started = true; + } + + if (IS_SET_KEY_USAGE_FLAG(cert, KEY_USAGE_KEY_AGREEMENT)) + { + if (has_started) + printf(", "); + + printf("Key Agreement"); + has_started = true; + } + + if (IS_SET_KEY_USAGE_FLAG(cert, KEY_USAGE_KEY_CERT_SIGN)) + { + if (has_started) + printf(", "); + + printf("Key Cert Sign"); + has_started = true; + } + + if (IS_SET_KEY_USAGE_FLAG(cert, KEY_USAGE_CRL_SIGN)) + { + if (has_started) + printf(", "); + + printf("CRL Sign"); + has_started = true; + } + + if (IS_SET_KEY_USAGE_FLAG(cert, KEY_USAGE_ENCIPHER_ONLY)) + { + if (has_started) + printf(", "); + + printf("Encipher Only"); + has_started = true; + } + + if (IS_SET_KEY_USAGE_FLAG(cert, KEY_USAGE_DECIPHER_ONLY)) + { + if (has_started) + printf(", "); + + printf("Decipher Only"); + has_started = true; + } + + printf("\n"); + } + + if (cert->subject_alt_name_present) + { + printf("Subject Alt Name:\t\t%s", cert->subject_alt_name_is_critical + ? "critical, " : ""); + if (cert->subject_alt_dnsnames) + { + int i = 0; + + while (cert->subject_alt_dnsnames[i]) + printf("%s ", cert->subject_alt_dnsnames[i++]); + } + printf("\n"); + + } + + printf("=== CERTIFICATE ISSUED BY ===\n"); + printf("Common Name (CN):\t\t"); + printf("%s\n", cert->ca_cert_dn[X509_COMMON_NAME] ? + cert->ca_cert_dn[X509_COMMON_NAME] : not_part_of_cert); + + printf("Organization (O):\t\t"); + printf("%s\n", cert->ca_cert_dn[X509_ORGANIZATION] ? + cert->ca_cert_dn[X509_ORGANIZATION] : not_part_of_cert); + + if (cert->ca_cert_dn[X509_ORGANIZATIONAL_UNIT]) + { + printf("Organizational Unit (OU):\t"); + printf("%s\n", cert->ca_cert_dn[X509_ORGANIZATIONAL_UNIT]); + } + + if (cert->ca_cert_dn[X509_LOCATION]) + { + printf("Location (L):\t\t\t"); + printf("%s\n", cert->ca_cert_dn[X509_LOCATION]); + } + + if (cert->ca_cert_dn[X509_COUNTRY]) + { + printf("Country (C):\t\t\t"); + printf("%s\n", cert->ca_cert_dn[X509_COUNTRY]); + } + + if (cert->ca_cert_dn[X509_STATE]) + { + printf("State (ST):\t\t\t"); + printf("%s\n", cert->ca_cert_dn[X509_STATE]); + } + + printf("Not Before:\t\t\t%s", ctime(&cert->not_before)); + printf("Not After:\t\t\t%s", ctime(&cert->not_after)); + printf("RSA bitsize:\t\t\t%d\n", cert->rsa_ctx->num_octets*8); + printf("Sig Type:\t\t\t"); + switch (cert->sig_type) + { + case SIG_TYPE_MD5: + printf("MD5\n"); + break; + case SIG_TYPE_SHA1: + printf("SHA1\n"); + break; + case SIG_TYPE_SHA256: + printf("SHA256\n"); + break; + case SIG_TYPE_SHA384: + printf("SHA384\n"); + break; + case SIG_TYPE_SHA512: + printf("SHA512\n"); + break; + default: + printf("Unrecognized: %d\n", cert->sig_type); + break; + } + + if (ca_cert_ctx) + { + int pathLenConstraint = 0; + char buff[64]; + printf("Verify:\t\t\t\t%s\n", + x509_display_error(x509_verify(ca_cert_ctx, cert, + &pathLenConstraint), buff)); + } + +#if 0 + print_blob("Signature", cert->signature, cert->sig_len); + bi_print("Modulus", cert->rsa_ctx->m); + bi_print("Pub Exp", cert->rsa_ctx->e); +#endif + + if (ca_cert_ctx) + { + x509_print(cert->next, ca_cert_ctx); + } + + TTY_FLUSH(); +} + +const char * x509_display_error(int error, char *buff) +{ + switch (error) + { + case X509_OK: + strcpy_P(buff, "Certificate verify successful"); + return buff; + + case X509_NOT_OK: + strcpy_P(buff, "X509 not ok"); + return buff; + + case X509_VFY_ERROR_NO_TRUSTED_CERT: + strcpy_P(buff, "No trusted cert is available"); + return buff; + + case X509_VFY_ERROR_BAD_SIGNATURE: + strcpy_P(buff, "Bad signature"); + return buff; + + case X509_VFY_ERROR_NOT_YET_VALID: + strcpy_P(buff, "Cert is not yet valid"); + return buff; + + case X509_VFY_ERROR_EXPIRED: + strcpy_P(buff, "Cert has expired"); + return buff; + + case X509_VFY_ERROR_SELF_SIGNED: + strcpy_P(buff, "Cert is self-signed"); + return buff; + + case X509_VFY_ERROR_INVALID_CHAIN: + strcpy_P(buff, "Chain is invalid (check order of certs)"); + return buff; + + case X509_VFY_ERROR_UNSUPPORTED_DIGEST: + strcpy_P(buff, "Unsupported digest"); + return buff; + + case X509_INVALID_PRIV_KEY: + strcpy_P(buff, "Invalid private key"); + return buff; + + case X509_VFY_ERROR_BASIC_CONSTRAINT: + strcpy_P(buff, "Basic constraint invalid"); + return buff; + + default: + strcpy_P(buff, "Unknown"); + return buff; + } +} +#endif /* CONFIG_SSL_FULL_MODE */ + diff --git a/tools/sdk/axtls/tools/make_certs.sh b/tools/sdk/axtls/tools/make_certs.sh new file mode 100644 index 0000000000..fc6cc90ae8 --- /dev/null +++ b/tools/sdk/axtls/tools/make_certs.sh @@ -0,0 +1,256 @@ +#!/bin/sh +# +# Copyright (c) 2007-2016, 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. +# + +AXDIR=`pwd`/`dirname $0` +CWD=`mktemp -d` && cd $dir +cd $CWD + +# +# Generate the certificates and keys for testing. +# + +PROJECT_NAME="axTLS Project" + +# Generate the openssl configuration files. +cat > ca_cert.conf << EOF +[ req ] +distinguished_name = req_distinguished_name +prompt = no +req_extensions = v3_ca + +[ req_distinguished_name ] + O = $PROJECT_NAME Dodgy Certificate Authority + +[ v3_ca ] +basicConstraints = critical, CA:true +keyUsage = critical, cRLSign, keyCertSign, digitalSignature +EOF + +cat > certs.conf << EOF +[ req ] +distinguished_name = req_distinguished_name +prompt = no +req_extensions = v3_usr_cert + +[ req_distinguished_name ] + O = $PROJECT_NAME + CN = localhost + +[ v3_usr_cert ] +basicConstraints = critical, CA:false +keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment +subjectAltName = @alt_names + +[alt_names] +DNS.1 = www.example.net +DNS.2 = www.example.org +EOF + +cat > device_cert.conf << EOF +[ req ] +distinguished_name = req_distinguished_name +prompt = no + +[ req_distinguished_name ] + O = $PROJECT_NAME Device Certificate +EOF + +cat > intermediate_ca.conf << EOF +[ req ] +distinguished_name = req_distinguished_name +prompt = no +req_extensions = v3_intermediate_ca + +[ req_distinguished_name ] + O = $PROJECT_NAME Intermediate CA + +[ v3_intermediate_ca ] +basicConstraints = critical, CA:true, pathlen:0 +keyUsage = cRLSign, keyCertSign, digitalSignature +EOF + +cat > intermediate_ca2.conf << EOF +[ req ] +distinguished_name = req_distinguished_name +prompt = no +req_extensions = v3_intermediate_ca2 + +[ req_distinguished_name ] + O = $PROJECT_NAME Intermediate 2 CA + +[ v3_intermediate_ca2 ] +basicConstraints = critical, CA:true, pathlen:10 +keyUsage = encipherOnly, keyCertSign, decipherOnly +EOF + +# private key generation +openssl genrsa -out axTLS.ca_key.pem 2048 +openssl genrsa -out axTLS.key_1024.pem 1024 +openssl genrsa -out axTLS.key_2048.pem 2048 +openssl genrsa -out axTLS.key_4096.pem 4096 +openssl genrsa -out axTLS.key_device.pem 2048 +openssl genrsa -out axTLS.key_intermediate_ca.pem 2048 +openssl genrsa -out axTLS.key_intermediate_ca2.pem 2048 +openssl genrsa -out axTLS.key_end_chain.pem 2048 +openssl genrsa -aes128 -passout pass:abcd -out axTLS.key_aes128.pem 1024 +openssl genrsa -aes256 -passout pass:abcd -out axTLS.key_aes256.pem 1024 + +# convert private keys into DER format +openssl rsa -in axTLS.key_1024.pem -out axTLS.key_1024 -outform DER +openssl rsa -in axTLS.key_2048.pem -out axTLS.key_2048 -outform DER +openssl rsa -in axTLS.key_4096.pem -out axTLS.key_4096 -outform DER + +# cert requests +openssl req -out axTLS.ca_x509.csr -key axTLS.ca_key.pem -new \ + -config ./ca_cert.conf +openssl req -out axTLS.x509_1024.csr -key axTLS.key_1024.pem -new \ + -config ./certs.conf +openssl req -out axTLS.x509_2048.csr -key axTLS.key_2048.pem -new \ + -config ./certs.conf +openssl req -out axTLS.x509_4096.csr -key axTLS.key_4096.pem -new \ + -config ./certs.conf +openssl req -out axTLS.x509_device.csr -key axTLS.key_device.pem -new \ + -config ./device_cert.conf +openssl req -out axTLS.x509_intermediate_ca.csr \ + -key axTLS.key_intermediate_ca.pem -new \ + -config ./intermediate_ca.conf +openssl req -out axTLS.x509_intermediate_ca2.csr \ + -key axTLS.key_intermediate_ca2.pem -new \ + -config ./intermediate_ca2.conf +openssl req -out axTLS.x509_end_chain.csr -key axTLS.key_end_chain.pem -new \ + -config ./certs.conf +openssl req -out axTLS.x509_aes128.csr -key axTLS.key_aes128.pem \ + -new -config ./certs.conf -passin pass:abcd +openssl req -out axTLS.x509_aes256.csr -key axTLS.key_aes256.pem \ + -new -config ./certs.conf -passin pass:abcd + +# generate the actual certs. +openssl x509 -req -in axTLS.ca_x509.csr -out axTLS.ca_x509.pem \ + -sha1 -days 5000 -signkey axTLS.ca_key.pem \ + -CAkey axTLS.ca_key.pem -extfile ./ca_cert.conf -extensions v3_ca +openssl x509 -req -in axTLS.ca_x509.csr -out axTLS.ca_x509_sha256.pem \ + -sha256 -days 5000 -signkey axTLS.ca_key.pem \ + -CAkey axTLS.ca_key.pem -extfile ./ca_cert.conf -extensions v3_ca +openssl x509 -req -in axTLS.x509_1024.csr -out axTLS.x509_1024.pem \ + -sha1 -CAcreateserial -days 5000 \ + -CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem +openssl x509 -req -in axTLS.x509_1024.csr -out axTLS.x509_1024_sha256.pem \ + -sha256 -CAcreateserial -days 5000 \ + -CA axTLS.ca_x509_sha256.pem -CAkey axTLS.ca_key.pem +openssl x509 -req -in axTLS.x509_1024.csr -out axTLS.x509_1024_sha384.pem \ + -sha384 -CAcreateserial -days 5000 \ + -CA axTLS.ca_x509_sha256.pem -CAkey axTLS.ca_key.pem +openssl x509 -req -in axTLS.x509_1024.csr -out axTLS.x509_1024_sha512.pem \ + -sha512 -CAcreateserial -days 5000 \ + -CA axTLS.ca_x509_sha256.pem -CAkey axTLS.ca_key.pem +openssl x509 -req -in axTLS.x509_2048.csr -out axTLS.x509_2048.pem \ + -sha1 -CAcreateserial -days 5000 \ + -CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem +openssl x509 -req -in axTLS.x509_4096.csr -out axTLS.x509_4096.pem \ + -sha1 -CAcreateserial -days 5000 \ + -CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem +openssl x509 -req -in axTLS.x509_device.csr -out axTLS.x509_device.pem \ + -sha1 -CAcreateserial -days 5000 \ + -CA axTLS.x509_1024.pem -CAkey axTLS.key_1024.pem +openssl x509 -req -in axTLS.x509_intermediate_ca.csr -out axTLS.x509_intermediate_ca.pem \ + -sha256 -CAcreateserial -days 5000 \ + -CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem \ + -extfile ./intermediate_ca.conf -extensions v3_intermediate_ca +openssl x509 -req -in axTLS.x509_intermediate_ca2.csr -out axTLS.x509_intermediate_ca2.pem \ + -sha256 -CAcreateserial -days 5000 \ + -CA axTLS.x509_intermediate_ca.pem \ + -CAkey axTLS.key_intermediate_ca.pem \ + -extfile ./intermediate_ca2.conf -extensions v3_intermediate_ca2 +openssl x509 -req -in axTLS.x509_end_chain.csr -out axTLS.x509_end_chain.pem \ + -sha256 -CAcreateserial -days 5000 \ + -CA axTLS.x509_intermediate_ca.pem \ + -CAkey axTLS.key_intermediate_ca.pem \ + -extfile ./certs.conf -extensions v3_usr_cert +# basic constraint path len failure +openssl x509 -req -in axTLS.x509_end_chain.csr \ + -out axTLS.x509_end_chain_bad.pem \ + -sha256 -CAcreateserial -days 5000 \ + -CA axTLS.x509_intermediate_ca2.pem \ + -CAkey axTLS.key_intermediate_ca2.pem \ + -extfile ./certs.conf -extensions v3_usr_cert +cat axTLS.x509_intermediate_ca.pem >> axTLS.x509_intermediate_ca2.pem +openssl x509 -req -in axTLS.x509_aes128.csr \ + -out axTLS.x509_aes128.pem \ + -sha1 -CAcreateserial -days 5000 \ + -CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem +openssl x509 -req -in axTLS.x509_aes256.csr \ + -out axTLS.x509_aes256.pem \ + -sha1 -CAcreateserial -days 5000 \ + -CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem + +# note: must be root to do this +DATE_NOW=`date` +if date -s "Jan 1 2025"; then +openssl x509 -req -in axTLS.x509_1024.csr -out axTLS.x509_bad_before.pem \ + -sha1 -CAcreateserial -days 365 \ + -CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem +date -s "$DATE_NOW" +touch axTLS.x509_bad_before.pem +fi +openssl x509 -req -in axTLS.x509_1024.csr -out axTLS.x509_bad_after.pem \ + -sha1 -CAcreateserial -days -365 \ + -CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem + +# some cleanup +rm axTLS*.csr +rm *.srl +rm *.conf + +# need this for the client tests +openssl x509 -in axTLS.ca_x509.pem -outform DER -out axTLS.ca_x509.cer +openssl x509 -in axTLS.x509_1024.pem -outform DER -out axTLS.x509_1024.cer +openssl x509 -in axTLS.x509_2048.pem -outform DER -out axTLS.x509_2048.cer +openssl x509 -in axTLS.x509_4096.pem -outform DER -out axTLS.x509_4096.cer + +# generate pkcs8 files (use RC4-128 for encryption) +openssl pkcs8 -in axTLS.key_1024.pem -passout pass:abcd -topk8 -v1 PBE-SHA1-RC4-128 -out axTLS.encrypted_pem.p8 +openssl pkcs8 -in axTLS.key_1024.pem -passout pass:abcd -topk8 -outform DER -v1 PBE-SHA1-RC4-128 -out axTLS.encrypted.p8 +openssl pkcs8 -in axTLS.key_1024.pem -nocrypt -topk8 -out axTLS.unencrypted_pem.p8 +openssl pkcs8 -in axTLS.key_1024.pem -nocrypt -topk8 -outform DER -out axTLS.unencrypted.p8 + +# generate pkcs12 files (use RC4-128 for encryption) +openssl pkcs12 -export -in axTLS.x509_1024.pem -inkey axTLS.key_1024.pem -certfile axTLS.ca_x509.pem -keypbe PBE-SHA1-RC4-128 -certpbe PBE-SHA1-RC4-128 -name "p12_with_CA" -out axTLS.withCA.p12 -password pass:abcd +openssl pkcs12 -export -in axTLS.x509_1024.pem -inkey axTLS.key_1024.pem -keypbe PBE-SHA1-RC4-128 -certpbe PBE-SHA1-RC4-128 -name "p12_without_CA" -out axTLS.withoutCA.p12 -password pass:abcd +openssl pkcs12 -export -in axTLS.x509_1024.pem -inkey axTLS.key_1024.pem -keypbe PBE-SHA1-RC4-128 -certpbe PBE-SHA1-RC4-128 -out axTLS.noname.p12 -password pass:abcd + +# PEM certificate chain +cat axTLS.ca_x509.pem >> axTLS.x509_device.pem + +# set default key/cert for use in the server +xxd -i axTLS.x509_1024.cer | sed -e \ + "s/axTLS_x509_1024_cer/default_certificate/" > $AXDIR/../ssl/cert.h +xxd -i axTLS.key_1024 | sed -e \ + "s/axTLS_key_1024/default_private_key/" > $AXDIR/../ssl/private_key.h diff --git a/tools/sdk/axtls/util/time.h b/tools/sdk/axtls/util/time.h new file mode 100644 index 0000000000..78e37b1d39 --- /dev/null +++ b/tools/sdk/axtls/util/time.h @@ -0,0 +1,11 @@ +#ifndef TIME_H +#define TIME_H + +struct timeval +{ + time_t tv_sec; + long tv_usec; +}; + + +#endif //TIME_H diff --git a/tools/sdk/axtls/www/index.html b/tools/sdk/axtls/www/index.html new file mode 100755 index 0000000000..2b1d8b3eb6 --- /dev/null +++ b/tools/sdk/axtls/www/index.html @@ -0,0 +1,7103 @@ + + + + + + + + + + + + axTLS Embedded SSL - changes, notes and errata + + + + + + + + + + + + + +
+
+
+
+
changes, notes and errata
+
Type the text for 'YourName'
+
@@bgcolor(#ff0000):color(#ffffff):Changes for 2.1.2 (2016-12-31)@@\n\n!!__SSL Library__\n* Basic constraint/key usage v3 extensions now supported\n* Test harness must now be run without built-in default cert\n@@bgcolor(#ff0000):color(#ffffff):Changes for 2.1.1 (2016-12-20)@@\n\n!!__SSL Library__\n* X509 State, country and location are now used for verification and display.\n* SNI hostname memory is now managed by the calling application\n* X509 version number is checked before processing v3 extensions.\n@@bgcolor(#ff0000):color(#ffffff):Changes for 2.1.0 (2016-12-13)@@\n\n!!__SSL Library__\n* SNI added\n* Some non-C sample code updated.\n@@bgcolor(#ff0000):color(#ffffff):Changes for 2.0.1 (2016-08-30)@@\n\n!!__SSL Library__\n* ~RC4 only used if ~PKCS12 is used.\n* Buffer sizes tightned up.\n* Buffer check on client handshake due to some incompatibilities.\n@@bgcolor(#ff0000):color(#ffffff):Changes for 2.0.0 (2016-08-17)@@\n\n!!__SSL Library__\n* Support for TLS 1.2\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.5.4 (2016-07-07)@@\n\n!!__SSL Library__\n* Fixed client certificate issue where there is no client certificate and a certificate verify msg was still being sent.\n* Tag 64-bit constants with "LL" (e.g. keep ~AVR32 gcc happy)\n* Removed ~RC4 from the list of ciphers\n* Can handle chains that are out of order (thanks Paul Johnstone)\n* Removed some printfs in skeleton mode\n* Removed endian.h as it was causing some porting issues\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.5.3 (2015-04-30)@@\n\n!!__SSL Library__\n* Added named unions to ~SHA512 code as some compilers don't support it\n* Some other porting suggesions from Chris Ghormley\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.5.2 (2015-03-10)@@\n\n!!__SSL Library__\n* ~SHA384/~SHA512 support added\n* Security issue fixed where a plain text could be injected before the handshake was completed\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.5.1 (2014-11-19)@@\n\n!!__SSL Library__\n* ~SHA256 support added\n* All padding/separator bytes checked in ~RSA_decrypt()\n* Added check to get_asn1_length() to limit the number of octets and to not allow overflow\n* ~MD2 removed\n* Return code checked for get_random()\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.5.0 (2014-10-31)@@\n\n!!__SSL Library__\n* Fixed array access out of bounds bug in add_cert() (thanks Ole Reinhardt)\n* Fix handling of return values of ~SOCKET_READ in process_sslv23_client_hello() (thanks Ole Reinhardt)\n* added generalized time for certificates\n* added printf changes from Fabian Frank to stop warnings/errors\n* Moved setting encryption flags to after handshake completion (thanks Eric Hu)\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.4.9@@\n\n!!__SSL Library__\n* Fixed issue where the Chrome browser could not connect. This was due to Chrome sending different version numbers in its record header and client hello. ~AxTLS has been modified to use the client hello version as part of ~RFC5246.\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.4.8@@\n\n!!__SSL Library__\n* Fixed issue where the stdint typedefs were not imported by default (stdint.h had to be included explicity) (thanks Anthony G. Basile)\n\n!!__axhttpd__\n* The password hash broke due to an over zealous buffer overflow check. \n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.4.6@@\n\n!!__SSL Library__\n* Fixed issue where the stdint typedefs were not imported by default (stdint.h had to be included explicity) (thanks Anthony G. Basile)\n* Fixed RNG initialization issue where client library was performed incorrectly (thanks Gilles Boccon~-Gibod). \n\n!!__axhttpd__\n* Now compiles properly under TCP/IP v6.\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.4.5@@\n\n!!__SSL Library__\n* Fixed possible buffer overflow when doing base64 decoding (thanks Emil Kvarnhammar).\n* Fixed unicode parsing error in certificates (thanks Eric Hu)\n\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.4.4@@\n\n!!__axhttpd__\n* Allow other CGI applications (such as PHP) to call HTML files from their command line.\n\n!!__SSL Library__\n* Fixed memory leak with invalid certificates (thanks Jon Trauntvein)\n* Fixed issue with non-blocking client connections not working properly (thanks Richard Titmuss).\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.4.3@@\n\n!!__SSL Library__\n* axtlswrap compilation error fixed.\n\n!!__axhttpd__\n* added '-w' command-line option to set the webroot directory.\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.4.2@@\n\n!!__SSL Library__\n* bi_export could have a buffer overrun with incorrect input (thanks Gilles ~Boccon-Gibod - 3334305)\n\n!!__axhttpd__\n* ~RFC1123 time format used in the headers.\n* Expires heading added (current time + ~CONFIG_HTTP_TIMEOUT)\n* UTC/localtime issue with ~If-Modified-Since header.\n\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.4.1@@\n\n!!__SSL Library__\n* Allow reading of ~PKCS8/12 unencrypted keys in PEM format and mconf will allow the option in server mode (thanks Steve Bennett).\n* Issue where comparing a null and an empty string could return a false positive for cert check (thanks Gilles ~Boccon-Gibod - 3310885).\n* -fPIC added as a Linux compile option.\n\n!!__axhttpd__\n* Killing connections on session timeout is guaranteed.\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.4.0@@\n\n!!__SSL Library__\n* TLS v1.1 implemented and is enabled by default.\n* Closure alerts implemented correctly.\n* Fixed issue with ~SSLv23 hello versioning. \n \n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.3.4@@\n\n!!__SSL Library__\n* SSL 2.0 client hello is turned off by default as per RFC 4346 Appendix E.\n* Client determines the cipher suite selected rather than the server as per RFC 4346 7.4.1.2.\n* Guard against timing HMAC timing attacks as per RFC 4346 6.2.3.2.\n* Fixed ~SOCKET_WRITE buffer issue (thanks Hardy Griech - 3177419)\n* Fixed variable length MAC issue as used by gnutls.\n* Fixed version issue when TLS >=1.1 is used.\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.3.2@@\n\n!!__SSL Library__\n* Loading of PEM certificate bundles now loads CA certs properly.\n* ssl_client_new() can now be broken up into an ssl_client_new() and successive ssl_read()'s now by setting the ~SSL_CONNECT_IN_PARTS as an option in ssl_ctx_new().\n* Non-blocked mode is now not a requirement but calls may still be blocked.\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.3.1@@\n\n!!__SSL Library__\n* Certificate bundles which contain "invalid" certificates (i.e. invalid digests types etc) are ignored rather than cause failure.\n\n!!__axhttpd__\n* ~HTTPv1.0 packets close a connection upon completion.\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.3.0@@\n\n!!__SSL Library__\n* Close notify is now sent as an error code from ssl_read(). Server code should be modified to check for ~SSL_CLOSE_NOTIFY (thanks to Eric Hu - 3132700).\n* regular_square() issue fixed (3078672)\n* partial_multiply() removed and merged with regular_multiply() (3078372).\n* Invalid session id size now returns ~SSL_ERROR_INVALID_SESSION (thanks to Hardy Griech - 3072881)\n* q-dash issue with Barrett reduction fixed (thanks to Hardy Griech - 3079291).\n* PEM file detection now looks for "-BEGIN" in any part of the file rather than at the start (3123838).\n* 8/16/32 bit native int sizes can be selected in configuration.\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.2.7@@\n\n!!__SSL Library__\n* A fix to find_max_exp_index() (thanks to Hardy Griech).\n* Check is made to get_cipher_info() if the appropriate cipher is not found (thanks to Hardy Griech).\n* Extra x509_free() removed from do_client_connect().\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.2.5@@\n\n!!__SSL Library__\n* The custom RNG updated to use an entropy pool (with better hooks to use counters).\n\n!!__axhttpd__\n* Headers are case insensitive (thanks to Joe Pruett for this and the following).\n* Child zombie issue fixed.\n* EOF on ~POSTs fixed.\n* Expect is ignored.\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.2.4@@\n\n!!__SSL Library__\n* Client renegotiation now results in an error. This is the result of a security flaw described in this paper http://extendedsubset.com/Renegotiating_TLS.pdf, and also is explained in detail here http://www.cupfighter.net/index.php/2009/11/tls-renegotiation-attack/.\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.2.3@@\n\n!!__SSL Library__\n* v3 certificates with ~SANs now supports (thanks to Carsten Sørensen).\n* axtlswrap added - a port of sslwrap (thanks to Steve Bennett)\n\n!!__axhttpd__\n* shutdown() called before socket close in CGI (thanks to Tom Brown)\n* command-line parameters to specify the http/https port.\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.2.2@@\n\n!!__axhttpd__\n* File uploads over 1kB (but under MAXPOSTDATASIZE) are now supported.\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.2.1@@\n\n!!__SSL Library__\n* Certificate verification now works for Firefox.\n* Extended the openssl API.\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.2.0@@\n\n!!__SSL Library__\n* A self-signed certificate will be verified as ok provided that that it is on the certificate authority list.\n* Certificates are not verified when added as certificate authorities (since self-signed and expired certificates can be added to browsers etc)\n\n@@bgcolor(#ff0000):color(#ffffff):Changes for 1.1.9@@\n\n!!__SSL Library__\n* Now support MS IIS resource kit certificates (thanks to Carsten Sørensen).\n* Fixed a memory leak when freeing more than one CA certificate.\n* The bigint library had a problem with squaring which affected classical reduction (thanks to Manuel Klimek).\n\n!!__axhttpd__\n* Brought back setuid()/setgid() as an option.\n\n!@@bgcolor(#ff0000):color(#ffffff):Changes for 1.1.8@@\n\n!!__SSL Library__\n* Now using a BSD style license.\n* Self-signed certificates can now be automatically generated (the keys still need to be provided).\n* A new API call //ssl_x509_create()// can be used to programatically create the certificate.\n* Certificate/keys can be loaded automatically given a file location.\n\n!@@bgcolor(#ff0000):color(#ffffff):Changes for 1.1.7@@\n\n!!__SSL Library__\n\n* Variable sized session id's is now better handled for session caching. It has meant a new API call //ssl_get_session_id_size()// and a change to //ssl_client_new()// to define the session id size.\n* Muliple records with a single header are now better supported (thanks to Hervé Sibert).\n* ~MD2 added for Verisign root cert verification (thanks to Byron Rakitzis).\n* The ~MD5/~SHA1 digests are calculated incrementally to reduce memory (thanks to Byron Rakitzis).\n* The bigint cache is now cleared regularly to reduce memory.\n\n!!__axhttpd__\n\n* Improved the POST handling (thanks to Christian Melki).\n* CSS files now work properly.\n* Lua's CGI launcher location is configurable.\n* //vfork()// is now used for CGI for performance reasons.\n\n!@@bgcolor(#ff0000):color(#ffffff):Changes for 1.1.6@@\n\n!!__SSL Library__\n\n* ~RC4 speed improvements\n* Lua samples/bindings now work properly\n\n!@@bgcolor(#ff0000):color(#ffffff):Changes for 1.1.5@@\n\n!!__SSL Library__\n\n* Session id's can now be variable lengths in server hello messages.\n* 0 length client certificates are now supported.\n* ssl_version() now returns just the version and not the date.\n* ssl_write() was not sending complete packets under load.\n\n!!__axhttpd__\n\n* Completely updated the CGI code.\n* Lua now integrated - Lua scripts and Lua Pages now run.\n\n!@@bgcolor(#ff0000):color(#ffffff):Changes for 1.1.4@@\n\n!!__SSL Library__\n\n* Fixed a Win32 crypto library issue with non-Administrator users\n* Removed compiler warnings that showed up in ~FC6.\n* GNU TLS certificates are now accepted.\n* Separated the send/receive headers for HMAC calculations.\n* Fixed a compilation problem with swig/perl/~FC6.\n* Fixed an issue with loading PEM CA certificates.\n\n!!__axhttpd__\n\n* Made //setuid()/setgid()// call an mconf option.\n* Made //chroot()// an mconf option. Default to //chdir()// instead.\n* Removed optional permissions checking.\n\n!@@bgcolor(#ff0000):color(#ffffff):Changes for 1.1.1@@\n\n!!__SSL Library__\n\n* AES should now work on 16bit processors (there was an alignment problem).\n* Various freed objects are cleared before freeing.\n* Header files now installed in ///usr/local/include/axTLS//.\n* -DCYGWIN replaced with -~DCONFIG_PLATFORM_CYGWIN (and the same for Solaris).\n* removed "-noextern" option in Swig. Fixed some other warnings in Win32.\n* SSLCTX changed to ~SSL_CTX (to be consistent with openssl). SSLCTX still exists for backwards compatibility.\n* malloc() and friends call abort() on failure.\n* Fixed a memory leak in directory listings.\n* Added openssl() compatibility functions.\n* Fixed Cygwin 'make install' issue.\n\n!!__axhttpd__\n\n* main.c now becomes axhttpd.c.\n* Header file issue fixed (in mime_types.c).\n* //chroot()// now used for better security.\n* Basic authentication implemented (via .htpasswd).\n* SSL access/denial protection implemented (via .htaccess).\n* Directory access protection implemented (via .htaccess).\n* Can now have more than one CGI file extension in mconf.\n* "~If-Modified-Since" request now handled properly.\n* Performance tweaks to remove //ssl_find()//.
[[Read Me]]
axTLS uses a BSD style license:\n\nCopyright (c) 2008, Cameron Rich All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer. Redistributions in binary\nform must reproduce the above copyright notice, this list of conditions and\nthe following disclaimer in the documentation and/or other materials\nprovided with the distribution. Neither the name of the axTLS Project nor\nthe names of its contributors may be used to endorse or promote products\nderived from this software without specific prior written permission. \n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\nOUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\nDAMAGE.
[[Read Me]] \n[[Changelog]]\n[[axhttpd]]\n[[License]]
+
<div class='header' macro='gradient vert #390108 #900'>\n<div class='headerShadow'>\n<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>&nbsp;\n<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>\n</div>\n<div class='headerForeground'>\n<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>&nbsp;\n<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>\n</div>\n</div>\n<div id='mainMenu'>\n<div refresh='content' tiddler='MainMenu'></div>\n</div>\n<div id='sidebar'>\n<div id='sidebarOptions' refresh='content' tiddler='SideBarOptions'></div>\n<div id='sidebarTabs' refresh='content' force='true' tiddler='SideBarTabs'></div>\n</div>\n<div id='displayArea'>\n<div id='messageArea'></div>\n<div id='tiddlerDisplay'></div>\n</div>
+
!@@bgcolor(#ff0000):color(#ffffff):axTLS Quick Start Guide@@\n\nThis is a guide to get a small SSL web-server up and running quickly.\n\n!!__Introduction__\n\nThe axTLS project is an SSL client/server library using the ~TLSv1 protocol. It is designed to be small and fast, and is suited to embedded projects. A web server is included.\n\nThe basic web server + SSL library is around 60-70kB and is configurable for features or size.\n\n!!__Compilation__\n\nAll platforms require GNU make. This means on Win32 that Cygwin needs to be installed with "make" and various developer options selected.\n\nConfiguration now uses a tool called "mconf" which gives a nice way to configure options (similar to what is used in ~BusyBox and the Linux kernel).\n\nYou should be able to compile axTLS simply by extracting it, change into the extracted directory and typing:\n\n{{indent{{{{> make}}}\n\nSelect your platform type, save the configuration, exit, and then type "make" again.\n\nIf all goes well, you should end up with an executable called "axhttpd" (or axhttpd.exe) in the //_stage// directory.\n\nTo play with all the various axTLS options, type:\n\n{{indent{{{{> make menuconfig}}}\n\nSave the new configuration and rebuild.\n\n!!__Running it__\n\nTo run it, go to the //_stage// directory, and type (as superuser):\n\n{{indent{{{{> axhttpd}}}\n\nNote: you may have to set your ~LD_LIBRARY_PATH - e.g. go to //_stage// and type //export ~LD_LIBRARY_PATH=`pwd`//\n\nAnd then point your browser at https://127.0.0.1 And you should see a this html page with a padlock appearing on your browser. or type http://127.0.0.1 to see the same page unencrypted.\n\n!!__The axssl utilities__\n\nThe axssl suite of tools are the SSL test tools in the various language bindings. They are:\n\n* axssl - C sample\n* axssl.csharp - C# sample\n* axssl.vbnet - VB.NET sample\n* axtls.jar - Java sample\n* axssl.pl - Perl sample\n* axssl.lua - Lua sample\n\nAll the tools have identical command-line parameters. e.g. to run something interesting:\n\n{{indent{{{{> axssl s_server -verify -CAfile ../ssl/test/axTLS.ca_x509}}}\n\nand\n\n{{indent{{{{> axssl s_client -cert ../ssl/test/axTLS.x509_1024 -key ../ssl/test/axTLS.key_1024 -reconnect}}}\n\n!!!!C#\n\nIf building under Linux or other non-Win32 platforms, Mono must be installed and the executable is run as:\n\n{{indent{{{{> mono axssl.csharp.exe ...}}}\n\n!!!!Java\n\nThe java version is run as:\n\n{{indent{{{{> java -jar axtls.jar <options>}}}\n\n!!!!Perl\n\n{{indent{{{{> [perl] ./axssl.pl <options>}}}\n\nIf running under Win32, be sure to use the correct version of Perl (i.e. ~ActiveState's version works ok).\n\n!!!!Lua\n\n{{indent{{{{> [lua] ./axssl.lua <options>}}}\n\n!__Known Issues__\n\n* Firefox doesn't handle legacy ~SSLv2 at all well. Disabling ~SSLv2 still initiates a ~SSLv23 handshake (v1.5). And continuous pressing of the "Reload" page instigates a change to ~SSLv3 for some reason (even though the TLS 1.0 option is selected). This will cause a "Firefox and <server> cannot communicate securely because they have no common encryption algorithms" (v1.5), or "Firefox can't connect to <server> because the site uses a security protocol which isn't enabled" (v2.0). See bugzilla issues 343543 and 359484 (Comment #7). It's all broken (hopefully fixed soon).\n* Perl/Java bindings don't work on 64 bit Linux machines. I can't even compile the latest version of Perl on an ~AMD64 box (using ~FC3).\n* Java 1.4 or better is required for the Java interfaces.\n* Processes that fork can't use session resumption unless some form of IPC is used.\n* Ensure libperl.so and libaxtls.so are in the shared library path when running with the perl bindings. A way to do this is with:\n\n{{indent{{{{> export LD_LIBRARY_PATH=`perl -e 'use Config; print $Config{archlib};'`/CORE:.}}}\n* The lua sample requires the luabit library from http://luaforge.net/projects/bit.\n\n!!!!Win32 issues\n\n* Be careful about doing .NET executions on network drives - .NET complains with security exceptions on the binary. //TODO: Add a manifest file to prevent this.//\n* CGI has been removed from Win32 - it needs a lot more work to get it right.\n* The default Microsoft .NET SDK is v2.0.50727. Download from: http://msdn.microsoft.com/netframework/downloads/updates/default.aspx.\n\n!!!!Solaris issues\n\n* mconf doesn't work well - some manual tweaking is required for string values.\n* GNU make is required and needs to be in $PATH.\n* To get swig's library dependencies to work (and for the C library to be found), I needed to type:\n\n{{indent{{{{> export LD_LIBRARY_PATH=/usr/local/gcc-3.3.1/lib:.}}}\n\n!!!!Cygwin issues\n\n* The bindings all compile but don't run under Cygwin with the exception of Perl. This is due to win32 executables being incompatible with Cygwin libraries.\n\n
+
changes, notes and errata
+
axTLS Embedded SSL
+
http://axtls.cerocclub.com.au
+
/***\nhttp://tiddlystyles.com/#theme:DevFire\nAuthor: Clint Checketts\n***/\n\n/*{{{*/\nbody {\nbackground: #000;\n}\n/*}}}*/\n/***\n!Link styles /% ============================================================= %/\n***/\n/*{{{*/\na,\na.button,\n#mainMenu a.button,\n#sidebarOptions .sliderPanel a{\n color: #ffbf00;\n border: 0;\n background: transparent;\n}\n\na:hover,\na.button:hover,\n#mainMenu a.button:hover,\n#sidebarOptions .sliderPanel a:hover\n#sidebarOptions .sliderPanel a:active{\n color: #ff7f00;\n border: 0;\n border-bottom: #ff7f00 1px dashed;\n background: transparent;\n text-decoration: none;\n}\n\n#displayArea .button.highlight{\n color: #ffbf00;\n background: #4c4c4c;\n}\n/*}}}*/\n/***\n!Header styles /% ============================================================= %/\n***/\n/*{{{*/\n.header{\n border-bottom: 2px solid #ffbf00;\n color: #fff;\n}\n\n.headerForeground a {\n color: #fff;\n}\n\n.header a:hover {\n border-bottom: 1px dashed #fff;\n}\n/*}}}*/\n/***\n!Main menu styles /% ============================================================= %/\n***/\n/*{{{*/\n#mainMenu {color: #fff;}\n#mainMenu h1{\n font-size: 1.1em;\n}\n#mainMenu li,#mainMenu ul{\n list-style: none;\n margin: 0;\n padding: 0;\n}\n/*}}}*/\n/***\n!Sidebar styles /% ============================================================= %/\n***/\n/*{{{*/\n#sidebar {\n right: 0;\n color: #fff;\n border: 2px solid #ffbf00;\n border-width: 0 0 2px 2px;\n}\n#sidebarOptions {\n background-color: #4c4c4c;\n padding: 0;\n}\n\n#sidebarOptions a{\n margin: 0;\n color: #ffbf00;\n border: 0;\n}\n#sidebarOptions a:hover {\n color: #4c4c4c;\n background-color: #ffbf00;\n\n}\n\n#sidebarOptions a:active {\n color: #ffbf00;\n background-color: transparent;\n}\n\n#sidebarOptions .sliderPanel {\n background-color: #333;\n margin: 0;\n}\n\n#sidebarTabs {background-color: #4c4c4c;}\n#sidebarTabs .tabSelected {\n padding: 3px 3px;\n cursor: default;\n color: #ffbf00;\n background-color: #666;\n}\n#sidebarTabs .tabUnselected {\n color: #ffbf00;\n background-color: #5f5f5f;\n padding: 0 4px;\n}\n\n#sidebarTabs .tabUnselected:hover,\n#sidebarTabs .tabContents {\n background-color: #666;\n}\n\n.listTitle{color: #FFF;}\n#sidebarTabs .tabContents a{\n color: #ffbf00;\n}\n\n#sidebarTabs .tabContents a:hover{\n color: #ff7f00;\n background: transparent;\n}\n\n#sidebarTabs .txtMoreTab .tabSelected,\n#sidebarTabs .txtMoreTab .tab:hover,\n#sidebarTabs .txtMoreTab .tabContents{\n color: #ffbf00;\n background: #4c4c4c;\n}\n\n#sidebarTabs .txtMoreTab .tabUnselected {\n color: #ffbf00;\n background: #5f5f5f;\n}\n\n.tab.tabSelected, .tab.tabSelected:hover{color: #ffbf00; border: 0; background-color: #4c4c4c;cursor:default;}\n.tab.tabUnselected {background-color: #666;}\n.tab.tabUnselected:hover{color:#ffbf00; border: 0;background-color: #4c4c4c;}\n.tabContents {\n background-color: #4c4c4c;\n border: 0;\n}\n.tabContents .tabContents{background: #666;}\n.tabContents .tabSelected{background: #666;}\n.tabContents .tabUnselected{background: #5f5f5f;}\n.tabContents .tab:hover{background: #666;}\n/*}}}*/\n/***\n!Message area styles /% ============================================================= %/\n***/\n/*{{{*/\n#messageArea {background-color: #666; color: #fff; border: 2px solid #ffbf00;}\n#messageArea a:link, #messageArea a:visited {color: #ffbf00; text-decoration:none;}\n#messageArea a:hover {color: #ff7f00;}\n#messageArea a:active {color: #ff7f00;}\n#messageArea .messageToolbar a{\n border: 1px solid #ffbf00;\n background: #4c4c4c;\n}\n/*}}}*/\n/***\n!Popup styles /% ============================================================= %/\n***/\n/*{{{*/\n.popup {color: #fff; background-color: #4c4c4c; border: 1px solid #ffbf00;}\n.popup li.disabled{color: #fff;}\n.popup a {color: #ffbf00; }\n.popup a:hover { background: transparent; color: #ff7f00; border: 0;}\n.popup hr {color: #ffbf00; background: #ffbf00;}\n/*}}}*/\n/***\n!Tiddler Display styles /% ============================================================= %/\n***/\n/*{{{*/\n.title{color: #fff;}\nh1, h2, h3, h4, h5 {\n color: #fff;\n background-color: transparent;\n border-bottom: 1px solid #333;\n}\n\n.subtitle{\n color: #666;\n}\n\n.viewer {color: #fff; }\n\n.viewer table{background: #666; color: #fff;}\n\n.viewer th {background-color: #996; color: #fff;}\n\n.viewer pre, .viewer code {color: #ddd; background-color: #4c4c4c; border: 1px solid #ffbf00;}\n\n.viewer hr {color: #666;}\n\n.tiddler .button {color: #4c4c4c;}\n.tiddler .button:hover { color: #ffbf00; background-color: #4c4c4c;}\n.tiddler .button:active {color: #ffbf00; background-color: #4c4c4c;}\n\n.toolbar {\n color: #4c4c4c;\n}\n\n.toolbar a.button,\n.toolbar a.button:hover,\n.toolbar a.button:active,\n.editorFooter a{\n border: 0;\n}\n\n.footer {\n color: #ddd;\n}\n\n.selected .footer {\n color: #888;\n}\n\n.highlight, .marked {\n color: #000;\n background-color: #ffe72f;\n}\n.editorFooter {\n color: #aaa;\n}\n\n.tab{\n-moz-border-radius-topleft: 3px;\n-moz-border-radius-topright: 3px;\n}\n\n.tagging,\n.tagged{\n background: #4c4c4c;\n border: 1px solid #4c4c4c; \n}\n\n.selected .tagging,\n.selected .tagged{\n background-color: #333;\n border: 1px solid #ffbf00;\n}\n\n.tagging .listTitle,\n.tagged .listTitle{\n color: #fff;\n}\n\n.tagging .button,\n.tagged .button{\n color: #ffbf00;\n border: 0;\n padding: 0;\n}\n\n.tagging .button:hover,\n.tagged .button:hover{\nbackground: transparent;\n}\n\n.selected .isTag .tagging.simple,\n.selected .tagged.simple,\n.isTag .tagging.simple,\n.tagged.simple {\n float: none;\n display: inline;\n border: 0;\n background: transparent;\n color: #fff;\n margin: 0;\n}\n\n.cascade {\n background: #4c4c4c;\n color: #ddd;\n border: 1px solid #ffbf00;\n}\n/*}}}*/
+
axhttpd is a small embedded web server using the axTLS library. It is based originally on the web server written by Doug Currie which is at http://www.hcsw.org/awhttpd.\n\n!@@bgcolor(#ff0000):color(#ffffff):axhttpd Features@@ \n\n!!__Basic Authentication__\n\nBasic Authentication uses a password file called ".htpasswd", in the directory to be protected. This file is formatted as the familiar colon-separated username/encrypted-password pair, records delimited by newlines. The protection does not carry over to subdirectories. The utility program htpasswd is included to help manually edit .htpasswd files.\n\nThe encryption of this password uses a proprietary algorithm due to the dependency of many crypt libraries on DES. An example is in [[/test_dir/no_http|https://localhost/test_dir/no_http]] (username 'abcd', password is '1234').\n\n//Note: This is an mconf enabled configuration option.//\n\n!!__SSL Protection__\n\nDirectories/files can be accessed using the 'http' or 'https' uri prefix. If normal http access for a directory needs to be disabled, then put "~SSLRequireSSL" into a '.htaccess' file in the directory to be protected. \n\nConversely, use "~SSLDenySSL" to deny access to directories via SSL.\n\nAn example is in [[/test_dir/no_http|http://localhost/test_dir/no_http]] and [[/test_dir/no_ssl|https://localhost/test_dir/no_ssl]].\n\nEntire directories can be denied access with a "Deny all" directive (regardless of SSL or authentication). An example is in [[/test_dir/bin|http://localhost/test_dir/bin]]\n\n!!__CGI__\n\nMost of the CGI 1.1 variables are now placed into the script environment and should work as normal.\n\n!!__Lua and Lua Pages__\n\nThis is a small scripting language gaining popularity in embedded applications due to its small footprint and fast speed.\n\nLua has been incorporated into the build, so simply select it and it will automatically install. Try pointing your browser at [[test_main.html|http://localhost/lua/test_main.html]] to see an example of Lua Pages.\n\n//Note: This is an mconf enabled configuration option.//\n\nThe readline development library may have to be downloaded: //yum install readline-devel//\n\n!!__Directory Listing__\n\nAn mconf option. Allow the files in directories to be displayed. An example is in [[/test_dir|http://localhost/test_dir]]\n\n!!__Other Features__\n\n* Timeout - HTTP 1.1 allows for persistent connections. This is the time allowed for this connection in seconds.\n* Daemon - Puts the process in daemon mode. \n* SSL session cache size - The size of the session cache (a heavily loaded server should maintain many sessions). A session will save on expensive SSL handshaking.\n\n
+
+ + + + +