Browse Source

Merge pull request #2340 from nodemcu/dev

2.2 master snap
Marcel Stör 6 years ago
parent
commit
67027c0d05
100 changed files with 8013 additions and 3629 deletions
  1. 1 0
      .gitignore
  2. 48 24
      Makefile
  3. 4 4
      README.md
  4. 3 0
      app/Makefile
  5. 1 1
      app/coap/coap.c
  6. 1 1
      app/driver/key.c
  7. 2 2
      app/fatfs/myfatfs.c
  8. 4 1
      app/http/httpclient.c
  9. 1 1
      app/include/arch/cc.h
  10. 211 3
      app/include/lwip/app/espconn.h
  11. 3 0
      app/include/lwip/app/espconn_tcp.h
  12. 0 53
      app/include/lwip/app/time.h
  13. 1 1
      app/include/lwip/mem.h
  14. 0 60
      app/include/lwip/sntp.h
  15. 262 142
      app/include/mbedtls/aes.h
  16. 2 1
      app/include/mbedtls/aesni.h
  17. 37 1
      app/include/mbedtls/arc4.h
  18. 3 2
      app/include/mbedtls/asn1.h
  19. 2 1
      app/include/mbedtls/asn1write.h
  20. 2 1
      app/include/mbedtls/base64.h
  21. 85 36
      app/include/mbedtls/bignum.h
  22. 3 1
      app/include/mbedtls/blowfish.h
  23. 23 13
      app/include/mbedtls/bn_mul.h
  24. 3 1
      app/include/mbedtls/camellia.h
  25. 91 59
      app/include/mbedtls/ccm.h
  26. 2 5
      app/include/mbedtls/certs.h
  27. 132 2
      app/include/mbedtls/check_config.h
  28. 310 256
      app/include/mbedtls/cipher.h
  29. 2 1
      app/include/mbedtls/cipher_internal.h
  30. 208 0
      app/include/mbedtls/cmac.h
  31. 3 113
      app/include/mbedtls/compat-1.3.h
  32. 371 65
      app/include/mbedtls/config.h
  33. 142 110
      app/include/mbedtls/ctr_drbg.h
  34. 110 6
      app/include/mbedtls/debug.h
  35. 51 0
      app/include/mbedtls/des.h
  36. 935 179
      app/include/mbedtls/dhm.h
  37. 151 88
      app/include/mbedtls/ecdh.h
  38. 196 110
      app/include/mbedtls/ecdsa.h
  39. 20 3
      app/include/mbedtls/ecjpake.h
  40. 21 4
      app/include/mbedtls/ecp.h
  41. 293 0
      app/include/mbedtls/ecp_internal.h
  42. 39 2
      app/include/mbedtls/entropy.h
  43. 23 2
      app/include/mbedtls/entropy_poll.h
  44. 26 16
      app/include/mbedtls/error.h
  45. 129 86
      app/include/mbedtls/gcm.h
  46. 2 1
      app/include/mbedtls/havege.h
  47. 2 1
      app/include/mbedtls/hmac_drbg.h
  48. 0 13
      app/include/mbedtls/mbedtls_debug.h
  49. 236 136
      app/include/mbedtls/md.h
  50. 206 9
      app/include/mbedtls/md2.h
  51. 211 9
      app/include/mbedtls/md4.h
  52. 210 8
      app/include/mbedtls/md5.h
  53. 8 7
      app/include/mbedtls/md_internal.h
  54. 10 5
      app/include/mbedtls/memory_buffer_alloc.h
  55. 11 204
      app/include/mbedtls/net.h
  56. 226 0
      app/include/mbedtls/net_sockets.h
  57. 2 1
      app/include/mbedtls/oid.h
  58. 2 1
      app/include/mbedtls/padlock.h
  59. 2 1
      app/include/mbedtls/pem.h
  60. 7 4
      app/include/mbedtls/pk.h
  61. 3 2
      app/include/mbedtls/pk_internal.h
  62. 2 1
      app/include/mbedtls/pkcs11.h
  63. 2 1
      app/include/mbedtls/pkcs12.h
  64. 2 1
      app/include/mbedtls/pkcs5.h
  65. 168 35
      app/include/mbedtls/platform.h
  66. 82 0
      app/include/mbedtls/platform_time.h
  67. 134 12
      app/include/mbedtls/ripemd160.h
  68. 632 229
      app/include/mbedtls/rsa.h
  69. 216 0
      app/include/mbedtls/rsa_internal.h
  70. 241 31
      app/include/mbedtls/sha1.h
  71. 200 39
      app/include/mbedtls/sha256.h
  72. 203 41
      app/include/mbedtls/sha512.h
  73. 294 64
      app/include/mbedtls/ssl.h
  74. 3 2
      app/include/mbedtls/ssl_cache.h
  75. 167 2
      app/include/mbedtls/ssl_ciphersuites.h
  76. 2 1
      app/include/mbedtls/ssl_cookie.h
  77. 177 16
      app/include/mbedtls/ssl_internal.h
  78. 2 1
      app/include/mbedtls/ssl_ticket.h
  79. 4 1
      app/include/mbedtls/threading.h
  80. 25 5
      app/include/mbedtls/timing.h
  81. 7 6
      app/include/mbedtls/version.h
  82. 9 7
      app/include/mbedtls/x509.h
  83. 2 1
      app/include/mbedtls/x509_crl.h
  84. 41 23
      app/include/mbedtls/x509_crt.h
  85. 9 2
      app/include/mbedtls/x509_csr.h
  86. 3 1
      app/include/mbedtls/xtea.h
  87. 35 28
      app/include/rtc/rtctime_internal.h
  88. 1 1
      app/include/sys/espconn_mbedtls.h
  89. 98 0
      app/include/sys/network_80211.h
  90. 35 18
      app/include/user_mbedtls.h
  91. 7 0
      app/include/user_modules.h
  92. 12 6
      app/include/user_version.h
  93. 3 0
      app/lua/ldo.c
  94. 6 2
      app/lua/lua.c
  95. 5 2
      app/lwip/app/espconn.c
  96. 76 2
      app/lwip/app/espconn_tcp.c
  97. 4 3
      app/lwip/app/espconn_udp.c
  98. 0 1185
      app/lwip/core/sntp.c
  99. 1 1
      app/lwip/core/tcp_in.c
  100. 8 0
      app/lwip/core/tcp_out.c

+ 1 - 0
.gitignore

@@ -1,5 +1,6 @@
 sdk/
 cache/
+.ccache/
 user_config.h
 server-ca.crt
 

+ 48 - 24
Makefile

@@ -2,24 +2,26 @@
 #
 .NOTPARALLEL:
 
-# SDK version NodeMCU is locked to
-SDK_VER:=2.1.0
+# SDK base version, as released by Espressif
+SDK_BASE_VER:=2.2.0
 
-# no patch: SDK_BASE_VER equals SDK_VER and sdk dir depends on sdk_extracted
-SDK_BASE_VER:=$(SDK_VER)
-SDK_DIR_DEPENDS:=sdk_extracted
-# with patch: SDK_BASE_VER differs from SDK_VER and sdk dir depends on sdk_patched
-#SDK_BASE_VER:=1.5.4
-#SDK_DIR_DEPENDS:=sdk_patched
+# no patch: SDK_VER equals SDK_BASE_VER and sdk dir depends on sdk_extracted
+#SDK_VER:=$(SDK_BASE_VER)
+#SDK_DIR_DEPENDS:=sdk_extracted
+
+# with patch: SDK_VER differs from SDK_BASE_VER and sdk dir depends on sdk_patched
+SDK_PATCH_VER:=f8f27ce
+SDK_VER:=$(SDK_BASE_VER)-$(SDK_PATCH_VER)
+SDK_DIR_DEPENDS:=sdk_patched
 
 SDK_FILE_VER:=$(SDK_BASE_VER)
-SDK_FILE_SHA1:=66a4272894dc1bcec19f5f8bf79fee80f60a021b
-#SDK_PATCH_VER:=$(SDK_VER)_patch_20160704
-#SDK_PATCH_SHA1:=388d9e91df74e3b49fca126da482cf822cf1ebf1
+SDK_FILE_SHA1:=8b63f1066d3560ff77f119e8ba30a9c39e7baaad
+SDK_PATCH_SHA1:=0bc21ec77b08488f04d3e1c9d161b711d07201a8
 # Ensure we search "our" SDK before the tool-chain's SDK (if any)
 TOP_DIR:=$(abspath $(dir $(lastword $(MAKEFILE_LIST))))
-SDK_DIR:=$(TOP_DIR)/sdk/esp_iot_sdk_v$(SDK_VER)
-CCFLAGS:= -I$(TOP_DIR)/sdk-overrides/include -I$(SDK_DIR)/include
+SDK_REL_DIR=sdk/esp_iot_sdk_v$(SDK_VER)
+SDK_DIR:=$(TOP_DIR)/$(SDK_REL_DIR)
+CCFLAGS:= -I$(TOP_DIR)/sdk-overrides/include -I$(TOP_DIR)/app/include/lwip/app -I$(SDK_DIR)/include
 LDFLAGS:= -L$(SDK_DIR)/lib -L$(SDK_DIR)/ld $(LDFLAGS)
 
 ifdef DEBUG
@@ -39,6 +41,7 @@ ifeq ($(OS),Windows_NT)
 		# It is xcc
 		AR = xt-ar
 		CC = xt-xcc
+		CXX = xt-xcc
 		NM = xt-nm
 		CPP = xt-cpp
 		OBJCOPY = xt-objcopy
@@ -50,6 +53,7 @@ ifeq ($(OS),Windows_NT)
 		CCFLAGS += -ffunction-sections -fno-jump-tables -fdata-sections
 		AR = xtensa-lx106-elf-ar
 		CC = xtensa-lx106-elf-gcc
+		CXX = xtensa-lx106-elf-g++
 		NM = xtensa-lx106-elf-nm
 		CPP = xtensa-lx106-elf-cpp
 		OBJCOPY = xtensa-lx106-elf-objcopy
@@ -77,6 +81,7 @@ else
 	CCFLAGS += -ffunction-sections -fno-jump-tables -fdata-sections
 	AR = xtensa-lx106-elf-ar
 	CC = $(WRAPCC) xtensa-lx106-elf-gcc
+	CXX = $(WRAPCC) xtensa-lx106-elf-g++
 	NM = xtensa-lx106-elf-nm
 	CPP = $(WRAPCC) xtensa-lx106-elf-gcc -E
 	OBJCOPY = xtensa-lx106-elf-objcopy
@@ -104,6 +109,7 @@ ESPTOOL ?= ../tools/esptool.py
 
 
 CSRCS ?= $(wildcard *.c)
+CXXSRCS ?= $(wildcard *.cpp)
 ASRCs ?= $(wildcard *.s)
 ASRCS ?= $(wildcard *.S)
 SUBDIRS ?= $(patsubst %/,%,$(dir $(filter-out tools/Makefile,$(wildcard */Makefile))))
@@ -112,10 +118,12 @@ ODIR := .output
 OBJODIR := $(ODIR)/$(TARGET)/$(FLAVOR)/obj
 
 OBJS := $(CSRCS:%.c=$(OBJODIR)/%.o) \
+        $(CXXSRCS:%.cpp=$(OBJODIR)/%.o) \
         $(ASRCs:%.s=$(OBJODIR)/%.o) \
         $(ASRCS:%.S=$(OBJODIR)/%.o)
 
 DEPS := $(CSRCS:%.c=$(OBJODIR)/%.d) \
+        $(CXXSCRS:%.cpp=$(OBJODIR)/%.d) \
         $(ASRCs:%.s=$(OBJODIR)/%.d) \
         $(ASRCS:%.S=$(OBJODIR)/%.d)
 
@@ -196,26 +204,31 @@ $(BINODIR)/%.bin: $(IMAGEODIR)/%.out
 # Should be done in top-level makefile only
 #
 
-all:	$(SDK_DIR_DEPENDS) pre_build .subdirs $(OBJS) $(OLIBS) $(OIMAGES) $(OBINS) $(SPECIAL_MKTARGETS)
+all:	sdk_pruned pre_build .subdirs $(OBJS) $(OLIBS) $(OIMAGES) $(OBINS) $(SPECIAL_MKTARGETS)
 
 .PHONY: sdk_extracted
 .PHONY: sdk_patched
+.PHONY: sdk_pruned
 
 sdk_extracted: $(TOP_DIR)/sdk/.extracted-$(SDK_BASE_VER)
 sdk_patched: sdk_extracted $(TOP_DIR)/sdk/.patched-$(SDK_VER)
+sdk_pruned: $(SDK_DIR_DEPENDS) $(TOP_DIR)/sdk/.pruned-$(SDK_VER)
 
 $(TOP_DIR)/sdk/.extracted-$(SDK_BASE_VER): $(TOP_DIR)/cache/v$(SDK_FILE_VER).zip
 	mkdir -p "$(dir $@)"
-	(cd "$(dir $@)" && rm -fr esp_iot_sdk_v$(SDK_VER) ESP8266_NONOS_SDK-$(SDK_VER) && unzip $(TOP_DIR)/cache/v$(SDK_FILE_VER).zip ESP8266_NONOS_SDK-$(SDK_VER)/lib/* ESP8266_NONOS_SDK-$(SDK_VER)/ld/eagle.rom.addr.v6.ld ESP8266_NONOS_SDK-$(SDK_VER)/include/* ESP8266_NONOS_SDK-$(SDK_VER)/bin/esp_init_data_default.bin)
-	mv $(dir $@)/ESP8266_NONOS_SDK-$(SDK_VER) $(dir $@)/esp_iot_sdk_v$(SDK_VER)
-	rm -f $(SDK_DIR)/lib/liblwip.a
+	(cd "$(dir $@)" && rm -fr esp_iot_sdk_v$(SDK_VER) ESP8266_NONOS_SDK-$(SDK_BASE_VER) && unzip $(TOP_DIR)/cache/v$(SDK_FILE_VER).zip ESP8266_NONOS_SDK-$(SDK_BASE_VER)/lib/* ESP8266_NONOS_SDK-$(SDK_BASE_VER)/ld/eagle.rom.addr.v6.ld ESP8266_NONOS_SDK-$(SDK_BASE_VER)/include/* ESP8266_NONOS_SDK-$(SDK_BASE_VER)/bin/esp_init_data_default_v05.bin)
+	mv $(dir $@)/ESP8266_NONOS_SDK-$(SDK_BASE_VER) $(dir $@)/esp_iot_sdk_v$(SDK_BASE_VER)
+	touch $@
+
+$(TOP_DIR)/sdk/.patched-$(SDK_VER): $(TOP_DIR)/cache/$(SDK_PATCH_VER).patch
+	mv $(dir $@)/esp_iot_sdk_v$(SDK_BASE_VER) $(dir $@)/esp_iot_sdk_v$(SDK_VER)
+	git apply --verbose -p1 --exclude='*VERSION' --exclude='*bin/at*' --directory=$(SDK_REL_DIR) $<
 	touch $@
 
-$(TOP_DIR)/sdk/.patched-$(SDK_VER): $(TOP_DIR)/cache/esp_iot_sdk_v$(SDK_PATCH_VER).zip
-	mkdir -p "$(dir $@)/patch"
-	(cd "$(dir $@)/patch" && unzip $(TOP_DIR)/cache/esp_iot_sdk_v$(SDK_PATCH_VER)*.zip *.a esp_init_data_default.bin && mv *.a $(SDK_DIR)/lib/ && mv esp_init_data_default.bin $(SDK_DIR)/bin/)
-	rmdir $(dir $@)/patch
-	rm -f $(SDK_DIR)/lib/liblwip.a
+$(TOP_DIR)/sdk/.pruned-$(SDK_VER):
+	rm -f $(SDK_DIR)/lib/liblwip.a $(SDK_DIR)/lib/libssl.a $(SDK_DIR)/lib/libmbedtls.a
+	ar d $(SDK_DIR)/lib/libmain.a time.o
+	ar d $(SDK_DIR)/lib/libc.a lib_a-time.o
 	touch $@
 
 $(TOP_DIR)/cache/v$(SDK_FILE_VER).zip:
@@ -223,9 +236,9 @@ $(TOP_DIR)/cache/v$(SDK_FILE_VER).zip:
 	wget --tries=10 --timeout=15 --waitretry=30 --read-timeout=20 --retry-connrefused https://github.com/espressif/ESP8266_NONOS_SDK/archive/v$(SDK_FILE_VER).zip -O $@ || { rm -f "$@"; exit 1; }
 	(echo "$(SDK_FILE_SHA1)  $@" | sha1sum -c -) || { rm -f "$@"; exit 1; }
 
-$(TOP_DIR)/cache/esp_iot_sdk_v$(SDK_PATCH_VER).zip:
+$(TOP_DIR)/cache/$(SDK_PATCH_VER).patch:
 	mkdir -p "$(dir $@)"
-	wget --tries=10 --timeout=15 --waitretry=30 --read-timeout=20 --retry-connrefused http://espressif.com/sites/default/files/sdks/esp8266_nonos_sdk_v$(SDK_PATCH_VER).zip -O $@ || { rm -f "$@"; exit 1; }
+	wget --tries=10 --timeout=15 --waitretry=30 --read-timeout=20 --retry-connrefused "https://github.com/espressif/ESP8266_NONOS_SDK/compare/v$(SDK_BASE_VER)...$(SDK_PATCH_VER).patch" -O $@ || { rm -f "$@"; exit 1; }
 	(echo "$(SDK_PATCH_SHA1)  $@" | sha1sum -c -) || { rm -f "$@"; exit 1; }
 
 clean:
@@ -306,6 +319,17 @@ $(OBJODIR)/%.d: %.c
 	sed 's,\($*\.o\)[ :]*,$(OBJODIR)/\1 $@ : ,g' < $@.$$$$ > $@; \
 	rm -f $@.$$$$
 
+$(OBJODIR)/%.o: %.cpp
+	@mkdir -p $(OBJODIR);
+	$(CXX) $(if $(findstring $<,$(DSRCS)),$(DFLAGS),$(CFLAGS)) $(COPTS_$(*F)) -o $@ -c $<
+
+$(OBJODIR)/%.d: %.cpp
+	@mkdir -p $(OBJODIR);
+	@echo DEPEND: $(CXX) -M $(CFLAGS) $<
+	@set -e; rm -f $@; \
+	sed 's,\($*\.o\)[ :]*,$(OBJODIR)/\1 $@ : ,g' < $@.$$$$ > $@; \
+	rm -f $@.$$$$
+
 $(OBJODIR)/%.o: %.s
 	@mkdir -p $(OBJODIR);
 	$(CC) $(CFLAGS) -o $@ -c $<

+ 4 - 4
README.md

@@ -1,4 +1,4 @@
-# **NodeMCU 2.1.0** #
+# **NodeMCU 2.2.0** #
 
 [![Join the chat at https://gitter.im/nodemcu/nodemcu-firmware](https://img.shields.io/gitter/room/badges/shields.svg)](https://gitter.im/nodemcu/nodemcu-firmware?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
 [![Build Status](https://travis-ci.org/nodemcu/nodemcu-firmware.svg)](https://travis-ci.org/nodemcu/nodemcu-firmware)
@@ -7,7 +7,7 @@
 
 ### A Lua based firmware for ESP8266 WiFi SOC
 
-NodeMCU is an [eLua](http://www.eluaproject.net/) based firmware for the [ESP8266 WiFi SOC from Espressif](http://espressif.com/en/products/esp8266/). The firmware is based on the [Espressif NON-OS SDK 2.1.0](https://github.com/espressif/ESP8266_NONOS_SDK/releases/tag/v2.1.0) and uses a file system based on [spiffs](https://github.com/pellepl/spiffs). The code repository consists of 98.1% C-code that glues the thin Lua veneer to the SDK.
+NodeMCU is an [eLua](http://www.eluaproject.net/) based firmware for the [ESP8266 WiFi SOC from Espressif](http://espressif.com/en/products/esp8266/). The firmware is based on the [Espressif NON-OS SDK 2.2.0](https://github.com/espressif/ESP8266_NONOS_SDK/releases/tag/v2.2.0) and uses a file system based on [spiffs](https://github.com/pellepl/spiffs). The code repository consists of 98.1% C-code that glues the thin Lua veneer to the SDK.
 
 The NodeMCU *firmware* is a companion project to the popular [NodeMCU dev kits](https://github.com/nodemcu/nodemcu-devkit-v1.0), ready-made open source development boards with ESP8266-12E chips.
 
@@ -16,7 +16,7 @@ The NodeMCU *firmware* is a companion project to the popular [NodeMCU dev kits](
 - Easy to program wireless node and/or access point
 - Based on Lua 5.1.4 (without *debug, os* modules)
 - Asynchronous event-driven programming model
-- 55+ built-in modules
+- more than 65 built-in modules
 - Firmware available with or without floating point support (integer-only uses less memory)
 - Up-to-date documentation at [https://nodemcu.readthedocs.io](https://nodemcu.readthedocs.io)
 
@@ -38,7 +38,7 @@ end)
 ```lua
 -- connect to WiFi access point
 wifi.setmode(wifi.STATION)
-wifi.sta.config("SSID", "password")
+wifi.sta.config{ssid="SSID", pwd="password"}
 ```
 
 # Documentation

+ 3 - 0
app/Makefile

@@ -50,6 +50,7 @@ SUBDIRS= 					\
 	misc					\
 	pm					\
 	sjson					\
+ 	sqlite3					\
 	
 
 endif # } PDIR
@@ -104,6 +105,7 @@ COMPONENTS_eagle.app.v6 = 			\
 	swTimer/libswtimer.a			\
 	misc/libmisc.a				\
 	sjson/libsjson.a			\
+  sqlite3/libsqlite3.a			\
 	
 
 # Inspect the modules library and work out which modules need to be linked.
@@ -164,6 +166,7 @@ CONFIGURATION_DEFINES =	-D__ets__ 		\
 			-DLWIP_OPEN_SRC 	\
 			-DPBUF_RSV_FOR_WLAN 	\
 			-DEBUF_LWIP		\
+			-DUSE_OPTIMIZE_PRINTF \
 			-DMBEDTLS_USER_CONFIG_FILE=\"user_mbedtls.h\"  \
 
 DEFINES += 					\

+ 1 - 1
app/coap/coap.c

@@ -549,7 +549,7 @@ void coap_setup(void)
     message_id = (unsigned short)os_random();      // calculate only once
 }
 
-inline int
+int
 check_token(coap_packet_t *pkt) {
   return pkt->tok.len == the_token.len && c_memcmp(pkt->tok.p, the_token.p, the_token.len) == 0;
 }

+ 1 - 1
app/driver/key.c

@@ -132,9 +132,9 @@ key_50ms_cb(struct single_key_param *single_key)
 LOCAL void
 key_intr_handler(void *arg)
 {
-    struct keys_param *keys = arg;
     uint8 i;
     uint32 gpio_status = GPIO_REG_READ(GPIO_STATUS_ADDRESS);
+    struct keys_param *keys = arg;
 
     for (i = 0; i < keys->key_num; i++) {
         if (gpio_status & BIT(keys->single_key[i]->gpio_id)) {

+ 2 - 2
app/fatfs/myfatfs.c

@@ -112,12 +112,12 @@ struct myvfs_dir {
 // ---------------------------------------------------------------------------
 // exported helper functions for FatFS
 //
-inline void *ff_memalloc( UINT size )
+void *ff_memalloc( UINT size )
 {
   return c_malloc( size );
 }
 
-inline void ff_memfree( void *mblock )
+void ff_memfree( void *mblock )
 {
   c_free( mblock );
 }

+ 4 - 1
app/http/httpclient.c

@@ -215,20 +215,23 @@ static void ICACHE_FLASH_ATTR http_connect_callback( void * arg )
         ua_len = strlen(ua_header);
     }
 
-	char host_header[32] = "";
+	char * host_header = "";
     int host_len = 0;
     if ( os_strstr( req->headers, "Host:" ) == NULL && os_strstr( req->headers, "host:" ) == NULL)
     {
+        int max_header_len = 9 + strlen(req->hostname); // 9 is fixed size of "Host:[space][cr][lf]\0"
         if ((req->port == 80)
 #ifdef CLIENT_SSL_ENABLE
             || ((req->port == 443) && ( req->secure ))
 #endif
             )
         {
+            host_header = alloca(max_header_len);
             os_sprintf( host_header, "Host: %s\r\n", req->hostname );
         }
         else
         {
+            host_header = alloca(max_header_len + 6); // 6 is worst case of ":port" where port is maximum 5 digits
             os_sprintf( host_header, "Host: %s:%d\r\n", req->hostname, req->port );
         }
         host_len = strlen(host_header);

+ 1 - 1
app/include/arch/cc.h

@@ -65,7 +65,7 @@ typedef uint32_t   mem_ptr_t;
 #define U32_F "d"
 #define X32_F "x"
 
-
+#define LWIP_ERR_T s32_t
 
 //#define PACK_STRUCT_FIELD(x) x __attribute__((packed))
 #define PACK_STRUCT_FIELD(x) x

+ 211 - 3
app/include/lwip/app/espconn.h

@@ -1,6 +1,31 @@
+/*
+ * ESPRESSIF MIT License
+ *
+ * Copyright (c) 2016 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
+ *
+ * Permission is hereby granted for use on ESPRESSIF SYSTEMS ESP8266 only, in which case,
+ * it is free of charge, to any person obtaining a copy of this software and associated
+ * documentation files (the "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the Software is furnished
+ * to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+ * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+ * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ */
+
 #ifndef __ESPCONN_H__
 #define __ESPCONN_H__
 
+#include "lwip/err.h"
 #include "lwip/dns.h"
 #include "os_type.h"
 #include "lwip/app/espconn_buf.h"
@@ -37,8 +62,7 @@ typedef void (* espconn_reconnect_callback)(void *arg, sint8 err);
 #define ESPCONN_NODATA	   -17	 /* No data can be read	     */
 
 #define ESPCONN_HANDSHAKE  -28   /* ssl handshake failed	 */
-#define ESPCONN_RESP_TIMEOUT -29 /* ssl handshake no response*/
-#define ESPCONN_PROTO_MSG  -61   /* ssl application invalid	 */
+#define ESPCONN_SSL_INVALID_DATA  -61   /* ssl application invalid	 */
 
 #define ESPCONN_SSL			0x01
 #define ESPCONN_NORM		0x00
@@ -121,6 +145,7 @@ enum espconn_option{
 	ESPCONN_NODELAY = 0x02,
 	ESPCONN_COPY = 0x04,
 	ESPCONN_KEEPALIVE = 0x08,
+	ESPCONN_MANUALRECV = 0x10,
 	ESPCONN_END
 };
 
@@ -461,6 +486,17 @@ extern sint8 espconn_regist_sentcb(struct espconn *espconn, espconn_sent_callbac
 *******************************************************************************/
 extern sint8 espconn_regist_write_finish(struct espconn *espconn, espconn_connect_callback write_finish_fn);
 
+/******************************************************************************
+ * FunctionName : espconn_send
+ * Description  : sent data for client or server
+ * Parameters   : espconn -- espconn to set for client or server
+ *                psent -- data to send
+ *                length -- length of data to send
+ * Returns      : none
+*******************************************************************************/
+extern sint8 espconn_send(struct espconn *espconn, uint8 *psent, uint16 length);
+
+
 /******************************************************************************
  * FunctionName : espconn_sent
  * Description  : sent data for client or server
@@ -573,7 +609,163 @@ extern sint8 espconn_get_keepalive(struct espconn *espconn, uint8 level, void *o
  *                - ESPCONN_ARG: dns client not initialized or invalid hostname
 *******************************************************************************/
 
-extern sint8 espconn_gethostbyname(struct espconn *pespconn, const char *name, ip_addr_t *addr, dns_found_callback found);
+extern err_t espconn_gethostbyname(struct espconn *pespconn, const char *name, ip_addr_t *addr, dns_found_callback found);
+
+/******************************************************************************
+ * FunctionName : espconn_abort
+ * Description  : Forcely abort with host
+ * Parameters   : espconn -- the espconn used to connect with the host
+ * Returns      : result
+*******************************************************************************/
+
+extern sint8 espconn_abort(struct espconn *espconn);
+
+/******************************************************************************
+ * FunctionName : espconn_encry_connect
+ * Description  : The function given as connection
+ * Parameters   : espconn -- the espconn used to connect with the host
+ * Returns      : none
+*******************************************************************************/
+
+extern sint8 espconn_secure_connect(struct espconn *espconn);
+
+/******************************************************************************
+ * FunctionName : espconn_encry_disconnect
+ * Description  : The function given as the disconnection
+ * Parameters   : espconn -- the espconn used to disconnect with the host
+ * Returns      : none
+*******************************************************************************/
+
+extern sint8 espconn_secure_disconnect(struct espconn *espconn);
+
+/******************************************************************************
+ * FunctionName : espconn_secure_send
+ * Description  : sent data for client or server
+ * Parameters   : espconn -- espconn to set for client or server
+ *                               psent -- data to send
+ *                length -- length of data to send
+ * Returns      : none
+*******************************************************************************/
+
+extern sint8 espconn_secure_send(struct espconn *espconn, uint8 *psent, uint16 length);
+
+/******************************************************************************
+ * FunctionName : espconn_encry_sent
+ * Description  : sent data for client or server
+ * Parameters   : espconn -- espconn to set for client or server
+ *                               psent -- data to send
+ *                length -- length of data to send
+ * Returns      : none
+*******************************************************************************/
+
+extern sint8 espconn_secure_sent(struct espconn *espconn, uint8 *psent, uint16 length);
+
+/******************************************************************************
+ * FunctionName : espconn_secure_set_size
+ * Description  : set the buffer size for client or server
+ * Parameters   : level -- set for client or server
+ *                               1: client,2:server,3:client and server
+ *                               size -- buffer size
+ * Returns      : true or false
+*******************************************************************************/
+
+extern bool espconn_secure_set_size(uint8 level, uint16 size);
+
+/******************************************************************************
+ * FunctionName : espconn_secure_get_size
+ * Description  : get buffer size for client or server
+ * Parameters   : level -- set for client or server
+ *                               1: client,2:server,3:client and server
+ * Returns      : buffer size for client or server
+*******************************************************************************/
+
+extern sint16 espconn_secure_get_size(uint8 level);
+
+/******************************************************************************
+ * FunctionName : espconn_secure_ca_enable
+ * Description  : enable the certificate authenticate and set the flash sector
+ *                               as client or server
+ * Parameters   : level -- set for client or server
+ *                               1: client,2:server,3:client and server
+ *                               flash_sector -- flash sector for save certificate
+ * Returns      : result true or false
+*******************************************************************************/
+
+extern bool espconn_secure_ca_enable(uint8 level, uint32 flash_sector );
+
+/******************************************************************************
+ * FunctionName : espconn_secure_ca_disable
+ * Description  : disable the certificate authenticate  as client or server
+ * Parameters   : level -- set for client or server
+ *                               1: client,2:server,3:client and server
+ * Returns      : result true or false
+*******************************************************************************/
+
+extern bool espconn_secure_ca_disable(uint8 level);
+
+
+/******************************************************************************
+ * FunctionName : espconn_secure_cert_req_enable
+ * Description  : enable the client certificate authenticate and set the flash sector
+ *                               as client or server
+ * Parameters   : level -- set for client or server
+ *                               1: client,2:server,3:client and server
+ *                               flash_sector -- flash sector for save certificate
+ * Returns      : result true or false
+*******************************************************************************/
+
+extern bool espconn_secure_cert_req_enable(uint8 level, uint32 flash_sector );
+
+/******************************************************************************
+ * FunctionName : espconn_secure_ca_disable
+ * Description  : disable the client certificate authenticate  as client or server
+ * Parameters   : level -- set for client or server
+ *                               1: client,2:server,3:client and server
+ * Returns      : result true or false
+*******************************************************************************/
+
+extern bool espconn_secure_cert_req_disable(uint8 level);
+
+/******************************************************************************
+ * FunctionName : espconn_secure_set_default_certificate
+ * Description  : Load the certificates in memory depending on compile-time
+ *                               and user options.
+ * Parameters   : certificate -- Load the certificate
+ *                               length -- Load the certificate length
+ * Returns      : result true or false
+*******************************************************************************/
+
+extern bool espconn_secure_set_default_certificate(const uint8* certificate, uint16 length);
+
+/******************************************************************************
+ * FunctionName : espconn_secure_set_default_private_key
+ * Description  : Load the key in memory depending on compile-time
+ *                               and user options.
+ * Parameters   : private_key -- Load the key
+ *                               length -- Load the key length
+ * Returns      : result true or false
+*******************************************************************************/
+
+extern bool espconn_secure_set_default_private_key(const uint8* private_key, uint16 length);
+
+/******************************************************************************
+ * FunctionName : espconn_secure_accept
+ * Description  : The function given as the listen
+ * Parameters   : espconn -- the espconn used to listen the connection
+ * Returns      : result
+*******************************************************************************/
+
+extern sint8 espconn_secure_accept(struct espconn *espconn);
+
+/******************************************************************************
+ * FunctionName : espconn_secure_accepts
+ * Description  : delete the secure server host
+ * Parameters   : espconn -- the espconn used to listen the connection
+ * Returns      : result
+*******************************************************************************/
+
+extern sint8 espconn_secure_delete(struct espconn *espconn);
+
 
 /******************************************************************************
  * FunctionName : espconn_igmp_join
@@ -593,6 +785,22 @@ extern sint8 espconn_igmp_join(ip_addr_t *host_ip, ip_addr_t *multicast_ip);
 *******************************************************************************/
 extern sint8 espconn_igmp_leave(ip_addr_t *host_ip, ip_addr_t *multicast_ip);
 
+/******************************************************************************
+ * FunctionName : espconn_recv_hold
+ * Description  : hold tcp receive
+ * Parameters   : espconn -- espconn to hold
+ * Returns      : none
+*******************************************************************************/
+extern sint8 espconn_recv_hold(struct espconn *pespconn);
+
+/******************************************************************************
+ * FunctionName : espconn_recv_unhold
+ * Description  : unhold tcp receive
+ * Parameters   : espconn -- espconn to unhold
+ * Returns      : none
+*******************************************************************************/
+extern sint8 espconn_recv_unhold(struct espconn *pespconn);
+
 /******************************************************************************
  * FunctionName : espconn_mdns_init
  * Description  : register a device with mdns

+ 3 - 0
app/include/lwip/app/espconn_tcp.h

@@ -13,6 +13,9 @@
 #define  espconn_keepalive_enable(pcb)   ((pcb)->so_options |= SOF_KEEPALIVE)
 #define  espconn_keepalive_disable(pcb)   ((pcb)->so_options &= ~SOF_KEEPALIVE)
 
+#define   espconn_manual_recv_disabled(espconn)  (((espconn)->pcommon.espconn_opt & ESPCONN_MANUALRECV) != 0)
+#define   espconn_manual_recv_enabled(espconn)  (((espconn)->pcommon.espconn_opt & ESPCONN_MANUALRECV) == 0)
+
 /******************************************************************************
  * FunctionName : espconn_kill_oldest_pcb
  * Description  : A oldest incoming connection has been killed.

+ 0 - 53
app/include/lwip/app/time.h

@@ -1,53 +0,0 @@
-/*
- * time.h
- *
- *  Created on: May 31, 2016
- *      Author: liuhan
- */
-
-#ifndef TIME_H_
-#define TIME_H_
-#include "osapi.h"
-#include "os_type.h"
-#include "lwip/sntp.h"
-
-struct timeval {
-  unsigned long  tv_sec;         /* seconds */
-  unsigned long  tv_usec;        /* and microseconds */
-};
-
-/***************************RTC TIME OPTION***************************************/
-// daylight settings
-// Base calculated with value obtained from NTP server (64 bits)
-#define sntp_base   (*((uint64_t*)RTC_STORE0))
-// Timer value when base was obtained
-#define TIM_REF_SET(value) WRITE_PERI_REG(RTC_STORE2, value)
-#define TIM_REF_GET()      READ_PERI_REG(RTC_STORE2)
-
-// Setters and getters for CAL, TZ and DST.
-#define RTC_CAL_SET(val)    do {uint32 value = READ_PERI_REG(RTC_STORE3);\
-    value |= ((val) & 0x0000FFFF);\
-    WRITE_PERI_REG(RTC_STORE3, value);\
-    }while(0)
-#define RTC_DST_SET(val)    do {uint32 value = READ_PERI_REG(RTC_STORE3);\
-    value |= (((val)<<16) & 0x00010000);\
-    WRITE_PERI_REG(RTC_STORE3, value);\
-    }while(0)
-#define RTC_TZ_SET(val)     do {uint32 value = READ_PERI_REG(RTC_STORE3);\
-    value |= (((val)<<24) & 0xFF000000);\
-    WRITE_PERI_REG(RTC_STORE3, value);\
-    }while(0)
-
-#define RTC_CAL_GET()       (READ_PERI_REG(RTC_STORE3) & 0x0000FFFF)
-#define RTC_DST_GET()       ((READ_PERI_REG(RTC_STORE3) & 0x00010000)>>16)
-#define RTC_TZ_GET()        ((((int)READ_PERI_REG(RTC_STORE3)) & ((int)0xFF000000))>>24)
-void system_update_rtc(time_t t, uint32_t us);
-time_t sntp_get_rtc_time(sint32_t *us);
-
-int  gettimeofday(struct timeval* t, void* timezone);
-void updateTime(uint32 ms);
-bool configTime(int timezone, int daylightOffset, char *server1, char *server2, char *server3, bool enable);
-time_t time(time_t *t);
-unsigned long millis(void);
-unsigned long micros(void);
-#endif /* TIME_H_ */

+ 1 - 1
app/include/lwip/mem.h

@@ -78,7 +78,7 @@ do{\
 #define mem_malloc(s) ({const char *file = mem_debug_file; pvPortMalloc(s, file, __LINE__);})
 #endif
 #ifndef mem_calloc
-#define mem_calloc(s) ({const char *file = mem_debug_file; pvPortCalloc(s, file, __LINE__);})
+#define mem_calloc(l, s) ({const char *file = mem_debug_file; pvPortCalloc(l, s, file, __LINE__);})
 #endif
 #ifndef mem_realloc
 #define mem_realloc(p, s) ({const char *file = mem_debug_file; pvPortRealloc(p, s, file, __LINE__);})

+ 0 - 60
app/include/lwip/sntp.h

@@ -1,60 +0,0 @@
-#ifndef LWIP_SNTP_H
-#define LWIP_SNTP_H
-
-#include "lwip/opt.h"
-#include "lwip/ip_addr.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef long     time_t;
-
-/** The maximum number of SNTP servers that can be set */
-#ifndef SNTP_MAX_SERVERS
-#define SNTP_MAX_SERVERS           3
-#endif
-
-/** Set this to 1 to implement the callback function called by dhcp when
- * NTP servers are received. */
-#ifndef SNTP_GET_SERVERS_FROM_DHCP
-#define SNTP_GET_SERVERS_FROM_DHCP 0//LWIP_DHCP_GET_NTP_SRV
-#endif
-
-/* Set this to 1 to support DNS names (or IP address strings) to set sntp servers */
-#ifndef SNTP_SERVER_DNS
-#define SNTP_SERVER_DNS            1
-#endif
-
-bool sntp_get_timetype(void);
-void sntp_set_receive_time_size(void);
-/** One server address/name can be defined as default if SNTP_SERVER_DNS == 1:
- * #define SNTP_SERVER_ADDRESS "pool.ntp.org"
- */
-uint32 sntp_get_current_timestamp();
-char* sntp_get_real_time(long t);
-
-void sntp_init(void);
-void sntp_stop(void);
-
-sint8 sntp_get_timezone(void);
-bool sntp_set_timezone(sint8 timezone);
-void sntp_setserver(u8_t idx, ip_addr_t *addr);
-ip_addr_t sntp_getserver(u8_t idx);
-
-#if SNTP_SERVER_DNS
-void sntp_setservername(u8_t idx, char *server);
-char *sntp_getservername(u8_t idx);
-#endif /* SNTP_SERVER_DNS */
-
-#if SNTP_GET_SERVERS_FROM_DHCP
-void sntp_servermode_dhcp(int set_servers_from_dhcp);
-#else /* SNTP_GET_SERVERS_FROM_DHCP */
-#define sntp_servermode_dhcp(x)
-#endif /* SNTP_GET_SERVERS_FROM_DHCP */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* LWIP_SNTP_H */

+ 262 - 142
app/include/mbedtls/aes.h

@@ -1,9 +1,18 @@
 /**
  * \file aes.h
  *
- * \brief AES block cipher
- *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * \brief   The Advanced Encryption Standard (AES) specifies a FIPS-approved
+ *          cryptographic algorithm that can be used to protect electronic
+ *          data.
+ *
+ *          The AES algorithm is a symmetric block cipher that can
+ *          encrypt and decrypt information. For more information, see
+ *          <em>FIPS Publication 197: Advanced Encryption Standard</em> and
+ *          <em>ISO/IEC 18033-2:2006: Information technology -- Security
+ *          techniques -- Encryption algorithms -- Part 2: Asymmetric
+ *          ciphers</em>.
+ */
+/*  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved.
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,8 +27,9 @@
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *
- *  This file is part of mbed TLS (https://tls.mbed.org)
+ *  This file is part of Mbed TLS (https://tls.mbed.org)
  */
+
 #ifndef MBEDTLS_AES_H
 #define MBEDTLS_AES_H
 
@@ -33,12 +43,22 @@
 #include <stdint.h>
 
 /* padlock.c and aesni.c rely on these values! */
-#define MBEDTLS_AES_ENCRYPT     1
-#define MBEDTLS_AES_DECRYPT     0
+#define MBEDTLS_AES_ENCRYPT     1 /**< AES encryption. */
+#define MBEDTLS_AES_DECRYPT     0 /**< AES decryption. */
 
+/* Error codes in range 0x0020-0x0022 */
 #define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH                -0x0020  /**< Invalid key length. */
 #define MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH              -0x0022  /**< Invalid data input length. */
 
+/* Error codes in range 0x0023-0x0025 */
+#define MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE               -0x0023  /**< Feature not available. For example, an unsupported AES key size. */
+#define MBEDTLS_ERR_AES_HW_ACCEL_FAILED                   -0x0025  /**< AES hardware accelerator failed. */
+
+#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
+    !defined(inline) && !defined(__cplusplus)
+#define inline __inline
+#endif
+
 #if !defined(MBEDTLS_AES_ALT)
 // Regular implementation
 //
@@ -48,68 +68,90 @@ extern "C" {
 #endif
 
 /**
- * \brief          AES context structure
- *
- * \note           buf is able to hold 32 extra bytes, which can be used:
- *                 - for alignment purposes if VIA padlock is used, and/or
- *                 - to simplify key expansion in the 256-bit case by
- *                 generating an extra round key
+ * \brief The AES context-type definition.
  */
 typedef struct
 {
-    int nr;                     /*!<  number of rounds  */
-    uint32_t *rk;               /*!<  AES round keys    */
-    uint32_t buf[68];           /*!<  unaligned data    */
+    int nr;                     /*!< The number of rounds. */
+    uint32_t *rk;               /*!< AES round keys. */
+    uint32_t buf[68];           /*!< Unaligned data buffer. This buffer can
+                                     hold 32 extra Bytes, which can be used for
+                                     one of the following purposes:
+                                     <ul><li>Alignment if VIA padlock is
+                                             used.</li>
+                                     <li>Simplifying key expansion in the 256-bit
+                                         case by generating an extra round key.
+                                         </li></ul> */
 }
 mbedtls_aes_context;
 
 /**
- * \brief          Initialize AES context
+ * \brief          This function initializes the specified AES context.
  *
- * \param ctx      AES context to be initialized
+ *                 It must be the first API called before using
+ *                 the context.
+ *
+ * \param ctx      The AES context to initialize.
  */
 void mbedtls_aes_init( mbedtls_aes_context *ctx );
 
 /**
- * \brief          Clear AES context
+ * \brief          This function releases and clears the specified AES context.
  *
- * \param ctx      AES context to be cleared
+ * \param ctx      The AES context to clear.
  */
 void mbedtls_aes_free( mbedtls_aes_context *ctx );
 
 /**
- * \brief          AES key schedule (encryption)
+ * \brief          This function sets the encryption key.
  *
- * \param ctx      AES context to be initialized
- * \param key      encryption key
- * \param keybits  must be 128, 192 or 256
+ * \param ctx      The AES context to which the key should be bound.
+ * \param key      The encryption key.
+ * \param keybits  The size of data passed in bits. Valid options are:
+ *                 <ul><li>128 bits</li>
+ *                 <li>192 bits</li>
+ *                 <li>256 bits</li></ul>
  *
- * \return         0 if successful, or MBEDTLS_ERR_AES_INVALID_KEY_LENGTH
+ * \return         \c 0 on success or #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH
+ *                 on failure.
  */
 int mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key,
                     unsigned int keybits );
 
 /**
- * \brief          AES key schedule (decryption)
+ * \brief          This function sets the decryption key.
  *
- * \param ctx      AES context to be initialized
- * \param key      decryption key
- * \param keybits  must be 128, 192 or 256
+ * \param ctx      The AES context to which the key should be bound.
+ * \param key      The decryption key.
+ * \param keybits  The size of data passed. Valid options are:
+ *                 <ul><li>128 bits</li>
+ *                 <li>192 bits</li>
+ *                 <li>256 bits</li></ul>
  *
- * \return         0 if successful, or MBEDTLS_ERR_AES_INVALID_KEY_LENGTH
+ * \return         \c 0 on success, or #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
  */
 int mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key,
                     unsigned int keybits );
 
 /**
- * \brief          AES-ECB block encryption/decryption
- *
- * \param ctx      AES context
- * \param mode     MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
- * \param input    16-byte input block
- * \param output   16-byte output block
- *
- * \return         0 if successful
+ * \brief          This function performs an AES single-block encryption or
+ *                 decryption operation.
+ *
+ *                 It performs the operation defined in the \p mode parameter
+ *                 (encrypt or decrypt), on the input data buffer defined in
+ *                 the \p input parameter.
+ *
+ *                 mbedtls_aes_init(), and either mbedtls_aes_setkey_enc() or
+ *                 mbedtls_aes_setkey_dec() must be called before the first
+ *                 call to this API with the same context.
+ *
+ * \param ctx      The AES context to use for encryption or decryption.
+ * \param mode     The AES operation: #MBEDTLS_AES_ENCRYPT or
+ *                 #MBEDTLS_AES_DECRYPT.
+ * \param input    The 16-Byte buffer holding the input data.
+ * \param output   The 16-Byte buffer holding the output data.
+
+ * \return         \c 0 on success.
  */
 int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx,
                     int mode,
@@ -118,26 +160,40 @@ int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx,
 
 #if defined(MBEDTLS_CIPHER_MODE_CBC)
 /**
- * \brief          AES-CBC buffer encryption/decryption
- *                 Length should be a multiple of the block
- *                 size (16 bytes)
- *
- * \note           Upon exit, the content of the IV is updated so that you can
- *                 call the function same function again on the following
- *                 block(s) of data and get the same result as if it was
- *                 encrypted in one call. This allows a "streaming" usage.
- *                 If on the other hand you need to retain the contents of the
- *                 IV, you should either save it manually or use the cipher
- *                 module instead.
- *
- * \param ctx      AES context
- * \param mode     MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
- * \param length   length of the input data
- * \param iv       initialization vector (updated after use)
- * \param input    buffer holding the input data
- * \param output   buffer holding the output data
- *
- * \return         0 if successful, or MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH
+ * \brief  This function performs an AES-CBC encryption or decryption operation
+ *         on full blocks.
+ *
+ *         It performs the operation defined in the \p mode
+ *         parameter (encrypt/decrypt), on the input data buffer defined in
+ *         the \p input parameter.
+ *
+ *         It can be called as many times as needed, until all the input
+ *         data is processed. mbedtls_aes_init(), and either
+ *         mbedtls_aes_setkey_enc() or mbedtls_aes_setkey_dec() must be called
+ *         before the first call to this API with the same context.
+ *
+ * \note   This function operates on aligned blocks, that is, the input size
+ *         must be a multiple of the AES block size of 16 Bytes.
+ *
+ * \note   Upon exit, the content of the IV is updated so that you can
+ *         call the same function again on the next
+ *         block(s) of data and get the same result as if it was
+ *         encrypted in one call. This allows a "streaming" usage.
+ *         If you need to retain the contents of the IV, you should
+ *         either save it manually or use the cipher module instead.
+ *
+ *
+ * \param ctx      The AES context to use for encryption or decryption.
+ * \param mode     The AES operation: #MBEDTLS_AES_ENCRYPT or
+ *                 #MBEDTLS_AES_DECRYPT.
+ * \param length   The length of the input data in Bytes. This must be a
+ *                 multiple of the block size (16 Bytes).
+ * \param iv       Initialization vector (updated after use).
+ * \param input    The buffer holding the input data.
+ * \param output   The buffer holding the output data.
+ *
+ * \return         \c 0 on success, or #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH
+ *                 on failure.
  */
 int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx,
                     int mode,
@@ -149,29 +205,38 @@ int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx,
 
 #if defined(MBEDTLS_CIPHER_MODE_CFB)
 /**
- * \brief          AES-CFB128 buffer encryption/decryption.
- *
- * Note: Due to the nature of CFB you should use the same key schedule for
- * both encryption and decryption. So a context initialized with
- * mbedtls_aes_setkey_enc() for both MBEDTLS_AES_ENCRYPT and MBEDTLS_AES_DECRYPT.
- *
- * \note           Upon exit, the content of the IV is updated so that you can
- *                 call the function same function again on the following
- *                 block(s) of data and get the same result as if it was
- *                 encrypted in one call. This allows a "streaming" usage.
- *                 If on the other hand you need to retain the contents of the
- *                 IV, you should either save it manually or use the cipher
- *                 module instead.
- *
- * \param ctx      AES context
- * \param mode     MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
- * \param length   length of the input data
- * \param iv_off   offset in IV (updated after use)
- * \param iv       initialization vector (updated after use)
- * \param input    buffer holding the input data
- * \param output   buffer holding the output data
- *
- * \return         0 if successful
+ * \brief This function performs an AES-CFB128 encryption or decryption
+ *        operation.
+ *
+ *        It performs the operation defined in the \p mode
+ *        parameter (encrypt or decrypt), on the input data buffer
+ *        defined in the \p input parameter.
+ *
+ *        For CFB, you must set up the context with mbedtls_aes_setkey_enc(),
+ *        regardless of whether you are performing an encryption or decryption
+ *        operation, that is, regardless of the \p mode parameter. This is
+ *        because CFB mode uses the same key schedule for encryption and
+ *        decryption.
+ *
+ * \note  Upon exit, the content of the IV is updated so that you can
+ *        call the same function again on the next
+ *        block(s) of data and get the same result as if it was
+ *        encrypted in one call. This allows a "streaming" usage.
+ *        If you need to retain the contents of the
+ *        IV, you must either save it manually or use the cipher
+ *        module instead.
+ *
+ *
+ * \param ctx      The AES context to use for encryption or decryption.
+ * \param mode     The AES operation: #MBEDTLS_AES_ENCRYPT or
+ *                 #MBEDTLS_AES_DECRYPT.
+ * \param length   The length of the input data.
+ * \param iv_off   The offset in IV (updated after use).
+ * \param iv       The initialization vector (updated after use).
+ * \param input    The buffer holding the input data.
+ * \param output   The buffer holding the output data.
+ *
+ * \return         \c 0 on success.
  */
 int mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx,
                        int mode,
@@ -182,28 +247,36 @@ int mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx,
                        unsigned char *output );
 
 /**
- * \brief          AES-CFB8 buffer encryption/decryption.
- *
- * Note: Due to the nature of CFB you should use the same key schedule for
- * both encryption and decryption. So a context initialized with
- * mbedtls_aes_setkey_enc() for both MBEDTLS_AES_ENCRYPT and MBEDTLS_AES_DECRYPT.
- *
- * \note           Upon exit, the content of the IV is updated so that you can
- *                 call the function same function again on the following
- *                 block(s) of data and get the same result as if it was
- *                 encrypted in one call. This allows a "streaming" usage.
- *                 If on the other hand you need to retain the contents of the
- *                 IV, you should either save it manually or use the cipher
- *                 module instead.
- *
- * \param ctx      AES context
- * \param mode     MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
- * \param length   length of the input data
- * \param iv       initialization vector (updated after use)
- * \param input    buffer holding the input data
- * \param output   buffer holding the output data
- *
- * \return         0 if successful
+ * \brief This function performs an AES-CFB8 encryption or decryption
+ *        operation.
+ *
+ *        It performs the operation defined in the \p mode
+ *        parameter (encrypt/decrypt), on the input data buffer defined
+ *        in the \p input parameter.
+ *
+ *        Due to the nature of CFB, you must use the same key schedule for
+ *        both encryption and decryption operations. Therefore, you must
+ *        use the context initialized with mbedtls_aes_setkey_enc() for
+ *        both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT.
+ *
+ * \note  Upon exit, the content of the IV is updated so that you can
+ *        call the same function again on the next
+ *        block(s) of data and get the same result as if it was
+ *        encrypted in one call. This allows a "streaming" usage.
+ *        If you need to retain the contents of the
+ *        IV, you should either save it manually or use the cipher
+ *        module instead.
+ *
+ *
+ * \param ctx      The AES context to use for encryption or decryption.
+ * \param mode     The AES operation: #MBEDTLS_AES_ENCRYPT or
+ *                 #MBEDTLS_AES_DECRYPT
+ * \param length   The length of the input data.
+ * \param iv       The initialization vector (updated after use).
+ * \param input    The buffer holding the input data.
+ * \param output   The buffer holding the output data.
+ *
+ * \return         \c 0 on success.
  */
 int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx,
                     int mode,
@@ -215,26 +288,32 @@ int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx,
 
 #if defined(MBEDTLS_CIPHER_MODE_CTR)
 /**
- * \brief               AES-CTR buffer encryption/decryption
- *
- * Warning: You have to keep the maximum use of your counter in mind!
- *
- * Note: Due to the nature of CTR you should use the same key schedule for
- * both encryption and decryption. So a context initialized with
- * mbedtls_aes_setkey_enc() for both MBEDTLS_AES_ENCRYPT and MBEDTLS_AES_DECRYPT.
- *
- * \param ctx           AES context
- * \param length        The length of the data
- * \param nc_off        The offset in the current stream_block (for resuming
- *                      within current cipher stream). The offset pointer to
- *                      should be 0 at the start of a stream.
- * \param nonce_counter The 128-bit nonce and counter.
- * \param stream_block  The saved stream-block for resuming. Is overwritten
- *                      by the function.
- * \param input         The input data stream
- * \param output        The output data stream
- *
- * \return         0 if successful
+ * \brief      This function performs an AES-CTR encryption or decryption
+ *             operation.
+ *
+ *             This function performs the operation defined in the \p mode
+ *             parameter (encrypt/decrypt), on the input data buffer
+ *             defined in the \p input parameter.
+ *
+ *             Due to the nature of CTR, you must use the same key schedule
+ *             for both encryption and decryption operations. Therefore, you
+ *             must use the context initialized with mbedtls_aes_setkey_enc()
+ *             for both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT.
+ *
+ * \warning    You must keep the maximum use of your counter in mind.
+ *
+ * \param ctx              The AES context to use for encryption or decryption.
+ * \param length           The length of the input data.
+ * \param nc_off           The offset in the current \p stream_block, for
+ *                         resuming within the current cipher stream. The
+ *                         offset pointer should be 0 at the start of a stream.
+ * \param nonce_counter    The 128-bit nonce and counter.
+ * \param stream_block     The saved stream block for resuming. This is
+ *                         overwritten by the function.
+ * \param input            The buffer holding the input data.
+ * \param output           The buffer holding the output data.
+ *
+ * \return     \c 0 on success.
  */
 int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx,
                        size_t length,
@@ -246,30 +325,71 @@ int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx,
 #endif /* MBEDTLS_CIPHER_MODE_CTR */
 
 /**
- * \brief           Internal AES block encryption function
- *                  (Only exposed to allow overriding it,
- *                  see MBEDTLS_AES_ENCRYPT_ALT)
+ * \brief           Internal AES block encryption function. This is only
+ *                  exposed to allow overriding it using
+ *                  \c MBEDTLS_AES_ENCRYPT_ALT.
+ *
+ * \param ctx       The AES context to use for encryption.
+ * \param input     The plaintext block.
+ * \param output    The output (ciphertext) block.
+ *
+ * \return          \c 0 on success.
+ */
+int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx,
+                                  const unsigned char input[16],
+                                  unsigned char output[16] );
+
+/**
+ * \brief           Internal AES block decryption function. This is only
+ *                  exposed to allow overriding it using see
+ *                  \c MBEDTLS_AES_DECRYPT_ALT.
+ *
+ * \param ctx       The AES context to use for decryption.
+ * \param input     The ciphertext block.
+ * \param output    The output (plaintext) block.
  *
- * \param ctx       AES context
- * \param input     Plaintext block
- * \param output    Output (ciphertext) block
+ * \return          \c 0 on success.
  */
-void mbedtls_aes_encrypt( mbedtls_aes_context *ctx,
-                          const unsigned char input[16],
-                          unsigned char output[16] );
+int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx,
+                                  const unsigned char input[16],
+                                  unsigned char output[16] );
 
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
 /**
- * \brief           Internal AES block decryption function
- *                  (Only exposed to allow overriding it,
- *                  see MBEDTLS_AES_DECRYPT_ALT)
+ * \brief           Deprecated internal AES block encryption function
+ *                  without return value.
+ *
+ * \deprecated      Superseded by mbedtls_aes_encrypt_ext() in 2.5.0.
  *
- * \param ctx       AES context
- * \param input     Ciphertext block
- * \param output    Output (plaintext) block
+ * \param ctx       The AES context to use for encryption.
+ * \param input     Plaintext block.
+ * \param output    Output (ciphertext) block.
  */
-void mbedtls_aes_decrypt( mbedtls_aes_context *ctx,
-                          const unsigned char input[16],
-                          unsigned char output[16] );
+MBEDTLS_DEPRECATED void mbedtls_aes_encrypt( mbedtls_aes_context *ctx,
+                                             const unsigned char input[16],
+                                             unsigned char output[16] );
+
+/**
+ * \brief           Deprecated internal AES block decryption function
+ *                  without return value.
+ *
+ * \deprecated      Superseded by mbedtls_aes_decrypt_ext() in 2.5.0.
+ *
+ * \param ctx       The AES context to use for decryption.
+ * \param input     Ciphertext block.
+ * \param output    Output (plaintext) block.
+ */
+MBEDTLS_DEPRECATED void mbedtls_aes_decrypt( mbedtls_aes_context *ctx,
+                                             const unsigned char input[16],
+                                             unsigned char output[16] );
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 #ifdef __cplusplus
 }
@@ -284,9 +404,9 @@ extern "C" {
 #endif
 
 /**
- * \brief          Checkup routine
+ * \brief          Checkup routine.
  *
- * \return         0 if successful, or 1 if the test failed
+ * \return         \c 0 on success, or \c 1 on failure.
  */
 int mbedtls_aes_self_test( int verbose );
 

+ 2 - 1
app/include/mbedtls/aesni.h

@@ -2,7 +2,8 @@
  * \file aesni.h
  *
  * \brief AES-NI for hardware AES acceleration on some Intel processors
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 37 - 1
app/include/mbedtls/arc4.h

@@ -3,6 +3,10 @@
  *
  * \brief The ARCFOUR stream cipher
  *
+ * \warning   ARC4 is considered a weak cipher and its use constitutes a
+ *            security risk. We recommend considering stronger ciphers instead.
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -19,6 +23,7 @@
  *  limitations under the License.
  *
  *  This file is part of mbed TLS (https://tls.mbed.org)
+ *
  */
 #ifndef MBEDTLS_ARC4_H
 #define MBEDTLS_ARC4_H
@@ -31,6 +36,8 @@
 
 #include <stddef.h>
 
+#define MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED                  -0x0019  /**< ARC4 hardware accelerator failed. */
+
 #if !defined(MBEDTLS_ARC4_ALT)
 // Regular implementation
 //
@@ -40,7 +47,11 @@ extern "C" {
 #endif
 
 /**
- * \brief          ARC4 context structure
+ * \brief     ARC4 context structure
+ *
+ * \warning   ARC4 is considered a weak cipher and its use constitutes a
+ *            security risk. We recommend considering stronger ciphers instead.
+ *
  */
 typedef struct
 {
@@ -54,6 +65,11 @@ mbedtls_arc4_context;
  * \brief          Initialize ARC4 context
  *
  * \param ctx      ARC4 context to be initialized
+ *
+ * \warning        ARC4 is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
+ *
  */
 void mbedtls_arc4_init( mbedtls_arc4_context *ctx );
 
@@ -61,6 +77,11 @@ void mbedtls_arc4_init( mbedtls_arc4_context *ctx );
  * \brief          Clear ARC4 context
  *
  * \param ctx      ARC4 context to be cleared
+ *
+ * \warning        ARC4 is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
+ *
  */
 void mbedtls_arc4_free( mbedtls_arc4_context *ctx );
 
@@ -70,6 +91,11 @@ void mbedtls_arc4_free( mbedtls_arc4_context *ctx );
  * \param ctx      ARC4 context to be setup
  * \param key      the secret key
  * \param keylen   length of the key, in bytes
+ *
+ * \warning        ARC4 is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
+ *
  */
 void mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key,
                  unsigned int keylen );
@@ -83,6 +109,11 @@ void mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key,
  * \param output   buffer for the output data
  *
  * \return         0 if successful
+ *
+ * \warning        ARC4 is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
+ *
  */
 int mbedtls_arc4_crypt( mbedtls_arc4_context *ctx, size_t length, const unsigned char *input,
                 unsigned char *output );
@@ -103,6 +134,11 @@ extern "C" {
  * \brief          Checkup routine
  *
  * \return         0 if successful, or 1 if the test failed
+ *
+ * \warning        ARC4 is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
+ *
  */
 int mbedtls_arc4_self_test( int verbose );
 

+ 3 - 2
app/include/mbedtls/asn1.h

@@ -2,7 +2,8 @@
  * \file asn1.h
  *
  * \brief Generic ASN.1 parsing
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -59,7 +60,7 @@
 
 /**
  * \name DER constants
- * These constants comply with DER encoded the ANS1 type tags.
+ * These constants comply with the DER encoded ASN.1 type tags.
  * DER encoding uses hexadecimal representation.
  * An example DER sequence is:\n
  * - 0x02 -- tag indicating INTEGER

+ 2 - 1
app/include/mbedtls/asn1write.h

@@ -2,7 +2,8 @@
  * \file asn1write.h
  *
  * \brief ASN.1 buffer writing functionality
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 2 - 1
app/include/mbedtls/base64.h

@@ -2,7 +2,8 @@
  * \file base64.h
  *
  * \brief RFC 1521 base64 encoding/decoding
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 85 - 36
app/include/mbedtls/bignum.h

@@ -1,8 +1,9 @@
 /**
  * \file bignum.h
  *
- * \brief  Multi-precision integer library
- *
+ * \brief Multi-precision integer library
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -70,7 +71,7 @@
  * Maximum size of MPIs allowed in bits and bytes for user-MPIs.
  * ( Default: 512 bytes => 4096 bits, Maximum tested: 2048 bytes => 16384 bits )
  *
- * Note: Calculations can results temporarily in larger MPIs. So the number
+ * Note: Calculations can temporarily result in larger MPIs. So the number
  * of limbs required (MBEDTLS_MPI_MAX_LIMBS) is higher.
  */
 #define MBEDTLS_MPI_MAX_SIZE                              1024     /**< Maximum number of bytes for usable MPIs. */
@@ -103,36 +104,71 @@
 /*
  * Define the base integer type, architecture-wise.
  *
- * 32-bit integers can be forced on 64-bit arches (eg. for testing purposes)
- * by defining MBEDTLS_HAVE_INT32 and undefining MBEDTLS_HAVE_ASM
- */
-#if ( ! defined(MBEDTLS_HAVE_INT32) && \
-        defined(_MSC_VER) && defined(_M_AMD64) )
-  #define MBEDTLS_HAVE_INT64
-  typedef  int64_t mbedtls_mpi_sint;
-  typedef uint64_t mbedtls_mpi_uint;
-#else
-  #if ( ! defined(MBEDTLS_HAVE_INT32) &&               \
-        defined(__GNUC__) && (                          \
-        defined(__amd64__) || defined(__x86_64__)    || \
-        defined(__ppc64__) || defined(__powerpc64__) || \
-        defined(__ia64__)  || defined(__alpha__)     || \
-        (defined(__sparc__) && defined(__arch64__))  || \
-        defined(__s390x__) || defined(__mips64) ) )
-     #define MBEDTLS_HAVE_INT64
-     typedef  int64_t mbedtls_mpi_sint;
-     typedef uint64_t mbedtls_mpi_uint;
-     /* mbedtls_t_udbl defined as 128-bit unsigned int */
-     typedef unsigned int mbedtls_t_udbl __attribute__((mode(TI)));
-     #define MBEDTLS_HAVE_UDBL
-  #else
-     #define MBEDTLS_HAVE_INT32
-     typedef  int32_t mbedtls_mpi_sint;
-     typedef uint32_t mbedtls_mpi_uint;
-     typedef uint64_t mbedtls_t_udbl;
-     #define MBEDTLS_HAVE_UDBL
-  #endif /* !MBEDTLS_HAVE_INT32 && __GNUC__ && 64-bit platform */
-#endif /* !MBEDTLS_HAVE_INT32 && _MSC_VER && _M_AMD64 */
+ * 32 or 64-bit integer types can be forced regardless of the underlying
+ * architecture by defining MBEDTLS_HAVE_INT32 or MBEDTLS_HAVE_INT64
+ * respectively and undefining MBEDTLS_HAVE_ASM.
+ *
+ * Double-width integers (e.g. 128-bit in 64-bit architectures) can be
+ * disabled by defining MBEDTLS_NO_UDBL_DIVISION.
+ */
+#if !defined(MBEDTLS_HAVE_INT32)
+    #if defined(_MSC_VER) && defined(_M_AMD64)
+        /* Always choose 64-bit when using MSC */
+        #if !defined(MBEDTLS_HAVE_INT64)
+            #define MBEDTLS_HAVE_INT64
+        #endif /* !MBEDTLS_HAVE_INT64 */
+        typedef  int64_t mbedtls_mpi_sint;
+        typedef uint64_t mbedtls_mpi_uint;
+    #elif defined(__GNUC__) && (                         \
+        defined(__amd64__) || defined(__x86_64__)     || \
+        defined(__ppc64__) || defined(__powerpc64__)  || \
+        defined(__ia64__)  || defined(__alpha__)      || \
+        ( defined(__sparc__) && defined(__arch64__) ) || \
+        defined(__s390x__) || defined(__mips64) )
+        #if !defined(MBEDTLS_HAVE_INT64)
+            #define MBEDTLS_HAVE_INT64
+        #endif /* MBEDTLS_HAVE_INT64 */
+        typedef  int64_t mbedtls_mpi_sint;
+        typedef uint64_t mbedtls_mpi_uint;
+        #if !defined(MBEDTLS_NO_UDBL_DIVISION)
+            /* mbedtls_t_udbl defined as 128-bit unsigned int */
+            typedef unsigned int mbedtls_t_udbl __attribute__((mode(TI)));
+            #define MBEDTLS_HAVE_UDBL
+        #endif /* !MBEDTLS_NO_UDBL_DIVISION */
+    #elif defined(__ARMCC_VERSION) && defined(__aarch64__)
+        /*
+         * __ARMCC_VERSION is defined for both armcc and armclang and
+         * __aarch64__ is only defined by armclang when compiling 64-bit code
+         */
+        #if !defined(MBEDTLS_HAVE_INT64)
+            #define MBEDTLS_HAVE_INT64
+        #endif /* !MBEDTLS_HAVE_INT64 */
+        typedef  int64_t mbedtls_mpi_sint;
+        typedef uint64_t mbedtls_mpi_uint;
+        #if !defined(MBEDTLS_NO_UDBL_DIVISION)
+            /* mbedtls_t_udbl defined as 128-bit unsigned int */
+            typedef __uint128_t mbedtls_t_udbl;
+            #define MBEDTLS_HAVE_UDBL
+        #endif /* !MBEDTLS_NO_UDBL_DIVISION */
+    #elif defined(MBEDTLS_HAVE_INT64)
+        /* Force 64-bit integers with unknown compiler */
+        typedef  int64_t mbedtls_mpi_sint;
+        typedef uint64_t mbedtls_mpi_uint;
+    #endif
+#endif /* !MBEDTLS_HAVE_INT32 */
+
+#if !defined(MBEDTLS_HAVE_INT64)
+    /* Default to 32-bit compilation */
+    #if !defined(MBEDTLS_HAVE_INT32)
+        #define MBEDTLS_HAVE_INT32
+    #endif /* !MBEDTLS_HAVE_INT32 */
+    typedef  int32_t mbedtls_mpi_sint;
+    typedef uint32_t mbedtls_mpi_uint;
+    #if !defined(MBEDTLS_NO_UDBL_DIVISION)
+        typedef uint64_t mbedtls_t_udbl;
+        #define MBEDTLS_HAVE_UDBL
+    #endif /* !MBEDTLS_NO_UDBL_DIVISION */
+#endif /* !MBEDTLS_HAVE_INT64 */
 
 #ifdef __cplusplus
 extern "C" {
@@ -340,7 +376,7 @@ int mbedtls_mpi_write_string( const mbedtls_mpi *X, int radix,
 
 #if defined(MBEDTLS_FS_IO)
 /**
- * \brief          Read X from an opened file
+ * \brief          Read MPI from a line in an opened file
  *
  * \param X        Destination MPI
  * \param radix    Input numeric base
@@ -349,6 +385,15 @@ int mbedtls_mpi_write_string( const mbedtls_mpi *X, int radix,
  * \return         0 if successful, MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if
  *                 the file read buffer is too small or a
  *                 MBEDTLS_ERR_MPI_XXX error code
+ *
+ * \note           On success, this function advances the file stream
+ *                 to the end of the current line or to EOF.
+ *
+ *                 The function returns 0 on an empty line.
+ *
+ *                 Leading whitespaces are ignored, as is a
+ *                 '0x' prefix for radix 16.
+ *
  */
 int mbedtls_mpi_read_file( mbedtls_mpi *X, int radix, FILE *fin );
 
@@ -639,6 +684,10 @@ int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi
  *
  * \return         0 if successful,
  *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed
+ *
+ * \note           The bytes obtained from the PRNG are interpreted
+ *                 as a big-endian representation of an MPI; this can
+ *                 be relevant in applications like deterministic ECDSA.
  */
 int mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size,
                      int (*f_rng)(void *, unsigned char *, size_t),
@@ -665,8 +714,8 @@ int mbedtls_mpi_gcd( mbedtls_mpi *G, const mbedtls_mpi *A, const mbedtls_mpi *B
  *
  * \return         0 if successful,
  *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed,
- *                 MBEDTLS_ERR_MPI_BAD_INPUT_DATA if N is negative or nil
-                   MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if A has no inverse mod N
+ *                 MBEDTLS_ERR_MPI_BAD_INPUT_DATA if N is <= 1,
+                   MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if A has no inverse mod N.
  */
 int mbedtls_mpi_inv_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *N );
 

+ 3 - 1
app/include/mbedtls/blowfish.h

@@ -2,7 +2,8 @@
  * \file blowfish.h
  *
  * \brief Blowfish block cipher
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -40,6 +41,7 @@
 #define MBEDTLS_BLOWFISH_BLOCKSIZE   8          /* Blowfish uses 64 bit blocks */
 
 #define MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH                -0x0016  /**< Invalid key length. */
+#define MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED                   -0x0017  /**< Blowfish hardware accelerator failed. */
 #define MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH              -0x0018  /**< Invalid data input length. */
 
 #if !defined(MBEDTLS_BLOWFISH_ALT)

+ 23 - 13
app/include/mbedtls/bn_mul.h

@@ -1,8 +1,9 @@
 /**
  * \file bn_mul.h
  *
- * \brief  Multi-precision integer library
- *
+ * \brief Multi-precision integer library
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -162,10 +163,6 @@
 
 #define MULADDC_INIT                        \
     asm(                                    \
-        "movq   %3, %%rsi           \n\t"   \
-        "movq   %4, %%rdi           \n\t"   \
-        "movq   %5, %%rcx           \n\t"   \
-        "movq   %6, %%rbx           \n\t"   \
         "xorq   %%r8, %%r8          \n\t"
 
 #define MULADDC_CORE                        \
@@ -181,12 +178,9 @@
         "addq   $8,      %%rdi      \n\t"
 
 #define MULADDC_STOP                        \
-        "movq   %%rcx, %0           \n\t"   \
-        "movq   %%rdi, %1           \n\t"   \
-        "movq   %%rsi, %2           \n\t"   \
-        : "=m" (c), "=m" (d), "=m" (s)                      \
-        : "m" (s), "m" (d), "m" (c), "m" (b)                \
-        : "rax", "rcx", "rdx", "rbx", "rsi", "rdi", "r8"    \
+        : "+c" (c), "+D" (d), "+S" (s)      \
+        : "b" (b)                           \
+        : "rax", "rdx", "r8"                \
     );
 
 #endif /* AMD64 */
@@ -563,7 +557,23 @@
 
 #endif /* TriCore */
 
-#if defined(__arm__)
+/*
+ * gcc -O0 by default uses r7 for the frame pointer, so it complains about our
+ * use of r7 below, unless -fomit-frame-pointer is passed. Unfortunately,
+ * passing that option is not easy when building with yotta.
+ *
+ * On the other hand, -fomit-frame-pointer is implied by any -Ox options with
+ * x !=0, which we can detect using __OPTIMIZE__ (which is also defined by
+ * clang and armcc5 under the same conditions).
+ *
+ * So, only use the optimized assembly below for optimized build, which avoids
+ * the build error and is pretty reasonable anyway.
+ */
+#if defined(__GNUC__) && !defined(__OPTIMIZE__)
+#define MULADDC_CANNOT_USE_R7
+#endif
+
+#if defined(__arm__) && !defined(MULADDC_CANNOT_USE_R7)
 
 #if defined(__thumb__) && !defined(__thumb2__)
 

+ 3 - 1
app/include/mbedtls/camellia.h

@@ -2,7 +2,8 @@
  * \file camellia.h
  *
  * \brief Camellia block cipher
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -37,6 +38,7 @@
 
 #define MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH           -0x0024  /**< Invalid key length. */
 #define MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH         -0x0026  /**< Invalid data input length. */
+#define MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED              -0x0027  /**< Camellia hardware accelerator failed. */
 
 #if !defined(MBEDTLS_CAMELLIA_ALT)
 // Regular implementation

+ 91 - 59
app/include/mbedtls/ccm.h

@@ -1,9 +1,19 @@
 /**
  * \file ccm.h
  *
- * \brief Counter with CBC-MAC (CCM) for 128-bit block ciphers
+ * \brief CCM combines Counter mode encryption with CBC-MAC authentication
+ *        for 128-bit block ciphers.
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * Input to CCM includes the following elements:
+ * <ul><li>Payload - data that is both authenticated and encrypted.</li>
+ * <li>Associated data (Adata) - data that is authenticated but not
+ * encrypted, For example, a header.</li>
+ * <li>Nonce - A unique value that is assigned to the payload and the
+ * associated data.</li></ul>
+ *
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,46 +28,54 @@
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *
- *  This file is part of mbed TLS (https://tls.mbed.org)
+ *  This file is part of Mbed TLS (https://tls.mbed.org)
  */
+
 #ifndef MBEDTLS_CCM_H
 #define MBEDTLS_CCM_H
 
 #include "cipher.h"
 
-#define MBEDTLS_ERR_CCM_BAD_INPUT      -0x000D /**< Bad input parameters to function. */
-#define MBEDTLS_ERR_CCM_AUTH_FAILED    -0x000F /**< Authenticated decryption failed. */
+#define MBEDTLS_ERR_CCM_BAD_INPUT       -0x000D /**< Bad input parameters to the function. */
+#define MBEDTLS_ERR_CCM_AUTH_FAILED     -0x000F /**< Authenticated decryption failed. */
+#define MBEDTLS_ERR_CCM_HW_ACCEL_FAILED -0x0011 /**< CCM hardware accelerator failed. */
+
+#if !defined(MBEDTLS_CCM_ALT)
+// Regular implementation
+//
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
 /**
- * \brief          CCM context structure
+ * \brief    The CCM context-type definition. The CCM context is passed
+ *           to the APIs called.
  */
 typedef struct {
-    mbedtls_cipher_context_t cipher_ctx;    /*!< cipher context used */
+    mbedtls_cipher_context_t cipher_ctx;    /*!< The cipher context used. */
 }
 mbedtls_ccm_context;
 
 /**
- * \brief           Initialize CCM context (just makes references valid)
- *                  Makes the context ready for mbedtls_ccm_setkey() or
- *                  mbedtls_ccm_free().
+ * \brief           This function initializes the specified CCM context,
+ *                  to make references valid, and prepare the context
+ *                  for mbedtls_ccm_setkey() or mbedtls_ccm_free().
  *
- * \param ctx       CCM context to initialize
+ * \param ctx       The CCM context to initialize.
  */
 void mbedtls_ccm_init( mbedtls_ccm_context *ctx );
 
 /**
- * \brief           CCM initialization (encryption and decryption)
+ * \brief           This function initializes the CCM context set in the
+ *                  \p ctx parameter and sets the encryption key.
  *
- * \param ctx       CCM context to be initialized
- * \param cipher    cipher to use (a 128-bit block cipher)
- * \param key       encryption key
- * \param keybits   key size in bits (must be acceptable by the cipher)
+ * \param ctx       The CCM context to initialize.
+ * \param cipher    The 128-bit block cipher to use.
+ * \param key       The encryption key.
+ * \param keybits   The key size in bits. This must be acceptable by the cipher.
  *
- * \return          0 if successful, or a cipher specific error code
+ * \return          \c 0 on success, or a cipher-specific error code.
  */
 int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,
                         mbedtls_cipher_id_t cipher,
@@ -65,36 +83,37 @@ int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,
                         unsigned int keybits );
 
 /**
- * \brief           Free a CCM context and underlying cipher sub-context
+ * \brief   This function releases and clears the specified CCM context
+ *          and underlying cipher sub-context.
  *
- * \param ctx       CCM context to free
+ * \param ctx       The CCM context to clear.
  */
 void mbedtls_ccm_free( mbedtls_ccm_context *ctx );
 
 /**
- * \brief           CCM buffer encryption
- *
- * \param ctx       CCM context
- * \param length    length of the input data in bytes
- * \param iv        nonce (initialization vector)
- * \param iv_len    length of IV in bytes
- *                  must be 2, 3, 4, 5, 6, 7 or 8
- * \param add       additional data
- * \param add_len   length of additional data in bytes
- *                  must be less than 2^16 - 2^8
- * \param input     buffer holding the input data
- * \param output    buffer for holding the output data
- *                  must be at least 'length' bytes wide
- * \param tag       buffer for holding the tag
- * \param tag_len   length of the tag to generate in bytes
- *                  must be 4, 6, 8, 10, 14 or 16
- *
- * \note            The tag is written to a separate buffer. To get the tag
- *                  concatenated with the output as in the CCM spec, use
- *                  tag = output + length and make sure the output buffer is
- *                  at least length + tag_len wide.
- *
- * \return          0 if successful
+ * \brief           This function encrypts a buffer using CCM.
+ *
+ * \param ctx       The CCM context to use for encryption.
+ * \param length    The length of the input data in Bytes.
+ * \param iv        Initialization vector (nonce).
+ * \param iv_len    The length of the IV in Bytes: 7, 8, 9, 10, 11, 12, or 13.
+ * \param add       The additional data field.
+ * \param add_len   The length of additional data in Bytes.
+ *                  Must be less than 2^16 - 2^8.
+ * \param input     The buffer holding the input data.
+ * \param output    The buffer holding the output data.
+ *                  Must be at least \p length Bytes wide.
+ * \param tag       The buffer holding the tag.
+ * \param tag_len   The length of the tag to generate in Bytes:
+ *                  4, 6, 8, 10, 14 or 16.
+ *
+ * \note            The tag is written to a separate buffer. To concatenate
+ *                  the \p tag with the \p output, as done in <em>RFC-3610:
+ *                  Counter with CBC-MAC (CCM)</em>, use
+ *                  \p tag = \p output + \p length, and make sure that the
+ *                  output buffer is at least \p length + \p tag_len wide.
+ *
+ * \return          \c 0 on success.
  */
 int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
                          const unsigned char *iv, size_t iv_len,
@@ -103,21 +122,22 @@ int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
                          unsigned char *tag, size_t tag_len );
 
 /**
- * \brief           CCM buffer authenticated decryption
- *
- * \param ctx       CCM context
- * \param length    length of the input data
- * \param iv        initialization vector
- * \param iv_len    length of IV
- * \param add       additional data
- * \param add_len   length of additional data
- * \param input     buffer holding the input data
- * \param output    buffer for holding the output data
- * \param tag       buffer holding the tag
- * \param tag_len   length of the tag
- *
- * \return         0 if successful and authenticated,
- *                 MBEDTLS_ERR_CCM_AUTH_FAILED if tag does not match
+ * \brief           This function performs a CCM authenticated decryption of a
+ *                  buffer.
+ *
+ * \param ctx       The CCM context to use for decryption.
+ * \param length    The length of the input data in Bytes.
+ * \param iv        Initialization vector.
+ * \param iv_len    The length of the IV in Bytes: 7, 8, 9, 10, 11, 12, or 13.
+ * \param add       The additional data field.
+ * \param add_len   The length of additional data in Bytes.
+ * \param input     The buffer holding the input data.
+ * \param output    The buffer holding the output data.
+ * \param tag       The buffer holding the tag.
+ * \param tag_len   The length of the tag in Bytes.
+ *
+ * \return          0 if successful and authenticated, or
+ *                  #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match.
  */
 int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
                       const unsigned char *iv, size_t iv_len,
@@ -125,11 +145,23 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
                       const unsigned char *input, unsigned char *output,
                       const unsigned char *tag, size_t tag_len );
 
+#ifdef __cplusplus
+}
+#endif
+
+#else  /* MBEDTLS_CCM_ALT */
+#include "ccm_alt.h"
+#endif /* MBEDTLS_CCM_ALT */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
 /**
- * \brief          Checkup routine
+ * \brief          The CCM checkup routine.
  *
- * \return         0 if successful, or 1 if the test failed
+ * \return         \c 0 on success, or \c 1 on failure.
  */
 int mbedtls_ccm_self_test( int verbose );
 #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */

+ 2 - 5
app/include/mbedtls/certs.h

@@ -2,7 +2,8 @@
  * \file certs.h
  *
  * \brief Sample certificates and DHM parameters for testing
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -29,8 +30,6 @@
 extern "C" {
 #endif
 
-#if defined(MBEDTLS_SELF_TEST)
-
 #if defined(MBEDTLS_PEM_PARSE_C)
 /* Concatenation of all CA certificates in PEM format if available */
 extern const char   mbedtls_test_cas_pem[];
@@ -94,8 +93,6 @@ extern const char   mbedtls_test_cli_key_rsa[];
 extern const size_t mbedtls_test_cli_key_rsa_len;
 #endif
 
-#endif
-
 #ifdef __cplusplus
 }
 #endif

+ 132 - 2
app/include/mbedtls/check_config.h

@@ -2,8 +2,9 @@
  * \file check_config.h
  *
  * \brief Consistency checks for configuration options
- *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ */
+/*
+ *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -77,6 +78,11 @@
 #error "MBEDTLS_DHM_C defined, but not all prerequisites"
 #endif
 
+#if defined(MBEDTLS_CMAC_C) && \
+    !defined(MBEDTLS_AES_C) && !defined(MBEDTLS_DES_C)
+#error "MBEDTLS_CMAC_C defined, but not all prerequisites"
+#endif
+
 #if defined(MBEDTLS_ECDH_C) && !defined(MBEDTLS_ECP_C)
 #error "MBEDTLS_ECDH_C defined, but not all prerequisites"
 #endif
@@ -130,11 +136,53 @@
 #error "MBEDTLS_ENTROPY_FORCE_SHA256 defined, but not all prerequisites"
 #endif
 
+#if defined(MBEDTLS_TEST_NULL_ENTROPY) && \
+    ( !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES) )
+#error "MBEDTLS_TEST_NULL_ENTROPY defined, but not all prerequisites"
+#endif
+#if defined(MBEDTLS_TEST_NULL_ENTROPY) && \
+     ( defined(MBEDTLS_ENTROPY_NV_SEED) || defined(MBEDTLS_ENTROPY_HARDWARE_ALT) || \
+    defined(MBEDTLS_HAVEGE_C) )
+#error "MBEDTLS_TEST_NULL_ENTROPY defined, but entropy sources too"
+#endif
+
 #if defined(MBEDTLS_GCM_C) && (                                        \
         !defined(MBEDTLS_AES_C) && !defined(MBEDTLS_CAMELLIA_C) )
 #error "MBEDTLS_GCM_C defined, but not all prerequisites"
 #endif
 
+#if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_RANDOMIZE_JAC_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_ADD_MIXED_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_ADD_MIXED_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_DOUBLE_JAC_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_NORMALIZE_JAC_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_RANDOMIZE_MXZ_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_NORMALIZE_MXZ_ALT defined, but not all prerequisites"
+#endif
+
 #if defined(MBEDTLS_HAVEGE_C) && !defined(MBEDTLS_TIMING_C)
 #error "MBEDTLS_HAVEGE_C defined, but not all prerequisites"
 #endif
@@ -246,6 +294,36 @@
 #error "MBEDTLS_PLATFORM_EXIT_MACRO and MBEDTLS_PLATFORM_STD_EXIT/MBEDTLS_PLATFORM_EXIT_ALT cannot be defined simultaneously"
 #endif
 
+#if defined(MBEDTLS_PLATFORM_TIME_ALT) &&\
+    ( !defined(MBEDTLS_PLATFORM_C) ||\
+        !defined(MBEDTLS_HAVE_TIME) )
+#error "MBEDTLS_PLATFORM_TIME_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_TIME_MACRO) &&\
+    ( !defined(MBEDTLS_PLATFORM_C) ||\
+        !defined(MBEDTLS_HAVE_TIME) )
+#error "MBEDTLS_PLATFORM_TIME_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO) &&\
+    ( !defined(MBEDTLS_PLATFORM_C) ||\
+        !defined(MBEDTLS_HAVE_TIME) )
+#error "MBEDTLS_PLATFORM_TIME_TYPE_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_TIME_MACRO) &&\
+    ( defined(MBEDTLS_PLATFORM_STD_TIME) ||\
+        defined(MBEDTLS_PLATFORM_TIME_ALT) )
+#error "MBEDTLS_PLATFORM_TIME_MACRO and MBEDTLS_PLATFORM_STD_TIME/MBEDTLS_PLATFORM_TIME_ALT cannot be defined simultaneously"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO) &&\
+    ( defined(MBEDTLS_PLATFORM_STD_TIME) ||\
+        defined(MBEDTLS_PLATFORM_TIME_ALT) )
+#error "MBEDTLS_PLATFORM_TIME_TYPE_MACRO and MBEDTLS_PLATFORM_STD_TIME/MBEDTLS_PLATFORM_TIME_ALT cannot be defined simultaneously"
+#endif
+
 #if defined(MBEDTLS_PLATFORM_FPRINTF_ALT) && !defined(MBEDTLS_PLATFORM_C)
 #error "MBEDTLS_PLATFORM_FPRINTF_ALT defined, but not all prerequisites"
 #endif
@@ -342,6 +420,12 @@
 #error "MBEDTLS_PLATFORM_STD_EXIT defined, but not all prerequisites"
 #endif
 
+#if defined(MBEDTLS_PLATFORM_STD_TIME) &&\
+    ( !defined(MBEDTLS_PLATFORM_TIME_ALT) ||\
+        !defined(MBEDTLS_HAVE_TIME) )
+#error "MBEDTLS_PLATFORM_STD_TIME defined, but not all prerequisites"
+#endif
+
 #if defined(MBEDTLS_PLATFORM_STD_FPRINTF) &&\
     !defined(MBEDTLS_PLATFORM_FPRINTF_ALT)
 #error "MBEDTLS_PLATFORM_STD_FPRINTF defined, but not all prerequisites"
@@ -357,11 +441,48 @@
 #error "MBEDTLS_PLATFORM_STD_SNPRINTF defined, but not all prerequisites"
 #endif
 
+#if defined(MBEDTLS_ENTROPY_NV_SEED) &&\
+    ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_ENTROPY_C) )
+#error "MBEDTLS_ENTROPY_NV_SEED defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_NV_SEED_ALT) &&\
+    !defined(MBEDTLS_ENTROPY_NV_SEED)
+#error "MBEDTLS_PLATFORM_NV_SEED_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ) &&\
+    !defined(MBEDTLS_PLATFORM_NV_SEED_ALT)
+#error "MBEDTLS_PLATFORM_STD_NV_SEED_READ defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE) &&\
+    !defined(MBEDTLS_PLATFORM_NV_SEED_ALT)
+#error "MBEDTLS_PLATFORM_STD_NV_SEED_WRITE defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_NV_SEED_READ_MACRO) &&\
+    ( defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ) ||\
+      defined(MBEDTLS_PLATFORM_NV_SEED_ALT) )
+#error "MBEDTLS_PLATFORM_NV_SEED_READ_MACRO and MBEDTLS_PLATFORM_STD_NV_SEED_READ cannot be defined simultaneously"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO) &&\
+    ( defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE) ||\
+      defined(MBEDTLS_PLATFORM_NV_SEED_ALT) )
+#error "MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO and MBEDTLS_PLATFORM_STD_NV_SEED_WRITE cannot be defined simultaneously"
+#endif
+
 #if defined(MBEDTLS_RSA_C) && ( !defined(MBEDTLS_BIGNUM_C) ||         \
     !defined(MBEDTLS_OID_C) )
 #error "MBEDTLS_RSA_C defined, but not all prerequisites"
 #endif
 
+#if defined(MBEDTLS_RSA_C) && ( !defined(MBEDTLS_PKCS1_V21) &&         \
+    !defined(MBEDTLS_PKCS1_V15) )
+#error "MBEDTLS_RSA_C defined, but none of the PKCS1 versions enabled"
+#endif
+
 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) &&                        \
     ( !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_PKCS1_V21) )
 #error "MBEDTLS_X509_RSASSA_PSS_SUPPORT defined, but not all prerequisites"
@@ -530,6 +651,15 @@
 #error "MBEDTLS_X509_CSR_WRITE_C defined, but not all prerequisites"
 #endif
 
+#if defined(MBEDTLS_HAVE_INT32) && defined(MBEDTLS_HAVE_INT64)
+#error "MBEDTLS_HAVE_INT32 and MBEDTLS_HAVE_INT64 cannot be defined simultaneously"
+#endif /* MBEDTLS_HAVE_INT32 && MBEDTLS_HAVE_INT64 */
+
+#if ( defined(MBEDTLS_HAVE_INT32) || defined(MBEDTLS_HAVE_INT64) ) && \
+    defined(MBEDTLS_HAVE_ASM)
+#error "MBEDTLS_HAVE_INT32/MBEDTLS_HAVE_INT64 and MBEDTLS_HAVE_ASM cannot be defined simultaneously"
+#endif /* (MBEDTLS_HAVE_INT32 || MBEDTLS_HAVE_INT64) && MBEDTLS_HAVE_ASM */
+
 /*
  * Avoid warning from -pedantic. This is a convenient place for this
  * workaround since this is included by every single file before the

+ 310 - 256
app/include/mbedtls/cipher.h

@@ -1,11 +1,12 @@
 /**
  * \file cipher.h
  *
- * \brief Generic cipher wrapper.
+ * \brief The generic cipher wrapper.
  *
  * \author Adriaan de Jong <dejong@fox-it.com>
- *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -20,7 +21,7 @@
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *
- *  This file is part of mbed TLS (https://tls.mbed.org)
+ *  This file is part of Mbed TLS (https://tls.mbed.org)
  */
 
 #ifndef MBEDTLS_CIPHER_H
@@ -51,20 +52,29 @@
 #define inline __inline
 #endif
 
-#define MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE            -0x6080  /**< The selected feature is not available. */
-#define MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA                 -0x6100  /**< Bad input parameters to function. */
-#define MBEDTLS_ERR_CIPHER_ALLOC_FAILED                   -0x6180  /**< Failed to allocate memory. */
-#define MBEDTLS_ERR_CIPHER_INVALID_PADDING                -0x6200  /**< Input data contains invalid padding and is rejected. */
-#define MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED            -0x6280  /**< Decryption of block requires a full block. */
-#define MBEDTLS_ERR_CIPHER_AUTH_FAILED                    -0x6300  /**< Authentication failed (for AEAD modes). */
+#define MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE  -0x6080  /**< The selected feature is not available. */
+#define MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA       -0x6100  /**< Bad input parameters. */
+#define MBEDTLS_ERR_CIPHER_ALLOC_FAILED         -0x6180  /**< Failed to allocate memory. */
+#define MBEDTLS_ERR_CIPHER_INVALID_PADDING      -0x6200  /**< Input data contains invalid padding and is rejected. */
+#define MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED  -0x6280  /**< Decryption of block requires a full block. */
+#define MBEDTLS_ERR_CIPHER_AUTH_FAILED          -0x6300  /**< Authentication failed (for AEAD modes). */
+#define MBEDTLS_ERR_CIPHER_INVALID_CONTEXT      -0x6380  /**< The context is invalid. For example, because it was freed. */
+#define MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED      -0x6400  /**< Cipher hardware accelerator failed. */
 
-#define MBEDTLS_CIPHER_VARIABLE_IV_LEN     0x01    /**< Cipher accepts IVs of variable length */
-#define MBEDTLS_CIPHER_VARIABLE_KEY_LEN    0x02    /**< Cipher accepts keys of variable length */
+#define MBEDTLS_CIPHER_VARIABLE_IV_LEN     0x01    /**< Cipher accepts IVs of variable length. */
+#define MBEDTLS_CIPHER_VARIABLE_KEY_LEN    0x02    /**< Cipher accepts keys of variable length. */
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
+/**
+ * \brief     An enumeration of supported ciphers.
+ *
+ * \warning   ARC4 and DES are considered weak ciphers and their use
+ *            constitutes a security risk. We recommend considering stronger
+ *            ciphers instead.
+ */
 typedef enum {
     MBEDTLS_CIPHER_ID_NONE = 0,
     MBEDTLS_CIPHER_ID_NULL,
@@ -76,6 +86,13 @@ typedef enum {
     MBEDTLS_CIPHER_ID_ARC4,
 } mbedtls_cipher_id_t;
 
+/**
+ * \brief     An enumeration of supported (cipher, mode) pairs.
+ *
+ * \warning   ARC4 and DES are considered weak ciphers and their use
+ *            constitutes a security risk. We recommend considering stronger
+ *            ciphers instead.
+ */
 typedef enum {
     MBEDTLS_CIPHER_NONE = 0,
     MBEDTLS_CIPHER_NULL,
@@ -128,6 +145,7 @@ typedef enum {
     MBEDTLS_CIPHER_CAMELLIA_256_CCM,
 } mbedtls_cipher_type_t;
 
+/** Supported cipher modes. */
 typedef enum {
     MBEDTLS_MODE_NONE = 0,
     MBEDTLS_MODE_ECB,
@@ -140,14 +158,16 @@ typedef enum {
     MBEDTLS_MODE_CCM,
 } mbedtls_cipher_mode_t;
 
+/** Supported cipher padding types. */
 typedef enum {
-    MBEDTLS_PADDING_PKCS7 = 0,     /**< PKCS7 padding (default)        */
-    MBEDTLS_PADDING_ONE_AND_ZEROS, /**< ISO/IEC 7816-4 padding         */
-    MBEDTLS_PADDING_ZEROS_AND_LEN, /**< ANSI X.923 padding             */
-    MBEDTLS_PADDING_ZEROS,         /**< zero padding (not reversible!) */
-    MBEDTLS_PADDING_NONE,          /**< never pad (full blocks only)   */
+    MBEDTLS_PADDING_PKCS7 = 0,     /**< PKCS7 padding (default).        */
+    MBEDTLS_PADDING_ONE_AND_ZEROS, /**< ISO/IEC 7816-4 padding.         */
+    MBEDTLS_PADDING_ZEROS_AND_LEN, /**< ANSI X.923 padding.             */
+    MBEDTLS_PADDING_ZEROS,         /**< zero padding (not reversible). */
+    MBEDTLS_PADDING_NONE,          /**< never pad (full blocks only).   */
 } mbedtls_cipher_padding_t;
 
+/** Type of operation. */
 typedef enum {
     MBEDTLS_OPERATION_NONE = -1,
     MBEDTLS_DECRYPT = 0,
@@ -155,19 +175,19 @@ typedef enum {
 } mbedtls_operation_t;
 
 enum {
-    /** Undefined key length */
+    /** Undefined key length. */
     MBEDTLS_KEY_LENGTH_NONE = 0,
-    /** Key length, in bits (including parity), for DES keys */
+    /** Key length, in bits (including parity), for DES keys. */
     MBEDTLS_KEY_LENGTH_DES  = 64,
-    /** Key length, in bits (including parity), for DES in two key EDE */
+    /** Key length in bits, including parity, for DES in two-key EDE. */
     MBEDTLS_KEY_LENGTH_DES_EDE = 128,
-    /** Key length, in bits (including parity), for DES in three-key EDE */
+    /** Key length in bits, including parity, for DES in three-key EDE. */
     MBEDTLS_KEY_LENGTH_DES_EDE3 = 192,
 };
 
-/** Maximum length of any IV, in bytes */
+/** Maximum length of any IV, in Bytes. */
 #define MBEDTLS_MAX_IV_LENGTH      16
-/** Maximum block size of any cipher, in bytes */
+/** Maximum block size of any cipher, in Bytes. */
 #define MBEDTLS_MAX_BLOCK_LENGTH   16
 
 /**
@@ -176,33 +196,45 @@ enum {
 typedef struct mbedtls_cipher_base_t mbedtls_cipher_base_t;
 
 /**
- * Cipher information. Allows cipher functions to be called in a generic way.
+ * CMAC context (opaque struct).
+ */
+typedef struct mbedtls_cmac_context_t mbedtls_cmac_context_t;
+
+/**
+ * Cipher information. Allows calling cipher functions
+ * in a generic way.
  */
 typedef struct {
-    /** Full cipher identifier (e.g. MBEDTLS_CIPHER_AES_256_CBC) */
+    /** Full cipher identifier. For example,
+     * MBEDTLS_CIPHER_AES_256_CBC.
+     */
     mbedtls_cipher_type_t type;
 
-    /** Cipher mode (e.g. MBEDTLS_MODE_CBC) */
+    /** The cipher mode. For example, MBEDTLS_MODE_CBC. */
     mbedtls_cipher_mode_t mode;
 
-    /** Cipher key length, in bits (default length for variable sized ciphers)
-     *  (Includes parity bits for ciphers like DES) */
+    /** The cipher key length, in bits. This is the
+     * default length for variable sized ciphers.
+     * Includes parity bits for ciphers like DES.
+     */
     unsigned int key_bitlen;
 
-    /** Name of the cipher */
+    /** Name of the cipher. */
     const char * name;
 
-    /** IV/NONCE size, in bytes.
-     *  For cipher that accept many sizes: recommended size */
+    /** IV or nonce size, in Bytes.
+     * For ciphers that accept variable IV sizes,
+     * this is the recommended size.
+     */
     unsigned int iv_size;
 
-    /** Flags for variable IV size, variable key size, etc. */
+    /** Flags to set. For example, if the cipher supports variable IV sizes or variable key sizes. */
     int flags;
 
-    /** block size, in bytes */
+    /** The block size, in Bytes. */
     unsigned int block_size;
 
-    /** Base cipher information and functions */
+    /** Struct for base cipher information and functions. */
     const mbedtls_cipher_base_t *base;
 
 } mbedtls_cipher_info_t;
@@ -211,120 +243,133 @@ typedef struct {
  * Generic cipher context.
  */
 typedef struct {
-    /** Information about the associated cipher */
+    /** Information about the associated cipher. */
     const mbedtls_cipher_info_t *cipher_info;
 
-    /** Key length to use */
+    /** Key length to use. */
     int key_bitlen;
 
-    /** Operation that the context's key has been initialised for */
+    /** Operation that the key of the context has been
+     * initialized for.
+     */
     mbedtls_operation_t operation;
 
 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
-    /** Padding functions to use, if relevant for cipher mode */
+    /** Padding functions to use, if relevant for
+     * the specific cipher mode.
+     */
     void (*add_padding)( unsigned char *output, size_t olen, size_t data_len );
     int (*get_padding)( unsigned char *input, size_t ilen, size_t *data_len );
 #endif
 
-    /** Buffer for data that hasn't been encrypted yet */
+    /** Buffer for input that has not been processed yet. */
     unsigned char unprocessed_data[MBEDTLS_MAX_BLOCK_LENGTH];
 
-    /** Number of bytes that still need processing */
+    /** Number of Bytes that have not been processed yet. */
     size_t unprocessed_len;
 
-    /** Current IV or NONCE_COUNTER for CTR-mode */
+    /** Current IV or NONCE_COUNTER for CTR-mode. */
     unsigned char iv[MBEDTLS_MAX_IV_LENGTH];
 
-    /** IV size in bytes (for ciphers with variable-length IVs) */
+    /** IV size in Bytes, for ciphers with variable-length IVs. */
     size_t iv_size;
 
-    /** Cipher-specific context */
+    /** The cipher-specific context. */
     void *cipher_ctx;
+
+#if defined(MBEDTLS_CMAC_C)
+    /** CMAC-specific context. */
+    mbedtls_cmac_context_t *cmac_ctx;
+#endif
 } mbedtls_cipher_context_t;
 
 /**
- * \brief Returns the list of ciphers supported by the generic cipher module.
+ * \brief This function retrieves the list of ciphers supported by the generic
+ * cipher module.
  *
- * \return              a statically allocated array of ciphers, the last entry
- *                      is 0.
+ * \return      A statically-allocated array of ciphers. The last entry
+ *              is zero.
  */
 const int *mbedtls_cipher_list( void );
 
 /**
- * \brief               Returns the cipher information structure associated
- *                      with the given cipher name.
+ * \brief               This function retrieves the cipher-information
+ *                      structure associated with the given cipher name.
  *
  * \param cipher_name   Name of the cipher to search for.
  *
- * \return              the cipher information structure associated with the
- *                      given cipher_name, or NULL if not found.
+ * \return              The cipher information structure associated with the
+ *                      given \p cipher_name, or NULL if not found.
  */
 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( const char *cipher_name );
 
 /**
- * \brief               Returns the cipher information structure associated
- *                      with the given cipher type.
+ * \brief               This function retrieves the cipher-information
+ *                      structure associated with the given cipher type.
  *
  * \param cipher_type   Type of the cipher to search for.
  *
- * \return              the cipher information structure associated with the
- *                      given cipher_type, or NULL if not found.
+ * \return              The cipher information structure associated with the
+ *                      given \p cipher_type, or NULL if not found.
  */
 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( const mbedtls_cipher_type_t cipher_type );
 
 /**
- * \brief               Returns the cipher information structure associated
- *                      with the given cipher id, key size and mode.
+ * \brief               This function retrieves the cipher-information
+ *                      structure associated with the given cipher ID,
+ *                      key size and mode.
  *
- * \param cipher_id     Id of the cipher to search for
- *                      (e.g. MBEDTLS_CIPHER_ID_AES)
- * \param key_bitlen    Length of the key in bits
- * \param mode          Cipher mode (e.g. MBEDTLS_MODE_CBC)
+ * \param cipher_id     The ID of the cipher to search for. For example,
+ *                      #MBEDTLS_CIPHER_ID_AES.
+ * \param key_bitlen    The length of the key in bits.
+ * \param mode          The cipher mode. For example, #MBEDTLS_MODE_CBC.
  *
- * \return              the cipher information structure associated with the
- *                      given cipher_type, or NULL if not found.
+ * \return              The cipher information structure associated with the
+ *                      given \p cipher_id, or NULL if not found.
  */
 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values( const mbedtls_cipher_id_t cipher_id,
                                               int key_bitlen,
                                               const mbedtls_cipher_mode_t mode );
 
 /**
- * \brief               Initialize a cipher_context (as NONE)
+ * \brief               This function initializes a \p cipher_context as NONE.
  */
 void mbedtls_cipher_init( mbedtls_cipher_context_t *ctx );
 
 /**
- * \brief               Free and clear the cipher-specific context of ctx.
- *                      Freeing ctx itself remains the responsibility of the
- *                      caller.
+ * \brief               This function frees and clears the cipher-specific
+ *                      context of \p ctx. Freeing \p ctx itself remains the
+ *                      responsibility of the caller.
  */
 void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx );
 
+
 /**
- * \brief               Initialises and fills the cipher context structure with
- *                      the appropriate values.
- *
- * \note                Currently also clears structure. In future versions you
- *                      will be required to call mbedtls_cipher_init() on the structure
- *                      first.
+ * \brief               This function initializes and fills the cipher-context
+ *                      structure with the appropriate values. It also clears
+ *                      the structure.
  *
- * \param ctx           context to initialise. May not be NULL.
- * \param cipher_info   cipher to use.
+ * \param ctx           The context to initialize. May not be NULL.
+ * \param cipher_info   The cipher to use.
  *
- * \return              0 on success,
- *                      MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on parameter failure,
- *                      MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the
+ * \return              \c 0 on success,
+ *                      #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on parameter failure,
+ *                      #MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the
  *                      cipher-specific context failed.
+ *
+ * \internal Currently, the function also clears the structure.
+ * In future versions, the caller will be required to call
+ * mbedtls_cipher_init() on the structure first.
  */
 int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_info_t *cipher_info );
 
 /**
- * \brief               Returns the block size of the given cipher.
+ * \brief        This function returns the block size of the given cipher.
  *
- * \param ctx           cipher's context. Must have been initialised.
+ * \param ctx    The context of the cipher. Must be initialized.
  *
- * \return              size of the cipher's blocks, or 0 if ctx has not been
- *                      initialised.
+ * \return       The size of the blocks of the cipher, or zero if \p ctx
+ *               has not been initialized.
  */
 static inline unsigned int mbedtls_cipher_get_block_size( const mbedtls_cipher_context_t *ctx )
 {
@@ -335,13 +380,13 @@ static inline unsigned int mbedtls_cipher_get_block_size( const mbedtls_cipher_c
 }
 
 /**
- * \brief               Returns the mode of operation for the cipher.
- *                      (e.g. MBEDTLS_MODE_CBC)
+ * \brief        This function returns the mode of operation for
+ *               the cipher. For example, MBEDTLS_MODE_CBC.
  *
- * \param ctx           cipher's context. Must have been initialised.
+ * \param ctx    The context of the cipher. Must be initialized.
  *
- * \return              mode of operation, or MBEDTLS_MODE_NONE if ctx
- *                      has not been initialised.
+ * \return       The mode of operation, or #MBEDTLS_MODE_NONE if
+ *               \p ctx has not been initialized.
  */
 static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode( const mbedtls_cipher_context_t *ctx )
 {
@@ -352,13 +397,14 @@ static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode( const mbedtl
 }
 
 /**
- * \brief               Returns the size of the cipher's IV/NONCE in bytes.
+ * \brief       This function returns the size of the IV or nonce
+ *              of the cipher, in Bytes.
  *
- * \param ctx           cipher's context. Must have been initialised.
+ * \param ctx   The context of the cipher. Must be initialized.
  *
- * \return              If IV has not been set yet: (recommended) IV size
- *                      (0 for ciphers not using IV/NONCE).
- *                      If IV has already been set: actual size.
+ * \return      <ul><li>If no IV has been set: the recommended IV size.
+ *              0 for ciphers not using IV or nonce.</li>
+ *              <li>If IV has already been set: the actual size.</li></ul>
  */
 static inline int mbedtls_cipher_get_iv_size( const mbedtls_cipher_context_t *ctx )
 {
@@ -372,12 +418,12 @@ static inline int mbedtls_cipher_get_iv_size( const mbedtls_cipher_context_t *ct
 }
 
 /**
- * \brief               Returns the type of the given cipher.
+ * \brief               This function returns the type of the given cipher.
  *
- * \param ctx           cipher's context. Must have been initialised.
+ * \param ctx           The context of the cipher. Must be initialized.
  *
- * \return              type of the cipher, or MBEDTLS_CIPHER_NONE if ctx has
- *                      not been initialised.
+ * \return              The type of the cipher, or #MBEDTLS_CIPHER_NONE if
+ *                      \p ctx has not been initialized.
  */
 static inline mbedtls_cipher_type_t mbedtls_cipher_get_type( const mbedtls_cipher_context_t *ctx )
 {
@@ -388,11 +434,13 @@ static inline mbedtls_cipher_type_t mbedtls_cipher_get_type( const mbedtls_ciphe
 }
 
 /**
- * \brief               Returns the name of the given cipher, as a string.
+ * \brief               This function returns the name of the given cipher
+ *                      as a string.
  *
- * \param ctx           cipher's context. Must have been initialised.
+ * \param ctx           The context of the cipher. Must be initialized.
  *
- * \return              name of the cipher, or NULL if ctx was not initialised.
+ * \return              The name of the cipher, or NULL if \p ctx has not
+ *                      been not initialized.
  */
 static inline const char *mbedtls_cipher_get_name( const mbedtls_cipher_context_t *ctx )
 {
@@ -403,13 +451,13 @@ static inline const char *mbedtls_cipher_get_name( const mbedtls_cipher_context_
 }
 
 /**
- * \brief               Returns the key length of the cipher.
+ * \brief               This function returns the key length of the cipher.
  *
- * \param ctx           cipher's context. Must have been initialised.
+ * \param ctx           The context of the cipher. Must be initialized.
  *
- * \return              cipher's key length, in bits, or
- *                      MBEDTLS_KEY_LENGTH_NONE if ctx has not been
- *                      initialised.
+ * \return              The key length of the cipher in bits, or
+ *                      #MBEDTLS_KEY_LENGTH_NONE if ctx \p has not been
+ *                      initialized.
  */
 static inline int mbedtls_cipher_get_key_bitlen( const mbedtls_cipher_context_t *ctx )
 {
@@ -420,13 +468,13 @@ static inline int mbedtls_cipher_get_key_bitlen( const mbedtls_cipher_context_t
 }
 
 /**
- * \brief               Returns the operation of the given cipher.
+ * \brief          This function returns the operation of the given cipher.
  *
- * \param ctx           cipher's context. Must have been initialised.
+ * \param ctx      The context of the cipher. Must be initialized.
  *
- * \return              operation (MBEDTLS_ENCRYPT or MBEDTLS_DECRYPT),
- *                      or MBEDTLS_OPERATION_NONE if ctx has not been
- *                      initialised.
+ * \return         The type of operation: #MBEDTLS_ENCRYPT or
+ *                 #MBEDTLS_DECRYPT, or #MBEDTLS_OPERATION_NONE if \p ctx
+ *                 has not been initialized.
  */
 static inline mbedtls_operation_t mbedtls_cipher_get_operation( const mbedtls_cipher_context_t *ctx )
 {
@@ -437,18 +485,18 @@ static inline mbedtls_operation_t mbedtls_cipher_get_operation( const mbedtls_ci
 }
 
 /**
- * \brief               Set the key to use with the given context.
+ * \brief               This function sets the key to use with the given context.
  *
- * \param ctx           generic cipher context. May not be NULL. Must have been
- *                      initialised using cipher_context_from_type or
- *                      cipher_context_from_string.
+ * \param ctx           The generic cipher context. May not be NULL. Must have
+ *                      been initialized using mbedtls_cipher_info_from_type()
+ *                      or mbedtls_cipher_info_from_string().
  * \param key           The key to use.
- * \param key_bitlen    key length to use, in bits.
- * \param operation     Operation that the key will be used for, either
- *                      MBEDTLS_ENCRYPT or MBEDTLS_DECRYPT.
+ * \param key_bitlen    The key length to use, in bits.
+ * \param operation     The operation that the key will be used for:
+ *                      #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT.
  *
- * \returns             0 on success, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if
- *                      parameter verification fails or a cipher specific
+ * \returns             \c 0 on success, #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if
+ *                      parameter verification fails, or a cipher-specific
  *                      error code.
  */
 int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *key,
@@ -456,170 +504,176 @@ int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *k
 
 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
 /**
- * \brief               Set padding mode, for cipher modes that use padding.
- *                      (Default: PKCS7 padding.)
+ * \brief               This function sets the padding mode, for cipher modes
+ *                      that use padding.
+ *
+ *                      The default passing mode is PKCS7 padding.
  *
- * \param ctx           generic cipher context
- * \param mode          padding mode
+ * \param ctx           The generic cipher context.
+ * \param mode          The padding mode.
  *
- * \returns             0 on success, MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE
- *                      if selected padding mode is not supported, or
- *                      MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if the cipher mode
+ * \returns             \c 0 on success, #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE
+ *                      if the selected padding mode is not supported, or
+ *                      #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if the cipher mode
  *                      does not support padding.
  */
 int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_cipher_padding_t mode );
 #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */
 
 /**
- * \brief               Set the initialization vector (IV) or nonce
+ * \brief           This function sets the initialization vector (IV)
+ *                  or nonce.
  *
- * \param ctx           generic cipher context
- * \param iv            IV to use (or NONCE_COUNTER for CTR-mode ciphers)
- * \param iv_len        IV length for ciphers with variable-size IV;
- *                      discarded by ciphers with fixed-size IV.
+ * \param ctx       The generic cipher context.
+ * \param iv        The IV to use, or NONCE_COUNTER for CTR-mode ciphers.
+ * \param iv_len    The IV length for ciphers with variable-size IV.
+ *                  This parameter is discarded by ciphers with fixed-size IV.
  *
- * \returns             0 on success, or MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA
+ * \returns         \c 0 on success, or #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA
  *
- * \note                Some ciphers don't use IVs nor NONCE. For these
- *                      ciphers, this function has no effect.
+ * \note            Some ciphers do not use IVs nor nonce. For these
+ *                  ciphers, this function has no effect.
  */
 int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx,
                    const unsigned char *iv, size_t iv_len );
 
 /**
- * \brief               Finish preparation of the given context
+ * \brief         This function resets the cipher state.
  *
- * \param ctx           generic cipher context
+ * \param ctx     The generic cipher context.
  *
- * \returns             0 on success, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA
- *                      if parameter verification fails.
+ * \returns       \c 0 on success, #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA
+ *                if parameter verification fails.
  */
 int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx );
 
 #if defined(MBEDTLS_GCM_C)
 /**
- * \brief               Add additional data (for AEAD ciphers).
- *                      Currently only supported with GCM.
- *                      Must be called exactly once, after mbedtls_cipher_reset().
+ * \brief               This function adds additional data for AEAD ciphers.
+ *                      Only supported with GCM. Must be called
+ *                      exactly once, after mbedtls_cipher_reset().
  *
- * \param ctx           generic cipher context
- * \param ad            Additional data to use.
- * \param ad_len        Length of ad.
+ * \param ctx           The generic cipher context.
+ * \param ad            The additional data to use.
+ * \param ad_len        the Length of \p ad.
  *
- * \return              0 on success, or a specific error code.
+ * \return              \c 0 on success, or a specific error code on failure.
  */
 int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx,
                       const unsigned char *ad, size_t ad_len );
 #endif /* MBEDTLS_GCM_C */
 
 /**
- * \brief               Generic cipher update function. Encrypts/decrypts
- *                      using the given cipher context. Writes as many block
- *                      size'd blocks of data as possible to output. Any data
- *                      that cannot be written immediately will either be added
- *                      to the next block, or flushed when cipher_final is
- *                      called.
- *                      Exception: for MBEDTLS_MODE_ECB, expects single block
- *                                 in size (e.g. 16 bytes for AES)
- *
- * \param ctx           generic cipher context
- * \param input         buffer holding the input data
- * \param ilen          length of the input data
- * \param output        buffer for the output data. Should be able to hold at
- *                      least ilen + block_size. Cannot be the same buffer as
- *                      input!
- * \param olen          length of the output data, will be filled with the
- *                      actual number of bytes written.
- *
- * \returns             0 on success, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if
+ * \brief               The generic cipher update function. It encrypts or
+ *                      decrypts using the given cipher context. Writes as
+ *                      many block-sized blocks of data as possible to output.
+ *                      Any data that cannot be written immediately is either
+ *                      added to the next block, or flushed when
+ *                      mbedtls_cipher_finish() is called.
+ *                      Exception: For MBEDTLS_MODE_ECB, expects a single block
+ *                      in size. For example, 16 Bytes for AES.
+ *
+ * \param ctx           The generic cipher context.
+ * \param input         The buffer holding the input data.
+ * \param ilen          The length of the input data.
+ * \param output        The buffer for the output data. Must be able to hold at
+ *                      least \p ilen + block_size. Must not be the same buffer
+ *                      as input.
+ * \param olen          The length of the output data, to be updated with the
+ *                      actual number of Bytes written.
+ *
+ * \returns             \c 0 on success, #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if
  *                      parameter verification fails,
- *                      MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE on an
- *                      unsupported mode for a cipher or a cipher specific
+ *                      #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE on an
+ *                      unsupported mode for a cipher, or a cipher-specific
  *                      error code.
  *
  * \note                If the underlying cipher is GCM, all calls to this
- *                      function, except the last one before mbedtls_cipher_finish(),
- *                      must have ilen a multiple of the block size.
+ *                      function, except the last one before
+ *                      mbedtls_cipher_finish(). Must have \p ilen as a
+ *                      multiple of the block_size.
  */
 int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input,
                    size_t ilen, unsigned char *output, size_t *olen );
 
 /**
- * \brief               Generic cipher finalisation function. If data still
- *                      needs to be flushed from an incomplete block, data
- *                      contained within it will be padded with the size of
- *                      the last block, and written to the output buffer.
+ * \brief               The generic cipher finalization function. If data still
+ *                      needs to be flushed from an incomplete block, the data
+ *                      contained in it is padded to the size of
+ *                      the last block, and written to the \p output buffer.
  *
- * \param ctx           Generic cipher context
- * \param output        buffer to write data to. Needs block_size available.
- * \param olen          length of the data written to the output buffer.
+ * \param ctx           The generic cipher context.
+ * \param output        The buffer to write data to. Needs block_size available.
+ * \param olen          The length of the data written to the \p output buffer.
  *
- * \returns             0 on success, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if
+ * \returns             \c 0 on success, #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if
  *                      parameter verification fails,
- *                      MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED if decryption
+ *                      #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED if decryption
  *                      expected a full block but was not provided one,
- *                      MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding
- *                      while decrypting or a cipher specific error code.
+ *                      #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding
+ *                      while decrypting, or a cipher-specific error code
+ *                      on failure for any other reason.
  */
 int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx,
                    unsigned char *output, size_t *olen );
 
 #if defined(MBEDTLS_GCM_C)
 /**
- * \brief               Write tag for AEAD ciphers.
- *                      Currently only supported with GCM.
+ * \brief               This function writes a tag for AEAD ciphers.
+ *                      Only supported with GCM.
  *                      Must be called after mbedtls_cipher_finish().
  *
- * \param ctx           Generic cipher context
- * \param tag           buffer to write the tag
- * \param tag_len       Length of the tag to write
+ * \param ctx           The generic cipher context.
+ * \param tag           The buffer to write the tag to.
+ * \param tag_len       The length of the tag to write.
  *
- * \return              0 on success, or a specific error code.
+ * \return              \c 0 on success, or a specific error code on failure.
  */
 int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx,
                       unsigned char *tag, size_t tag_len );
 
 /**
- * \brief               Check tag for AEAD ciphers.
- *                      Currently only supported with GCM.
+ * \brief               This function checks the tag for AEAD ciphers.
+ *                      Only supported with GCM.
  *                      Must be called after mbedtls_cipher_finish().
  *
- * \param ctx           Generic cipher context
- * \param tag           Buffer holding the tag
- * \param tag_len       Length of the tag to check
+ * \param ctx           The generic cipher context.
+ * \param tag           The buffer holding the tag.
+ * \param tag_len       The length of the tag to check.
  *
- * \return              0 on success, or a specific error code.
+ * \return              \c 0 on success, or a specific error code on failure.
  */
 int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx,
                       const unsigned char *tag, size_t tag_len );
 #endif /* MBEDTLS_GCM_C */
 
 /**
- * \brief               Generic all-in-one encryption/decryption
- *                      (for all ciphers except AEAD constructs).
- *
- * \param ctx           generic cipher context
- * \param iv            IV to use (or NONCE_COUNTER for CTR-mode ciphers)
- * \param iv_len        IV length for ciphers with variable-size IV;
- *                      discarded by ciphers with fixed-size IV.
- * \param input         buffer holding the input data
- * \param ilen          length of the input data
- * \param output        buffer for the output data. Should be able to hold at
- *                      least ilen + block_size. Cannot be the same buffer as
- *                      input!
- * \param olen          length of the output data, will be filled with the
- *                      actual number of bytes written.
- *
- * \note                Some ciphers don't use IVs nor NONCE. For these
- *                      ciphers, use iv = NULL and iv_len = 0.
- *
- * \returns             0 on success, or
- *                      MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or
- *                      MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED if decryption
+ * \brief               The generic all-in-one encryption/decryption function,
+ *                      for all ciphers except AEAD constructs.
+ *
+ * \param ctx           The generic cipher context.
+ * \param iv            The IV to use, or NONCE_COUNTER for CTR-mode ciphers.
+ * \param iv_len        The IV length for ciphers with variable-size IV.
+ *                      This parameter is discarded by ciphers with fixed-size
+ *                      IV.
+ * \param input         The buffer holding the input data.
+ * \param ilen          The length of the input data.
+ * \param output        The buffer for the output data. Must be able to hold at
+ *                      least \p ilen + block_size. Must not be the same buffer
+ *                      as input.
+ * \param olen          The length of the output data, to be updated with the
+ *                      actual number of Bytes written.
+ *
+ * \note                Some ciphers do not use IVs nor nonce. For these
+ *                      ciphers, use \p iv = NULL and \p iv_len = 0.
+ *
+ * \returns             \c 0 on success, or
+ *                      #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or
+ *                      #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED if decryption
  *                      expected a full block but was not provided one, or
- *                      MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding
- *                      while decrypting, or
- *                      a cipher specific error code.
+ *                      #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding
+ *                      while decrypting, or a cipher-specific error code on
+ *                      failure for any other reason.
  */
 int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx,
                   const unsigned char *iv, size_t iv_len,
@@ -628,26 +682,26 @@ int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx,
 
 #if defined(MBEDTLS_CIPHER_MODE_AEAD)
 /**
- * \brief               Generic autenticated encryption (AEAD ciphers).
- *
- * \param ctx           generic cipher context
- * \param iv            IV to use (or NONCE_COUNTER for CTR-mode ciphers)
- * \param iv_len        IV length for ciphers with variable-size IV;
- *                      discarded by ciphers with fixed-size IV.
- * \param ad            Additional data to authenticate.
- * \param ad_len        Length of ad.
- * \param input         buffer holding the input data
- * \param ilen          length of the input data
- * \param output        buffer for the output data.
- *                      Should be able to hold at least ilen.
- * \param olen          length of the output data, will be filled with the
- *                      actual number of bytes written.
- * \param tag           buffer for the authentication tag
- * \param tag_len       desired tag length
- *
- * \returns             0 on success, or
- *                      MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or
- *                      a cipher specific error code.
+ * \brief               The generic autenticated encryption (AEAD) function.
+ *
+ * \param ctx           The generic cipher context.
+ * \param iv            The IV to use, or NONCE_COUNTER for CTR-mode ciphers.
+ * \param iv_len        The IV length for ciphers with variable-size IV.
+ *                      This parameter is discarded by ciphers with fixed-size IV.
+ * \param ad            The additional data to authenticate.
+ * \param ad_len        The length of \p ad.
+ * \param input         The buffer holding the input data.
+ * \param ilen          The length of the input data.
+ * \param output        The buffer for the output data.
+ *                      Must be able to hold at least \p ilen.
+ * \param olen          The length of the output data, to be updated with the
+ *                      actual number of Bytes written.
+ * \param tag           The buffer for the authentication tag.
+ * \param tag_len       The desired length of the authentication tag.
+ *
+ * \returns             \c 0 on success, or
+ *                      #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or
+ *                      a cipher-specific error code.
  */
 int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx,
                          const unsigned char *iv, size_t iv_len,
@@ -657,31 +711,31 @@ int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx,
                          unsigned char *tag, size_t tag_len );
 
 /**
- * \brief               Generic autenticated decryption (AEAD ciphers).
- *
- * \param ctx           generic cipher context
- * \param iv            IV to use (or NONCE_COUNTER for CTR-mode ciphers)
- * \param iv_len        IV length for ciphers with variable-size IV;
- *                      discarded by ciphers with fixed-size IV.
- * \param ad            Additional data to be authenticated.
- * \param ad_len        Length of ad.
- * \param input         buffer holding the input data
- * \param ilen          length of the input data
- * \param output        buffer for the output data.
- *                      Should be able to hold at least ilen.
- * \param olen          length of the output data, will be filled with the
- *                      actual number of bytes written.
- * \param tag           buffer holding the authentication tag
- * \param tag_len       length of the authentication tag
- *
- * \returns             0 on success, or
- *                      MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or
- *                      MBEDTLS_ERR_CIPHER_AUTH_FAILED if data isn't authentic,
- *                      or a cipher specific error code.
+ * \brief               The generic autenticated decryption (AEAD) function.
+ *
+ * \param ctx           The generic cipher context.
+ * \param iv            The IV to use, or NONCE_COUNTER for CTR-mode ciphers.
+ * \param iv_len        The IV length for ciphers with variable-size IV.
+ *                      This parameter is discarded by ciphers with fixed-size IV.
+ * \param ad            The additional data to be authenticated.
+ * \param ad_len        The length of \p ad.
+ * \param input         The buffer holding the input data.
+ * \param ilen          The length of the input data.
+ * \param output        The buffer for the output data.
+ *                      Must be able to hold at least \p ilen.
+ * \param olen          The length of the output data, to be updated with the
+ *                      actual number of Bytes written.
+ * \param tag           The buffer holding the authentication tag.
+ * \param tag_len       The length of the authentication tag.
+ *
+ * \returns             \c 0 on success, or
+ *                      #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or
+ *                      #MBEDTLS_ERR_CIPHER_AUTH_FAILED if data is not authentic,
+ *                      or a cipher-specific error code on failure for any other reason.
  *
  * \note                If the data is not authentic, then the output buffer
- *                      is zeroed out to prevent the unauthentic plaintext to
- *                      be used by mistake, making this interface safer.
+ *                      is zeroed out to prevent the unauthentic plaintext being
+ *                      used, making this interface safer.
  */
 int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx,
                          const unsigned char *iv, size_t iv_len,

+ 2 - 1
app/include/mbedtls/cipher_internal.h

@@ -4,7 +4,8 @@
  * \brief Cipher wrappers.
  *
  * \author Adriaan de Jong <dejong@fox-it.com>
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 208 - 0
app/include/mbedtls/cmac.h

@@ -0,0 +1,208 @@
+/**
+ * \file cmac.h
+ *
+ * \brief The Cipher-based Message Authentication Code (CMAC) Mode for
+ *        Authentication.
+ */
+/*
+ *  Copyright (C) 2015-2018, Arm Limited (or its affiliates), All Rights Reserved
+ *  SPDX-License-Identifier: Apache-2.0
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License"); you may
+ *  not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ *  This file is part of Mbed TLS (https://tls.mbed.org)
+ */
+
+#ifndef MBEDTLS_CMAC_H
+#define MBEDTLS_CMAC_H
+
+#include "mbedtls/cipher.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED -0x007A  /**< CMAC hardware accelerator failed. */
+
+#define MBEDTLS_AES_BLOCK_SIZE          16
+#define MBEDTLS_DES3_BLOCK_SIZE         8
+
+#if defined(MBEDTLS_AES_C)
+#define MBEDTLS_CIPHER_BLKSIZE_MAX      16  /* The longest block used by CMAC is that of AES. */
+#else
+#define MBEDTLS_CIPHER_BLKSIZE_MAX      8   /* The longest block used by CMAC is that of 3DES. */
+#endif
+
+#if !defined(MBEDTLS_CMAC_ALT)
+
+/**
+ * The CMAC context structure.
+ */
+struct mbedtls_cmac_context_t
+{
+    /** The internal state of the CMAC algorithm.  */
+    unsigned char       state[MBEDTLS_CIPHER_BLKSIZE_MAX];
+
+    /** Unprocessed data - either data that was not block aligned and is still
+     *  pending processing, or the final block. */
+    unsigned char       unprocessed_block[MBEDTLS_CIPHER_BLKSIZE_MAX];
+
+    /** The length of data pending processing. */
+    size_t              unprocessed_len;
+};
+
+/**
+ * \brief               This function sets the CMAC key, and prepares to authenticate
+ *                      the input data.
+ *                      Must be called with an initialized cipher context.
+ *
+ * \param ctx           The cipher context used for the CMAC operation, initialized
+ *                      as one of the following types:<ul>
+ *                      <li>MBEDTLS_CIPHER_AES_128_ECB</li>
+ *                      <li>MBEDTLS_CIPHER_AES_192_ECB</li>
+ *                      <li>MBEDTLS_CIPHER_AES_256_ECB</li>
+ *                      <li>MBEDTLS_CIPHER_DES_EDE3_ECB</li></ul>
+ * \param key           The CMAC key.
+ * \param keybits       The length of the CMAC key in bits.
+ *                      Must be supported by the cipher.
+ *
+ * \return              \c 0 on success, or a cipher-specific error code.
+ */
+int mbedtls_cipher_cmac_starts( mbedtls_cipher_context_t *ctx,
+                                const unsigned char *key, size_t keybits );
+
+/**
+ * \brief               This function feeds an input buffer into an ongoing CMAC
+ *                      computation.
+ *
+ *                      It is called between mbedtls_cipher_cmac_starts() or
+ *                      mbedtls_cipher_cmac_reset(), and mbedtls_cipher_cmac_finish().
+ *                      Can be called repeatedly.
+ *
+ * \param ctx           The cipher context used for the CMAC operation.
+ * \param input         The buffer holding the input data.
+ * \param ilen          The length of the input data.
+ *
+ * \returns             \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA
+ *                      if parameter verification fails.
+ */
+int mbedtls_cipher_cmac_update( mbedtls_cipher_context_t *ctx,
+                                const unsigned char *input, size_t ilen );
+
+/**
+ * \brief               This function finishes the CMAC operation, and writes
+ *                      the result to the output buffer.
+ *
+ *                      It is called after mbedtls_cipher_cmac_update().
+ *                      It can be followed by mbedtls_cipher_cmac_reset() and
+ *                      mbedtls_cipher_cmac_update(), or mbedtls_cipher_free().
+ *
+ * \param ctx           The cipher context used for the CMAC operation.
+ * \param output        The output buffer for the CMAC checksum result.
+ *
+ * \returns             \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA
+ *                      if parameter verification fails.
+ */
+int mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx,
+                                unsigned char *output );
+
+/**
+ * \brief               This function prepares the authentication of another
+ *                      message with the same key as the previous CMAC
+ *                      operation.
+ *
+ *                      It is called after mbedtls_cipher_cmac_finish()
+ *                      and before mbedtls_cipher_cmac_update().
+ *
+ * \param ctx           The cipher context used for the CMAC operation.
+ *
+ * \returns             \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA
+ *                      if parameter verification fails.
+ */
+int mbedtls_cipher_cmac_reset( mbedtls_cipher_context_t *ctx );
+
+/**
+ * \brief               This function calculates the full generic CMAC
+ *                      on the input buffer with the provided key.
+ *
+ *                      The function allocates the context, performs the
+ *                      calculation, and frees the context.
+ *
+ *                      The CMAC result is calculated as
+ *                      output = generic CMAC(cmac key, input buffer).
+ *
+ *
+ * \param cipher_info   The cipher information.
+ * \param key           The CMAC key.
+ * \param keylen        The length of the CMAC key in bits.
+ * \param input         The buffer holding the input data.
+ * \param ilen          The length of the input data.
+ * \param output        The buffer for the generic CMAC result.
+ *
+ * \returns             \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA
+ *                      if parameter verification fails.
+ */
+int mbedtls_cipher_cmac( const mbedtls_cipher_info_t *cipher_info,
+                         const unsigned char *key, size_t keylen,
+                         const unsigned char *input, size_t ilen,
+                         unsigned char *output );
+
+#if defined(MBEDTLS_AES_C)
+/**
+ * \brief           This function implements the AES-CMAC-PRF-128 pseudorandom
+ *                  function, as defined in
+ *                  <em>RFC-4615: The Advanced Encryption Standard-Cipher-based
+ *                  Message Authentication Code-Pseudo-Random Function-128
+ *                  (AES-CMAC-PRF-128) Algorithm for the Internet Key
+ *                  Exchange Protocol (IKE).</em>
+ *
+ * \param key       The key to use.
+ * \param key_len   The key length in Bytes.
+ * \param input     The buffer holding the input data.
+ * \param in_len    The length of the input data in Bytes.
+ * \param output    The buffer holding the generated 16 Bytes of
+ *                  pseudorandom output.
+ *
+ * \return          \c 0 on success.
+ */
+int mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_len,
+                              const unsigned char *input, size_t in_len,
+                              unsigned char output[16] );
+#endif /* MBEDTLS_AES_C */
+
+#ifdef __cplusplus
+}
+#endif
+
+#else  /* !MBEDTLS_CMAC_ALT */
+#include "cmac_alt.h"
+#endif /* !MBEDTLS_CMAC_ALT */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(MBEDTLS_SELF_TEST) && ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_DES_C) )
+/**
+ * \brief          The CMAC checkup routine.
+ *
+ * \return         \c 0 on success, or \c 1 on failure.
+ */
+int mbedtls_cmac_self_test( int verbose );
+#endif /* MBEDTLS_SELF_TEST && ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_CMAC_H */

+ 3 - 113
app/include/mbedtls/compat-1.3.h

@@ -5,7 +5,8 @@
  *  for the PolarSSL naming conventions.
  *
  * \deprecated Use the new names directly instead
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -207,9 +208,6 @@
 #if defined MBEDTLS_ERROR_C
 #define POLARSSL_ERROR_C MBEDTLS_ERROR_C
 #endif
-#if defined MBEDTLS_ERROR_STRERROR_BC
-#define POLARSSL_ERROR_STRERROR_BC MBEDTLS_ERROR_STRERROR_BC
-#endif
 #if defined MBEDTLS_ERROR_STRERROR_DUMMY
 #define POLARSSL_ERROR_STRERROR_DUMMY MBEDTLS_ERROR_STRERROR_DUMMY
 #endif
@@ -318,9 +316,6 @@
 #if defined MBEDTLS_MEMORY_BUFFER_ALLOC_C
 #define POLARSSL_MEMORY_BUFFER_ALLOC_C MBEDTLS_MEMORY_BUFFER_ALLOC_C
 #endif
-#if defined MBEDTLS_MEMORY_C
-#define POLARSSL_MEMORY_C MBEDTLS_MEMORY_C
-#endif
 #if defined MBEDTLS_MEMORY_DEBUG
 #define POLARSSL_MEMORY_DEBUG MBEDTLS_MEMORY_DEBUG
 #endif
@@ -345,9 +340,6 @@
 #if defined MBEDTLS_PADLOCK_C
 #define POLARSSL_PADLOCK_C MBEDTLS_PADLOCK_C
 #endif
-#if defined MBEDTLS_PBKDF2_C
-#define POLARSSL_PBKDF2_C MBEDTLS_PBKDF2_C
-#endif
 #if defined MBEDTLS_PEM_PARSE_C
 #define POLARSSL_PEM_PARSE_C MBEDTLS_PEM_PARSE_C
 #endif
@@ -429,9 +421,6 @@
 #if defined MBEDTLS_PLATFORM_STD_FREE
 #define POLARSSL_PLATFORM_STD_FREE MBEDTLS_PLATFORM_STD_FREE
 #endif
-#if defined MBEDTLS_PLATFORM_STD_MALLOC
-#define POLARSSL_PLATFORM_STD_MALLOC MBEDTLS_PLATFORM_STD_MALLOC
-#endif
 #if defined MBEDTLS_PLATFORM_STD_MEM_HDR
 #define POLARSSL_PLATFORM_STD_MEM_HDR MBEDTLS_PLATFORM_STD_MEM_HDR
 #endif
@@ -492,12 +481,6 @@
 #if defined MBEDTLS_SHA512_PROCESS_ALT
 #define POLARSSL_SHA512_PROCESS_ALT MBEDTLS_SHA512_PROCESS_ALT
 #endif
-#if defined MBEDTLS_SSL_AEAD_RANDOM_IV
-#define POLARSSL_SSL_AEAD_RANDOM_IV MBEDTLS_SSL_AEAD_RANDOM_IV
-#endif
-#if defined MBEDTLS_SSL_ALERT_MESSAGES
-#define POLARSSL_SSL_ALERT_MESSAGES MBEDTLS_SSL_ALERT_MESSAGES
-#endif
 #if defined MBEDTLS_SSL_ALL_ALERT_MESSAGES
 #define POLARSSL_SSL_ALL_ALERT_MESSAGES MBEDTLS_SSL_ALL_ALERT_MESSAGES
 #endif
@@ -522,9 +505,6 @@
 #if defined MBEDTLS_SSL_DEBUG_ALL
 #define POLARSSL_SSL_DEBUG_ALL MBEDTLS_SSL_DEBUG_ALL
 #endif
-#if defined MBEDTLS_SSL_DISABLE_RENEGOTIATION
-#define POLARSSL_SSL_DISABLE_RENEGOTIATION MBEDTLS_SSL_DISABLE_RENEGOTIATION
-#endif
 #if defined MBEDTLS_SSL_DTLS_ANTI_REPLAY
 #define POLARSSL_SSL_DTLS_ANTI_REPLAY MBEDTLS_SSL_DTLS_ANTI_REPLAY
 #endif
@@ -752,7 +732,6 @@
 #define KU_KEY_ENCIPHERMENT MBEDTLS_X509_KU_KEY_ENCIPHERMENT
 #define KU_NON_REPUDIATION MBEDTLS_X509_KU_NON_REPUDIATION
 #define LN_2_DIV_LN_10_SCALE100 MBEDTLS_LN_2_DIV_LN_10_SCALE100
-#define MD_CONTEXT_T_INIT MBEDTLS_MD_CONTEXT_T_INIT
 #define MEMORY_VERIFY_ALLOC MBEDTLS_MEMORY_VERIFY_ALLOC
 #define MEMORY_VERIFY_ALWAYS MBEDTLS_MEMORY_VERIFY_ALWAYS
 #define MEMORY_VERIFY_FREE MBEDTLS_MEMORY_VERIFY_FREE
@@ -1017,19 +996,13 @@
 #define POLARSSL_CONFIG_H MBEDTLS_CONFIG_H
 #define POLARSSL_CTR_DRBG_H MBEDTLS_CTR_DRBG_H
 #define POLARSSL_DEBUG_H MBEDTLS_DEBUG_H
-#define POLARSSL_DEBUG_LOG_FULL MBEDTLS_DEBUG_LOG_FULL
-#define POLARSSL_DEBUG_LOG_RAW MBEDTLS_DEBUG_LOG_RAW
 #define POLARSSL_DECRYPT MBEDTLS_DECRYPT
 #define POLARSSL_DES_H MBEDTLS_DES_H
 #define POLARSSL_DHM_H MBEDTLS_DHM_H
-#define POLARSSL_DHM_RFC2409_MODP_1024_G MBEDTLS_DHM_RFC2409_MODP_1024_G
-#define POLARSSL_DHM_RFC2409_MODP_1024_P MBEDTLS_DHM_RFC2409_MODP_1024_P
 #define POLARSSL_DHM_RFC3526_MODP_2048_G MBEDTLS_DHM_RFC3526_MODP_2048_G
 #define POLARSSL_DHM_RFC3526_MODP_2048_P MBEDTLS_DHM_RFC3526_MODP_2048_P
 #define POLARSSL_DHM_RFC3526_MODP_3072_G MBEDTLS_DHM_RFC3526_MODP_3072_G
 #define POLARSSL_DHM_RFC3526_MODP_3072_P MBEDTLS_DHM_RFC3526_MODP_3072_P
-#define POLARSSL_DHM_RFC5114_MODP_1024_G MBEDTLS_DHM_RFC5114_MODP_1024_G
-#define POLARSSL_DHM_RFC5114_MODP_1024_P MBEDTLS_DHM_RFC5114_MODP_1024_P
 #define POLARSSL_DHM_RFC5114_MODP_2048_G MBEDTLS_DHM_RFC5114_MODP_2048_G
 #define POLARSSL_DHM_RFC5114_MODP_2048_P MBEDTLS_DHM_RFC5114_MODP_2048_P
 #define POLARSSL_ECDH_H MBEDTLS_ECDH_H
@@ -1117,9 +1090,6 @@
 #define POLARSSL_ERR_HMAC_DRBG_FILE_IO_ERROR MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR
 #define POLARSSL_ERR_HMAC_DRBG_INPUT_TOO_BIG MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG
 #define POLARSSL_ERR_HMAC_DRBG_REQUEST_TOO_BIG MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG
-#define POLARSSL_ERR_MD2_FILE_IO_ERROR MBEDTLS_ERR_MD2_FILE_IO_ERROR
-#define POLARSSL_ERR_MD4_FILE_IO_ERROR MBEDTLS_ERR_MD4_FILE_IO_ERROR
-#define POLARSSL_ERR_MD5_FILE_IO_ERROR MBEDTLS_ERR_MD5_FILE_IO_ERROR
 #define POLARSSL_ERR_MD_ALLOC_FAILED MBEDTLS_ERR_MD_ALLOC_FAILED
 #define POLARSSL_ERR_MD_BAD_INPUT_DATA MBEDTLS_ERR_MD_BAD_INPUT_DATA
 #define POLARSSL_ERR_MD_FEATURE_UNAVAILABLE MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE
@@ -1147,7 +1117,6 @@
 #define POLARSSL_ERR_OID_BUF_TOO_SMALL MBEDTLS_ERR_OID_BUF_TOO_SMALL
 #define POLARSSL_ERR_OID_NOT_FOUND MBEDTLS_ERR_OID_NOT_FOUND
 #define POLARSSL_ERR_PADLOCK_DATA_MISALIGNED MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED
-#define POLARSSL_ERR_PBKDF2_BAD_INPUT_DATA MBEDTLS_ERR_PBKDF2_BAD_INPUT_DATA
 #define POLARSSL_ERR_PEM_BAD_INPUT_DATA MBEDTLS_ERR_PEM_BAD_INPUT_DATA
 #define POLARSSL_ERR_PEM_FEATURE_UNAVAILABLE MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE
 #define POLARSSL_ERR_PEM_INVALID_DATA MBEDTLS_ERR_PEM_INVALID_DATA
@@ -1179,7 +1148,6 @@
 #define POLARSSL_ERR_PK_TYPE_MISMATCH MBEDTLS_ERR_PK_TYPE_MISMATCH
 #define POLARSSL_ERR_PK_UNKNOWN_NAMED_CURVE MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE
 #define POLARSSL_ERR_PK_UNKNOWN_PK_ALG MBEDTLS_ERR_PK_UNKNOWN_PK_ALG
-#define POLARSSL_ERR_RIPEMD160_FILE_IO_ERROR MBEDTLS_ERR_RIPEMD160_FILE_IO_ERROR
 #define POLARSSL_ERR_RSA_BAD_INPUT_DATA MBEDTLS_ERR_RSA_BAD_INPUT_DATA
 #define POLARSSL_ERR_RSA_INVALID_PADDING MBEDTLS_ERR_RSA_INVALID_PADDING
 #define POLARSSL_ERR_RSA_KEY_CHECK_FAILED MBEDTLS_ERR_RSA_KEY_CHECK_FAILED
@@ -1189,9 +1157,6 @@
 #define POLARSSL_ERR_RSA_PUBLIC_FAILED MBEDTLS_ERR_RSA_PUBLIC_FAILED
 #define POLARSSL_ERR_RSA_RNG_FAILED MBEDTLS_ERR_RSA_RNG_FAILED
 #define POLARSSL_ERR_RSA_VERIFY_FAILED MBEDTLS_ERR_RSA_VERIFY_FAILED
-#define POLARSSL_ERR_SHA1_FILE_IO_ERROR MBEDTLS_ERR_SHA1_FILE_IO_ERROR
-#define POLARSSL_ERR_SHA256_FILE_IO_ERROR MBEDTLS_ERR_SHA256_FILE_IO_ERROR
-#define POLARSSL_ERR_SHA512_FILE_IO_ERROR MBEDTLS_ERR_SHA512_FILE_IO_ERROR
 #define POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE
 #define POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST
 #define POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY
@@ -1305,7 +1270,6 @@
 #define POLARSSL_MD_SHA512 MBEDTLS_MD_SHA512
 #define POLARSSL_MD_WRAP_H MBEDTLS_MD_WRAP_H
 #define POLARSSL_MEMORY_BUFFER_ALLOC_H MBEDTLS_MEMORY_BUFFER_ALLOC_H
-#define POLARSSL_MEMORY_H MBEDTLS_MEMORY_H
 #define POLARSSL_MODE_CBC MBEDTLS_MODE_CBC
 #define POLARSSL_MODE_CCM MBEDTLS_MODE_CCM
 #define POLARSSL_MODE_CFB MBEDTLS_MODE_CFB
@@ -1319,7 +1283,7 @@
 #define POLARSSL_MPI_MAX_BITS_SCALE100 MBEDTLS_MPI_MAX_BITS_SCALE100
 #define POLARSSL_MPI_MAX_LIMBS MBEDTLS_MPI_MAX_LIMBS
 #define POLARSSL_MPI_RW_BUFFER_SIZE MBEDTLS_MPI_RW_BUFFER_SIZE
-#define POLARSSL_NET_H MBEDTLS_NET_H
+#define POLARSSL_NET_H MBEDTLS_NET_SOCKETS_H
 #define POLARSSL_NET_LISTEN_BACKLOG MBEDTLS_NET_LISTEN_BACKLOG
 #define POLARSSL_OID_H MBEDTLS_OID_H
 #define POLARSSL_OPERATION_NONE MBEDTLS_OPERATION_NONE
@@ -1329,7 +1293,6 @@
 #define POLARSSL_PADDING_ZEROS MBEDTLS_PADDING_ZEROS
 #define POLARSSL_PADDING_ZEROS_AND_LEN MBEDTLS_PADDING_ZEROS_AND_LEN
 #define POLARSSL_PADLOCK_H MBEDTLS_PADLOCK_H
-#define POLARSSL_PBKDF2_H MBEDTLS_PBKDF2_H
 #define POLARSSL_PEM_H MBEDTLS_PEM_H
 #define POLARSSL_PKCS11_H MBEDTLS_PKCS11_H
 #define POLARSSL_PKCS12_H MBEDTLS_PKCS12_H
@@ -1712,7 +1675,6 @@
 #define TLS_RSA_WITH_NULL_SHA256 MBEDTLS_TLS_RSA_WITH_NULL_SHA256
 #define TLS_RSA_WITH_RC4_128_MD5 MBEDTLS_TLS_RSA_WITH_RC4_128_MD5
 #define TLS_RSA_WITH_RC4_128_SHA MBEDTLS_TLS_RSA_WITH_RC4_128_SHA
-#define UL64 MBEDTLS_UL64
 #define X509_CRT_VERSION_1 MBEDTLS_X509_CRT_VERSION_1
 #define X509_CRT_VERSION_2 MBEDTLS_X509_CRT_VERSION_2
 #define X509_CRT_VERSION_3 MBEDTLS_X509_CRT_VERSION_3
@@ -1736,7 +1698,6 @@
 #define _ssl_key_cert mbedtls_ssl_key_cert
 #define _ssl_premaster_secret mbedtls_ssl_premaster_secret
 #define _ssl_session mbedtls_ssl_session
-#define _ssl_ticket_keys mbedtls_ssl_ticket_keys
 #define _ssl_transform mbedtls_ssl_transform
 #define _x509_crl mbedtls_x509_crl
 #define _x509_crl_entry mbedtls_x509_crl_entry
@@ -1836,7 +1797,6 @@
 #define cipher_definitions mbedtls_cipher_definitions
 #define cipher_finish mbedtls_cipher_finish
 #define cipher_free mbedtls_cipher_free
-#define cipher_free_ctx mbedtls_cipher_free_ctx
 #define cipher_get_block_size mbedtls_cipher_get_block_size
 #define cipher_get_cipher_mode mbedtls_cipher_get_cipher_mode
 #define cipher_get_iv_size mbedtls_cipher_get_iv_size
@@ -1855,7 +1815,6 @@
 #define cipher_mode_t mbedtls_cipher_mode_t
 #define cipher_padding_t mbedtls_cipher_padding_t
 #define cipher_reset mbedtls_cipher_reset
-#define cipher_self_test mbedtls_cipher_self_test
 #define cipher_set_iv mbedtls_cipher_set_iv
 #define cipher_set_padding_mode mbedtls_cipher_set_padding_mode
 #define cipher_setkey mbedtls_cipher_setkey
@@ -1866,7 +1825,6 @@
 #define ctr_drbg_context mbedtls_ctr_drbg_context
 #define ctr_drbg_free mbedtls_ctr_drbg_free
 #define ctr_drbg_init mbedtls_ctr_drbg_init
-#define ctr_drbg_init_entropy_len mbedtls_ctr_drbg_init_entropy_len
 #define ctr_drbg_random mbedtls_ctr_drbg_random
 #define ctr_drbg_random_with_add mbedtls_ctr_drbg_random_with_add
 #define ctr_drbg_reseed mbedtls_ctr_drbg_reseed
@@ -1877,14 +1835,12 @@
 #define ctr_drbg_update mbedtls_ctr_drbg_update
 #define ctr_drbg_update_seed_file mbedtls_ctr_drbg_update_seed_file
 #define ctr_drbg_write_seed_file mbedtls_ctr_drbg_write_seed_file
-#define debug_fmt mbedtls_debug_fmt
 #define debug_print_buf mbedtls_debug_print_buf
 #define debug_print_crt mbedtls_debug_print_crt
 #define debug_print_ecp mbedtls_debug_print_ecp
 #define debug_print_mpi mbedtls_debug_print_mpi
 #define debug_print_msg mbedtls_debug_print_msg
 #define debug_print_ret mbedtls_debug_print_ret
-#define debug_set_log_mode mbedtls_debug_set_log_mode
 #define debug_set_threshold mbedtls_debug_set_threshold
 #define des3_context mbedtls_des3_context
 #define des3_crypt_cbc mbedtls_des3_crypt_cbc
@@ -1928,7 +1884,6 @@
 #define ecdh_make_public mbedtls_ecdh_make_public
 #define ecdh_read_params mbedtls_ecdh_read_params
 #define ecdh_read_public mbedtls_ecdh_read_public
-#define ecdh_self_test mbedtls_ecdh_self_test
 #define ecdh_side mbedtls_ecdh_side
 #define ecdsa_context mbedtls_ecdsa_context
 #define ecdsa_free mbedtls_ecdsa_free
@@ -1937,7 +1892,6 @@
 #define ecdsa_info mbedtls_ecdsa_info
 #define ecdsa_init mbedtls_ecdsa_init
 #define ecdsa_read_signature mbedtls_ecdsa_read_signature
-#define ecdsa_self_test mbedtls_ecdsa_self_test
 #define ecdsa_sign mbedtls_ecdsa_sign
 #define ecdsa_sign_det mbedtls_ecdsa_sign_det
 #define ecdsa_verify mbedtls_ecdsa_verify
@@ -1945,7 +1899,6 @@
 #define ecdsa_write_signature_det mbedtls_ecdsa_write_signature_det
 #define eckey_info mbedtls_eckey_info
 #define eckeydh_info mbedtls_eckeydh_info
-#define ecp_add mbedtls_ecp_add
 #define ecp_check_privkey mbedtls_ecp_check_privkey
 #define ecp_check_pub_priv mbedtls_ecp_check_pub_priv
 #define ecp_check_pubkey mbedtls_ecp_check_pubkey
@@ -1962,7 +1915,6 @@
 #define ecp_group_free mbedtls_ecp_group_free
 #define ecp_group_id mbedtls_ecp_group_id
 #define ecp_group_init mbedtls_ecp_group_init
-#define ecp_group_read_string mbedtls_ecp_group_read_string
 #define ecp_grp_id_list mbedtls_ecp_grp_id_list
 #define ecp_is_zero mbedtls_ecp_is_zero
 #define ecp_keypair mbedtls_ecp_keypair
@@ -1977,7 +1929,6 @@
 #define ecp_point_write_binary mbedtls_ecp_point_write_binary
 #define ecp_self_test mbedtls_ecp_self_test
 #define ecp_set_zero mbedtls_ecp_set_zero
-#define ecp_sub mbedtls_ecp_sub
 #define ecp_tls_read_group mbedtls_ecp_tls_read_group
 #define ecp_tls_read_point mbedtls_ecp_tls_read_point
 #define ecp_tls_write_group mbedtls_ecp_tls_write_group
@@ -2015,7 +1966,6 @@
 #define hmac_drbg_context mbedtls_hmac_drbg_context
 #define hmac_drbg_free mbedtls_hmac_drbg_free
 #define hmac_drbg_init mbedtls_hmac_drbg_init
-#define hmac_drbg_init_buf mbedtls_hmac_drbg_init_buf
 #define hmac_drbg_random mbedtls_hmac_drbg_random
 #define hmac_drbg_random_with_add mbedtls_hmac_drbg_random_with_add
 #define hmac_drbg_reseed mbedtls_hmac_drbg_reseed
@@ -2031,14 +1981,8 @@
 #define md mbedtls_md
 #define md2 mbedtls_md2
 #define md2_context mbedtls_md2_context
-#define md2_file mbedtls_md2_file
 #define md2_finish mbedtls_md2_finish
 #define md2_free mbedtls_md2_free
-#define md2_hmac mbedtls_md2_hmac
-#define md2_hmac_finish mbedtls_md2_hmac_finish
-#define md2_hmac_reset mbedtls_md2_hmac_reset
-#define md2_hmac_starts mbedtls_md2_hmac_starts
-#define md2_hmac_update mbedtls_md2_hmac_update
 #define md2_info mbedtls_md2_info
 #define md2_init mbedtls_md2_init
 #define md2_process mbedtls_md2_process
@@ -2047,14 +1991,8 @@
 #define md2_update mbedtls_md2_update
 #define md4 mbedtls_md4
 #define md4_context mbedtls_md4_context
-#define md4_file mbedtls_md4_file
 #define md4_finish mbedtls_md4_finish
 #define md4_free mbedtls_md4_free
-#define md4_hmac mbedtls_md4_hmac
-#define md4_hmac_finish mbedtls_md4_hmac_finish
-#define md4_hmac_reset mbedtls_md4_hmac_reset
-#define md4_hmac_starts mbedtls_md4_hmac_starts
-#define md4_hmac_update mbedtls_md4_hmac_update
 #define md4_info mbedtls_md4_info
 #define md4_init mbedtls_md4_init
 #define md4_process mbedtls_md4_process
@@ -2063,14 +2001,8 @@
 #define md4_update mbedtls_md4_update
 #define md5 mbedtls_md5
 #define md5_context mbedtls_md5_context
-#define md5_file mbedtls_md5_file
 #define md5_finish mbedtls_md5_finish
 #define md5_free mbedtls_md5_free
-#define md5_hmac mbedtls_md5_hmac
-#define md5_hmac_finish mbedtls_md5_hmac_finish
-#define md5_hmac_reset mbedtls_md5_hmac_reset
-#define md5_hmac_starts mbedtls_md5_hmac_starts
-#define md5_hmac_update mbedtls_md5_hmac_update
 #define md5_info mbedtls_md5_info
 #define md5_init mbedtls_md5_init
 #define md5_process mbedtls_md5_process
@@ -2081,7 +2013,6 @@
 #define md_file mbedtls_md_file
 #define md_finish mbedtls_md_finish
 #define md_free mbedtls_md_free
-#define md_free_ctx mbedtls_md_free_ctx
 #define md_get_name mbedtls_md_get_name
 #define md_get_size mbedtls_md_get_size
 #define md_get_type mbedtls_md_get_type
@@ -2109,7 +2040,6 @@
 #define memory_buffer_alloc_status mbedtls_memory_buffer_alloc_status
 #define memory_buffer_alloc_verify mbedtls_memory_buffer_alloc_verify
 #define memory_buffer_set_verify mbedtls_memory_buffer_set_verify
-#define memory_set_own mbedtls_memory_set_own
 #define mpi mbedtls_mpi
 #define mpi_add_abs mbedtls_mpi_add_abs
 #define mpi_add_int mbedtls_mpi_add_int
@@ -2185,8 +2115,6 @@
 #define padlock_supports mbedtls_padlock_has_support
 #define padlock_xcryptcbc mbedtls_padlock_xcryptcbc
 #define padlock_xcryptecb mbedtls_padlock_xcryptecb
-#define pbkdf2_hmac mbedtls_pbkdf2_hmac
-#define pbkdf2_self_test mbedtls_pbkdf2_self_test
 #define pem_context mbedtls_pem_context
 #define pem_free mbedtls_pem_free
 #define pem_init mbedtls_pem_init
@@ -2246,13 +2174,11 @@
 #define platform_entropy_poll mbedtls_platform_entropy_poll
 #define platform_set_exit mbedtls_platform_set_exit
 #define platform_set_fprintf mbedtls_platform_set_fprintf
-#define platform_set_malloc_free mbedtls_platform_set_malloc_free
 #define platform_set_printf mbedtls_platform_set_printf
 #define platform_set_snprintf mbedtls_platform_set_snprintf
 #define polarssl_exit mbedtls_exit
 #define polarssl_fprintf mbedtls_fprintf
 #define polarssl_free mbedtls_free
-#define polarssl_malloc mbedtls_malloc
 #define polarssl_mutex_free mbedtls_mutex_free
 #define polarssl_mutex_init mbedtls_mutex_init
 #define polarssl_mutex_lock mbedtls_mutex_lock
@@ -2262,14 +2188,8 @@
 #define polarssl_strerror mbedtls_strerror
 #define ripemd160 mbedtls_ripemd160
 #define ripemd160_context mbedtls_ripemd160_context
-#define ripemd160_file mbedtls_ripemd160_file
 #define ripemd160_finish mbedtls_ripemd160_finish
 #define ripemd160_free mbedtls_ripemd160_free
-#define ripemd160_hmac mbedtls_ripemd160_hmac
-#define ripemd160_hmac_finish mbedtls_ripemd160_hmac_finish
-#define ripemd160_hmac_reset mbedtls_ripemd160_hmac_reset
-#define ripemd160_hmac_starts mbedtls_ripemd160_hmac_starts
-#define ripemd160_hmac_update mbedtls_ripemd160_hmac_update
 #define ripemd160_info mbedtls_ripemd160_info
 #define ripemd160_init mbedtls_ripemd160_init
 #define ripemd160_process mbedtls_ripemd160_process
@@ -2283,12 +2203,10 @@
 #define rsa_check_pubkey mbedtls_rsa_check_pubkey
 #define rsa_context mbedtls_rsa_context
 #define rsa_copy mbedtls_rsa_copy
-#define rsa_decrypt_func mbedtls_rsa_decrypt_func
 #define rsa_free mbedtls_rsa_free
 #define rsa_gen_key mbedtls_rsa_gen_key
 #define rsa_info mbedtls_rsa_info
 #define rsa_init mbedtls_rsa_init
-#define rsa_key_len_func mbedtls_rsa_key_len_func
 #define rsa_pkcs1_decrypt mbedtls_rsa_pkcs1_decrypt
 #define rsa_pkcs1_encrypt mbedtls_rsa_pkcs1_encrypt
 #define rsa_pkcs1_sign mbedtls_rsa_pkcs1_sign
@@ -2306,19 +2224,12 @@
 #define rsa_rsassa_pss_verify_ext mbedtls_rsa_rsassa_pss_verify_ext
 #define rsa_self_test mbedtls_rsa_self_test
 #define rsa_set_padding mbedtls_rsa_set_padding
-#define rsa_sign_func mbedtls_rsa_sign_func
 #define safer_memcmp mbedtls_ssl_safer_memcmp
 #define set_alarm mbedtls_set_alarm
 #define sha1 mbedtls_sha1
 #define sha1_context mbedtls_sha1_context
-#define sha1_file mbedtls_sha1_file
 #define sha1_finish mbedtls_sha1_finish
 #define sha1_free mbedtls_sha1_free
-#define sha1_hmac mbedtls_sha1_hmac
-#define sha1_hmac_finish mbedtls_sha1_hmac_finish
-#define sha1_hmac_reset mbedtls_sha1_hmac_reset
-#define sha1_hmac_starts mbedtls_sha1_hmac_starts
-#define sha1_hmac_update mbedtls_sha1_hmac_update
 #define sha1_info mbedtls_sha1_info
 #define sha1_init mbedtls_sha1_init
 #define sha1_process mbedtls_sha1_process
@@ -2328,14 +2239,8 @@
 #define sha224_info mbedtls_sha224_info
 #define sha256 mbedtls_sha256
 #define sha256_context mbedtls_sha256_context
-#define sha256_file mbedtls_sha256_file
 #define sha256_finish mbedtls_sha256_finish
 #define sha256_free mbedtls_sha256_free
-#define sha256_hmac mbedtls_sha256_hmac
-#define sha256_hmac_finish mbedtls_sha256_hmac_finish
-#define sha256_hmac_reset mbedtls_sha256_hmac_reset
-#define sha256_hmac_starts mbedtls_sha256_hmac_starts
-#define sha256_hmac_update mbedtls_sha256_hmac_update
 #define sha256_info mbedtls_sha256_info
 #define sha256_init mbedtls_sha256_init
 #define sha256_process mbedtls_sha256_process
@@ -2345,14 +2250,8 @@
 #define sha384_info mbedtls_sha384_info
 #define sha512 mbedtls_sha512
 #define sha512_context mbedtls_sha512_context
-#define sha512_file mbedtls_sha512_file
 #define sha512_finish mbedtls_sha512_finish
 #define sha512_free mbedtls_sha512_free
-#define sha512_hmac mbedtls_sha512_hmac
-#define sha512_hmac_finish mbedtls_sha512_hmac_finish
-#define sha512_hmac_reset mbedtls_sha512_hmac_reset
-#define sha512_hmac_starts mbedtls_sha512_hmac_starts
-#define sha512_hmac_update mbedtls_sha512_hmac_update
 #define sha512_info mbedtls_sha512_info
 #define sha512_init mbedtls_sha512_init
 #define sha512_process mbedtls_sha512_process
@@ -2385,7 +2284,6 @@
 #define ssl_cookie_setup mbedtls_ssl_cookie_setup
 #define ssl_cookie_write mbedtls_ssl_cookie_write
 #define ssl_cookie_write_t mbedtls_ssl_cookie_write_t
-#define ssl_curve_is_acceptable mbedtls_ssl_curve_is_acceptable
 #define ssl_derive_keys mbedtls_ssl_derive_keys
 #define ssl_dtls_replay_check mbedtls_ssl_dtls_replay_check
 #define ssl_dtls_replay_update mbedtls_ssl_dtls_replay_update
@@ -2453,7 +2351,6 @@
 #define ssl_set_arc4_support mbedtls_ssl_conf_arc4_support
 #define ssl_set_authmode mbedtls_ssl_conf_authmode
 #define ssl_set_bio mbedtls_ssl_set_bio
-#define ssl_set_bio mbedtls_ssl_set_bio_timeout
 #define ssl_set_ca_chain mbedtls_ssl_conf_ca_chain
 #define ssl_set_cbc_record_splitting mbedtls_ssl_conf_cbc_record_splitting
 #define ssl_set_ciphersuites mbedtls_ssl_conf_ciphersuites
@@ -2476,8 +2373,6 @@
 #define ssl_set_max_version mbedtls_ssl_conf_max_version
 #define ssl_set_min_version mbedtls_ssl_conf_min_version
 #define ssl_set_own_cert mbedtls_ssl_conf_own_cert
-#define ssl_set_own_cert_alt mbedtls_ssl_set_own_cert_alt
-#define ssl_set_own_cert_rsa mbedtls_ssl_set_own_cert_rsa
 #define ssl_set_psk mbedtls_ssl_conf_psk
 #define ssl_set_psk_cb mbedtls_ssl_conf_psk_cb
 #define ssl_set_renegotiation mbedtls_ssl_conf_renegotiation
@@ -2486,7 +2381,6 @@
 #define ssl_set_rng mbedtls_ssl_conf_rng
 #define ssl_set_session mbedtls_ssl_set_session
 #define ssl_set_session_cache mbedtls_ssl_conf_session_cache
-#define ssl_set_session_ticket_lifetime mbedtls_ssl_conf_session_ticket_lifetime
 #define ssl_set_session_tickets mbedtls_ssl_conf_session_tickets
 #define ssl_set_sni mbedtls_ssl_conf_sni
 #define ssl_set_transport mbedtls_ssl_conf_transport
@@ -2494,7 +2388,6 @@
 #define ssl_set_verify mbedtls_ssl_conf_verify
 #define ssl_sig_from_pk mbedtls_ssl_sig_from_pk
 #define ssl_states mbedtls_ssl_states
-#define ssl_ticket_keys mbedtls_ssl_ticket_keys
 #define ssl_transform mbedtls_ssl_transform
 #define ssl_transform_free mbedtls_ssl_transform_free
 #define ssl_write mbedtls_ssl_write
@@ -2523,7 +2416,6 @@
 #define test_cli_key mbedtls_test_cli_key
 #define test_cli_key_ec mbedtls_test_cli_key_ec
 #define test_cli_key_rsa mbedtls_test_cli_key_rsa
-#define test_dhm_params mbedtls_test_dhm_params
 #define test_srv_crt mbedtls_test_srv_crt
 #define test_srv_crt_ec mbedtls_test_srv_crt_ec
 #define test_srv_crt_rsa mbedtls_test_srv_crt_rsa
@@ -2578,8 +2470,6 @@
 #define x509_get_time mbedtls_x509_get_time
 #define x509_key_size_helper mbedtls_x509_key_size_helper
 #define x509_name mbedtls_x509_name
-#define x509_oid_get_description mbedtls_x509_oid_get_description
-#define x509_oid_get_numeric_string mbedtls_x509_oid_get_numeric_string
 #define x509_self_test mbedtls_x509_self_test
 #define x509_sequence mbedtls_x509_sequence
 #define x509_serial_gets mbedtls_x509_serial_gets

+ 371 - 65
app/include/mbedtls/config.h

@@ -6,7 +6,8 @@
  *  This set of compile-time options may be used to enable
  *  or disable features selectively, and reduce the global
  *  memory footprint.
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -55,6 +56,34 @@
  */
 #define MBEDTLS_HAVE_ASM
 
+/**
+ * \def MBEDTLS_NO_UDBL_DIVISION
+ *
+ * The platform lacks support for double-width integer division (64-bit
+ * division on a 32-bit platform, 128-bit division on a 64-bit platform).
+ *
+ * Used in:
+ *      include/mbedtls/bignum.h
+ *      library/bignum.c
+ *
+ * The bignum code uses double-width division to speed up some operations.
+ * Double-width division is often implemented in software that needs to
+ * be linked with the program. The presence of a double-width integer
+ * type is usually detected automatically through preprocessor macros,
+ * but the automatic detection cannot know whether the code needs to
+ * and can be linked with an implementation of division for that type.
+ * By default division is assumed to be usable if the type is present.
+ * Uncomment this option to prevent the use of double-width division.
+ *
+ * Note that division for the native integer type is always required.
+ * Furthermore, a 64-bit type is always required even on a 32-bit
+ * platform, but it need not support multiplication or division. In some
+ * cases it is also desirable to disable some double-width operations. For
+ * example, if double-width division is implemented in software, disabling
+ * it can reduce code size in some embedded targets.
+ */
+//#define MBEDTLS_NO_UDBL_DIVISION
+
 /**
  * \def MBEDTLS_HAVE_SSE2
  *
@@ -71,6 +100,10 @@
  * The time does not need to be correct, only time differences are used,
  * by contrast with MBEDTLS_HAVE_TIME_DATE
  *
+ * Defining MBEDTLS_HAVE_TIME allows you to specify MBEDTLS_PLATFORM_TIME_ALT,
+ * MBEDTLS_PLATFORM_TIME_MACRO, MBEDTLS_PLATFORM_TIME_TYPE_MACRO and
+ * MBEDTLS_PLATFORM_STD_TIME.
+ *
  * Comment if your system does not support time functions
  */
 #define MBEDTLS_HAVE_TIME
@@ -148,13 +181,18 @@
  * \warning MBEDTLS_PLATFORM_XXX_ALT cannot be defined at the same time as
  * MBEDTLS_PLATFORM_XXX_MACRO!
  *
+ * Requires: MBEDTLS_PLATFORM_TIME_ALT requires MBEDTLS_HAVE_TIME
+ *
  * Uncomment a macro to enable alternate implementation of specific base
  * platform function
  */
 //#define MBEDTLS_PLATFORM_EXIT_ALT
+//#define MBEDTLS_PLATFORM_TIME_ALT
 //#define MBEDTLS_PLATFORM_FPRINTF_ALT
 //#define MBEDTLS_PLATFORM_PRINTF_ALT
 //#define MBEDTLS_PLATFORM_SNPRINTF_ALT
+//#define MBEDTLS_PLATFORM_NV_SEED_ALT
+//#define MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT
 
 /**
  * \def MBEDTLS_DEPRECATED_WARNING
@@ -210,34 +248,56 @@
  * \def MBEDTLS_AES_ALT
  *
  * MBEDTLS__MODULE_NAME__ALT: Uncomment a macro to let mbed TLS use your
- * alternate core implementation of a symmetric crypto or hash module (e.g.
- * platform specific assembly optimized implementations). Keep in mind that
- * the function prototypes should remain the same.
+ * alternate core implementation of a symmetric crypto, an arithmetic or hash
+ * module (e.g. platform specific assembly optimized implementations). Keep
+ * in mind that the function prototypes should remain the same.
  *
  * This replaces the whole module. If you only want to replace one of the
  * functions, use one of the MBEDTLS__FUNCTION_NAME__ALT flags.
  *
  * Example: In case you uncomment MBEDTLS_AES_ALT, mbed TLS will no longer
- * provide the "struct mbedtls_aes_context" definition and omit the base function
- * declarations and implementations. "aes_alt.h" will be included from
+ * provide the "struct mbedtls_aes_context" definition and omit the base
+ * function declarations and implementations. "aes_alt.h" will be included from
  * "aes.h" to include the new function definitions.
  *
  * Uncomment a macro to enable alternate implementation of the corresponding
  * module.
+ *
+ * \warning   MD2, MD4, MD5, ARC4, DES and SHA-1 are considered weak and their
+ *            use constitutes a security risk. If possible, we recommend
+ *            avoiding dependencies on them, and considering stronger message
+ *            digests and ciphers instead.
+ *
  */
 //#define MBEDTLS_AES_ALT
 //#define MBEDTLS_ARC4_ALT
 //#define MBEDTLS_BLOWFISH_ALT
 //#define MBEDTLS_CAMELLIA_ALT
+//#define MBEDTLS_CCM_ALT
+//#define MBEDTLS_CMAC_ALT
 //#define MBEDTLS_DES_ALT
-//#define MBEDTLS_XTEA_ALT
+//#define MBEDTLS_DHM_ALT
+//#define MBEDTLS_ECJPAKE_ALT
+//#define MBEDTLS_GCM_ALT
 //#define MBEDTLS_MD2_ALT
 //#define MBEDTLS_MD4_ALT
 //#define MBEDTLS_MD5_ALT
 //#define MBEDTLS_RIPEMD160_ALT
+//#define MBEDTLS_RSA_ALT
 //#define MBEDTLS_SHA1_ALT
 //#define MBEDTLS_SHA256_ALT
 //#define MBEDTLS_SHA512_ALT
+//#define MBEDTLS_XTEA_ALT
+/*
+ * When replacing the elliptic curve module, pleace consider, that it is
+ * implemented with two .c files:
+ *      - ecp.c
+ *      - ecp_curves.c
+ * You can replace them very much like all the other MBEDTLS__MODULE_NAME__ALT
+ * macros as described above. The only difference is that you have to make sure
+ * that you provide functionality for both .c files.
+ */
+//#define MBEDTLS_ECP_ALT
 
 /**
  * \def MBEDTLS_MD2_PROCESS_ALT
@@ -255,12 +315,24 @@
  * of mbedtls_sha1_context, so your implementation of mbedtls_sha1_process must be compatible
  * with this definition.
  *
- * Note: if you use the AES_xxx_ALT macros, then is is recommended to also set
- * MBEDTLS_AES_ROM_TABLES in order to help the linker garbage-collect the AES
- * tables.
+ * \note Because of a signature change, the core AES encryption and decryption routines are
+ *       currently named mbedtls_aes_internal_encrypt and mbedtls_aes_internal_decrypt,
+ *       respectively. When setting up alternative implementations, these functions should
+ *       be overriden, but the wrapper functions mbedtls_aes_decrypt and mbedtls_aes_encrypt
+ *       must stay untouched.
+ *
+ * \note If you use the AES_xxx_ALT macros, then is is recommended to also set
+ *       MBEDTLS_AES_ROM_TABLES in order to help the linker garbage-collect the AES
+ *       tables.
  *
  * Uncomment a macro to enable alternate implementation of the corresponding
  * function.
+ *
+ * \warning   MD2, MD4, MD5, DES and SHA-1 are considered weak and their use
+ *            constitutes a security risk. If possible, we recommend avoiding
+ *            dependencies on them, and considering stronger message digests
+ *            and ciphers instead.
+ *
  */
 //#define MBEDTLS_MD2_PROCESS_ALT
 //#define MBEDTLS_MD4_PROCESS_ALT
@@ -276,6 +348,81 @@
 //#define MBEDTLS_AES_SETKEY_DEC_ALT
 //#define MBEDTLS_AES_ENCRYPT_ALT
 //#define MBEDTLS_AES_DECRYPT_ALT
+//#define MBEDTLS_ECDH_GEN_PUBLIC_ALT
+//#define MBEDTLS_ECDH_COMPUTE_SHARED_ALT
+//#define MBEDTLS_ECDSA_VERIFY_ALT
+//#define MBEDTLS_ECDSA_SIGN_ALT
+//#define MBEDTLS_ECDSA_GENKEY_ALT
+
+/**
+ * \def MBEDTLS_ECP_INTERNAL_ALT
+ *
+ * Expose a part of the internal interface of the Elliptic Curve Point module.
+ *
+ * MBEDTLS_ECP__FUNCTION_NAME__ALT: Uncomment a macro to let mbed TLS use your
+ * alternative core implementation of elliptic curve arithmetic. Keep in mind
+ * that function prototypes should remain the same.
+ *
+ * This partially replaces one function. The header file from mbed TLS is still
+ * used, in contrast to the MBEDTLS_ECP_ALT flag. The original implementation
+ * is still present and it is used for group structures not supported by the
+ * alternative.
+ *
+ * Any of these options become available by defining MBEDTLS_ECP_INTERNAL_ALT
+ * and implementing the following functions:
+ *      unsigned char mbedtls_internal_ecp_grp_capable(
+ *          const mbedtls_ecp_group *grp )
+ *      int  mbedtls_internal_ecp_init( const mbedtls_ecp_group *grp )
+ *      void mbedtls_internal_ecp_deinit( const mbedtls_ecp_group *grp )
+ * The mbedtls_internal_ecp_grp_capable function should return 1 if the
+ * replacement functions implement arithmetic for the given group and 0
+ * otherwise.
+ * The functions mbedtls_internal_ecp_init and mbedtls_internal_ecp_deinit are
+ * called before and after each point operation and provide an opportunity to
+ * implement optimized set up and tear down instructions.
+ *
+ * Example: In case you uncomment MBEDTLS_ECP_INTERNAL_ALT and
+ * MBEDTLS_ECP_DOUBLE_JAC_ALT, mbed TLS will still provide the ecp_double_jac
+ * function, but will use your mbedtls_internal_ecp_double_jac if the group is
+ * supported (your mbedtls_internal_ecp_grp_capable function returns 1 when
+ * receives it as an argument). If the group is not supported then the original
+ * implementation is used. The other functions and the definition of
+ * mbedtls_ecp_group and mbedtls_ecp_point will not change, so your
+ * implementation of mbedtls_internal_ecp_double_jac and
+ * mbedtls_internal_ecp_grp_capable must be compatible with this definition.
+ *
+ * Uncomment a macro to enable alternate implementation of the corresponding
+ * function.
+ */
+/* Required for all the functions in this section */
+//#define MBEDTLS_ECP_INTERNAL_ALT
+/* Support for Weierstrass curves with Jacobi representation */
+//#define MBEDTLS_ECP_RANDOMIZE_JAC_ALT
+//#define MBEDTLS_ECP_ADD_MIXED_ALT
+//#define MBEDTLS_ECP_DOUBLE_JAC_ALT
+//#define MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT
+//#define MBEDTLS_ECP_NORMALIZE_JAC_ALT
+/* Support for curves with Montgomery arithmetic */
+//#define MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT
+//#define MBEDTLS_ECP_RANDOMIZE_MXZ_ALT
+//#define MBEDTLS_ECP_NORMALIZE_MXZ_ALT
+
+/**
+ * \def MBEDTLS_TEST_NULL_ENTROPY
+ *
+ * Enables testing and use of mbed TLS without any configured entropy sources.
+ * This permits use of the library on platforms before an entropy source has
+ * been integrated (see for example the MBEDTLS_ENTROPY_HARDWARE_ALT or the
+ * MBEDTLS_ENTROPY_NV_SEED switches).
+ *
+ * WARNING! This switch MUST be disabled in production builds, and is suitable
+ * only for development.
+ * Enabling the switch negates any security provided by the library.
+ *
+ * Requires MBEDTLS_ENTROPY_C, MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES
+ *
+ */
+//#define MBEDTLS_TEST_NULL_ENTROPY
 
 /**
  * \def MBEDTLS_ENTROPY_HARDWARE_ALT
@@ -390,6 +537,9 @@
  *      MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA
  *
  * Uncomment this macro to enable weak ciphersuites
+ *
+ * \warning   DES is considered a weak cipher and its use constitutes a
+ *            security risk. We recommend considering stronger ciphers instead.
  */
 //#define MBEDTLS_ENABLE_WEAK_CIPHERSUITES
 
@@ -495,6 +645,13 @@
  *      MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256
  *      MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA
  *      MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA
+ *
+ * \warning    Using DHE constitutes a security risk as it
+ *             is not possible to validate custom DH parameters.
+ *             If possible, it is recommended users should consider
+ *             preferring other methods of key exchange.
+ *             See dhm.h for more details.
+ *
  */
 #define MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED
 
@@ -594,6 +751,13 @@
  *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
  *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
  *      MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
+ *
+ * \warning    Using DHE constitutes a security risk as it
+ *             is not possible to validate custom DH parameters.
+ *             If possible, it is recommended users should consider
+ *             preferring other methods of key exchange.
+ *             See dhm.h for more details.
+ *
  */
 #define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 
@@ -798,6 +962,34 @@
  */
 //#define MBEDTLS_ENTROPY_FORCE_SHA256
 
+/**
+ * \def MBEDTLS_ENTROPY_NV_SEED
+ *
+ * Enable the non-volatile (NV) seed file-based entropy source.
+ * (Also enables the NV seed read/write functions in the platform layer)
+ *
+ * This is crucial (if not required) on systems that do not have a
+ * cryptographic entropy source (in hardware or kernel) available.
+ *
+ * Requires: MBEDTLS_ENTROPY_C, MBEDTLS_PLATFORM_C
+ *
+ * \note The read/write functions that are used by the entropy source are
+ *       determined in the platform layer, and can be modified at runtime and/or
+ *       compile-time depending on the flags (MBEDTLS_PLATFORM_NV_SEED_*) used.
+ *
+ * \note If you use the default implementation functions that read a seedfile
+ *       with regular fopen(), please make sure you make a seedfile with the
+ *       proper name (defined in MBEDTLS_PLATFORM_STD_NV_SEED_FILE) and at
+ *       least MBEDTLS_ENTROPY_BLOCK_SIZE bytes in size that can be read from
+ *       and written to or you will get an entropy source error! The default
+ *       implementation will only use the first MBEDTLS_ENTROPY_BLOCK_SIZE
+ *       bytes from the file.
+ *
+ * \note The entropy collector will write to the seed file before entropy is
+ *       given to an external source, to update it.
+ */
+//#define MBEDTLS_ENTROPY_NV_SEED
+
 /**
  * \def MBEDTLS_MEMORY_DEBUG
  *
@@ -887,18 +1079,6 @@
  */
 //#define MBEDTLS_SHA256_SMALLER
 
-/**
- * \def MBEDTLS_SSL_AEAD_RANDOM_IV
- *
- * Generate a random IV rather than using the record sequence number as a
- * nonce for ciphersuites using and AEAD algorithm (GCM or CCM).
- *
- * Using the sequence number is generally recommended.
- *
- * Uncomment this macro to always use random IVs with AEAD ciphersuites.
- */
-//#define MBEDTLS_SSL_AEAD_RANDOM_IV
-
 /**
  * \def MBEDTLS_SSL_ALL_ALERT_MESSAGES
  *
@@ -1016,6 +1196,13 @@
  * misuse/misunderstand.
  *
  * Comment this to disable support for renegotiation.
+ *
+ * \note   Even if this option is disabled, both client and server are aware
+ *         of the Renegotiation Indication Extension (RFC 5746) used to
+ *         prevent the SSL renegotiation attack (see RFC 5746 Sect. 1).
+ *         (See \c mbedtls_ssl_conf_legacy_renegotiation for the
+ *          configuration of this extension).
+ *
  */
 #define MBEDTLS_SSL_RENEGOTIATION
 
@@ -1058,7 +1245,7 @@
  *
  * Comment this macro to disable support for SSL 3.0
  */
-#define MBEDTLS_SSL_PROTO_SSL3
+//#define MBEDTLS_SSL_PROTO_SSL3
 
 /**
  * \def MBEDTLS_SSL_PROTO_TLS1
@@ -1457,6 +1644,11 @@
  *      MBEDTLS_TLS_RSA_WITH_RC4_128_MD5
  *      MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA
  *      MBEDTLS_TLS_PSK_WITH_RC4_128_SHA
+ *
+ * \warning   ARC4 is considered a weak cipher and its use constitutes a
+ *            security risk. If possible, we recommend avoidng dependencies on
+ *            it, and considering stronger ciphers instead.
+ *
  */
 #define MBEDTLS_ARC4_C
 
@@ -1484,7 +1676,7 @@
  *          library/pkwrite.c
  *          library/x509_create.c
  *          library/x509write_crt.c
- *          library/mbedtls_x509write_csr.c
+ *          library/x509write_csr.c
  */
 #define MBEDTLS_ASN1_WRITE_C
 
@@ -1510,6 +1702,7 @@
  *          library/ecp.c
  *          library/ecdsa.c
  *          library/rsa.c
+ *          library/rsa_internal.c
  *          library/ssl_tls.c
  *
  * This module is required for RSA, DHM and ECC (ECDH, ECDSA) support.
@@ -1618,6 +1811,19 @@
  */
 #define MBEDTLS_CIPHER_C
 
+/**
+ * \def MBEDTLS_CMAC_C
+ *
+ * Enable the CMAC (Cipher-based Message Authentication Code) mode for block
+ * ciphers.
+ *
+ * Module:  library/cmac.c
+ *
+ * Requires: MBEDTLS_AES_C or MBEDTLS_DES_C
+ *
+ */
+//#define MBEDTLS_CMAC_C
+
 /**
  * \def MBEDTLS_CTR_DRBG_C
  *
@@ -1669,6 +1875,9 @@
  *      MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA
  *
  * PEM_PARSE uses DES/3DES for decrypting encrypted keys.
+ *
+ * \warning   DES is considered a weak cipher and its use constitutes a
+ *            security risk. We recommend considering stronger ciphers instead.
  */
 #define MBEDTLS_DES_C
 
@@ -1683,6 +1892,13 @@
  *
  * This module is used by the following key exchanges:
  *      DHE-RSA, DHE-PSK
+ *
+ * \warning    Using DHE constitutes a security risk as it
+ *             is not possible to validate custom DH parameters.
+ *             If possible, it is recommended users should consider
+ *             preferring other methods of key exchange.
+ *             See dhm.h for more details.
+ *
  */
 #define MBEDTLS_DHM_C
 
@@ -1832,7 +2048,7 @@
  *
  * Enable the generic message digest layer.
  *
- * Module:  library/mbedtls_md.c
+ * Module:  library/md.c
  * Caller:
  *
  * Uncomment to enable generic message digest wrappers.
@@ -1844,10 +2060,15 @@
  *
  * Enable the MD2 hash algorithm.
  *
- * Module:  library/mbedtls_md2.c
+ * Module:  library/md2.c
  * Caller:
  *
  * Uncomment to enable support for (rare) MD2-signed X.509 certs.
+ *
+ * \warning   MD2 is considered a weak message digest and its use constitutes a
+ *            security risk. If possible, we recommend avoiding dependencies on
+ *            it, and considering stronger message digests instead.
+ *
  */
 //#define MBEDTLS_MD2_C
 
@@ -1856,10 +2077,15 @@
  *
  * Enable the MD4 hash algorithm.
  *
- * Module:  library/mbedtls_md4.c
+ * Module:  library/md4.c
  * Caller:
  *
  * Uncomment to enable support for (rare) MD4-signed X.509 certs.
+ *
+ * \warning   MD4 is considered a weak message digest and its use constitutes a
+ *            security risk. If possible, we recommend avoiding dependencies on
+ *            it, and considering stronger message digests instead.
+ *
  */
 //#define MBEDTLS_MD4_C
 
@@ -1868,13 +2094,20 @@
  *
  * Enable the MD5 hash algorithm.
  *
- * Module:  library/mbedtls_md5.c
- * Caller:  library/mbedtls_md.c
+ * Module:  library/md5.c
+ * Caller:  library/md.c
  *          library/pem.c
  *          library/ssl_tls.c
  *
- * This module is required for SSL/TLS and X.509.
- * PEM_PARSE uses MD5 for decrypting encrypted keys.
+ * This module is required for SSL/TLS up to version 1.1, and for TLS 1.2
+ * depending on the handshake parameters. Further, it is used for checking
+ * MD5-signed certificates, and for PBKDF1 when decrypting PEM-encoded
+ * encrypted keys.
+ *
+ * \warning   MD5 is considered a weak message digest and its use constitutes a
+ *            security risk. If possible, we recommend avoiding dependencies on
+ *            it, and considering stronger message digests instead.
+ *
  */
 #define MBEDTLS_MD5_C
 
@@ -1897,11 +2130,19 @@
 /**
  * \def MBEDTLS_NET_C
  *
- * Enable the TCP/IP networking routines.
+ * Enable the TCP and UDP over IPv6/IPv4 networking routines.
+ *
+ * \note This module only works on POSIX/Unix (including Linux, BSD and OS X)
+ * and Windows. For other platforms, you'll want to disable it, and write your
+ * own networking callbacks to be passed to \c mbedtls_ssl_set_bio().
  *
- * Module:  library/net.c
+ * \note See also our Knowledge Base article about porting to a new
+ * environment:
+ * https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS
  *
- * This module provides TCP/IP networking routines.
+ * Module:  library/net_sockets.c
+ *
+ * This module provides networking routines.
  */
 #define MBEDTLS_NET_C
 
@@ -1918,11 +2159,11 @@
  *          library/rsa.c
  *          library/x509.c
  *          library/x509_create.c
- *          library/mbedtls_x509_crl.c
- *          library/mbedtls_x509_crt.c
- *          library/mbedtls_x509_csr.c
+ *          library/x509_crl.c
+ *          library/x509_crt.c
+ *          library/x509_csr.c
  *          library/x509write_crt.c
- *          library/mbedtls_x509write_csr.c
+ *          library/x509write_csr.c
  *
  * This modules translates between OIDs and internal values.
  */
@@ -1950,9 +2191,9 @@
  * Module:  library/pem.c
  * Caller:  library/dhm.c
  *          library/pkparse.c
- *          library/mbedtls_x509_crl.c
- *          library/mbedtls_x509_crt.c
- *          library/mbedtls_x509_csr.c
+ *          library/x509_crl.c
+ *          library/x509_crt.c
+ *          library/x509_csr.c
  *
  * Requires: MBEDTLS_BASE64_C
  *
@@ -1968,7 +2209,7 @@
  * Module:  library/pem.c
  * Caller:  library/pkwrite.c
  *          library/x509write_crt.c
- *          library/mbedtls_x509write_csr.c
+ *          library/x509write_csr.c
  *
  * Requires: MBEDTLS_BASE64_C
  *
@@ -1998,8 +2239,8 @@
  * Enable the generic public (asymetric) key parser.
  *
  * Module:  library/pkparse.c
- * Caller:  library/mbedtls_x509_crt.c
- *          library/mbedtls_x509_csr.c
+ * Caller:  library/x509_crt.c
+ *          library/x509_csr.c
  *
  * Requires: MBEDTLS_PK_C
  *
@@ -2090,8 +2331,8 @@
  *
  * Enable the RIPEMD-160 hash algorithm.
  *
- * Module:  library/mbedtls_ripemd160.c
- * Caller:  library/mbedtls_md.c
+ * Module:  library/ripemd160.c
+ * Caller:  library/md.c
  *
  */
 #define MBEDTLS_RIPEMD160_C
@@ -2102,6 +2343,7 @@
  * Enable the RSA public-key cryptosystem.
  *
  * Module:  library/rsa.c
+ *          library/rsa_internal.c
  * Caller:  library/ssl_cli.c
  *          library/ssl_srv.c
  *          library/ssl_tls.c
@@ -2119,14 +2361,20 @@
  *
  * Enable the SHA1 cryptographic hash algorithm.
  *
- * Module:  library/mbedtls_sha1.c
- * Caller:  library/mbedtls_md.c
+ * Module:  library/sha1.c
+ * Caller:  library/md.c
  *          library/ssl_cli.c
  *          library/ssl_srv.c
  *          library/ssl_tls.c
  *          library/x509write_crt.c
  *
- * This module is required for SSL/TLS and SHA1-signed certificates.
+ * This module is required for SSL/TLS up to version 1.1, for TLS 1.2
+ * depending on the handshake parameters, and for SHA1-signed certificates.
+ *
+ * \warning   SHA-1 is considered a weak message digest and its use constitutes
+ *            a security risk. If possible, we recommend avoiding dependencies
+ *            on it, and considering stronger message digests instead.
+ *
  */
 #define MBEDTLS_SHA1_C
 
@@ -2135,9 +2383,9 @@
  *
  * Enable the SHA-224 and SHA-256 cryptographic hash algorithms.
  *
- * Module:  library/mbedtls_sha256.c
+ * Module:  library/sha256.c
  * Caller:  library/entropy.c
- *          library/mbedtls_md.c
+ *          library/md.c
  *          library/ssl_cli.c
  *          library/ssl_srv.c
  *          library/ssl_tls.c
@@ -2152,9 +2400,9 @@
  *
  * Enable the SHA-384 and SHA-512 cryptographic hash algorithms.
  *
- * Module:  library/mbedtls_sha512.c
+ * Module:  library/sha512.c
  * Caller:  library/entropy.c
- *          library/mbedtls_md.c
+ *          library/md.c
  *          library/ssl_cli.c
  *          library/ssl_srv.c
  *
@@ -2247,7 +2495,8 @@
  * By default mbed TLS assumes it is used in a non-threaded environment or that
  * contexts are not shared between threads. If you do intend to use contexts
  * between threads, you will need to enable this layer to prevent race
- * conditions.
+ * conditions. See also our Knowledge Base article about threading:
+ * https://tls.mbed.org/kb/development/thread-safety-and-multi-threading
  *
  * Module:  library/threading.c
  *
@@ -2264,7 +2513,18 @@
 /**
  * \def MBEDTLS_TIMING_C
  *
- * Enable the portable timing interface.
+ * Enable the semi-portable timing interface.
+ *
+ * \note The provided implementation only works on POSIX/Unix (including Linux,
+ * BSD and OS X) and Windows. On other platforms, you can either disable that
+ * module and provide your own implementations of the callbacks needed by
+ * \c mbedtls_ssl_set_timer_cb() for DTLS, or leave it enabled and provide
+ * your own implementation of the whole module by setting
+ * \c MBEDTLS_TIMING_ALT in the current file.
+ *
+ * \note See also our Knowledge Base article about porting to a new
+ * environment:
+ * https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS
  *
  * Module:  library/timing.c
  * Caller:  library/havege.c
@@ -2290,9 +2550,9 @@
  * Enable X.509 core for using certificates.
  *
  * Module:  library/x509.c
- * Caller:  library/mbedtls_x509_crl.c
- *          library/mbedtls_x509_crt.c
- *          library/mbedtls_x509_csr.c
+ * Caller:  library/x509_crl.c
+ *          library/x509_crt.c
+ *          library/x509_csr.c
  *
  * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_BIGNUM_C, MBEDTLS_OID_C,
  *           MBEDTLS_PK_PARSE_C
@@ -2306,7 +2566,7 @@
  *
  * Enable X.509 certificate parsing.
  *
- * Module:  library/mbedtls_x509_crt.c
+ * Module:  library/x509_crt.c
  * Caller:  library/ssl_cli.c
  *          library/ssl_srv.c
  *          library/ssl_tls.c
@@ -2322,8 +2582,8 @@
  *
  * Enable X.509 CRL parsing.
  *
- * Module:  library/mbedtls_x509_crl.c
- * Caller:  library/mbedtls_x509_crt.c
+ * Module:  library/x509_crl.c
+ * Caller:  library/x509_crt.c
  *
  * Requires: MBEDTLS_X509_USE_C
  *
@@ -2336,7 +2596,7 @@
  *
  * Enable X.509 Certificate Signing Request (CSR) parsing.
  *
- * Module:  library/mbedtls_x509_csr.c
+ * Module:  library/x509_csr.c
  * Caller:  library/x509_crt_write.c
  *
  * Requires: MBEDTLS_X509_USE_C
@@ -2436,6 +2696,7 @@
 /* Entropy options */
 //#define MBEDTLS_ENTROPY_MAX_SOURCES                20 /**< Maximum number of sources supported */
 //#define MBEDTLS_ENTROPY_MAX_GATHER                128 /**< Maximum amount requested from entropy sources */
+//#define MBEDTLS_ENTROPY_MIN_HARDWARE               32 /**< Default minimum number of bytes required for the hardware entropy source mbedtls_hardware_poll() before entropy is released */
 
 /* Memory buffer allocator options */
 //#define MBEDTLS_MEMORY_ALIGN_MULTIPLE      4 /**< Align on multiples of this value */
@@ -2445,20 +2706,30 @@
 //#define MBEDTLS_PLATFORM_STD_CALLOC        calloc /**< Default allocator to use, can be undefined */
 //#define MBEDTLS_PLATFORM_STD_FREE            free /**< Default free to use, can be undefined */
 //#define MBEDTLS_PLATFORM_STD_EXIT            exit /**< Default exit to use, can be undefined */
+//#define MBEDTLS_PLATFORM_STD_TIME            time /**< Default time to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */
 //#define MBEDTLS_PLATFORM_STD_FPRINTF      fprintf /**< Default fprintf to use, can be undefined */
 //#define MBEDTLS_PLATFORM_STD_PRINTF        printf /**< Default printf to use, can be undefined */
 /* Note: your snprintf must correclty zero-terminate the buffer! */
 //#define MBEDTLS_PLATFORM_STD_SNPRINTF    snprintf /**< Default snprintf to use, can be undefined */
+//#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS       0 /**< Default exit value to use, can be undefined */
+//#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE       1 /**< Default exit value to use, can be undefined */
+//#define MBEDTLS_PLATFORM_STD_NV_SEED_READ   mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */
+//#define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE  mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */
+//#define MBEDTLS_PLATFORM_STD_NV_SEED_FILE  "seedfile" /**< Seed file to read/write with default implementation */
 
 /* To Use Function Macros MBEDTLS_PLATFORM_C must be enabled */
 /* MBEDTLS_PLATFORM_XXX_MACRO and MBEDTLS_PLATFORM_XXX_ALT cannot both be defined */
 //#define MBEDTLS_PLATFORM_CALLOC_MACRO        calloc /**< Default allocator macro to use, can be undefined */
 //#define MBEDTLS_PLATFORM_FREE_MACRO            free /**< Default free macro to use, can be undefined */
 //#define MBEDTLS_PLATFORM_EXIT_MACRO            exit /**< Default exit macro to use, can be undefined */
+//#define MBEDTLS_PLATFORM_TIME_MACRO            time /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */
+//#define MBEDTLS_PLATFORM_TIME_TYPE_MACRO       time_t /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */
 //#define MBEDTLS_PLATFORM_FPRINTF_MACRO      fprintf /**< Default fprintf macro to use, can be undefined */
 //#define MBEDTLS_PLATFORM_PRINTF_MACRO        printf /**< Default printf macro to use, can be undefined */
 /* Note: your snprintf must correclty zero-terminate the buffer! */
 //#define MBEDTLS_PLATFORM_SNPRINTF_MACRO    snprintf /**< Default snprintf macro to use, can be undefined */
+//#define MBEDTLS_PLATFORM_NV_SEED_READ_MACRO   mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */
+//#define MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO  mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */
 
 /* SSL Cache options */
 //#define MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT       86400 /**< 1 day  */
@@ -2486,11 +2757,46 @@
 
 /* X509 options */
 //#define MBEDTLS_X509_MAX_INTERMEDIATE_CA   8   /**< Maximum number of intermediate CAs in a verification chain. */
+//#define MBEDTLS_X509_MAX_FILE_PATH_LEN     512 /**< Maximum length of a path/filename string in bytes including the null terminator character ('\0'). */
+
+/**
+ * Allow SHA-1 in the default TLS configuration for certificate signing.
+ * Without this build-time option, SHA-1 support must be activated explicitly
+ * through mbedtls_ssl_conf_cert_profile. Turning on this option is not
+ * recommended because of it is possible to generate SHA-1 collisions, however
+ * this may be safe for legacy infrastructure where additional controls apply.
+ *
+ * \warning   SHA-1 is considered a weak message digest and its use constitutes
+ *            a security risk. If possible, we recommend avoiding dependencies
+ *            on it, and considering stronger message digests instead.
+ *
+ */
+// #define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES
+
+/**
+ * Allow SHA-1 in the default TLS configuration for TLS 1.2 handshake
+ * signature and ciphersuite selection. Without this build-time option, SHA-1
+ * support must be activated explicitly through mbedtls_ssl_conf_sig_hashes.
+ * The use of SHA-1 in TLS <= 1.1 and in HMAC-SHA-1 is always allowed by
+ * default. At the time of writing, there is no practical attack on the use
+ * of SHA-1 in handshake signatures, hence this option is turned on by default
+ * to preserve compatibility with existing peers, but the general
+ * warning applies nonetheless:
+ *
+ * \warning   SHA-1 is considered a weak message digest and its use constitutes
+ *            a security risk. If possible, we recommend avoiding dependencies
+ *            on it, and considering stronger message digests instead.
+ *
+ */
+#define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE
+
+/* \} name SECTION: Customisation configuration options */
 
-/* \} name SECTION: Module configuration options */
+/* Target and application specific configurations */
+//#define YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE "mbedtls/target_config.h"
 
-#if defined(TARGET_LIKE_MBED)
-#include "mbedtls/target_config.h"
+#if defined(TARGET_LIKE_MBED) && defined(YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE)
+#include YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE
 #endif
 
 /*

+ 142 - 110
app/include/mbedtls/ctr_drbg.h

@@ -1,9 +1,13 @@
 /**
  * \file ctr_drbg.h
  *
- * \brief CTR_DRBG based on AES-256 (NIST SP 800-90)
+ * \brief    CTR_DRBG is based on AES-256, as defined in <em>NIST SP 800-90A:
+ *           Recommendation for Random Number Generation Using Deterministic
+ *           Random Bit Generators</em>.
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,8 +22,9 @@
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *
- *  This file is part of mbed TLS (https://tls.mbed.org)
+ *  This file is part of Mbed TLS (https://tls.mbed.org)
  */
+
 #ifndef MBEDTLS_CTR_DRBG_H
 #define MBEDTLS_CTR_DRBG_H
 
@@ -30,78 +35,95 @@
 #endif
 
 #define MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED        -0x0034  /**< The entropy source failed. */
-#define MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG              -0x0036  /**< Too many random requested in single call. */
-#define MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG                -0x0038  /**< Input too large (Entropy + additional). */
-#define MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR                -0x003A  /**< Read/write error in file. */
+#define MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG              -0x0036  /**< The requested random buffer length is too big. */
+#define MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG                -0x0038  /**< The input (entropy + additional data) is too large. */
+#define MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR                -0x003A  /**< Read or write error in file. */
 
-#define MBEDTLS_CTR_DRBG_BLOCKSIZE          16      /**< Block size used by the cipher                  */
-#define MBEDTLS_CTR_DRBG_KEYSIZE            32      /**< Key size used by the cipher                    */
-#define MBEDTLS_CTR_DRBG_KEYBITS            ( MBEDTLS_CTR_DRBG_KEYSIZE * 8 )
-#define MBEDTLS_CTR_DRBG_SEEDLEN            ( MBEDTLS_CTR_DRBG_KEYSIZE + MBEDTLS_CTR_DRBG_BLOCKSIZE )
-                                            /**< The seed length (counter + AES key)            */
+#define MBEDTLS_CTR_DRBG_BLOCKSIZE          16 /**< The block size used by the cipher. */
+#define MBEDTLS_CTR_DRBG_KEYSIZE            32 /**< The key size used by the cipher. */
+#define MBEDTLS_CTR_DRBG_KEYBITS            ( MBEDTLS_CTR_DRBG_KEYSIZE * 8 ) /**< The key size for the DRBG operation, in bits. */
+#define MBEDTLS_CTR_DRBG_SEEDLEN            ( MBEDTLS_CTR_DRBG_KEYSIZE + MBEDTLS_CTR_DRBG_BLOCKSIZE ) /**< The seed length, calculated as (counter + AES key). */
 
 /**
  * \name SECTION: Module settings
  *
  * The configuration options you can set for this module are in this section.
- * Either change them in config.h or define them on the compiler command line.
+ * Either change them in config.h or define them using the compiler command
+ * line.
  * \{
  */
 
 #if !defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN)
 #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256)
-#define MBEDTLS_CTR_DRBG_ENTROPY_LEN        48      /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */
+#define MBEDTLS_CTR_DRBG_ENTROPY_LEN        48
+/**< The amount of entropy used per seed by default:
+ * <ul><li>48 with SHA-512.</li>
+ * <li>32 with SHA-256.</li></ul>
+ */
 #else
-#define MBEDTLS_CTR_DRBG_ENTROPY_LEN        32      /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */
+#define MBEDTLS_CTR_DRBG_ENTROPY_LEN        32
+/**< Amount of entropy used per seed by default:
+ * <ul><li>48 with SHA-512.</li>
+ * <li>32 with SHA-256.</li></ul>
+ */
 #endif
 #endif
 
 #if !defined(MBEDTLS_CTR_DRBG_RESEED_INTERVAL)
-#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL    10000   /**< Interval before reseed is performed by default */
+#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL    10000
+/**< The interval before reseed is performed by default. */
 #endif
 
 #if !defined(MBEDTLS_CTR_DRBG_MAX_INPUT)
-#define MBEDTLS_CTR_DRBG_MAX_INPUT          256     /**< Maximum number of additional input bytes */
+#define MBEDTLS_CTR_DRBG_MAX_INPUT          256
+/**< The maximum number of additional input Bytes. */
 #endif
 
 #if !defined(MBEDTLS_CTR_DRBG_MAX_REQUEST)
-#define MBEDTLS_CTR_DRBG_MAX_REQUEST        1024    /**< Maximum number of requested bytes per call */
+#define MBEDTLS_CTR_DRBG_MAX_REQUEST        1024
+/**< The maximum number of requested Bytes per call. */
 #endif
 
 #if !defined(MBEDTLS_CTR_DRBG_MAX_SEED_INPUT)
-#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT     384     /**< Maximum size of (re)seed buffer */
+#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT     384
+/**< The maximum size of seed or reseed buffer. */
 #endif
 
 /* \} name SECTION: Module settings */
 
-#define MBEDTLS_CTR_DRBG_PR_OFF             0       /**< No prediction resistance       */
-#define MBEDTLS_CTR_DRBG_PR_ON              1       /**< Prediction resistance enabled  */
+#define MBEDTLS_CTR_DRBG_PR_OFF             0
+/**< Prediction resistance is disabled. */
+#define MBEDTLS_CTR_DRBG_PR_ON              1
+/**< Prediction resistance is enabled. */
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
 /**
- * \brief          CTR_DRBG context structure
+ * \brief          The CTR_DRBG context structure.
  */
 typedef struct
 {
-    unsigned char counter[16];  /*!<  counter (V)       */
-    int reseed_counter;         /*!<  reseed counter    */
-    int prediction_resistance;  /*!<  enable prediction resistance (Automatic
-                                      reseed before every random generation)  */
-    size_t entropy_len;         /*!<  amount of entropy grabbed on each
-                                      (re)seed          */
-    int reseed_interval;        /*!<  reseed interval   */
-
-    mbedtls_aes_context aes_ctx;        /*!<  AES context       */
+    unsigned char counter[16];  /*!< The counter (V). */
+    int reseed_counter;         /*!< The reseed counter. */
+    int prediction_resistance;  /*!< This determines whether prediction
+                                     resistance is enabled, that is
+                                     whether to systematically reseed before
+                                     each random generation. */
+    size_t entropy_len;         /*!< The amount of entropy grabbed on each
+                                     seed or reseed operation. */
+    int reseed_interval;        /*!< The reseed interval. */
+
+    mbedtls_aes_context aes_ctx;        /*!< The AES context. */
 
     /*
      * Callbacks (Entropy)
      */
     int (*f_entropy)(void *, unsigned char *, size_t);
+                                /*!< The entropy callback function. */
 
-    void *p_entropy;            /*!<  context for the entropy function */
+    void *p_entropy;            /*!< The context for the entropy function. */
 
 #if defined(MBEDTLS_THREADING_C)
     mbedtls_threading_mutex_t mutex;
@@ -110,31 +132,32 @@ typedef struct
 mbedtls_ctr_drbg_context;
 
 /**
- * \brief               CTR_DRBG context initialization
- *                      Makes the context ready for mbedtls_ctr_drbg_seed() or
- *                      mbedtls_ctr_drbg_free().
+ * \brief               This function initializes the CTR_DRBG context,
+ *                      and prepares it for mbedtls_ctr_drbg_seed()
+ *                      or mbedtls_ctr_drbg_free().
  *
- * \param ctx           CTR_DRBG context to be initialized
+ * \param ctx           The CTR_DRBG context to initialize.
  */
 void mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *ctx );
 
 /**
- * \brief               CTR_DRBG initial seeding
- *                      Seed and setup entropy source for future reseeds.
+ * \brief               This function seeds and sets up the CTR_DRBG
+ *                      entropy source for future reseeds.
  *
- * Note: Personalization data can be provided in addition to the more generic
- *       entropy source to make this instantiation as unique as possible.
+ * \note Personalization data can be provided in addition to the more generic
+ *       entropy source, to make this instantiation as unique as possible.
  *
- * \param ctx           CTR_DRBG context to be seeded
- * \param f_entropy     Entropy callback (p_entropy, buffer to fill, buffer
- *                      length)
- * \param p_entropy     Entropy context
- * \param custom        Personalization data (Device specific identifiers)
- *                      (Can be NULL)
- * \param len           Length of personalization data
+ * \param ctx           The CTR_DRBG context to seed.
+ * \param f_entropy     The entropy callback, taking as arguments the
+ *                      \p p_entropy context, the buffer to fill, and the
+                        length of the buffer.
+ * \param p_entropy     The entropy context.
+ * \param custom        Personalization data, that is device-specific
+                        identifiers. Can be NULL.
+ * \param len           The length of the personalization data.
  *
- * \return              0 if successful, or
- *                      MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED
+ * \return              \c 0 on success, or
+ *                      #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure.
  */
 int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx,
                    int (*f_entropy)(void *, unsigned char *, size_t),
@@ -143,138 +166,147 @@ int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx,
                    size_t len );
 
 /**
- * \brief               Clear CTR_CRBG context data
+ * \brief               This function clears CTR_CRBG context data.
  *
- * \param ctx           CTR_DRBG context to clear
+ * \param ctx           The CTR_DRBG context to clear.
  */
 void mbedtls_ctr_drbg_free( mbedtls_ctr_drbg_context *ctx );
 
 /**
- * \brief               Enable / disable prediction resistance (Default: Off)
+ * \brief               This function turns prediction resistance on or off.
+ *                      The default value is off.
  *
- * Note: If enabled, entropy is used for ctx->entropy_len before each call!
- *       Only use this if you have ample supply of good entropy!
+ * \note                If enabled, entropy is gathered at the beginning of
+ *                      every call to mbedtls_ctr_drbg_random_with_add().
+ *                      Only use this if your entropy source has sufficient
+ *                      throughput.
  *
- * \param ctx           CTR_DRBG context
- * \param resistance    MBEDTLS_CTR_DRBG_PR_ON or MBEDTLS_CTR_DRBG_PR_OFF
+ * \param ctx           The CTR_DRBG context.
+ * \param resistance    #MBEDTLS_CTR_DRBG_PR_ON or #MBEDTLS_CTR_DRBG_PR_OFF.
  */
 void mbedtls_ctr_drbg_set_prediction_resistance( mbedtls_ctr_drbg_context *ctx,
                                          int resistance );
 
 /**
- * \brief               Set the amount of entropy grabbed on each (re)seed
- *                      (Default: MBEDTLS_CTR_DRBG_ENTROPY_LEN)
+ * \brief               This function sets the amount of entropy grabbed on each
+ *                      seed or reseed. The default value is
+ *                      #MBEDTLS_CTR_DRBG_ENTROPY_LEN.
  *
- * \param ctx           CTR_DRBG context
- * \param len           Amount of entropy to grab
+ * \param ctx           The CTR_DRBG context.
+ * \param len           The amount of entropy to grab.
  */
 void mbedtls_ctr_drbg_set_entropy_len( mbedtls_ctr_drbg_context *ctx,
                                size_t len );
 
 /**
- * \brief               Set the reseed interval
- *                      (Default: MBEDTLS_CTR_DRBG_RESEED_INTERVAL)
+ * \brief               This function sets the reseed interval.
+ *                      The default value is #MBEDTLS_CTR_DRBG_RESEED_INTERVAL.
  *
- * \param ctx           CTR_DRBG context
- * \param interval      Reseed interval
+ * \param ctx           The CTR_DRBG context.
+ * \param interval      The reseed interval.
  */
 void mbedtls_ctr_drbg_set_reseed_interval( mbedtls_ctr_drbg_context *ctx,
                                    int interval );
 
 /**
- * \brief               CTR_DRBG reseeding (extracts data from entropy source)
+ * \brief               This function reseeds the CTR_DRBG context, that is
+ *                      extracts data from the entropy source.
  *
- * \param ctx           CTR_DRBG context
- * \param additional    Additional data to add to state (Can be NULL)
- * \param len           Length of additional data
+ * \param ctx           The CTR_DRBG context.
+ * \param additional    Additional data to add to the state. Can be NULL.
+ * \param len           The length of the additional data.
  *
- * \return              0 if successful, or
- *                      MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED
+ * \return   \c 0 on success, or
+ *           #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure.
  */
 int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,
                      const unsigned char *additional, size_t len );
 
 /**
- * \brief               CTR_DRBG update state
+ * \brief               This function updates the state of the CTR_DRBG context.
  *
- * \param ctx           CTR_DRBG context
- * \param additional    Additional data to update state with
- * \param add_len       Length of additional data
+ * \param ctx           The CTR_DRBG context.
+ * \param additional    The data to update the state with.
+ * \param add_len       Length of \p additional data.
  *
- * \note                If add_len is greater than MBEDTLS_CTR_DRBG_MAX_SEED_INPUT,
- *                      only the first MBEDTLS_CTR_DRBG_MAX_SEED_INPUT bytes are used,
- *                      the remaining ones are silently discarded.
+ * \note     If \p add_len is greater than #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT,
+ *           only the first #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT Bytes are used.
+ *           The remaining Bytes are silently discarded.
  */
 void mbedtls_ctr_drbg_update( mbedtls_ctr_drbg_context *ctx,
                       const unsigned char *additional, size_t add_len );
 
 /**
- * \brief               CTR_DRBG generate random with additional update input
+ * \brief   This function updates a CTR_DRBG instance with additional
+ *          data and uses it to generate random data.
  *
- * Note: Automatically reseeds if reseed_counter is reached.
+ * \note    The function automatically reseeds if the reseed counter is exceeded.
  *
- * \param p_rng         CTR_DRBG context
- * \param output        Buffer to fill
- * \param output_len    Length of the buffer
- * \param additional    Additional data to update with (Can be NULL)
- * \param add_len       Length of additional data
+ * \param p_rng         The CTR_DRBG context. This must be a pointer to a
+ *                      #mbedtls_ctr_drbg_context structure.
+ * \param output        The buffer to fill.
+ * \param output_len    The length of the buffer.
+ * \param additional    Additional data to update. Can be NULL.
+ * \param add_len       The length of the additional data.
  *
- * \return              0 if successful, or
- *                      MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED, or
- *                      MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG
+ * \return    \c 0 on success, or
+ *            #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
+ *            #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure.
  */
 int mbedtls_ctr_drbg_random_with_add( void *p_rng,
                               unsigned char *output, size_t output_len,
                               const unsigned char *additional, size_t add_len );
 
 /**
- * \brief               CTR_DRBG generate random
+ * \brief   This function uses CTR_DRBG to generate random data.
  *
- * Note: Automatically reseeds if reseed_counter is reached.
+ * \note    The function automatically reseeds if the reseed counter is exceeded.
  *
- * \param p_rng         CTR_DRBG context
- * \param output        Buffer to fill
- * \param output_len    Length of the buffer
+ * \param p_rng         The CTR_DRBG context. This must be a pointer to a
+ *                      #mbedtls_ctr_drbg_context structure.
+ * \param output        The buffer to fill.
+ * \param output_len    The length of the buffer.
  *
- * \return              0 if successful, or
- *                      MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED, or
- *                      MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG
+ * \return              \c 0 on success, or
+ *                      #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
+ *                      #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure.
  */
 int mbedtls_ctr_drbg_random( void *p_rng,
                      unsigned char *output, size_t output_len );
 
 #if defined(MBEDTLS_FS_IO)
 /**
- * \brief               Write a seed file
+ * \brief               This function writes a seed file.
  *
- * \param ctx           CTR_DRBG context
- * \param path          Name of the file
+ * \param ctx           The CTR_DRBG context.
+ * \param path          The name of the file.
  *
- * \return              0 if successful,
- *                      MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error, or
- *                      MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED
+ * \return              \c 0 on success,
+ *                      #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error, or
+ *                      #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on
+ *                      failure.
  */
 int mbedtls_ctr_drbg_write_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path );
 
 /**
- * \brief               Read and update a seed file. Seed is added to this
- *                      instance
+ * \brief               This function reads and updates a seed file. The seed
+ *                      is added to this instance.
  *
- * \param ctx           CTR_DRBG context
- * \param path          Name of the file
+ * \param ctx           The CTR_DRBG context.
+ * \param path          The name of the file.
  *
- * \return              0 if successful,
- *                      MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error,
- *                      MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
- *                      MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG
+ * \return              \c 0 on success,
+ *                      #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error,
+ *                      #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
+ *                      #MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG on failure.
  */
 int mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path );
 #endif /* MBEDTLS_FS_IO */
 
 /**
- * \brief               Checkup routine
+ * \brief               The CTR_DRBG checkup routine.
  *
- * \return              0 if successful, or 1 if the test failed
+ * \return              \c 0 on success, or \c 1 on failure.
  */
 int mbedtls_ctr_drbg_self_test( int verbose );
 

+ 110 - 6
app/include/mbedtls/debug.h

@@ -1,8 +1,9 @@
 /**
  * \file debug.h
  *
- * \brief Debug functions
- *
+ * \brief Functions for controlling and providing debug output from the library.
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -80,39 +81,141 @@ extern "C" {
 #endif
 
 /**
- * \brief   Set the level threshold to handle globally. Messages that have a
- *          level over the threshold value are ignored.
- *          (Default value: 0 (No debug))
+ * \brief   Set the threshold error level to handle globally all debug output.
+ *          Debug messages that have a level over the threshold value are
+ *          discarded.
+ *          (Default value: 0 = No debug )
  *
- * \param threshold     maximum level of messages to pass on
+ * \param threshold     theshold level of messages to filter on. Messages at a
+ *                      higher level will be discarded.
+ *                          - Debug levels
+ *                              - 0 No debug
+ *                              - 1 Error
+ *                              - 2 State change
+ *                              - 3 Informational
+ *                              - 4 Verbose
  */
 void mbedtls_debug_set_threshold( int threshold );
 
+/**
+ * \brief    Print a message to the debug output. This function is always used
+ *          through the MBEDTLS_SSL_DEBUG_MSG() macro, which supplies the ssl
+ *          context, file and line number parameters.
+ *
+ * \param ssl       SSL context
+ * \param level     error level of the debug message
+ * \param file      file the message has occurred in
+ * \param line      line number the message has occurred at
+ * \param format    format specifier, in printf format
+ * \param ...       variables used by the format specifier
+ *
+ * \attention       This function is intended for INTERNAL usage within the
+ *                  library only.
+ */
 void mbedtls_debug_print_msg( const mbedtls_ssl_context *ssl, int level,
                               const char *file, int line,
                               const char *format, ... );
 
+/**
+ * \brief   Print the return value of a function to the debug output. This
+ *          function is always used through the MBEDTLS_SSL_DEBUG_RET() macro,
+ *          which supplies the ssl context, file and line number parameters.
+ *
+ * \param ssl       SSL context
+ * \param level     error level of the debug message
+ * \param file      file the error has occurred in
+ * \param line      line number the error has occurred in
+ * \param text      the name of the function that returned the error
+ * \param ret       the return code value
+ *
+ * \attention       This function is intended for INTERNAL usage within the
+ *                  library only.
+ */
 void mbedtls_debug_print_ret( const mbedtls_ssl_context *ssl, int level,
                       const char *file, int line,
                       const char *text, int ret );
 
+/**
+ * \brief   Output a buffer of size len bytes to the debug output. This function
+ *          is always used through the MBEDTLS_SSL_DEBUG_BUF() macro,
+ *          which supplies the ssl context, file and line number parameters.
+ *
+ * \param ssl       SSL context
+ * \param level     error level of the debug message
+ * \param file      file the error has occurred in
+ * \param line      line number the error has occurred in
+ * \param text      a name or label for the buffer being dumped. Normally the
+ *                  variable or buffer name
+ * \param buf       the buffer to be outputted
+ * \param len       length of the buffer
+ *
+ * \attention       This function is intended for INTERNAL usage within the
+ *                  library only.
+ */
 void mbedtls_debug_print_buf( const mbedtls_ssl_context *ssl, int level,
                       const char *file, int line, const char *text,
                       const unsigned char *buf, size_t len );
 
 #if defined(MBEDTLS_BIGNUM_C)
+/**
+ * \brief   Print a MPI variable to the debug output. This function is always
+ *          used through the MBEDTLS_SSL_DEBUG_MPI() macro, which supplies the
+ *          ssl context, file and line number parameters.
+ *
+ * \param ssl       SSL context
+ * \param level     error level of the debug message
+ * \param file      file the error has occurred in
+ * \param line      line number the error has occurred in
+ * \param text      a name or label for the MPI being output. Normally the
+ *                  variable name
+ * \param X         the MPI variable
+ *
+ * \attention       This function is intended for INTERNAL usage within the
+ *                  library only.
+ */
 void mbedtls_debug_print_mpi( const mbedtls_ssl_context *ssl, int level,
                       const char *file, int line,
                       const char *text, const mbedtls_mpi *X );
 #endif
 
 #if defined(MBEDTLS_ECP_C)
+/**
+ * \brief   Print an ECP point to the debug output. This function is always
+ *          used through the MBEDTLS_SSL_DEBUG_ECP() macro, which supplies the
+ *          ssl context, file and line number parameters.
+ *
+ * \param ssl       SSL context
+ * \param level     error level of the debug message
+ * \param file      file the error has occurred in
+ * \param line      line number the error has occurred in
+ * \param text      a name or label for the ECP point being output. Normally the
+ *                  variable name
+ * \param X         the ECP point
+ *
+ * \attention       This function is intended for INTERNAL usage within the
+ *                  library only.
+ */
 void mbedtls_debug_print_ecp( const mbedtls_ssl_context *ssl, int level,
                       const char *file, int line,
                       const char *text, const mbedtls_ecp_point *X );
 #endif
 
 #if defined(MBEDTLS_X509_CRT_PARSE_C)
+/**
+ * \brief   Print a X.509 certificate structure to the debug output. This
+ *          function is always used through the MBEDTLS_SSL_DEBUG_CRT() macro,
+ *          which supplies the ssl context, file and line number parameters.
+ *
+ * \param ssl       SSL context
+ * \param level     error level of the debug message
+ * \param file      file the error has occurred in
+ * \param line      line number the error has occurred in
+ * \param text      a name or label for the certificate being output
+ * \param crt       X.509 certificate structure
+ *
+ * \attention       This function is intended for INTERNAL usage within the
+ *                  library only.
+ */
 void mbedtls_debug_print_crt( const mbedtls_ssl_context *ssl, int level,
                       const char *file, int line,
                       const char *text, const mbedtls_x509_crt *crt );
@@ -123,3 +226,4 @@ void mbedtls_debug_print_crt( const mbedtls_ssl_context *ssl, int level,
 #endif
 
 #endif /* debug.h */
+

+ 51 - 0
app/include/mbedtls/des.h

@@ -3,6 +3,11 @@
  *
  * \brief DES block cipher
  *
+ * \warning   DES is considered a weak cipher and its use constitutes a
+ *            security risk. We recommend considering stronger ciphers
+ *            instead.
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -19,6 +24,7 @@
  *  limitations under the License.
  *
  *  This file is part of mbed TLS (https://tls.mbed.org)
+ *
  */
 #ifndef MBEDTLS_DES_H
 #define MBEDTLS_DES_H
@@ -36,6 +42,7 @@
 #define MBEDTLS_DES_DECRYPT     0
 
 #define MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH              -0x0032  /**< The data input has an invalid length. */
+#define MBEDTLS_ERR_DES_HW_ACCEL_FAILED                   -0x0033  /**< DES hardware accelerator failed. */
 
 #define MBEDTLS_DES_KEY_SIZE    8
 
@@ -49,6 +56,10 @@ extern "C" {
 
 /**
  * \brief          DES context structure
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
 typedef struct
 {
@@ -69,6 +80,10 @@ mbedtls_des3_context;
  * \brief          Initialize DES context
  *
  * \param ctx      DES context to be initialized
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
 void mbedtls_des_init( mbedtls_des_context *ctx );
 
@@ -76,6 +91,10 @@ void mbedtls_des_init( mbedtls_des_context *ctx );
  * \brief          Clear DES context
  *
  * \param ctx      DES context to be cleared
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
 void mbedtls_des_free( mbedtls_des_context *ctx );
 
@@ -100,6 +119,10 @@ void mbedtls_des3_free( mbedtls_des3_context *ctx );
  *                 a parity bit to allow verification.
  *
  * \param key      8-byte secret key
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
 void mbedtls_des_key_set_parity( unsigned char key[MBEDTLS_DES_KEY_SIZE] );
 
@@ -112,6 +135,10 @@ void mbedtls_des_key_set_parity( unsigned char key[MBEDTLS_DES_KEY_SIZE] );
  * \param key      8-byte secret key
  *
  * \return         0 is parity was ok, 1 if parity was not correct.
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
 int mbedtls_des_key_check_key_parity( const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
 
@@ -121,6 +148,10 @@ int mbedtls_des_key_check_key_parity( const unsigned char key[MBEDTLS_DES_KEY_SI
  * \param key      8-byte secret key
  *
  * \return         0 if no weak key was found, 1 if a weak key was identified.
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
 int mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
 
@@ -131,6 +162,10 @@ int mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
  * \param key      8-byte secret key
  *
  * \return         0
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
 int mbedtls_des_setkey_enc( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
 
@@ -141,6 +176,10 @@ int mbedtls_des_setkey_enc( mbedtls_des_context *ctx, const unsigned char key[MB
  * \param key      8-byte secret key
  *
  * \return         0
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
 int mbedtls_des_setkey_dec( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
 
@@ -196,6 +235,10 @@ int mbedtls_des3_set3key_dec( mbedtls_des3_context *ctx,
  * \param output   64-bit output block
  *
  * \return         0 if successful
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
 int mbedtls_des_crypt_ecb( mbedtls_des_context *ctx,
                     const unsigned char input[8],
@@ -219,6 +262,10 @@ int mbedtls_des_crypt_ecb( mbedtls_des_context *ctx,
  * \param iv       initialization vector (updated after use)
  * \param input    buffer holding the input data
  * \param output   buffer holding the output data
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
 int mbedtls_des_crypt_cbc( mbedtls_des_context *ctx,
                     int mode,
@@ -277,6 +324,10 @@ int mbedtls_des3_crypt_cbc( mbedtls_des3_context *ctx,
  *
  * \param SK       Round keys
  * \param key      Base key
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
 void mbedtls_des_setkey( uint32_t SK[32],
                          const unsigned char key[MBEDTLS_DES_KEY_SIZE] );

+ 935 - 179
app/include/mbedtls/dhm.h

@@ -1,9 +1,44 @@
 /**
  * \file dhm.h
  *
- * \brief Diffie-Hellman-Merkle key exchange
+ * \brief Diffie-Hellman-Merkle key exchange.
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * <em>RFC-3526: More Modular Exponential (MODP) Diffie-Hellman groups for
+ * Internet Key Exchange (IKE)</em> defines a number of standardized
+ * Diffie-Hellman groups for IKE.
+ *
+ * <em>RFC-5114: Additional Diffie-Hellman Groups for Use with IETF
+ * Standards</em> defines a number of standardized Diffie-Hellman
+ * groups that can be used.
+ *
+ * \warning  The security of the DHM key exchange relies on the proper choice
+ *           of prime modulus - optimally, it should be a safe prime. The usage
+ *           of non-safe primes both decreases the difficulty of the underlying
+ *           discrete logarithm problem and can lead to small subgroup attacks
+ *           leaking private exponent bits when invalid public keys are used
+ *           and not detected. This is especially relevant if the same DHM
+ *           parameters are reused for multiple key exchanges as in static DHM,
+ *           while the criticality of small-subgroup attacks is lower for
+ *           ephemeral DHM.
+ *
+ * \warning  For performance reasons, the code does neither perform primality
+ *           nor safe primality tests, nor the expensive checks for invalid
+ *           subgroups. Moreover, even if these were performed, non-standardized
+ *           primes cannot be trusted because of the possibility of backdoors
+ *           that can't be effectively checked for.
+ *
+ * \warning  Diffie-Hellman-Merkle is therefore a security risk when not using
+ *           standardized primes generated using a trustworthy ("nothing up
+ *           my sleeve") method, such as the RFC 3526 / 7919 primes. In the TLS
+ *           protocol, DH parameters need to be negotiated, so using the default
+ *           primes systematically is not always an option. If possible, use
+ *           Elliptic Curve Diffie-Hellman (ECDH), which has better performance,
+ *           and for which the TLS protocol mandates the use of standard
+ *           parameters.
+ *
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,17 +53,24 @@
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *
- *  This file is part of mbed TLS (https://tls.mbed.org)
+ *  This file is part of Mbed TLS (https://tls.mbed.org)
  */
+
 #ifndef MBEDTLS_DHM_H
 #define MBEDTLS_DHM_H
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
 #include "bignum.h"
+#if !defined(MBEDTLS_DHM_ALT)
 
 /*
  * DHM Error codes
  */
-#define MBEDTLS_ERR_DHM_BAD_INPUT_DATA                    -0x3080  /**< Bad input parameters to function. */
+#define MBEDTLS_ERR_DHM_BAD_INPUT_DATA                    -0x3080  /**< Bad input parameters. */
 #define MBEDTLS_ERR_DHM_READ_PARAMS_FAILED                -0x3100  /**< Reading of the DHM parameters failed. */
 #define MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED                -0x3180  /**< Making of the DHM parameters failed. */
 #define MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED                -0x3200  /**< Reading of the public values failed. */
@@ -36,167 +78,85 @@
 #define MBEDTLS_ERR_DHM_CALC_SECRET_FAILED                -0x3300  /**< Calculation of the DHM secret failed. */
 #define MBEDTLS_ERR_DHM_INVALID_FORMAT                    -0x3380  /**< The ASN.1 data is not formatted correctly. */
 #define MBEDTLS_ERR_DHM_ALLOC_FAILED                      -0x3400  /**< Allocation of memory failed. */
-#define MBEDTLS_ERR_DHM_FILE_IO_ERROR                     -0x3480  /**< Read/write of file failed. */
-
-/**
- * RFC 3526 defines a number of standardized Diffie-Hellman groups
- * for IKE.
- * RFC 5114 defines a number of standardized Diffie-Hellman groups
- * that can be used.
- *
- * Some are included here for convenience.
- *
- * Included are:
- *  RFC 3526 3.    2048-bit MODP Group
- *  RFC 3526 4.    3072-bit MODP Group
- *  RFC 3526 5.    4096-bit MODP Group
- *  RFC 5114 2.2.  2048-bit MODP Group with 224-bit Prime Order Subgroup
- */
-#define MBEDTLS_DHM_RFC3526_MODP_2048_P               \
-    "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \
-    "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \
-    "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \
-    "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \
-    "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \
-    "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \
-    "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \
-    "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \
-    "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \
-    "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \
-    "15728E5A8AACAA68FFFFFFFFFFFFFFFF"
-
-#define MBEDTLS_DHM_RFC3526_MODP_2048_G          "02"
-
-#define MBEDTLS_DHM_RFC3526_MODP_3072_P               \
-    "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \
-    "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \
-    "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \
-    "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \
-    "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \
-    "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \
-    "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \
-    "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \
-    "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \
-    "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \
-    "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \
-    "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \
-    "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \
-    "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \
-    "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \
-    "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF"
-
-#define MBEDTLS_DHM_RFC3526_MODP_3072_G          "02"
-
-#define MBEDTLS_DHM_RFC3526_MODP_4096_P                \
-    "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \
-    "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \
-    "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \
-    "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \
-    "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \
-    "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \
-    "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \
-    "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \
-    "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \
-    "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \
-    "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \
-    "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \
-    "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \
-    "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \
-    "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \
-    "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" \
-    "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" \
-    "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" \
-    "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" \
-    "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" \
-    "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" \
-    "FFFFFFFFFFFFFFFF"
-
-#define MBEDTLS_DHM_RFC3526_MODP_4096_G          "02"
-
-#define MBEDTLS_DHM_RFC5114_MODP_2048_P               \
-    "AD107E1E9123A9D0D660FAA79559C51FA20D64E5683B9FD1" \
-    "B54B1597B61D0A75E6FA141DF95A56DBAF9A3C407BA1DF15" \
-    "EB3D688A309C180E1DE6B85A1274A0A66D3F8152AD6AC212" \
-    "9037C9EDEFDA4DF8D91E8FEF55B7394B7AD5B7D0B6C12207" \
-    "C9F98D11ED34DBF6C6BA0B2C8BBC27BE6A00E0A0B9C49708" \
-    "B3BF8A317091883681286130BC8985DB1602E714415D9330" \
-    "278273C7DE31EFDC7310F7121FD5A07415987D9ADC0A486D" \
-    "CDF93ACC44328387315D75E198C641A480CD86A1B9E587E8" \
-    "BE60E69CC928B2B9C52172E413042E9B23F10B0E16E79763" \
-    "C9B53DCF4BA80A29E3FB73C16B8E75B97EF363E2FFA31F71" \
-    "CF9DE5384E71B81C0AC4DFFE0C10E64F"
-
-#define MBEDTLS_DHM_RFC5114_MODP_2048_G              \
-    "AC4032EF4F2D9AE39DF30B5C8FFDAC506CDEBE7B89998CAF"\
-    "74866A08CFE4FFE3A6824A4E10B9A6F0DD921F01A70C4AFA"\
-    "AB739D7700C29F52C57DB17C620A8652BE5E9001A8D66AD7"\
-    "C17669101999024AF4D027275AC1348BB8A762D0521BC98A"\
-    "E247150422EA1ED409939D54DA7460CDB5F6C6B250717CBE"\
-    "F180EB34118E98D119529A45D6F834566E3025E316A330EF"\
-    "BB77A86F0C1AB15B051AE3D428C8F8ACB70A8137150B8EEB"\
-    "10E183EDD19963DDD9E263E4770589EF6AA21E7F5F2FF381"\
-    "B539CCE3409D13CD566AFBB48D6C019181E1BCFE94B30269"\
-    "EDFE72FE9B6AA4BD7B5A0F1C71CFFF4C19C418E1F6EC0179"\
-    "81BC087F2A7065B384B890D3191F2BFA"
+#define MBEDTLS_ERR_DHM_FILE_IO_ERROR                     -0x3480  /**< Read or write of file failed. */
+#define MBEDTLS_ERR_DHM_HW_ACCEL_FAILED                   -0x3500  /**< DHM hardware accelerator failed. */
+#define MBEDTLS_ERR_DHM_SET_GROUP_FAILED                  -0x3580  /**< Setting the modulus and generator failed. */
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
 /**
- * \brief          DHM context structure
+ * \brief          The DHM context structure.
  */
 typedef struct
 {
-    size_t len; /*!<  size(P) in chars  */
-    mbedtls_mpi P;      /*!<  prime modulus     */
-    mbedtls_mpi G;      /*!<  generator         */
-    mbedtls_mpi X;      /*!<  secret value      */
-    mbedtls_mpi GX;     /*!<  self = G^X mod P  */
-    mbedtls_mpi GY;     /*!<  peer = G^Y mod P  */
-    mbedtls_mpi K;      /*!<  key = GY^X mod P  */
-    mbedtls_mpi RP;     /*!<  cached R^2 mod P  */
-    mbedtls_mpi Vi;     /*!<  blinding value    */
-    mbedtls_mpi Vf;     /*!<  un-blinding value */
-    mbedtls_mpi pX;     /*!<  previous X        */
+    size_t len;         /*!<  The size of \p P in Bytes. */
+    mbedtls_mpi P;      /*!<  The prime modulus. */
+    mbedtls_mpi G;      /*!<  The generator. */
+    mbedtls_mpi X;      /*!<  Our secret value. */
+    mbedtls_mpi GX;     /*!<  Our public key = \c G^X mod \c P. */
+    mbedtls_mpi GY;     /*!<  The public key of the peer = \c G^Y mod \c P. */
+    mbedtls_mpi K;      /*!<  The shared secret = \c G^(XY) mod \c P. */
+    mbedtls_mpi RP;     /*!<  The cached value = \c R^2 mod \c P. */
+    mbedtls_mpi Vi;     /*!<  The blinding value. */
+    mbedtls_mpi Vf;     /*!<  The unblinding value. */
+    mbedtls_mpi pX;     /*!<  The previous \c X. */
 }
 mbedtls_dhm_context;
 
 /**
- * \brief          Initialize DHM context
+ * \brief          This function initializes the DHM context.
  *
- * \param ctx      DHM context to be initialized
+ * \param ctx      The DHM context to initialize.
  */
 void mbedtls_dhm_init( mbedtls_dhm_context *ctx );
 
 /**
- * \brief          Parse the ServerKeyExchange parameters
+ * \brief          This function parses the ServerKeyExchange parameters.
  *
- * \param ctx      DHM context
- * \param p        &(start of input buffer)
- * \param end      end of buffer
+ * \param ctx      The DHM context.
+ * \param p        On input, *p must be the start of the input buffer.
+ *                 On output, *p is updated to point to the end of the data
+ *                 that has been read. On success, this is the first byte
+ *                 past the end of the ServerKeyExchange parameters.
+ *                 On error, this is the point at which an error has been
+ *                 detected, which is usually not useful except to debug
+ *                 failures.
+ * \param end      The end of the input buffer.
  *
- * \return         0 if successful, or an MBEDTLS_ERR_DHM_XXX error code
+ * \return         \c 0 on success, or an \c MBEDTLS_ERR_DHM_XXX error code
+ *                 on failure.
  */
 int mbedtls_dhm_read_params( mbedtls_dhm_context *ctx,
                      unsigned char **p,
                      const unsigned char *end );
 
 /**
- * \brief          Setup and write the ServerKeyExchange parameters
+ * \brief          This function sets up and writes the ServerKeyExchange
+ *                 parameters.
  *
- * \param ctx      DHM context
- * \param x_size   private value size in bytes
- * \param output   destination buffer
- * \param olen     number of chars written
- * \param f_rng    RNG function
- * \param p_rng    RNG parameter
+ * \param ctx      The DHM context.
+ * \param x_size   The private value size in Bytes.
+ * \param olen     The number of characters written.
+ * \param output   The destination buffer.
+ * \param f_rng    The RNG function.
+ * \param p_rng    The RNG parameter.
  *
- * \note           This function assumes that ctx->P and ctx->G
- *                 have already been properly set (for example
- *                 using mbedtls_mpi_read_string or mbedtls_mpi_read_binary).
+ * \note           The destination buffer must be large enough to hold
+ *                 the reduced binary presentation of the modulus, the generator
+ *                 and the public key, each wrapped with a 2-byte length field.
+ *                 It is the responsibility of the caller to ensure that enough
+ *                 space is available. Refer to \c mbedtls_mpi_size to computing
+ *                 the byte-size of an MPI.
  *
- * \return         0 if successful, or an MBEDTLS_ERR_DHM_XXX error code
+ * \note           This function assumes that \c ctx->P and \c ctx->G
+ *                 have already been properly set. For that, use
+ *                 mbedtls_dhm_set_group() below in conjunction with
+ *                 mbedtls_mpi_read_binary() and mbedtls_mpi_read_string().
+ *
+ * \return         \c 0 on success, or an \c MBEDTLS_ERR_DHM_XXX error code
+ *                 on failure.
  */
 int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,
                      unsigned char *output, size_t *olen,
@@ -204,28 +164,54 @@ int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,
                      void *p_rng );
 
 /**
- * \brief          Import the peer's public value G^Y
+ * \brief          Set prime modulus and generator
+ *
+ * \param ctx      The DHM context.
+ * \param P        The MPI holding DHM prime modulus.
+ * \param G        The MPI holding DHM generator.
  *
- * \param ctx      DHM context
- * \param input    input buffer
- * \param ilen     size of buffer
+ * \note           This function can be used to set P, G
+ *                 in preparation for \c mbedtls_dhm_make_params.
  *
- * \return         0 if successful, or an MBEDTLS_ERR_DHM_XXX error code
+ * \return         \c 0 if successful, or an \c MBEDTLS_ERR_DHM_XXX error code
+ *                 on failure.
+ */
+int mbedtls_dhm_set_group( mbedtls_dhm_context *ctx,
+                           const mbedtls_mpi *P,
+                           const mbedtls_mpi *G );
+
+/**
+ * \brief          This function imports the public value G^Y of the peer.
+ *
+ * \param ctx      The DHM context.
+ * \param input    The input buffer.
+ * \param ilen     The size of the input buffer.
+ *
+ * \return         \c 0 on success, or an \c MBEDTLS_ERR_DHM_XXX error code
+ *                 on failure.
  */
 int mbedtls_dhm_read_public( mbedtls_dhm_context *ctx,
                      const unsigned char *input, size_t ilen );
 
 /**
- * \brief          Create own private value X and export G^X
+ * \brief          This function creates its own private value \c X and
+ *                 exports \c G^X.
+ *
+ * \param ctx      The DHM context.
+ * \param x_size   The private value size in Bytes.
+ * \param output   The destination buffer.
+ * \param olen     The length of the destination buffer. Must be at least
+                   equal to ctx->len (the size of \c P).
+ * \param f_rng    The RNG function.
+ * \param p_rng    The RNG parameter.
  *
- * \param ctx      DHM context
- * \param x_size   private value size in bytes
- * \param output   destination buffer
- * \param olen     must be equal to ctx->P.len
- * \param f_rng    RNG function
- * \param p_rng    RNG parameter
+ * \note           The destination buffer will always be fully written
+ *                 so as to contain a big-endian presentation of G^X mod P.
+ *                 If it is larger than ctx->len, it will accordingly be
+ *                 padded with zero-bytes in the beginning.
  *
- * \return         0 if successful, or an MBEDTLS_ERR_DHM_XXX error code
+ * \return         \c 0 on success, or an \c MBEDTLS_ERR_DHM_XXX error code
+ *                 on failure.
  */
 int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size,
                      unsigned char *output, size_t olen,
@@ -233,22 +219,25 @@ int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size,
                      void *p_rng );
 
 /**
- * \brief          Derive and export the shared secret (G^Y)^X mod P
- *
- * \param ctx      DHM context
- * \param output   destination buffer
- * \param output_size   size of the destination buffer
- * \param olen     on exit, holds the actual number of bytes written
- * \param f_rng    RNG function, for blinding purposes
- * \param p_rng    RNG parameter
- *
- * \return         0 if successful, or an MBEDTLS_ERR_DHM_XXX error code
- *
- * \note           If non-NULL, f_rng is used to blind the input as
- *                 countermeasure against timing attacks. Blinding is
- *                 automatically used if and only if our secret value X is
- *                 re-used and costs nothing otherwise, so it is recommended
- *                 to always pass a non-NULL f_rng argument.
+ * \brief               This function derives and exports the shared secret
+ *                      \c (G^Y)^X mod \c P.
+ *
+ * \param ctx           The DHM context.
+ * \param output        The destination buffer.
+ * \param output_size   The size of the destination buffer. Must be at least
+ *                      the size of ctx->len.
+ * \param olen          On exit, holds the actual number of Bytes written.
+ * \param f_rng         The RNG function, for blinding purposes.
+ * \param p_rng         The RNG parameter.
+ *
+ * \return         \c 0 on success, or an \c MBEDTLS_ERR_DHM_XXX error code
+ *                 on failure.
+ *
+ * \note           If non-NULL, \p f_rng is used to blind the input as
+ *                 a countermeasure against timing attacks. Blinding is used
+ *                 only if our secret value \p X is re-used and omitted
+ *                 otherwise. Therefore, we recommend always passing a
+ *                 non-NULL \p f_rng argument.
  */
 int mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx,
                      unsigned char *output, size_t output_size, size_t *olen,
@@ -256,23 +245,24 @@ int mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx,
                      void *p_rng );
 
 /**
- * \brief          Free and clear the components of a DHM key
+ * \brief          This function frees and clears the components of a DHM key.
  *
- * \param ctx      DHM context to free and clear
+ * \param ctx      The DHM context to free and clear.
  */
 void mbedtls_dhm_free( mbedtls_dhm_context *ctx );
 
 #if defined(MBEDTLS_ASN1_PARSE_C)
 /** \ingroup x509_module */
 /**
- * \brief          Parse DHM parameters in PEM or DER format
+ * \brief             This function parses DHM parameters in PEM or DER format.
  *
- * \param dhm      DHM context to be initialized
- * \param dhmin    input buffer
- * \param dhminlen size of the buffer
- *                 (including the terminating null byte for PEM data)
+ * \param dhm         The DHM context to initialize.
+ * \param dhmin       The input buffer.
+ * \param dhminlen    The size of the buffer, including the terminating null
+ *                    Byte for PEM data.
  *
- * \return         0 if successful, or a specific DHM or PEM error code
+ * \return            \c 0 on success, or a specific DHM or PEM error code
+ *                    on failure.
  */
 int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin,
                    size_t dhminlen );
@@ -280,21 +270,34 @@ int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin,
 #if defined(MBEDTLS_FS_IO)
 /** \ingroup x509_module */
 /**
- * \brief          Load and parse DHM parameters
+ * \brief          This function loads and parses DHM parameters from a file.
  *
- * \param dhm      DHM context to be initialized
- * \param path     filename to read the DHM Parameters from
+ * \param dhm      The DHM context to load the parameters to.
+ * \param path     The filename to read the DHM parameters from.
  *
- * \return         0 if successful, or a specific DHM or PEM error code
+ * \return         \c 0 on success, or a specific DHM or PEM error code
+ *                 on failure.
  */
 int mbedtls_dhm_parse_dhmfile( mbedtls_dhm_context *dhm, const char *path );
 #endif /* MBEDTLS_FS_IO */
 #endif /* MBEDTLS_ASN1_PARSE_C */
 
+#ifdef __cplusplus
+}
+#endif
+
+#else /* MBEDTLS_DHM_ALT */
+#include "dhm_alt.h"
+#endif /* MBEDTLS_DHM_ALT */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 /**
- * \brief          Checkup routine
+ * \brief          The DMH checkup routine.
  *
- * \return         0 if successful, or 1 if the test failed
+ * \return         \c 0 on success, or \c 1 on failure.
  */
 int mbedtls_dhm_self_test( int verbose );
 
@@ -302,4 +305,757 @@ int mbedtls_dhm_self_test( int verbose );
 }
 #endif
 
+/**
+ * RFC 3526, RFC 5114 and RFC 7919 standardize a number of
+ * Diffie-Hellman groups, some of which are included here
+ * for use within the SSL/TLS module and the user's convenience
+ * when configuring the Diffie-Hellman parameters by hand
+ * through \c mbedtls_ssl_conf_dh_param.
+ *
+ * The following lists the source of the above groups in the standards:
+ * - RFC 5114 section 2.2:  2048-bit MODP Group with 224-bit Prime Order Subgroup
+ * - RFC 3526 section 3:    2048-bit MODP Group
+ * - RFC 3526 section 4:    3072-bit MODP Group
+ * - RFC 3526 section 5:    4096-bit MODP Group
+ * - RFC 7919 section A.1:  ffdhe2048
+ * - RFC 7919 section A.2:  ffdhe3072
+ * - RFC 7919 section A.3:  ffdhe4096
+ * - RFC 7919 section A.4:  ffdhe6144
+ * - RFC 7919 section A.5:  ffdhe8192
+ *
+ * The constants with suffix "_p" denote the chosen prime moduli, while
+ * the constants with suffix "_g" denote the chosen generator
+ * of the associated prime field.
+ *
+ * The constants further suffixed with "_bin" are provided in binary format,
+ * while all other constants represent null-terminated strings holding the
+ * hexadecimal presentation of the respective numbers.
+ *
+ * The primes from RFC 3526 and RFC 7919 have been generating by the following
+ * trust-worthy procedure:
+ * - Fix N in { 2048, 3072, 4096, 6144, 8192 } and consider the N-bit number
+ *   the first and last 64 bits are all 1, and the remaining N - 128 bits of
+ *   which are 0x7ff...ff.
+ * - Add the smallest multiple of the first N - 129 bits of the binary expansion
+ *   of pi (for RFC 5236) or e (for RFC 7919) to this intermediate bit-string
+ *   such that the resulting integer is a safe-prime.
+ * - The result is the respective RFC 3526 / 7919 prime, and the corresponding
+ *   generator is always chosen to be 2 (which is a square for these prime,
+ *   hence the corresponding subgroup has order (p-1)/2 and avoids leaking a
+ *   bit in the private exponent).
+ *
+ */
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED __attribute__((deprecated))
+MBEDTLS_DEPRECATED typedef char const * mbedtls_deprecated_constant_t;
+#define MBEDTLS_DEPRECATED_STRING_CONSTANT( VAL )       \
+    ( (mbedtls_deprecated_constant_t) ( VAL ) )
+#else
+#define MBEDTLS_DEPRECATED_STRING_CONSTANT( VAL ) VAL
+#endif /* ! MBEDTLS_DEPRECATED_WARNING */
+
+/**
+ * \warning The origin of the primes in RFC 5114 is not documented and
+ *          their use therefore constitutes a security risk!
+ *
+ * \deprecated The hex-encoded primes from RFC 5114 are deprecated and are
+ *             likely to be removed in a future version of the library without
+ *             replacement.
+ */
+
+/**
+ * The hexadecimal presentation of the prime underlying the
+ * 2048-bit MODP Group with 224-bit Prime Order Subgroup, as defined
+ * in <em>RFC-5114: Additional Diffie-Hellman Groups for Use with
+ * IETF Standards</em>.
+ */
+#define MBEDTLS_DHM_RFC5114_MODP_P                              \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT(                         \
+        "AD107E1E9123A9D0D660FAA79559C51FA20D64E5683B9FD1"      \
+        "B54B1597B61D0A75E6FA141DF95A56DBAF9A3C407BA1DF15"      \
+        "EB3D688A309C180E1DE6B85A1274A0A66D3F8152AD6AC212"      \
+        "9037C9EDEFDA4DF8D91E8FEF55B7394B7AD5B7D0B6C12207"      \
+        "C9F98D11ED34DBF6C6BA0B2C8BBC27BE6A00E0A0B9C49708"      \
+        "B3BF8A317091883681286130BC8985DB1602E714415D9330"      \
+        "278273C7DE31EFDC7310F7121FD5A07415987D9ADC0A486D"      \
+        "CDF93ACC44328387315D75E198C641A480CD86A1B9E587E8"      \
+        "BE60E69CC928B2B9C52172E413042E9B23F10B0E16E79763"      \
+        "C9B53DCF4BA80A29E3FB73C16B8E75B97EF363E2FFA31F71"      \
+        "CF9DE5384E71B81C0AC4DFFE0C10E64F" )
+
+/**
+ * The hexadecimal presentation of the chosen generator of the 2048-bit MODP
+ * Group with 224-bit Prime Order Subgroup, as defined in <em>RFC-5114:
+ * Additional Diffie-Hellman Groups for Use with IETF Standards</em>.
+ */
+#define MBEDTLS_DHM_RFC5114_MODP_2048_G                         \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT(                         \
+        "AC4032EF4F2D9AE39DF30B5C8FFDAC506CDEBE7B89998CAF"      \
+        "74866A08CFE4FFE3A6824A4E10B9A6F0DD921F01A70C4AFA"      \
+        "AB739D7700C29F52C57DB17C620A8652BE5E9001A8D66AD7"      \
+        "C17669101999024AF4D027275AC1348BB8A762D0521BC98A"      \
+        "E247150422EA1ED409939D54DA7460CDB5F6C6B250717CBE"      \
+        "F180EB34118E98D119529A45D6F834566E3025E316A330EF"      \
+        "BB77A86F0C1AB15B051AE3D428C8F8ACB70A8137150B8EEB"      \
+        "10E183EDD19963DDD9E263E4770589EF6AA21E7F5F2FF381"      \
+        "B539CCE3409D13CD566AFBB48D6C019181E1BCFE94B30269"      \
+        "EDFE72FE9B6AA4BD7B5A0F1C71CFFF4C19C418E1F6EC0179"      \
+        "81BC087F2A7065B384B890D3191F2BFA" )
+
+/**
+ * The hexadecimal presentation of the prime underlying the 2048-bit MODP
+ * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP)
+ * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.
+ *
+ * \deprecated The hex-encoded primes from RFC 3625 are deprecated and
+ *             superseded by the corresponding macros providing them as
+ *             binary constants. Their hex-encoded constants are likely
+ *             to be removed in a future version of the library.
+ *
+ */
+#define MBEDTLS_DHM_RFC3526_MODP_2048_P                         \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT(                         \
+        "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"      \
+        "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"      \
+        "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"      \
+        "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"      \
+        "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"      \
+        "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"      \
+        "83655D23DCA3AD961C62F356208552BB9ED529077096966D"      \
+        "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"      \
+        "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"      \
+        "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"      \
+        "15728E5A8AACAA68FFFFFFFFFFFFFFFF" )
+
+/**
+ * The hexadecimal presentation of the chosen generator of the 2048-bit MODP
+ * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP)
+ * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.
+ */
+#define MBEDTLS_DHM_RFC3526_MODP_2048_G                         \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT( "02" )
+
+/**
+ * The hexadecimal presentation of the prime underlying the 3072-bit MODP
+ * Group, as defined in <em>RFC-3072: More Modular Exponential (MODP)
+ * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.
+ */
+#define MBEDTLS_DHM_RFC3526_MODP_3072_P                         \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT(                         \
+        "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"      \
+        "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"      \
+        "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"      \
+        "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"      \
+        "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"      \
+        "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"      \
+        "83655D23DCA3AD961C62F356208552BB9ED529077096966D"      \
+        "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"      \
+        "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"      \
+        "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"      \
+        "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"      \
+        "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"      \
+        "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"      \
+        "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"      \
+        "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"      \
+        "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF" )
+
+/**
+ * The hexadecimal presentation of the chosen generator of the 3072-bit MODP
+ * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP)
+ * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.
+ */
+#define MBEDTLS_DHM_RFC3526_MODP_3072_G                      \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT( "02" )
+
+/**
+ * The hexadecimal presentation of the prime underlying the 4096-bit MODP
+ * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP)
+ * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.
+ */
+#define MBEDTLS_DHM_RFC3526_MODP_4096_P                      \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT(                      \
+        "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"   \
+        "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"   \
+        "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"   \
+        "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"   \
+        "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"   \
+        "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"   \
+        "83655D23DCA3AD961C62F356208552BB9ED529077096966D"   \
+        "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"   \
+        "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"   \
+        "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"   \
+        "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"   \
+        "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"   \
+        "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"   \
+        "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"   \
+        "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"   \
+        "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7"   \
+        "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA"   \
+        "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6"   \
+        "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED"   \
+        "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9"   \
+        "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199"   \
+        "FFFFFFFFFFFFFFFF" )
+
+/**
+ * The hexadecimal presentation of the chosen generator of the 4096-bit MODP
+ * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP)
+ * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.
+ */
+#define MBEDTLS_DHM_RFC3526_MODP_4096_G                      \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT( "02" )
+
+#endif /* MBEDTLS_DEPRECATED_REMOVED */
+
+/*
+ * Trustworthy DHM parameters in binary form
+ */
+
+#define MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN {        \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+     0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \
+     0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \
+     0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \
+     0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \
+     0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \
+     0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \
+     0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \
+     0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \
+     0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \
+     0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \
+     0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \
+     0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \
+     0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \
+     0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \
+     0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \
+     0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \
+     0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \
+     0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \
+     0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \
+     0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \
+     0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \
+     0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \
+     0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \
+     0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \
+     0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \
+     0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \
+     0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \
+     0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \
+     0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \
+     0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68, \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC3526_MODP_3072_P_BIN {       \
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+    0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \
+    0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \
+    0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \
+    0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \
+    0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \
+    0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \
+    0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \
+    0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \
+    0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \
+    0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \
+    0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \
+    0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \
+    0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \
+    0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \
+    0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \
+    0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \
+    0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \
+    0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \
+    0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \
+    0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \
+    0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \
+    0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \
+    0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \
+    0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \
+    0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \
+    0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \
+    0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \
+    0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \
+    0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \
+    0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, \
+    0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33, \
+    0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, \
+    0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A, \
+    0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, \
+    0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7, \
+    0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, \
+    0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D, \
+    0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, \
+    0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64, \
+    0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, \
+    0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C, \
+    0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, \
+    0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2, \
+    0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, \
+    0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E, \
+    0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x3A, 0xD2, 0xCA, \
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC3526_MODP_3072_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC3526_MODP_4096_P_BIN  {       \
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  \
+    0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,  \
+    0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,  \
+    0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,  \
+    0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22,  \
+    0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,  \
+    0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B,  \
+    0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,  \
+    0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,  \
+    0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,  \
+    0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B,  \
+    0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,  \
+    0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5,  \
+    0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,  \
+    0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D,  \
+    0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,  \
+    0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A,  \
+    0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,  \
+    0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96,  \
+    0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,  \
+    0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D,  \
+    0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,  \
+    0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C,  \
+    0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,  \
+    0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03,  \
+    0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,  \
+    0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9,  \
+    0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,  \
+    0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5,  \
+    0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,  \
+    0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D,  \
+    0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33,  \
+    0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64,  \
+    0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A,  \
+    0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D,  \
+    0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7,  \
+    0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7,  \
+    0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D,  \
+    0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B,  \
+    0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64,  \
+    0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64,  \
+    0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C,  \
+    0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C,  \
+    0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2,  \
+    0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31,  \
+    0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E,  \
+    0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x21, 0x08, 0x01,  \
+    0x1A, 0x72, 0x3C, 0x12, 0xA7, 0x87, 0xE6, 0xD7,  \
+    0x88, 0x71, 0x9A, 0x10, 0xBD, 0xBA, 0x5B, 0x26,  \
+    0x99, 0xC3, 0x27, 0x18, 0x6A, 0xF4, 0xE2, 0x3C,  \
+    0x1A, 0x94, 0x68, 0x34, 0xB6, 0x15, 0x0B, 0xDA,  \
+    0x25, 0x83, 0xE9, 0xCA, 0x2A, 0xD4, 0x4C, 0xE8,  \
+    0xDB, 0xBB, 0xC2, 0xDB, 0x04, 0xDE, 0x8E, 0xF9,  \
+    0x2E, 0x8E, 0xFC, 0x14, 0x1F, 0xBE, 0xCA, 0xA6,  \
+    0x28, 0x7C, 0x59, 0x47, 0x4E, 0x6B, 0xC0, 0x5D,  \
+    0x99, 0xB2, 0x96, 0x4F, 0xA0, 0x90, 0xC3, 0xA2,  \
+    0x23, 0x3B, 0xA1, 0x86, 0x51, 0x5B, 0xE7, 0xED,  \
+    0x1F, 0x61, 0x29, 0x70, 0xCE, 0xE2, 0xD7, 0xAF,  \
+    0xB8, 0x1B, 0xDD, 0x76, 0x21, 0x70, 0x48, 0x1C,  \
+    0xD0, 0x06, 0x91, 0x27, 0xD5, 0xB0, 0x5A, 0xA9,  \
+    0x93, 0xB4, 0xEA, 0x98, 0x8D, 0x8F, 0xDD, 0xC1,  \
+    0x86, 0xFF, 0xB7, 0xDC, 0x90, 0xA6, 0xC0, 0x8F,  \
+    0x4D, 0xF4, 0x35, 0xC9, 0x34, 0x06, 0x31, 0x99,  \
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC3526_MODP_4096_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE2048_P_BIN {        \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+     0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \
+     0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \
+     0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \
+     0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \
+     0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \
+     0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \
+     0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \
+     0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \
+     0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \
+     0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \
+     0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \
+     0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \
+     0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \
+     0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \
+     0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \
+     0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \
+     0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \
+     0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \
+     0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \
+     0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \
+     0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \
+     0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \
+     0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \
+     0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \
+     0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \
+     0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \
+     0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \
+     0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \
+     0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \
+     0x88, 0x6B, 0x42, 0x38, 0x61, 0x28, 0x5C, 0x97, \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE2048_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE3072_P_BIN { \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+     0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \
+     0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \
+     0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \
+     0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \
+     0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \
+     0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \
+     0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \
+     0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \
+     0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \
+     0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \
+     0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \
+     0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \
+     0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \
+     0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \
+     0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \
+     0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \
+     0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \
+     0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \
+     0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \
+     0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \
+     0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \
+     0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \
+     0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \
+     0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \
+     0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \
+     0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \
+     0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \
+     0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \
+     0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \
+     0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \
+     0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \
+     0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \
+     0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \
+     0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \
+     0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \
+     0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \
+     0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \
+     0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \
+     0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \
+     0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \
+     0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \
+     0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \
+     0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \
+     0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \
+     0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \
+     0x25, 0xE4, 0x1D, 0x2B, 0x66, 0xC6, 0x2E, 0x37, \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE3072_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE4096_P_BIN {        \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+     0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \
+     0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \
+     0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \
+     0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \
+     0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \
+     0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \
+     0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \
+     0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \
+     0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \
+     0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \
+     0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \
+     0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \
+     0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \
+     0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \
+     0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \
+     0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \
+     0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \
+     0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \
+     0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \
+     0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \
+     0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \
+     0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \
+     0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \
+     0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \
+     0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \
+     0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \
+     0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \
+     0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \
+     0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \
+     0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \
+     0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \
+     0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \
+     0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \
+     0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \
+     0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \
+     0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \
+     0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \
+     0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \
+     0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \
+     0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \
+     0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \
+     0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \
+     0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \
+     0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \
+     0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \
+     0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \
+     0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \
+     0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \
+     0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \
+     0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \
+     0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \
+     0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \
+     0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \
+     0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \
+     0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \
+     0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \
+     0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \
+     0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \
+     0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \
+     0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \
+     0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \
+     0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x65, 0x5F, 0x6A, \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE4096_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE6144_P_BIN {        \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+     0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \
+     0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \
+     0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \
+     0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \
+     0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \
+     0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \
+     0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \
+     0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \
+     0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \
+     0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \
+     0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \
+     0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \
+     0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \
+     0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \
+     0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \
+     0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \
+     0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \
+     0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \
+     0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \
+     0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \
+     0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \
+     0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \
+     0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \
+     0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \
+     0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \
+     0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \
+     0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \
+     0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \
+     0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \
+     0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \
+     0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \
+     0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \
+     0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \
+     0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \
+     0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \
+     0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \
+     0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \
+     0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \
+     0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \
+     0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \
+     0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \
+     0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \
+     0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \
+     0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \
+     0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \
+     0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \
+     0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \
+     0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \
+     0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \
+     0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \
+     0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \
+     0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \
+     0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \
+     0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \
+     0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \
+     0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \
+     0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \
+     0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \
+     0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \
+     0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \
+     0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \
+     0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, \
+     0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A, \
+     0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, \
+     0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6, \
+     0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, \
+     0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C, \
+     0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, \
+     0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71, \
+     0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, \
+     0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77, \
+     0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, \
+     0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8, \
+     0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, \
+     0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E, \
+     0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, \
+     0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4, \
+     0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, \
+     0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92, \
+     0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, \
+     0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82, \
+     0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, \
+     0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C, \
+     0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, \
+     0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46, \
+     0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, \
+     0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17, \
+     0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, \
+     0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04, \
+     0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, \
+     0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69, \
+     0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, \
+     0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4, \
+     0xA4, 0x0E, 0x32, 0x9C, 0xD0, 0xE4, 0x0E, 0x65, \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE6144_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE8192_P_BIN {        \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+     0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \
+     0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \
+     0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \
+     0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \
+     0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \
+     0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \
+     0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \
+     0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \
+     0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \
+     0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \
+     0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \
+     0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \
+     0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \
+     0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \
+     0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \
+     0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \
+     0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \
+     0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \
+     0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \
+     0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \
+     0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \
+     0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \
+     0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \
+     0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \
+     0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \
+     0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \
+     0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \
+     0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \
+     0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \
+     0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \
+     0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \
+     0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \
+     0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \
+     0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \
+     0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \
+     0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \
+     0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \
+     0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \
+     0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \
+     0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \
+     0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \
+     0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \
+     0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \
+     0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \
+     0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \
+     0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \
+     0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \
+     0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \
+     0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \
+     0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \
+     0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \
+     0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \
+     0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \
+     0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \
+     0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \
+     0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \
+     0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \
+     0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \
+     0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \
+     0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \
+     0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \
+     0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, \
+     0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A, \
+     0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, \
+     0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6, \
+     0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, \
+     0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C, \
+     0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, \
+     0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71, \
+     0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, \
+     0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77, \
+     0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, \
+     0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8, \
+     0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, \
+     0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E, \
+     0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, \
+     0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4, \
+     0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, \
+     0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92, \
+     0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, \
+     0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82, \
+     0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, \
+     0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C, \
+     0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, \
+     0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46, \
+     0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, \
+     0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17, \
+     0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, \
+     0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04, \
+     0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, \
+     0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69, \
+     0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, \
+     0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4, \
+     0xA4, 0x0E, 0x32, 0x9C, 0xCF, 0xF4, 0x6A, 0xAA, \
+     0x36, 0xAD, 0x00, 0x4C, 0xF6, 0x00, 0xC8, 0x38, \
+     0x1E, 0x42, 0x5A, 0x31, 0xD9, 0x51, 0xAE, 0x64, \
+     0xFD, 0xB2, 0x3F, 0xCE, 0xC9, 0x50, 0x9D, 0x43, \
+     0x68, 0x7F, 0xEB, 0x69, 0xED, 0xD1, 0xCC, 0x5E, \
+     0x0B, 0x8C, 0xC3, 0xBD, 0xF6, 0x4B, 0x10, 0xEF, \
+     0x86, 0xB6, 0x31, 0x42, 0xA3, 0xAB, 0x88, 0x29, \
+     0x55, 0x5B, 0x2F, 0x74, 0x7C, 0x93, 0x26, 0x65, \
+     0xCB, 0x2C, 0x0F, 0x1C, 0xC0, 0x1B, 0xD7, 0x02, \
+     0x29, 0x38, 0x88, 0x39, 0xD2, 0xAF, 0x05, 0xE4, \
+     0x54, 0x50, 0x4A, 0xC7, 0x8B, 0x75, 0x82, 0x82, \
+     0x28, 0x46, 0xC0, 0xBA, 0x35, 0xC3, 0x5F, 0x5C, \
+     0x59, 0x16, 0x0C, 0xC0, 0x46, 0xFD, 0x82, 0x51, \
+     0x54, 0x1F, 0xC6, 0x8C, 0x9C, 0x86, 0xB0, 0x22, \
+     0xBB, 0x70, 0x99, 0x87, 0x6A, 0x46, 0x0E, 0x74, \
+     0x51, 0xA8, 0xA9, 0x31, 0x09, 0x70, 0x3F, 0xEE, \
+     0x1C, 0x21, 0x7E, 0x6C, 0x38, 0x26, 0xE5, 0x2C, \
+     0x51, 0xAA, 0x69, 0x1E, 0x0E, 0x42, 0x3C, 0xFC, \
+     0x99, 0xE9, 0xE3, 0x16, 0x50, 0xC1, 0x21, 0x7B, \
+     0x62, 0x48, 0x16, 0xCD, 0xAD, 0x9A, 0x95, 0xF9, \
+     0xD5, 0xB8, 0x01, 0x94, 0x88, 0xD9, 0xC0, 0xA0, \
+     0xA1, 0xFE, 0x30, 0x75, 0xA5, 0x77, 0xE2, 0x31, \
+     0x83, 0xF8, 0x1D, 0x4A, 0x3F, 0x2F, 0xA4, 0x57, \
+     0x1E, 0xFC, 0x8C, 0xE0, 0xBA, 0x8A, 0x4F, 0xE8, \
+     0xB6, 0x85, 0x5D, 0xFE, 0x72, 0xB0, 0xA6, 0x6E, \
+     0xDE, 0xD2, 0xFB, 0xAB, 0xFB, 0xE5, 0x8A, 0x30, \
+     0xFA, 0xFA, 0xBE, 0x1C, 0x5D, 0x71, 0xA8, 0x7E, \
+     0x2F, 0x74, 0x1E, 0xF8, 0xC1, 0xFE, 0x86, 0xFE, \
+     0xA6, 0xBB, 0xFD, 0xE5, 0x30, 0x67, 0x7F, 0x0D, \
+     0x97, 0xD1, 0x1D, 0x49, 0xF7, 0xA8, 0x44, 0x3D, \
+     0x08, 0x22, 0xE5, 0x06, 0xA9, 0xF4, 0x61, 0x4E, \
+     0x01, 0x1E, 0x2A, 0x94, 0x83, 0x8F, 0xF8, 0x8C, \
+     0xD6, 0x8C, 0x8B, 0xB7, 0xC5, 0xC6, 0x42, 0x4C, \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE8192_G_BIN { 0x02 }
+
 #endif /* dhm.h */

+ 151 - 88
app/include/mbedtls/ecdh.h

@@ -1,9 +1,18 @@
 /**
  * \file ecdh.h
  *
- * \brief Elliptic curve Diffie-Hellman
+ * \brief The Elliptic Curve Diffie-Hellman (ECDH) protocol APIs.
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * ECDH is an anonymous key agreement protocol allowing two parties to
+ * establish a shared secret over an insecure channel. Each party must have an
+ * elliptic-curve public–private key pair.
+ *
+ * For more information, see <em>NIST SP 800-56A Rev. 2: Recommendation for
+ * Pair-Wise Key Establishment Schemes Using Discrete Logarithm
+ * Cryptography</em>.
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,8 +27,9 @@
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *
- *  This file is part of mbed TLS (https://tls.mbed.org)
+ *  This file is part of Mbed TLS (https://tls.mbed.org)
  */
+
 #ifndef MBEDTLS_ECDH_H
 #define MBEDTLS_ECDH_H
 
@@ -30,7 +40,9 @@ extern "C" {
 #endif
 
 /**
- * When importing from an EC key, select if it is our key or the peer's key
+ * Defines the source of the imported EC key:
+ * <ul><li>Our key.</li>
+ * <li>The key of the peer.</li></ul>
  */
 typedef enum
 {
@@ -39,56 +51,67 @@ typedef enum
 } mbedtls_ecdh_side;
 
 /**
- * \brief           ECDH context structure
+ * \brief           The ECDH context structure.
  */
 typedef struct
 {
-    mbedtls_ecp_group grp;      /*!<  elliptic curve used                           */
-    mbedtls_mpi d;              /*!<  our secret value (private key)                */
-    mbedtls_ecp_point Q;        /*!<  our public value (public key)                 */
-    mbedtls_ecp_point Qp;       /*!<  peer's public value (public key)              */
-    mbedtls_mpi z;              /*!<  shared secret                                 */
-    int point_format;   /*!<  format for point export in TLS messages       */
-    mbedtls_ecp_point Vi;       /*!<  blinding value (for later)                    */
-    mbedtls_ecp_point Vf;       /*!<  un-blinding value (for later)                 */
-    mbedtls_mpi _d;             /*!<  previous d (for later)                        */
+    mbedtls_ecp_group grp;   /*!< The elliptic curve used. */
+    mbedtls_mpi d;           /*!< The private key. */
+    mbedtls_ecp_point Q;     /*!< The public key. */
+    mbedtls_ecp_point Qp;    /*!< The value of the public key of the peer. */
+    mbedtls_mpi z;           /*!< The shared secret. */
+    int point_format;        /*!< The format of point export in TLS messages. */
+    mbedtls_ecp_point Vi;    /*!< The blinding value. */
+    mbedtls_ecp_point Vf;    /*!< The unblinding value. */
+    mbedtls_mpi _d;          /*!< The previous \p d. */
 }
 mbedtls_ecdh_context;
 
 /**
- * \brief           Generate a public key.
- *                  Raw function that only does the core computation.
+ * \brief           This function generates an ECDH keypair on an elliptic
+ *                  curve.
  *
- * \param grp       ECP group
- * \param d         Destination MPI (secret exponent, aka private key)
- * \param Q         Destination point (public key)
- * \param f_rng     RNG function
- * \param p_rng     RNG parameter
+ *                  This function performs the first of two core computations
+ *                  implemented during the ECDH key exchange. The second core
+ *                  computation is performed by mbedtls_ecdh_compute_shared().
  *
- * \return          0 if successful,
- *                  or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code
+ * \param grp       The ECP group.
+ * \param d         The destination MPI (private key).
+ * \param Q         The destination point (public key).
+ * \param f_rng     The RNG function.
+ * \param p_rng     The RNG parameter.
+ *
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX or
+ *                  \c MBEDTLS_MPI_XXX error code on failure.
+ *
+ * \see             ecp.h
  */
 int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q,
                      int (*f_rng)(void *, unsigned char *, size_t),
                      void *p_rng );
 
 /**
- * \brief           Compute shared secret
- *                  Raw function that only does the core computation.
+ * \brief           This function computes the shared secret.
+ *
+ *                  This function performs the second of two core computations
+ *                  implemented during the ECDH key exchange. The first core
+ *                  computation is performed by mbedtls_ecdh_gen_public().
  *
- * \param grp       ECP group
- * \param z         Destination MPI (shared secret)
- * \param Q         Public key from other party
- * \param d         Our secret exponent (private key)
- * \param f_rng     RNG function (see notes)
- * \param p_rng     RNG parameter
+ * \param grp       The ECP group.
+ * \param z         The destination MPI (shared secret).
+ * \param Q         The public key from another party.
+ * \param d         Our secret exponent (private key).
+ * \param f_rng     The RNG function.
+ * \param p_rng     The RNG parameter.
  *
- * \return          0 if successful,
- *                  or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX or
+ *                  \c MBEDTLS_MPI_XXX error code on failure.
  *
- * \note            If f_rng is not NULL, it is used to implement
+ * \see             ecp.h
+ *
+ * \note            If \p f_rng is not NULL, it is used to implement
  *                  countermeasures against potential elaborate timing
- *                  attacks, see \c mbedtls_ecp_mul() for details.
+ *                  attacks. For more information, see mbedtls_ecp_mul().
  */
 int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z,
                          const mbedtls_ecp_point *Q, const mbedtls_mpi *d,
@@ -96,34 +119,41 @@ int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z,
                          void *p_rng );
 
 /**
- * \brief           Initialize context
+ * \brief           This function initializes an ECDH context.
  *
- * \param ctx       Context to initialize
+ * \param ctx       The ECDH context to initialize.
  */
 void mbedtls_ecdh_init( mbedtls_ecdh_context *ctx );
 
 /**
- * \brief           Free context
+ * \brief           This function frees a context.
  *
- * \param ctx       Context to free
+ * \param ctx       The context to free.
  */
 void mbedtls_ecdh_free( mbedtls_ecdh_context *ctx );
 
 /**
- * \brief           Generate a public key and a TLS ServerKeyExchange payload.
- *                  (First function used by a TLS server for ECDHE.)
+ * \brief           This function generates a public key and a TLS
+ *                  ServerKeyExchange payload.
+ *
+ *                  This is the first function used by a TLS server for ECDHE
+ *                  ciphersuites.
+ *
+ * \param ctx       The ECDH context.
+ * \param olen      The number of characters written.
+ * \param buf       The destination buffer.
+ * \param blen      The length of the destination buffer.
+ * \param f_rng     The RNG function.
+ * \param p_rng     The RNG parameter.
  *
- * \param ctx       ECDH context
- * \param olen      number of chars written
- * \param buf       destination buffer
- * \param blen      length of buffer
- * \param f_rng     RNG function
- * \param p_rng     RNG parameter
+ * \note            This function assumes that the ECP group (grp) of the
+ *                  \p ctx context has already been properly set,
+ *                  for example, using mbedtls_ecp_group_load().
  *
- * \note            This function assumes that ctx->grp has already been
- *                  properly set (for example using mbedtls_ecp_group_load).
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code
+ *                  on failure.
  *
- * \return          0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
+ * \see             ecp.h
  */
 int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen,
                       unsigned char *buf, size_t blen,
@@ -131,45 +161,63 @@ int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen,
                       void *p_rng );
 
 /**
- * \brief           Parse and procress a TLS ServerKeyExhange payload.
- *                  (First function used by a TLS client for ECDHE.)
+ * \brief           This function parses and processes a TLS ServerKeyExhange
+ *                  payload.
+ *
+ *                  This is the first function used by a TLS client for ECDHE
+ *                  ciphersuites.
+ *
+ * \param ctx       The ECDH context.
+ * \param buf       The pointer to the start of the input buffer.
+ * \param end       The address for one Byte past the end of the buffer.
  *
- * \param ctx       ECDH context
- * \param buf       pointer to start of input buffer
- * \param end       one past end of buffer
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code
+ *                  on failure.
  *
- * \return          0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
+ * \see             ecp.h
  */
 int mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx,
                       const unsigned char **buf, const unsigned char *end );
 
 /**
- * \brief           Setup an ECDH context from an EC key.
- *                  (Used by clients and servers in place of the
- *                  ServerKeyEchange for static ECDH: import ECDH parameters
- *                  from a certificate's EC key information.)
+ * \brief           This function sets up an ECDH context from an EC key.
  *
- * \param ctx       ECDH constext to set
- * \param key       EC key to use
- * \param side      Is it our key (1) or the peer's key (0) ?
+ *                  It is used by clients and servers in place of the
+ *                  ServerKeyEchange for static ECDH, and imports ECDH
+ *                  parameters from the EC key information of a certificate.
  *
- * \return          0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
+ * \param ctx       The ECDH context to set up.
+ * \param key       The EC key to use.
+ * \param side      Defines the source of the key:
+ *                  <ul><li>1: Our key.</li>
+                    <li>0: The key of the peer.</li></ul>
+ *
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code
+ *                  on failure.
+ *
+ * \see             ecp.h
  */
 int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx, const mbedtls_ecp_keypair *key,
                      mbedtls_ecdh_side side );
 
 /**
- * \brief           Generate a public key and a TLS ClientKeyExchange payload.
- *                  (Second function used by a TLS client for ECDH(E).)
+ * \brief           This function generates a public key and a TLS
+ *                  ClientKeyExchange payload.
+ *
+ *                  This is the second function used by a TLS client for ECDH(E)
+ *                  ciphersuites.
  *
- * \param ctx       ECDH context
- * \param olen      number of bytes actually written
- * \param buf       destination buffer
- * \param blen      size of destination buffer
- * \param f_rng     RNG function
- * \param p_rng     RNG parameter
+ * \param ctx       The ECDH context.
+ * \param olen      The number of Bytes written.
+ * \param buf       The destination buffer.
+ * \param blen      The size of the destination buffer.
+ * \param f_rng     The RNG function.
+ * \param p_rng     The RNG parameter.
  *
- * \return          0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code
+ *                  on failure.
+ *
+ * \see             ecp.h
  */
 int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen,
                       unsigned char *buf, size_t blen,
@@ -177,30 +225,45 @@ int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen,
                       void *p_rng );
 
 /**
- * \brief           Parse and process a TLS ClientKeyExchange payload.
- *                  (Second function used by a TLS server for ECDH(E).)
+ * \brief       This function parses and processes a TLS ClientKeyExchange
+ *              payload.
+ *
+ *              This is the second function used by a TLS server for ECDH(E)
+ *              ciphersuites.
  *
- * \param ctx       ECDH context
- * \param buf       start of input buffer
- * \param blen      length of input buffer
+ * \param ctx   The ECDH context.
+ * \param buf   The start of the input buffer.
+ * \param blen  The length of the input buffer.
  *
- * \return          0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
+ * \return      \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code
+ *              on failure.
+ *
+ * \see         ecp.h
  */
 int mbedtls_ecdh_read_public( mbedtls_ecdh_context *ctx,
                       const unsigned char *buf, size_t blen );
 
 /**
- * \brief           Derive and export the shared secret.
- *                  (Last function used by both TLS client en servers.)
+ * \brief           This function derives and exports the shared secret.
+ *
+ *                  This is the last function used by both TLS client
+ *                  and servers.
+ *
+ * \param ctx       The ECDH context.
+ * \param olen      The number of Bytes written.
+ * \param buf       The destination buffer.
+ * \param blen      The length of the destination buffer.
+ * \param f_rng     The RNG function.
+ * \param p_rng     The RNG parameter.
  *
- * \param ctx       ECDH context
- * \param olen      number of bytes written
- * \param buf       destination buffer
- * \param blen      buffer length
- * \param f_rng     RNG function, see notes for \c mbedtls_ecdh_compute_shared()
- * \param p_rng     RNG parameter
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code
+ *                  on failure.
  *
- * \return          0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
+ * \see             ecp.h
+ *
+ * \note            If \p f_rng is not NULL, it is used to implement
+ *                  countermeasures against potential elaborate timing
+ *                  attacks. For more information, see mbedtls_ecp_mul().
  */
 int mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen,
                       unsigned char *buf, size_t blen,

+ 196 - 110
app/include/mbedtls/ecdsa.h

@@ -1,9 +1,16 @@
 /**
  * \file ecdsa.h
  *
- * \brief Elliptic curve DSA
+ * \brief The Elliptic Curve Digital Signature Algorithm (ECDSA).
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * ECDSA is defined in <em>Standards for Efficient Cryptography Group (SECG):
+ * SEC1 Elliptic Curve Cryptography</em>.
+ * The use of ECDSA for TLS is defined in <em>RFC-4492: Elliptic Curve
+ * Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS)</em>.
+ *
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,8 +25,9 @@
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *
- *  This file is part of mbed TLS (https://tls.mbed.org)
+ *  This file is part of Mbed TLS (https://tls.mbed.org)
  */
+
 #ifndef MBEDTLS_ECDSA_H
 #define MBEDTLS_ECDSA_H
 
@@ -27,7 +35,7 @@
 #include "md.h"
 
 /*
- * RFC 4492 page 20:
+ * RFC-4492 page 20:
  *
  *     Ecdsa-Sig-Value ::= SEQUENCE {
  *         r       INTEGER,
@@ -43,11 +51,11 @@
 #if MBEDTLS_ECP_MAX_BYTES > 124
 #error "MBEDTLS_ECP_MAX_BYTES bigger than expected, please fix MBEDTLS_ECDSA_MAX_LEN"
 #endif
-/** Maximum size of an ECDSA signature in bytes */
+/** The maximal size of an ECDSA signature in Bytes. */
 #define MBEDTLS_ECDSA_MAX_LEN  ( 3 + 2 * ( 3 + MBEDTLS_ECP_MAX_BYTES ) )
 
 /**
- * \brief           ECDSA context structure
+ * \brief           The ECDSA context structure.
  */
 typedef mbedtls_ecp_keypair mbedtls_ecdsa_context;
 
@@ -56,21 +64,30 @@ extern "C" {
 #endif
 
 /**
- * \brief           Compute ECDSA signature of a previously hashed message
+ * \brief           This function computes the ECDSA signature of a
+ *                  previously-hashed message.
  *
- * \note            The deterministic version is usually prefered.
+ * \note            The deterministic version is usually preferred.
  *
- * \param grp       ECP group
- * \param r         First output integer
- * \param s         Second output integer
- * \param d         Private signing key
- * \param buf       Message hash
- * \param blen      Length of buf
- * \param f_rng     RNG function
- * \param p_rng     RNG parameter
+ * \param grp       The ECP group.
+ * \param r         The first output integer.
+ * \param s         The second output integer.
+ * \param d         The private signing key.
+ * \param buf       The message hash.
+ * \param blen      The length of \p buf.
+ * \param f_rng     The RNG function.
+ * \param p_rng     The RNG parameter.
  *
- * \return          0 if successful,
- *                  or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code
+ * \note            If the bitlength of the message hash is larger than the
+ *                  bitlength of the group order, then the hash is truncated
+ *                  as defined in <em>Standards for Efficient Cryptography Group
+ *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ *                  4.1.3, step 5.
+ *
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX
+ *                  or \c MBEDTLS_MPI_XXX error code on failure.
+ *
+ * \see             ecp.h
  */
 int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
                 const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
@@ -78,19 +95,31 @@ int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
 
 #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
 /**
- * \brief           Compute ECDSA signature of a previously hashed message,
- *                  deterministic version (RFC 6979).
- *
- * \param grp       ECP group
- * \param r         First output integer
- * \param s         Second output integer
- * \param d         Private signing key
- * \param buf       Message hash
- * \param blen      Length of buf
- * \param md_alg    MD algorithm used to hash the message
- *
- * \return          0 if successful,
- *                  or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code
+ * \brief           This function computes the ECDSA signature of a
+ *                  previously-hashed message, deterministic version.
+ *                  For more information, see <em>RFC-6979: Deterministic
+ *                  Usage of the Digital Signature Algorithm (DSA) and Elliptic
+ *                  Curve Digital Signature Algorithm (ECDSA)</em>.
+ *
+ * \param grp       The ECP group.
+ * \param r         The first output integer.
+ * \param s         The second output integer.
+ * \param d         The private signing key.
+ * \param buf       The message hash.
+ * \param blen      The length of \p buf.
+ * \param md_alg    The MD algorithm used to hash the message.
+ *
+ * \note            If the bitlength of the message hash is larger than the
+ *                  bitlength of the group order, then the hash is truncated as
+ *                  defined in <em>Standards for Efficient Cryptography Group
+ *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ *                  4.1.3, step 5.
+ *
+ * \return          \c 0 on success,
+ *                  or an \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX
+ *                  error code on failure.
+ *
+ * \see             ecp.h
  */
 int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
                     const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
@@ -98,47 +127,73 @@ int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi
 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
 
 /**
- * \brief           Verify ECDSA signature of a previously hashed message
- *
- * \param grp       ECP group
- * \param buf       Message hash
- * \param blen      Length of buf
- * \param Q         Public key to use for verification
- * \param r         First integer of the signature
- * \param s         Second integer of the signature
- *
- * \return          0 if successful,
- *                  MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid
- *                  or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code
+ * \brief           This function verifies the ECDSA signature of a
+ *                  previously-hashed message.
+ *
+ * \param grp       The ECP group.
+ * \param buf       The message hash.
+ * \param blen      The length of \p buf.
+ * \param Q         The public key to use for verification.
+ * \param r         The first integer of the signature.
+ * \param s         The second integer of the signature.
+ *
+ * \note            If the bitlength of the message hash is larger than the
+ *                  bitlength of the group order, then the hash is truncated as
+ *                  defined in <em>Standards for Efficient Cryptography Group
+ *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ *                  4.1.4, step 3.
+ *
+ * \return          \c 0 on success,
+ *                  #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid,
+ *                  or an \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX
+ *                  error code on failure for any other reason.
+ *
+ * \see             ecp.h
  */
 int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp,
                   const unsigned char *buf, size_t blen,
                   const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s);
 
 /**
- * \brief           Compute ECDSA signature and write it to buffer,
- *                  serialized as defined in RFC 4492 page 20.
- *                  (Not thread-safe to use same context in multiple threads)
- *
- * \note            The deterministice version (RFC 6979) is used if
- *                  MBEDTLS_ECDSA_DETERMINISTIC is defined.
- *
- * \param ctx       ECDSA context
- * \param md_alg    Algorithm that was used to hash the message
- * \param hash      Message hash
- * \param hlen      Length of hash
- * \param sig       Buffer that will hold the signature
- * \param slen      Length of the signature written
- * \param f_rng     RNG function
- * \param p_rng     RNG parameter
- *
- * \note            The "sig" buffer must be at least as large as twice the
- *                  size of the curve used, plus 9 (eg. 73 bytes if a 256-bit
- *                  curve is used). MBEDTLS_ECDSA_MAX_LEN is always safe.
- *
- * \return          0 if successful,
- *                  or a MBEDTLS_ERR_ECP_XXX, MBEDTLS_ERR_MPI_XXX or
- *                  MBEDTLS_ERR_ASN1_XXX error code
+ * \brief           This function computes the ECDSA signature and writes it
+ *                  to a buffer, serialized as defined in <em>RFC-4492:
+ *                  Elliptic Curve Cryptography (ECC) Cipher Suites for
+ *                  Transport Layer Security (TLS)</em>.
+ *
+ * \warning         It is not thread-safe to use the same context in
+ *                  multiple threads.
+ *
+ * \note            The deterministic version is used if
+ *                  #MBEDTLS_ECDSA_DETERMINISTIC is defined. For more
+ *                  information, see <em>RFC-6979: Deterministic Usage
+ *                  of the Digital Signature Algorithm (DSA) and Elliptic
+ *                  Curve Digital Signature Algorithm (ECDSA)</em>.
+ *
+ * \param ctx       The ECDSA context.
+ * \param md_alg    The message digest that was used to hash the message.
+ * \param hash      The message hash.
+ * \param hlen      The length of the hash.
+ * \param sig       The buffer that holds the signature.
+ * \param slen      The length of the signature written.
+ * \param f_rng     The RNG function.
+ * \param p_rng     The RNG parameter.
+ *
+ * \note            The \p sig buffer must be at least twice as large as the
+ *                  size of the curve used, plus 9. For example, 73 Bytes if
+ *                  a 256-bit curve is used. A buffer length of
+ *                  #MBEDTLS_ECDSA_MAX_LEN is always safe.
+ *
+ * \note            If the bitlength of the message hash is larger than the
+ *                  bitlength of the group order, then the hash is truncated as
+ *                  defined in <em>Standards for Efficient Cryptography Group
+ *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ *                  4.1.3, step 5.
+ *
+ * \return          \c 0 on success,
+ *                  or an \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or
+ *                  \c MBEDTLS_ERR_ASN1_XXX error code on failure.
+ *
+ * \see             ecp.h
  */
 int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg,
                            const unsigned char *hash, size_t hlen,
@@ -154,27 +209,43 @@ int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t
 #define MBEDTLS_DEPRECATED
 #endif
 /**
- * \brief           Compute ECDSA signature and write it to buffer,
- *                  serialized as defined in RFC 4492 page 20.
- *                  Deterministic version, RFC 6979.
- *                  (Not thread-safe to use same context in multiple threads)
+ * \brief   This function computes an ECDSA signature and writes it to a buffer,
+ *          serialized as defined in <em>RFC-4492: Elliptic Curve Cryptography
+ *          (ECC) Cipher Suites for Transport Layer Security (TLS)</em>.
+ *
+ *          The deterministic version is defined in <em>RFC-6979:
+ *          Deterministic Usage of the Digital Signature Algorithm (DSA) and
+ *          Elliptic Curve Digital Signature Algorithm (ECDSA)</em>.
+ *
+ * \warning         It is not thread-safe to use the same context in
+ *                  multiple threads.
+
  *
  * \deprecated      Superseded by mbedtls_ecdsa_write_signature() in 2.0.0
  *
- * \param ctx       ECDSA context
- * \param hash      Message hash
- * \param hlen      Length of hash
- * \param sig       Buffer that will hold the signature
- * \param slen      Length of the signature written
- * \param md_alg    MD algorithm used to hash the message
+ * \param ctx       The ECDSA context.
+ * \param hash      The Message hash.
+ * \param hlen      The length of the hash.
+ * \param sig       The buffer that holds the signature.
+ * \param slen      The length of the signature written.
+ * \param md_alg    The MD algorithm used to hash the message.
  *
- * \note            The "sig" buffer must be at least as large as twice the
- *                  size of the curve used, plus 9 (eg. 73 bytes if a 256-bit
- *                  curve is used). MBEDTLS_ECDSA_MAX_LEN is always safe.
+ * \note            The \p sig buffer must be at least twice as large as the
+ *                  size of the curve used, plus 9. For example, 73 Bytes if a
+ *                  256-bit curve is used. A buffer length of
+ *                  #MBEDTLS_ECDSA_MAX_LEN is always safe.
  *
- * \return          0 if successful,
- *                  or a MBEDTLS_ERR_ECP_XXX, MBEDTLS_ERR_MPI_XXX or
- *                  MBEDTLS_ERR_ASN1_XXX error code
+ * \note            If the bitlength of the message hash is larger than the
+ *                  bitlength of the group order, then the hash is truncated as
+ *                  defined in <em>Standards for Efficient Cryptography Group
+ *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ *                  4.1.3, step 5.
+ *
+ * \return          \c 0 on success,
+ *                  or an \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or
+ *                  \c MBEDTLS_ERR_ASN1_XXX error code on failure.
+ *
+ * \see             ecp.h
  */
 int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx,
                                const unsigned char *hash, size_t hlen,
@@ -185,59 +256,74 @@ int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx,
 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
 
 /**
- * \brief           Read and verify an ECDSA signature
- *
- * \param ctx       ECDSA context
- * \param hash      Message hash
- * \param hlen      Size of hash
- * \param sig       Signature to read and verify
- * \param slen      Size of sig
- *
- * \return          0 if successful,
- *                  MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid,
- *                  MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if the signature is
- *                  valid but its actual length is less than siglen,
- *                  or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_ERR_MPI_XXX error code
+ * \brief           This function reads and verifies an ECDSA signature.
+ *
+ * \param ctx       The ECDSA context.
+ * \param hash      The message hash.
+ * \param hlen      The size of the hash.
+ * \param sig       The signature to read and verify.
+ * \param slen      The size of \p sig.
+ *
+ * \note            If the bitlength of the message hash is larger than the
+ *                  bitlength of the group order, then the hash is truncated as
+ *                  defined in <em>Standards for Efficient Cryptography Group
+ *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ *                  4.1.4, step 3.
+ *
+ * \return          \c 0 on success,
+ *                  #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid,
+ *                  #MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if the signature is
+ *                  valid but its actual length is less than \p siglen,
+ *                  or an \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_ERR_MPI_XXX
+ *                  error code on failure for any other reason.
+ *
+ * \see             ecp.h
  */
 int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx,
                           const unsigned char *hash, size_t hlen,
                           const unsigned char *sig, size_t slen );
 
 /**
- * \brief           Generate an ECDSA keypair on the given curve
+ * \brief          This function generates an ECDSA keypair on the given curve.
  *
- * \param ctx       ECDSA context in which the keypair should be stored
- * \param gid       Group (elliptic curve) to use. One of the various
- *                  MBEDTLS_ECP_DP_XXX macros depending on configuration.
- * \param f_rng     RNG function
- * \param p_rng     RNG parameter
+ * \param ctx      The ECDSA context to store the keypair in.
+ * \param gid      The elliptic curve to use. One of the various
+ *                 \c MBEDTLS_ECP_DP_XXX macros depending on configuration.
+ * \param f_rng    The RNG function.
+ * \param p_rng    The RNG parameter.
  *
- * \return          0 on success, or a MBEDTLS_ERR_ECP_XXX code.
+ * \return         \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX code on
+ *                 failure.
+ *
+ * \see            ecp.h
  */
 int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid,
                   int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );
 
 /**
- * \brief           Set an ECDSA context from an EC key pair
+ * \brief           This function sets an ECDSA context from an EC key pair.
+ *
+ * \param ctx       The ECDSA context to set.
+ * \param key       The EC key to use.
  *
- * \param ctx       ECDSA context to set
- * \param key       EC key to use
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX code on
+ *                  failure.
  *
- * \return          0 on success, or a MBEDTLS_ERR_ECP_XXX code.
+ * \see             ecp.h
  */
 int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key );
 
 /**
- * \brief           Initialize context
+ * \brief           This function initializes an ECDSA context.
  *
- * \param ctx       Context to initialize
+ * \param ctx       The ECDSA context to initialize.
  */
 void mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx );
 
 /**
- * \brief           Free context
+ * \brief           This function frees an ECDSA context.
  *
- * \param ctx       Context to free
+ * \param ctx       The ECDSA context to free.
  */
 void mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx );
 

+ 20 - 3
app/include/mbedtls/ecjpake.h

@@ -2,7 +2,8 @@
  * \file ecjpake.h
  *
  * \brief Elliptic curve J-PAKE
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -43,6 +44,8 @@
 #include "ecp.h"
 #include "md.h"
 
+#if !defined(MBEDTLS_ECJPAKE_ALT)
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -116,7 +119,7 @@ int mbedtls_ecjpake_setup( mbedtls_ecjpake_context *ctx,
                            const unsigned char *secret,
                            size_t len );
 
-/*
+/**
  * \brief           Check if a context is ready for use
  *
  * \param ctx       Context to check
@@ -222,17 +225,31 @@ int mbedtls_ecjpake_derive_secret( mbedtls_ecjpake_context *ctx,
  */
 void mbedtls_ecjpake_free( mbedtls_ecjpake_context *ctx );
 
+#ifdef __cplusplus
+}
+#endif
+
+#else  /* MBEDTLS_ECJPAKE_ALT */
+#include "ecjpake_alt.h"
+#endif /* MBEDTLS_ECJPAKE_ALT */
+
 #if defined(MBEDTLS_SELF_TEST)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 /**
  * \brief          Checkup routine
  *
  * \return         0 if successful, or 1 if a test failed
  */
 int mbedtls_ecjpake_self_test( int verbose );
-#endif
 
 #ifdef __cplusplus
 }
 #endif
 
+#endif /* MBEDTLS_SELF_TEST */
+
 #endif /* ecjpake.h */

+ 21 - 4
app/include/mbedtls/ecp.h

@@ -2,7 +2,8 @@
  * \file ecp.h
  *
  * \brief Elliptic curves over GF(p)
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -36,6 +37,16 @@
 #define MBEDTLS_ERR_ECP_RANDOM_FAILED                     -0x4D00  /**< Generation of random value, such as (ephemeral) key, failed. */
 #define MBEDTLS_ERR_ECP_INVALID_KEY                       -0x4C80  /**< Invalid private or public key. */
 #define MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH                  -0x4C00  /**< Signature is valid but shorter than the user-supplied length. */
+#define MBEDTLS_ERR_ECP_HW_ACCEL_FAILED                   -0x4B80  /**< ECP hardware accelerator failed. */
+
+#if !defined(MBEDTLS_ECP_ALT)
+/*
+ * default mbed TLS elliptic curve arithmetic implementation
+ *
+ * (in case MBEDTLS_ECP_ALT is defined then the developer has to provide an
+ * alternative implementation for the whole module and it will replace this
+ * one.)
+ */
 
 #ifdef __cplusplus
 extern "C" {
@@ -452,7 +463,7 @@ int mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *grp, const mbedtls_ecp
  * \brief           Set a group using well-known domain parameters
  *
  * \param grp       Destination group
- * \param index     Index in the list of well-known domain parameters
+ * \param id        Index in the list of well-known domain parameters
  *
  * \return          0 if successful,
  *                  MBEDTLS_ERR_MPI_XXX if initialization failed
@@ -461,7 +472,7 @@ int mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *grp, const mbedtls_ecp
  * \note            Index should be a value of RFC 4492's enum NamedCurve,
  *                  usually in the form of a MBEDTLS_ECP_DP_XXX macro.
  */
-int mbedtls_ecp_group_load( mbedtls_ecp_group *grp, mbedtls_ecp_group_id index );
+int mbedtls_ecp_group_load( mbedtls_ecp_group *grp, mbedtls_ecp_group_id id );
 
 /**
  * \brief           Set a group from a TLS ECParameters record
@@ -654,16 +665,22 @@ int mbedtls_ecp_gen_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,
 int mbedtls_ecp_check_pub_priv( const mbedtls_ecp_keypair *pub, const mbedtls_ecp_keypair *prv );
 
 #if defined(MBEDTLS_SELF_TEST)
+
 /**
  * \brief          Checkup routine
  *
  * \return         0 if successful, or 1 if a test failed
  */
 int mbedtls_ecp_self_test( int verbose );
-#endif
+
+#endif /* MBEDTLS_SELF_TEST */
 
 #ifdef __cplusplus
 }
 #endif
 
+#else  /* MBEDTLS_ECP_ALT */
+#include "ecp_alt.h"
+#endif /* MBEDTLS_ECP_ALT */
+
 #endif /* ecp.h */

+ 293 - 0
app/include/mbedtls/ecp_internal.h

@@ -0,0 +1,293 @@
+/**
+ * \file ecp_internal.h
+ *
+ * \brief Function declarations for alternative implementation of elliptic curve
+ * point arithmetic.
+ */
+/*
+ *  Copyright (C) 2016, ARM Limited, All Rights Reserved
+ *  SPDX-License-Identifier: Apache-2.0
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License"); you may
+ *  not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ *  This file is part of mbed TLS (https://tls.mbed.org)
+ */
+
+/*
+ * References:
+ *
+ * [1] BERNSTEIN, Daniel J. Curve25519: new Diffie-Hellman speed records.
+ *     <http://cr.yp.to/ecdh/curve25519-20060209.pdf>
+ *
+ * [2] CORON, Jean-S'ebastien. Resistance against differential power analysis
+ *     for elliptic curve cryptosystems. In : Cryptographic Hardware and
+ *     Embedded Systems. Springer Berlin Heidelberg, 1999. p. 292-302.
+ *     <http://link.springer.com/chapter/10.1007/3-540-48059-5_25>
+ *
+ * [3] HEDABOU, Mustapha, PINEL, Pierre, et B'EN'ETEAU, Lucien. A comb method to
+ *     render ECC resistant against Side Channel Attacks. IACR Cryptology
+ *     ePrint Archive, 2004, vol. 2004, p. 342.
+ *     <http://eprint.iacr.org/2004/342.pdf>
+ *
+ * [4] Certicom Research. SEC 2: Recommended Elliptic Curve Domain Parameters.
+ *     <http://www.secg.org/sec2-v2.pdf>
+ *
+ * [5] HANKERSON, Darrel, MENEZES, Alfred J., VANSTONE, Scott. Guide to Elliptic
+ *     Curve Cryptography.
+ *
+ * [6] Digital Signature Standard (DSS), FIPS 186-4.
+ *     <http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf>
+ *
+ * [7] Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer 
+ *     Security (TLS), RFC 4492.
+ *     <https://tools.ietf.org/search/rfc4492>
+ *
+ * [8] <http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html>
+ *
+ * [9] COHEN, Henri. A Course in Computational Algebraic Number Theory.
+ *     Springer Science & Business Media, 1 Aug 2000
+ */
+
+#ifndef MBEDTLS_ECP_INTERNAL_H
+#define MBEDTLS_ECP_INTERNAL_H
+
+#if defined(MBEDTLS_ECP_INTERNAL_ALT)
+
+/**
+ * \brief           Indicate if the Elliptic Curve Point module extension can
+ *                  handle the group.
+ *
+ * \param grp       The pointer to the elliptic curve group that will be the
+ *                  basis of the cryptographic computations.
+ *
+ * \return          Non-zero if successful.
+ */
+unsigned char mbedtls_internal_ecp_grp_capable( const mbedtls_ecp_group *grp );
+
+/**
+ * \brief           Initialise the Elliptic Curve Point module extension.
+ *
+ *                  If mbedtls_internal_ecp_grp_capable returns true for a
+ *                  group, this function has to be able to initialise the
+ *                  module for it.
+ *
+ *                  This module can be a driver to a crypto hardware
+ *                  accelerator, for which this could be an initialise function.
+ *
+ * \param grp       The pointer to the group the module needs to be
+ *                  initialised for.
+ *
+ * \return          0 if successful.
+ */
+int mbedtls_internal_ecp_init( const mbedtls_ecp_group *grp );
+
+/**
+ * \brief           Frees and deallocates the Elliptic Curve Point module
+ *                  extension.
+ *
+ * \param grp       The pointer to the group the module was initialised for.
+ */
+void mbedtls_internal_ecp_free( const mbedtls_ecp_group *grp );
+
+#if defined(ECP_SHORTWEIERSTRASS)
+
+#if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT)
+/**
+ * \brief           Randomize jacobian coordinates:
+ *                  (X, Y, Z) -> (l^2 X, l^3 Y, l Z) for random l.
+ *
+ * \param grp       Pointer to the group representing the curve.
+ *
+ * \param pt        The point on the curve to be randomised, given with Jacobian
+ *                  coordinates.
+ *
+ * \param f_rng     A function pointer to the random number generator.
+ *
+ * \param p_rng     A pointer to the random number generator state.
+ *
+ * \return          0 if successful.
+ */
+int mbedtls_internal_ecp_randomize_jac( const mbedtls_ecp_group *grp,
+        mbedtls_ecp_point *pt, int (*f_rng)(void *, unsigned char *, size_t),
+        void *p_rng );
+#endif
+
+#if defined(MBEDTLS_ECP_ADD_MIXED_ALT)
+/**
+ * \brief           Addition: R = P + Q, mixed affine-Jacobian coordinates.
+ *
+ *                  The coordinates of Q must be normalized (= affine),
+ *                  but those of P don't need to. R is not normalized.
+ *
+ *                  This function is used only as a subrutine of
+ *                  ecp_mul_comb().
+ *
+ *                  Special cases: (1) P or Q is zero, (2) R is zero,
+ *                      (3) P == Q.
+ *                  None of these cases can happen as intermediate step in
+ *                  ecp_mul_comb():
+ *                      - at each step, P, Q and R are multiples of the base
+ *                      point, the factor being less than its order, so none of
+ *                      them is zero;
+ *                      - Q is an odd multiple of the base point, P an even
+ *                      multiple, due to the choice of precomputed points in the
+ *                      modified comb method.
+ *                  So branches for these cases do not leak secret information.
+ *
+ *                  We accept Q->Z being unset (saving memory in tables) as
+ *                  meaning 1.
+ *
+ *                  Cost in field operations if done by [5] 3.22:
+ *                      1A := 8M + 3S
+ *
+ * \param grp       Pointer to the group representing the curve.
+ *
+ * \param R         Pointer to a point structure to hold the result.
+ *
+ * \param P         Pointer to the first summand, given with Jacobian
+ *                  coordinates
+ *
+ * \param Q         Pointer to the second summand, given with affine
+ *                  coordinates.
+ *
+ * \return          0 if successful.
+ */
+int mbedtls_internal_ecp_add_mixed( const mbedtls_ecp_group *grp,
+        mbedtls_ecp_point *R, const mbedtls_ecp_point *P,
+        const mbedtls_ecp_point *Q );
+#endif
+
+/**
+ * \brief           Point doubling R = 2 P, Jacobian coordinates.
+ *
+ *                  Cost:   1D := 3M + 4S    (A ==  0)
+ *                          4M + 4S          (A == -3)
+ *                          3M + 6S + 1a     otherwise
+ *                  when the implementation is based on the "dbl-1998-cmo-2"
+ *                  doubling formulas in [8] and standard optimizations are
+ *                  applied when curve parameter A is one of { 0, -3 }.
+ *
+ * \param grp       Pointer to the group representing the curve.
+ *
+ * \param R         Pointer to a point structure to hold the result.
+ *
+ * \param P         Pointer to the point that has to be doubled, given with
+ *                  Jacobian coordinates.
+ *
+ * \return          0 if successful.
+ */
+#if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT)
+int mbedtls_internal_ecp_double_jac( const mbedtls_ecp_group *grp,
+        mbedtls_ecp_point *R, const mbedtls_ecp_point *P );
+#endif
+
+/**
+ * \brief           Normalize jacobian coordinates of an array of (pointers to)
+ *                  points.
+ *
+ *                  Using Montgomery's trick to perform only one inversion mod P
+ *                  the cost is:
+ *                      1N(t) := 1I + (6t - 3)M + 1S
+ *                  (See for example Algorithm 10.3.4. in [9])
+ *
+ *                  This function is used only as a subrutine of
+ *                  ecp_mul_comb().
+ *
+ *                  Warning: fails (returning an error) if one of the points is
+ *                  zero!
+ *                  This should never happen, see choice of w in ecp_mul_comb().
+ *
+ * \param grp       Pointer to the group representing the curve.
+ *
+ * \param T         Array of pointers to the points to normalise.
+ *
+ * \param t_len     Number of elements in the array.
+ *
+ * \return          0 if successful,
+ *                      an error if one of the points is zero.
+ */
+#if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT)
+int mbedtls_internal_ecp_normalize_jac_many( const mbedtls_ecp_group *grp,
+        mbedtls_ecp_point *T[], size_t t_len );
+#endif
+
+/**
+ * \brief           Normalize jacobian coordinates so that Z == 0 || Z == 1.
+ *
+ *                  Cost in field operations if done by [5] 3.2.1:
+ *                      1N := 1I + 3M + 1S
+ *
+ * \param grp       Pointer to the group representing the curve.
+ *
+ * \param pt        pointer to the point to be normalised. This is an
+ *                  input/output parameter.
+ *
+ * \return          0 if successful.
+ */
+#if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)
+int mbedtls_internal_ecp_normalize_jac( const mbedtls_ecp_group *grp,
+        mbedtls_ecp_point *pt );
+#endif
+
+#endif /* ECP_SHORTWEIERSTRASS */
+
+#if defined(ECP_MONTGOMERY)
+
+#if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)
+int mbedtls_internal_ecp_double_add_mxz( const mbedtls_ecp_group *grp,
+        mbedtls_ecp_point *R, mbedtls_ecp_point *S, const mbedtls_ecp_point *P,
+        const mbedtls_ecp_point *Q, const mbedtls_mpi *d );
+#endif
+
+/**
+ * \brief           Randomize projective x/z coordinates:
+ *                      (X, Z) -> (l X, l Z) for random l
+ *
+ * \param grp       pointer to the group representing the curve
+ *
+ * \param P         the point on the curve to be randomised given with
+ *                  projective coordinates. This is an input/output parameter.
+ *
+ * \param f_rng     a function pointer to the random number generator
+ *
+ * \param p_rng     a pointer to the random number generator state
+ *
+ * \return          0 if successful
+ */
+#if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)
+int mbedtls_internal_ecp_randomize_mxz( const mbedtls_ecp_group *grp,
+        mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t),
+        void *p_rng );
+#endif
+
+/**
+ * \brief           Normalize Montgomery x/z coordinates: X = X/Z, Z = 1.
+ *
+ * \param grp       pointer to the group representing the curve
+ *
+ * \param P         pointer to the point to be normalised. This is an
+ *                  input/output parameter.
+ *
+ * \return          0 if successful
+ */
+#if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)
+int mbedtls_internal_ecp_normalize_mxz( const mbedtls_ecp_group *grp,
+        mbedtls_ecp_point *P );
+#endif
+
+#endif /* ECP_MONTGOMERY */
+
+#endif /* MBEDTLS_ECP_INTERNAL_ALT */
+
+#endif /* ecp_internal.h */
+

+ 39 - 2
app/include/mbedtls/entropy.h

@@ -2,8 +2,9 @@
  * \file entropy.h
  *
  * \brief Entropy accumulator implementation
- *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ */
+/*
+ *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -121,6 +122,7 @@ mbedtls_entropy_source_state;
  */
 typedef struct
 {
+    int accumulator_started;
 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
     mbedtls_sha512_context  accumulator;
 #else
@@ -134,6 +136,9 @@ typedef struct
 #if defined(MBEDTLS_THREADING_C)
     mbedtls_threading_mutex_t mutex;    /*!< mutex                  */
 #endif
+#if defined(MBEDTLS_ENTROPY_NV_SEED)
+    int initial_entropy_run;
+#endif
 }
 mbedtls_entropy_context;
 
@@ -208,6 +213,18 @@ int mbedtls_entropy_func( void *data, unsigned char *output, size_t len );
 int mbedtls_entropy_update_manual( mbedtls_entropy_context *ctx,
                            const unsigned char *data, size_t len );
 
+#if defined(MBEDTLS_ENTROPY_NV_SEED)
+/**
+ * \brief           Trigger an update of the seed file in NV by using the
+ *                  current entropy pool.
+ *
+ * \param ctx       Entropy context
+ *
+ * \return          0 if successful
+ */
+int mbedtls_entropy_update_nv_seed( mbedtls_entropy_context *ctx );
+#endif /* MBEDTLS_ENTROPY_NV_SEED */
+
 #if defined(MBEDTLS_FS_IO)
 /**
  * \brief               Write a seed file
@@ -240,9 +257,29 @@ int mbedtls_entropy_update_seed_file( mbedtls_entropy_context *ctx, const char *
 /**
  * \brief          Checkup routine
  *
+ *                 This module self-test also calls the entropy self-test,
+ *                 mbedtls_entropy_source_self_test();
+ *
  * \return         0 if successful, or 1 if a test failed
  */
 int mbedtls_entropy_self_test( int verbose );
+
+#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
+/**
+ * \brief          Checkup routine
+ *
+ *                 Verifies the integrity of the hardware entropy source
+ *                 provided by the function 'mbedtls_hardware_poll()'.
+ *
+ *                 Note this is the only hardware entropy source that is known
+ *                 at link time, and other entropy sources configured
+ *                 dynamically at runtime by the function
+ *                 mbedtls_entropy_add_source() will not be tested.
+ *
+ * \return         0 if successful, or 1 if a test failed
+ */
+int mbedtls_entropy_source_self_test( int verbose );
+#endif /* MBEDTLS_ENTROPY_HARDWARE_ALT */
 #endif /* MBEDTLS_SELF_TEST */
 
 #ifdef __cplusplus

+ 23 - 2
app/include/mbedtls/entropy_poll.h

@@ -2,8 +2,9 @@
  * \file entropy_poll.h
  *
  * \brief Platform-specific and custom entropy polling functions
- *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ */
+/*
+ *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -41,7 +42,17 @@ extern "C" {
 #define MBEDTLS_ENTROPY_MIN_PLATFORM     32     /**< Minimum for platform source    */
 #define MBEDTLS_ENTROPY_MIN_HAVEGE       32     /**< Minimum for HAVEGE             */
 #define MBEDTLS_ENTROPY_MIN_HARDCLOCK     4     /**< Minimum for mbedtls_timing_hardclock()        */
+#if !defined(MBEDTLS_ENTROPY_MIN_HARDWARE)
 #define MBEDTLS_ENTROPY_MIN_HARDWARE     32     /**< Minimum for the hardware source */
+#endif
+
+/**
+ * \brief           Entropy poll callback that provides 0 entropy.
+ */
+#if defined(MBEDTLS_TEST_NULL_ENTROPY)
+    int mbedtls_null_entropy_poll( void *data,
+                                unsigned char *output, size_t len, size_t *olen );
+#endif
 
 #if !defined(MBEDTLS_NO_PLATFORM_ENTROPY)
 /**
@@ -82,6 +93,16 @@ int mbedtls_hardware_poll( void *data,
                            unsigned char *output, size_t len, size_t *olen );
 #endif
 
+#if defined(MBEDTLS_ENTROPY_NV_SEED)
+/**
+ * \brief           Entropy poll callback for a non-volatile seed file
+ *
+ * \note            This must accept NULL as its first argument.
+ */
+int mbedtls_nv_seed_poll( void *data,
+                          unsigned char *output, size_t len, size_t *olen );
+#endif
+
 #ifdef __cplusplus
 }
 #endif

+ 26 - 16
app/include/mbedtls/error.h

@@ -2,7 +2,8 @@
  * \file error.h
  *
  * \brief Error to string translation
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -49,36 +50,45 @@
  *
  * Module   Nr  Codes assigned
  * MPI       7  0x0002-0x0010
- * GCM       2  0x0012-0x0014
- * BLOWFISH  2  0x0016-0x0018
+ * GCM       3  0x0012-0x0014   0x0013-0x0013
+ * BLOWFISH  3  0x0016-0x0018   0x0017-0x0017
  * THREADING 3  0x001A-0x001E
- * AES       2  0x0020-0x0022
- * CAMELLIA  2  0x0024-0x0026
- * XTEA      1  0x0028-0x0028
+ * AES       4  0x0020-0x0022   0x0023-0x0025
+ * CAMELLIA  3  0x0024-0x0026   0x0027-0x0027
+ * XTEA      2  0x0028-0x0028   0x0029-0x0029
  * BASE64    2  0x002A-0x002C
  * OID       1  0x002E-0x002E   0x000B-0x000B
  * PADLOCK   1  0x0030-0x0030
- * DES       1  0x0032-0x0032
+ * DES       2  0x0032-0x0032   0x0033-0x0033
  * CTR_DBRG  4  0x0034-0x003A
  * ENTROPY   3  0x003C-0x0040   0x003D-0x003F
  * NET      11  0x0042-0x0052   0x0043-0x0045
  * ASN1      7  0x0060-0x006C
+ * CMAC      1  0x007A-0x007A
  * PBKDF2    1  0x007C-0x007C
- * HMAC_DRBG 4  0x0003-0x0009
- * CCM       2                  0x000D-0x000F
+ * HMAC_DRBG 4                  0x0003-0x0009
+ * CCM       3                  0x000D-0x0011
+ * ARC4      1                  0x0019-0x0019
+ * MD2       1                  0x002B-0x002B
+ * MD4       1                  0x002D-0x002D
+ * MD5       1                  0x002F-0x002F
+ * RIPEMD160 1                  0x0031-0x0031
+ * SHA1      1                  0x0035-0x0035
+ * SHA256    1                  0x0037-0x0037
+ * SHA512    1                  0x0039-0x0039
  *
  * High-level module nr (3 bits - 0x0...-0x7...)
  * Name      ID  Nr of Errors
  * PEM       1   9
  * PKCS#12   1   4 (Started from top)
- * X509      2   19
+ * X509      2   20
  * PKCS5     2   4 (Started from top)
- * DHM       3   9
- * PK        3   14 (Started from top)
- * RSA       4   9
- * ECP       4   8 (Started from top)
- * MD        5   4
- * CIPHER    6   6
+ * DHM       3   11
+ * PK        3   15 (Started from top)
+ * RSA       4   11
+ * ECP       4   9 (Started from top)
+ * MD        5   5
+ * CIPHER    6   8
  * SSL       6   17 (Started from top)
  * SSL       7   31
  *

+ 129 - 86
app/include/mbedtls/gcm.h

@@ -1,9 +1,16 @@
 /**
  * \file gcm.h
  *
- * \brief Galois/Counter mode for 128-bit block ciphers
+ * \brief Galois/Counter Mode (GCM) for 128-bit block ciphers, as defined
+ *        in <em>D. McGrew, J. Viega, The Galois/Counter Mode of Operation
+ *        (GCM), Natl. Inst. Stand. Technol.</em>
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * For more information on GCM, see <em>NIST SP 800-38D: Recommendation for
+ * Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC</em>.
+ *
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,8 +25,9 @@
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *
- *  This file is part of mbed TLS (https://tls.mbed.org)
+ *  This file is part of Mbed TLS (https://tls.mbed.org)
  */
+
 #ifndef MBEDTLS_GCM_H
 #define MBEDTLS_GCM_H
 
@@ -31,46 +39,59 @@
 #define MBEDTLS_GCM_DECRYPT     0
 
 #define MBEDTLS_ERR_GCM_AUTH_FAILED                       -0x0012  /**< Authenticated decryption failed. */
+#define MBEDTLS_ERR_GCM_HW_ACCEL_FAILED                   -0x0013  /**< GCM hardware accelerator failed. */
 #define MBEDTLS_ERR_GCM_BAD_INPUT                         -0x0014  /**< Bad input parameters to function. */
 
+#if !defined(MBEDTLS_GCM_ALT)
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
 /**
- * \brief          GCM context structure
+ * \brief          The GCM context structure.
  */
 typedef struct {
-    mbedtls_cipher_context_t cipher_ctx;/*!< cipher context used */
-    uint64_t HL[16];            /*!< Precalculated HTable */
-    uint64_t HH[16];            /*!< Precalculated HTable */
-    uint64_t len;               /*!< Total data length */
-    uint64_t add_len;           /*!< Total add length */
-    unsigned char base_ectr[16];/*!< First ECTR for tag */
-    unsigned char y[16];        /*!< Y working value */
-    unsigned char buf[16];      /*!< buf working value */
-    int mode;                   /*!< Encrypt or Decrypt */
+    mbedtls_cipher_context_t cipher_ctx;  /*!< The cipher context used. */
+    uint64_t HL[16];                      /*!< Precalculated HTable low. */
+    uint64_t HH[16];                      /*!< Precalculated HTable high. */
+    uint64_t len;                         /*!< The total length of the encrypted data. */
+    uint64_t add_len;                     /*!< The total length of the additional data. */
+    unsigned char base_ectr[16];          /*!< The first ECTR for tag. */
+    unsigned char y[16];                  /*!< The Y working value. */
+    unsigned char buf[16];                /*!< The buf working value. */
+    int mode;                             /*!< The operation to perform:
+                                               #MBEDTLS_GCM_ENCRYPT or
+                                               #MBEDTLS_GCM_DECRYPT. */
 }
 mbedtls_gcm_context;
 
 /**
- * \brief           Initialize GCM context (just makes references valid)
- *                  Makes the context ready for mbedtls_gcm_setkey() or
- *                  mbedtls_gcm_free().
+ * \brief           This function initializes the specified GCM context,
+ *                  to make references valid, and prepares the context
+ *                  for mbedtls_gcm_setkey() or mbedtls_gcm_free().
+ *
+ *                  The function does not bind the GCM context to a particular
+ *                  cipher, nor set the key. For this purpose, use
+ *                  mbedtls_gcm_setkey().
  *
- * \param ctx       GCM context to initialize
+ * \param ctx       The GCM context to initialize.
  */
 void mbedtls_gcm_init( mbedtls_gcm_context *ctx );
 
 /**
- * \brief           GCM initialization (encryption)
+ * \brief           This function associates a GCM context with a
+ *                  cipher algorithm and a key.
  *
- * \param ctx       GCM context to be initialized
- * \param cipher    cipher to use (a 128-bit block cipher)
- * \param key       encryption key
- * \param keybits   must be 128, 192 or 256
+ * \param ctx       The GCM context to initialize.
+ * \param cipher    The 128-bit block cipher to use.
+ * \param key       The encryption key.
+ * \param keybits   The key size in bits. Valid options are:
+ *                  <ul><li>128 bits</li>
+ *                  <li>192 bits</li>
+ *                  <li>256 bits</li></ul>
  *
- * \return          0 if successful, or a cipher specific error code
+ * \return          \c 0 on success, or a cipher specific error code.
  */
 int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx,
                         mbedtls_cipher_id_t cipher,
@@ -78,26 +99,27 @@ int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx,
                         unsigned int keybits );
 
 /**
- * \brief           GCM buffer encryption/decryption using a block cipher
+ * \brief           This function performs GCM encryption or decryption of a buffer.
  *
- * \note On encryption, the output buffer can be the same as the input buffer.
- *       On decryption, the output buffer cannot be the same as input buffer.
- *       If buffers overlap, the output buffer must trail at least 8 bytes
+ * \note For encryption, the output buffer can be the same as the input buffer.
+ *       For decryption, the output buffer cannot be the same as input buffer.
+ *       If the buffers overlap, the output buffer must trail at least 8 Bytes
  *       behind the input buffer.
  *
- * \param ctx       GCM context
- * \param mode      MBEDTLS_GCM_ENCRYPT or MBEDTLS_GCM_DECRYPT
- * \param length    length of the input data
- * \param iv        initialization vector
- * \param iv_len    length of IV
- * \param add       additional data
- * \param add_len   length of additional data
- * \param input     buffer holding the input data
- * \param output    buffer for holding the output data
- * \param tag_len   length of the tag to generate
- * \param tag       buffer for holding the tag
- *
- * \return         0 if successful
+ * \param ctx       The GCM context to use for encryption or decryption.
+ * \param mode      The operation to perform: #MBEDTLS_GCM_ENCRYPT or
+ *                  #MBEDTLS_GCM_DECRYPT.
+ * \param length    The length of the input data. This must be a multiple of 16 except in the last call before mbedtls_gcm_finish().
+ * \param iv        The initialization vector.
+ * \param iv_len    The length of the IV.
+ * \param add       The buffer holding the additional data.
+ * \param add_len   The length of the additional data.
+ * \param input     The buffer holding the input data.
+ * \param output    The buffer for holding the output data.
+ * \param tag_len   The length of the tag to generate.
+ * \param tag       The buffer for holding the tag.
+ *
+ * \return         \c 0 on success.
  */
 int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx,
                        int mode,
@@ -112,25 +134,26 @@ int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx,
                        unsigned char *tag );
 
 /**
- * \brief           GCM buffer authenticated decryption using a block cipher
+ * \brief           This function performs a GCM authenticated decryption of a
+ *                  buffer.
  *
- * \note On decryption, the output buffer cannot be the same as input buffer.
- *       If buffers overlap, the output buffer must trail at least 8 bytes
+ * \note For decryption, the output buffer cannot be the same as input buffer.
+ *       If the buffers overlap, the output buffer must trail at least 8 Bytes
  *       behind the input buffer.
  *
- * \param ctx       GCM context
- * \param length    length of the input data
- * \param iv        initialization vector
- * \param iv_len    length of IV
- * \param add       additional data
- * \param add_len   length of additional data
- * \param tag       buffer holding the tag
- * \param tag_len   length of the tag
- * \param input     buffer holding the input data
- * \param output    buffer for holding the output data
- *
- * \return         0 if successful and authenticated,
- *                 MBEDTLS_ERR_GCM_AUTH_FAILED if tag does not match
+ * \param ctx       The GCM context.
+ * \param length    The length of the input data. This must be a multiple of 16 except in the last call before mbedtls_gcm_finish().
+ * \param iv        The initialization vector.
+ * \param iv_len    The length of the IV.
+ * \param add       The buffer holding the additional data.
+ * \param add_len   The length of the additional data.
+ * \param tag       The buffer holding the tag.
+ * \param tag_len   The length of the tag.
+ * \param input     The buffer holding the input data.
+ * \param output    The buffer for holding the output data.
+ *
+ * \return         0 if successful and authenticated, or
+ *                 #MBEDTLS_ERR_GCM_AUTH_FAILED if tag does not match.
  */
 int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx,
                       size_t length,
@@ -144,16 +167,18 @@ int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx,
                       unsigned char *output );
 
 /**
- * \brief           Generic GCM stream start function
+ * \brief           This function starts a GCM encryption or decryption
+ *                  operation.
  *
- * \param ctx       GCM context
- * \param mode      MBEDTLS_GCM_ENCRYPT or MBEDTLS_GCM_DECRYPT
- * \param iv        initialization vector
- * \param iv_len    length of IV
- * \param add       additional data (or NULL if length is 0)
- * \param add_len   length of additional data
+ * \param ctx       The GCM context.
+ * \param mode      The operation to perform: #MBEDTLS_GCM_ENCRYPT or
+ *                  #MBEDTLS_GCM_DECRYPT.
+ * \param iv        The initialization vector.
+ * \param iv_len    The length of the IV.
+ * \param add       The buffer holding the additional data, or NULL if \p add_len is 0.
+ * \param add_len   The length of the additional data. If 0, \p  add is NULL.
  *
- * \return         0 if successful
+ * \return         \c 0 on success.
  */
 int mbedtls_gcm_starts( mbedtls_gcm_context *ctx,
                 int mode,
@@ -163,21 +188,23 @@ int mbedtls_gcm_starts( mbedtls_gcm_context *ctx,
                 size_t add_len );
 
 /**
- * \brief           Generic GCM update function. Encrypts/decrypts using the
- *                  given GCM context. Expects input to be a multiple of 16
- *                  bytes! Only the last call before mbedtls_gcm_finish() can be less
- *                  than 16 bytes!
+ * \brief           This function feeds an input buffer into an ongoing GCM
+ *                  encryption or decryption operation.
+ *
+ *    `             The function expects input to be a multiple of 16
+ *                  Bytes. Only the last call before calling
+ *                  mbedtls_gcm_finish() can be less than 16 Bytes.
  *
- * \note On decryption, the output buffer cannot be the same as input buffer.
- *       If buffers overlap, the output buffer must trail at least 8 bytes
+ * \note For decryption, the output buffer cannot be the same as input buffer.
+ *       If the buffers overlap, the output buffer must trail at least 8 Bytes
  *       behind the input buffer.
  *
- * \param ctx       GCM context
- * \param length    length of the input data
- * \param input     buffer holding the input data
- * \param output    buffer for holding the output data
+ * \param ctx       The GCM context.
+ * \param length    The length of the input data. This must be a multiple of 16 except in the last call before mbedtls_gcm_finish().
+ * \param input     The buffer holding the input data.
+ * \param output    The buffer for holding the output data.
  *
- * \return         0 if successful or MBEDTLS_ERR_GCM_BAD_INPUT
+ * \return         \c 0 on success, or #MBEDTLS_ERR_GCM_BAD_INPUT on failure.
  */
 int mbedtls_gcm_update( mbedtls_gcm_context *ctx,
                 size_t length,
@@ -185,31 +212,46 @@ int mbedtls_gcm_update( mbedtls_gcm_context *ctx,
                 unsigned char *output );
 
 /**
- * \brief           Generic GCM finalisation function. Wraps up the GCM stream
- *                  and generates the tag. The tag can have a maximum length of
- *                  16 bytes.
+ * \brief           This function finishes the GCM operation and generates
+ *                  the authentication tag.
  *
- * \param ctx       GCM context
- * \param tag       buffer for holding the tag (may be NULL if tag_len is 0)
- * \param tag_len   length of the tag to generate
+ *                  It wraps up the GCM stream, and generates the
+ *                  tag. The tag can have a maximum length of 16 Bytes.
  *
- * \return          0 if successful or MBEDTLS_ERR_GCM_BAD_INPUT
+ * \param ctx       The GCM context.
+ * \param tag       The buffer for holding the tag.
+ * \param tag_len   The length of the tag to generate. Must be at least four.
+ *
+ * \return          \c 0 on success, or #MBEDTLS_ERR_GCM_BAD_INPUT on failure.
  */
 int mbedtls_gcm_finish( mbedtls_gcm_context *ctx,
                 unsigned char *tag,
                 size_t tag_len );
 
 /**
- * \brief           Free a GCM context and underlying cipher sub-context
+ * \brief           This function clears a GCM context and the underlying
+ *                  cipher sub-context.
  *
- * \param ctx       GCM context to free
+ * \param ctx       The GCM context to clear.
  */
 void mbedtls_gcm_free( mbedtls_gcm_context *ctx );
 
+#ifdef __cplusplus
+}
+#endif
+
+#else  /* !MBEDTLS_GCM_ALT */
+#include "gcm_alt.h"
+#endif /* !MBEDTLS_GCM_ALT */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 /**
- * \brief          Checkup routine
+ * \brief          The GCM checkup routine.
  *
- * \return         0 if successful, or 1 if the test failed
+ * \return         \c 0 on success, or \c 1 on failure.
  */
 int mbedtls_gcm_self_test( int verbose );
 
@@ -217,4 +259,5 @@ int mbedtls_gcm_self_test( int verbose );
 }
 #endif
 
+
 #endif /* gcm.h */

+ 2 - 1
app/include/mbedtls/havege.h

@@ -2,7 +2,8 @@
  * \file havege.h
  *
  * \brief HAVEGE: HArdware Volatile Entropy Gathering and Expansion
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 2 - 1
app/include/mbedtls/hmac_drbg.h

@@ -2,7 +2,8 @@
  * \file hmac_drbg.h
  *
  * \brief HMAC_DRBG (NIST SP 800-90A)
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 0 - 13
app/include/mbedtls/mbedtls_debug.h

@@ -1,13 +0,0 @@
-#ifndef _MBEDTLS_DEBUG_H_
-#define _MBEDTLS_DEBUG_H_
-
-#include "osapi.h"
-
-#define MBEDTLS_SSL_DEBUG_MSG( level, args )            os_printf args;
-#define MBEDTLS_SSL_DEBUG_RET( level, ... )             os_printf (__VA_ARGS__);
-#define MBEDTLS_SSL_DEBUG_BUF( level, ... )             os_printf (__VA_ARGS__);
-#define MBEDTLS_SSL_DEBUG_MPI( level, text, X )         do { } while( 0 )
-#define MBEDTLS_SSL_DEBUG_ECP( level, text, X )         do { } while( 0 )
-#define MBEDTLS_SSL_DEBUG_CRT( level, text, crt )       do { } while( 0 )
-
-#endif

+ 236 - 136
app/include/mbedtls/md.h

@@ -1,11 +1,12 @@
-/**
+ /**
  * \file md.h
  *
- * \brief Generic message digest wrapper
+ * \brief The generic message-digest wrapper.
  *
  * \author Adriaan de Jong <dejong@fox-it.com>
- *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -20,22 +21,38 @@
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *
- *  This file is part of mbed TLS (https://tls.mbed.org)
+ *  This file is part of Mbed TLS (https://tls.mbed.org)
  */
+
 #ifndef MBEDTLS_MD_H
 #define MBEDTLS_MD_H
 
 #include <stddef.h>
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #define MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE                -0x5080  /**< The selected feature is not available. */
 #define MBEDTLS_ERR_MD_BAD_INPUT_DATA                     -0x5100  /**< Bad input parameters to function. */
 #define MBEDTLS_ERR_MD_ALLOC_FAILED                       -0x5180  /**< Failed to allocate memory. */
 #define MBEDTLS_ERR_MD_FILE_IO_ERROR                      -0x5200  /**< Opening or reading of file failed. */
+#define MBEDTLS_ERR_MD_HW_ACCEL_FAILED                    -0x5280  /**< MD hardware accelerator failed. */
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
+/**
+ * \brief     Enumeration of supported message digests
+ *
+ * \warning   MD2, MD4, MD5 and SHA-1 are considered weak message digests and
+ *            their use constitutes a security risk. We recommend considering
+ *            stronger message digests instead.
+ *
+ */
 typedef enum {
     MBEDTLS_MD_NONE=0,
     MBEDTLS_MD_MD2,
@@ -56,65 +73,79 @@ typedef enum {
 #endif
 
 /**
- * Opaque struct defined in md_internal.h
+ * Opaque struct defined in md_internal.h.
  */
 typedef struct mbedtls_md_info_t mbedtls_md_info_t;
 
 /**
- * Generic message digest context.
+ * The generic message-digest context.
  */
 typedef struct {
-    /** Information about the associated message digest */
+    /** Information about the associated message digest. */
     const mbedtls_md_info_t *md_info;
 
-    /** Digest-specific context */
+    /** The digest-specific context. */
     void *md_ctx;
 
-    /** HMAC part of the context */
+    /** The HMAC part of the context. */
     void *hmac_ctx;
 } mbedtls_md_context_t;
 
 /**
- * \brief Returns the list of digests supported by the generic digest module.
+ * \brief           This function returns the list of digests supported by the
+ *                  generic digest module.
  *
- * \return          a statically allocated array of digests, the last entry
- *                  is 0.
+ * \return          A statically allocated array of digests. Each element
+ *                  in the returned list is an integer belonging to the
+ *                  message-digest enumeration #mbedtls_md_type_t.
+ *                  The last entry is 0.
  */
 const int *mbedtls_md_list( void );
 
 /**
- * \brief           Returns the message digest information associated with the
- *                  given digest name.
+ * \brief           This function returns the message-digest information
+ *                  associated with the given digest name.
  *
- * \param md_name   Name of the digest to search for.
+ * \param md_name   The name of the digest to search for.
  *
- * \return          The message digest information associated with md_name or
- *                  NULL if not found.
+ * \return          The message-digest information associated with \p md_name,
+ *                  or NULL if not found.
  */
 const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name );
 
 /**
- * \brief           Returns the message digest information associated with the
- *                  given digest type.
+ * \brief           This function returns the message-digest information
+ *                  associated with the given digest type.
  *
- * \param md_type   type of digest to search for.
+ * \param md_type   The type of digest to search for.
  *
- * \return          The message digest information associated with md_type or
- *                  NULL if not found.
+ * \return          The message-digest information associated with \p md_type,
+ *                  or NULL if not found.
  */
 const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type );
 
 /**
- * \brief           Initialize a md_context (as NONE)
- *                  This should always be called first.
- *                  Prepares the context for mbedtls_md_setup() or mbedtls_md_free().
+ * \brief           This function initializes a message-digest context without
+ *                  binding it to a particular message-digest algorithm.
+ *
+ *                  This function should always be called first. It prepares the
+ *                  context for mbedtls_md_setup() for binding it to a
+ *                  message-digest algorithm.
  */
 void mbedtls_md_init( mbedtls_md_context_t *ctx );
 
 /**
- * \brief           Free and clear the internal structures of ctx.
- *                  Can be called at any time after mbedtls_md_init().
- *                  Mandatory once mbedtls_md_setup() has been called.
+ * \brief           This function clears the internal structure of \p ctx and
+ *                  frees any embedded internal structure, but does not free
+ *                  \p ctx itself.
+ *
+ *                  If you have called mbedtls_md_setup() on \p ctx, you must
+ *                  call mbedtls_md_free() when you are no longer using the
+ *                  context.
+ *                  Calling this function if you have previously
+ *                  called mbedtls_md_init() and nothing else is optional.
+ *                  You must not call this function if you have not called
+ *                  mbedtls_md_init().
  */
 void mbedtls_md_free( mbedtls_md_context_t *ctx );
 
@@ -125,219 +156,288 @@ void mbedtls_md_free( mbedtls_md_context_t *ctx );
 #define MBEDTLS_DEPRECATED
 #endif
 /**
- * \brief           Select MD to use and allocate internal structures.
- *                  Should be called after mbedtls_md_init() or mbedtls_md_free().
+ * \brief           This function selects the message digest algorithm to use,
+ *                  and allocates internal structures.
+ *
+ *                  It should be called after mbedtls_md_init() or mbedtls_md_free().
  *                  Makes it necessary to call mbedtls_md_free() later.
  *
  * \deprecated      Superseded by mbedtls_md_setup() in 2.0.0
  *
- * \param ctx       Context to set up.
- * \param md_info   Message digest to use.
+ * \param ctx       The context to set up.
+ * \param md_info   The information structure of the message-digest algorithm
+ *                  to use.
  *
  * \returns         \c 0 on success,
- *                  \c MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure,
- *                  \c MBEDTLS_ERR_MD_ALLOC_FAILED memory allocation failure.
+ *                  #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure,
+ *                  #MBEDTLS_ERR_MD_ALLOC_FAILED memory allocation failure.
  */
 int mbedtls_md_init_ctx( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info ) MBEDTLS_DEPRECATED;
 #undef MBEDTLS_DEPRECATED
 #endif /* MBEDTLS_DEPRECATED_REMOVED */
 
 /**
- * \brief           Select MD to use and allocate internal structures.
- *                  Should be called after mbedtls_md_init() or mbedtls_md_free().
- *                  Makes it necessary to call mbedtls_md_free() later.
+ * \brief           This function selects the message digest algorithm to use,
+ *                  and allocates internal structures.
  *
- * \param ctx       Context to set up.
- * \param md_info   Message digest to use.
- * \param hmac      0 to save some memory if HMAC will not be used,
- *                  non-zero is HMAC is going to be used with this context.
+ *                  It should be called after mbedtls_md_init() or
+ *                  mbedtls_md_free(). Makes it necessary to call
+ *                  mbedtls_md_free() later.
+ *
+ * \param ctx       The context to set up.
+ * \param md_info   The information structure of the message-digest algorithm
+ *                  to use.
+ * \param hmac      <ul><li>0: HMAC is not used. Saves some memory.</li>
+ *                  <li>non-zero: HMAC is used with this context.</li></ul>
  *
  * \returns         \c 0 on success,
- *                  \c MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure,
- *                  \c MBEDTLS_ERR_MD_ALLOC_FAILED memory allocation failure.
+ *                  #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure, or
+ *                  #MBEDTLS_ERR_MD_ALLOC_FAILED on memory allocation failure.
  */
 int mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac );
 
 /**
- * \brief           Clone the state of an MD context
+ * \brief           This function clones the state of an message-digest
+ *                  context.
+ *
+ * \note            You must call mbedtls_md_setup() on \c dst before calling
+ *                  this function.
  *
- * \note            The two contexts must have been setup to the same type
- *                  (cloning from SHA-256 to SHA-512 make no sense).
+ * \note            The two contexts must have the same type,
+ *                  for example, both are SHA-256.
  *
- * \warning         Only clones the MD state, not the HMAC state! (for now)
+ * \warning         This function clones the message-digest state, not the
+ *                  HMAC state.
  *
- * \param dst       The destination context
- * \param src       The context to be cloned
+ * \param dst       The destination context.
+ * \param src       The context to be cloned.
  *
  * \return          \c 0 on success,
- *                  \c MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure.
+ *                  #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure.
  */
 int mbedtls_md_clone( mbedtls_md_context_t *dst,
                       const mbedtls_md_context_t *src );
 
 /**
- * \brief           Returns the size of the message digest output.
+ * \brief           This function extracts the message-digest size from the
+ *                  message-digest information structure.
  *
- * \param md_info   message digest info
+ * \param md_info   The information structure of the message-digest algorithm
+ *                  to use.
  *
- * \return          size of the message digest output in bytes.
+ * \return          The size of the message-digest output in Bytes.
  */
-int mbedtls_md_get_size( const mbedtls_md_info_t *md_info );
+unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info );
 
 /**
- * \brief           Returns the type of the message digest output.
+ * \brief           This function extracts the message-digest type from the
+ *                  message-digest information structure.
  *
- * \param md_info   message digest info
+ * \param md_info   The information structure of the message-digest algorithm
+ *                  to use.
  *
- * \return          type of the message digest output.
+ * \return          The type of the message digest.
  */
 mbedtls_md_type_t mbedtls_md_get_type( const mbedtls_md_info_t *md_info );
 
 /**
- * \brief           Returns the name of the message digest output.
+ * \brief           This function extracts the message-digest name from the
+ *                  message-digest information structure.
  *
- * \param md_info   message digest info
+ * \param md_info   The information structure of the message-digest algorithm
+ *                  to use.
  *
- * \return          name of the message digest output.
+ * \return          The name of the message digest.
  */
 const char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info );
 
 /**
- * \brief           Prepare the context to digest a new message.
- *                  Generally called after mbedtls_md_setup() or mbedtls_md_finish().
- *                  Followed by mbedtls_md_update().
+ * \brief           This function starts a message-digest computation.
  *
- * \param ctx       generic message digest context.
+ *                  You must call this function after setting up the context
+ *                  with mbedtls_md_setup(), and before passing data with
+ *                  mbedtls_md_update().
  *
- * \returns         0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                  verification fails.
+ * \param ctx       The generic message-digest context.
+ *
+ * \returns         \c 0 on success, #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                  parameter verification fails.
  */
 int mbedtls_md_starts( mbedtls_md_context_t *ctx );
 
 /**
- * \brief           Generic message digest process buffer
- *                  Called between mbedtls_md_starts() and mbedtls_md_finish().
- *                  May be called repeatedly.
+ * \brief           This function feeds an input buffer into an ongoing
+ *                  message-digest computation.
+ *
+ *                  You must call mbedtls_md_starts() before calling this
+ *                  function. You may call this function multiple times.
+ *                  Afterwards, call mbedtls_md_finish().
  *
- * \param ctx       Generic message digest context
- * \param input     buffer holding the  datal
- * \param ilen      length of the input data
+ * \param ctx       The generic message-digest context.
+ * \param input     The buffer holding the input data.
+ * \param ilen      The length of the input data.
  *
- * \returns         0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                  verification fails.
+ * \returns         \c 0 on success, #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                  parameter verification fails.
  */
 int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen );
 
 /**
- * \brief           Generic message digest final digest
- *                  Called after mbedtls_md_update().
- *                  Usually followed by mbedtls_md_free() or mbedtls_md_starts().
+ * \brief           This function finishes the digest operation,
+ *                  and writes the result to the output buffer.
  *
- * \param ctx       Generic message digest context
- * \param output    Generic message digest checksum result
+ *                  Call this function after a call to mbedtls_md_starts(),
+ *                  followed by any number of calls to mbedtls_md_update().
+ *                  Afterwards, you may either clear the context with
+ *                  mbedtls_md_free(), or call mbedtls_md_starts() to reuse
+ *                  the context for another digest operation with the same
+ *                  algorithm.
  *
- * \returns         0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                  verification fails.
+ * \param ctx       The generic message-digest context.
+ * \param output    The buffer for the generic message-digest checksum result.
+ *
+ * \returns         \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                  parameter verification fails.
  */
 int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output );
 
 /**
- * \brief          Output = message_digest( input buffer )
+ * \brief          This function calculates the message-digest of a buffer,
+ *                 with respect to a configurable message-digest algorithm
+ *                 in a single call.
+ *
+ *                 The result is calculated as
+ *                 Output = message_digest(input buffer).
  *
- * \param md_info  message digest info
- * \param input    buffer holding the  data
- * \param ilen     length of the input data
- * \param output   Generic message digest checksum result
+ * \param md_info  The information structure of the message-digest algorithm
+ *                 to use.
+ * \param input    The buffer holding the data.
+ * \param ilen     The length of the input data.
+ * \param output   The generic message-digest checksum result.
  *
- * \returns        0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                 verification fails.
+ * \returns        \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                 parameter verification fails.
  */
 int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen,
         unsigned char *output );
 
 #if defined(MBEDTLS_FS_IO)
 /**
- * \brief          Output = message_digest( file contents )
+ * \brief          This function calculates the message-digest checksum
+ *                 result of the contents of the provided file.
+ *
+ *                 The result is calculated as
+ *                 Output = message_digest(file contents).
  *
- * \param md_info  message digest info
- * \param path     input file name
- * \param output   generic message digest checksum result
+ * \param md_info  The information structure of the message-digest algorithm
+ *                 to use.
+ * \param path     The input file name.
+ * \param output   The generic message-digest checksum result.
  *
- * \return         0 if successful,
- *                 MBEDTLS_ERR_MD_FILE_IO_ERROR if file input failed,
- *                 MBEDTLS_ERR_MD_BAD_INPUT_DATA if md_info was NULL.
+ * \return         \c 0 on success,
+ *                 #MBEDTLS_ERR_MD_FILE_IO_ERROR if file input failed, or
+ *                 #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info was NULL.
  */
 int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path,
                      unsigned char *output );
 #endif /* MBEDTLS_FS_IO */
 
 /**
- * \brief           Set HMAC key and prepare to authenticate a new message.
- *                  Usually called after mbedtls_md_setup() or mbedtls_md_hmac_finish().
+ * \brief           This function sets the HMAC key and prepares to
+ *                  authenticate a new message.
  *
- * \param ctx       HMAC context
- * \param key       HMAC secret key
- * \param keylen    length of the HMAC key in bytes
+ *                  Call this function after mbedtls_md_setup(), to use
+ *                  the MD context for an HMAC calculation, then call
+ *                  mbedtls_md_hmac_update() to provide the input data, and
+ *                  mbedtls_md_hmac_finish() to get the HMAC value.
  *
- * \returns         0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                  verification fails.
+ * \param ctx       The message digest context containing an embedded HMAC
+ *                  context.
+ * \param key       The HMAC secret key.
+ * \param keylen    The length of the HMAC key in Bytes.
+ *
+ * \returns         \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                  parameter verification fails.
  */
 int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key,
                     size_t keylen );
 
 /**
- * \brief           Generic HMAC process buffer.
- *                  Called between mbedtls_md_hmac_starts() or mbedtls_md_hmac_reset()
- *                  and mbedtls_md_hmac_finish().
- *                  May be called repeatedly.
- *
- * \param ctx       HMAC context
- * \param input     buffer holding the  data
- * \param ilen      length of the input data
- *
- * \returns         0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                  verification fails.
+ * \brief           This function feeds an input buffer into an ongoing HMAC
+ *                  computation.
+ *
+ *                  Call mbedtls_md_hmac_starts() or mbedtls_md_hmac_reset()
+ *                  before calling this function.
+ *                  You may call this function multiple times to pass the
+ *                  input piecewise.
+ *                  Afterwards, call mbedtls_md_hmac_finish().
+ *
+ * \param ctx       The message digest context containing an embedded HMAC
+ *                  context.
+ * \param input     The buffer holding the input data.
+ * \param ilen      The length of the input data.
+ *
+ * \returns         \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                  parameter verification fails.
  */
 int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *input,
                     size_t ilen );
 
 /**
- * \brief           Output HMAC.
- *                  Called after mbedtls_md_hmac_update().
- *                  Usually followed my mbedtls_md_hmac_reset(), mbedtls_md_hmac_starts(),
- *                  or mbedtls_md_free().
+ * \brief           This function finishes the HMAC operation, and writes
+ *                  the result to the output buffer.
+ *
+ *                  Call this function after mbedtls_md_hmac_starts() and
+ *                  mbedtls_md_hmac_update() to get the HMAC value. Afterwards
+ *                  you may either call mbedtls_md_free() to clear the context,
+ *                  or call mbedtls_md_hmac_reset() to reuse the context with
+ *                  the same HMAC key.
  *
- * \param ctx       HMAC context
- * \param output    Generic HMAC checksum result
+ * \param ctx       The message digest context containing an embedded HMAC
+ *                  context.
+ * \param output    The generic HMAC checksum result.
  *
- * \returns         0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                  verification fails.
+ * \returns         \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                  parameter verification fails.
  */
 int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output);
 
 /**
- * \brief           Prepare to authenticate a new message with the same key.
- *                  Called after mbedtls_md_hmac_finish() and before mbedtls_md_hmac_update().
+ * \brief           This function prepares to authenticate a new message with
+ *                  the same key as the previous HMAC operation.
  *
- * \param ctx       HMAC context to be reset
+ *                  You may call this function after mbedtls_md_hmac_finish().
+ *                  Afterwards call mbedtls_md_hmac_update() to pass the new
+ *                  input.
  *
- * \returns         0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                  verification fails.
+ * \param ctx       The message digest context containing an embedded HMAC
+ *                  context.
+ *
+ * \returns         \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                  parameter verification fails.
  */
 int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx );
 
 /**
- * \brief          Output = Generic_HMAC( hmac key, input buffer )
+ * \brief          This function calculates the full generic HMAC
+ *                 on the input buffer with the provided key.
+ *
+ *                 The function allocates the context, performs the
+ *                 calculation, and frees the context.
+ *
+ *                 The HMAC result is calculated as
+ *                 output = generic HMAC(hmac key, input buffer).
  *
- * \param md_info  message digest info
- * \param key      HMAC secret key
- * \param keylen   length of the HMAC key in bytes
- * \param input    buffer holding the  data
- * \param ilen     length of the input data
- * \param output   Generic HMAC-result
+ * \param md_info  The information structure of the message-digest algorithm
+ *                 to use.
+ * \param key      The HMAC secret key.
+ * \param keylen   The length of the HMAC secret key in Bytes.
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
+ * \param output   The generic HMAC result.
  *
- * \returns        0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                 verification fails.
+ * \returns        \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                 parameter verification fails.
  */
 int mbedtls_md_hmac( const mbedtls_md_info_t *md_info, const unsigned char *key, size_t keylen,
                 const unsigned char *input, size_t ilen,

+ 206 - 9
app/include/mbedtls/md2.h

@@ -3,6 +3,11 @@
  *
  * \brief MD2 message digest algorithm (hash function)
  *
+ * \warning MD2 is considered a weak message digest and its use constitutes a
+ *          security risk. We recommend considering stronger message digests
+ *          instead.
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -19,6 +24,7 @@
  *  limitations under the License.
  *
  *  This file is part of mbed TLS (https://tls.mbed.org)
+ *
  */
 #ifndef MBEDTLS_MD2_H
 #define MBEDTLS_MD2_H
@@ -31,6 +37,13 @@
 
 #include <stddef.h>
 
+#define MBEDTLS_ERR_MD2_HW_ACCEL_FAILED                   -0x002B  /**< MD2 hardware accelerator failed */
+
+#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
+    !defined(inline) && !defined(__cplusplus)
+#define inline __inline
+#endif
+
 #if !defined(MBEDTLS_MD2_ALT)
 // Regular implementation
 //
@@ -41,6 +54,11 @@ extern "C" {
 
 /**
  * \brief          MD2 context structure
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 typedef struct
 {
@@ -55,6 +73,11 @@ mbedtls_md2_context;
  * \brief          Initialize MD2 context
  *
  * \param ctx      MD2 context to be initialized
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 void mbedtls_md2_init( mbedtls_md2_context *ctx );
 
@@ -62,6 +85,11 @@ void mbedtls_md2_init( mbedtls_md2_context *ctx );
  * \brief          Clear MD2 context
  *
  * \param ctx      MD2 context to be cleared
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 void mbedtls_md2_free( mbedtls_md2_context *ctx );
 
@@ -70,6 +98,11 @@ void mbedtls_md2_free( mbedtls_md2_context *ctx );
  *
  * \param dst      The destination context
  * \param src      The context to be cloned
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 void mbedtls_md2_clone( mbedtls_md2_context *dst,
                         const mbedtls_md2_context *src );
@@ -78,25 +111,150 @@ void mbedtls_md2_clone( mbedtls_md2_context *dst,
  * \brief          MD2 context setup
  *
  * \param ctx      context to be initialized
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md2_starts_ret( mbedtls_md2_context *ctx );
+
+/**
+ * \brief          MD2 process buffer
+ *
+ * \param ctx      MD2 context
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md2_update_ret( mbedtls_md2_context *ctx,
+                            const unsigned char *input,
+                            size_t ilen );
+
+/**
+ * \brief          MD2 final digest
+ *
+ * \param ctx      MD2 context
+ * \param output   MD2 checksum result
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md2_finish_ret( mbedtls_md2_context *ctx,
+                            unsigned char output[16] );
+
+/**
+ * \brief          MD2 process data block (internal use only)
+ *
+ * \param ctx      MD2 context
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_internal_md2_process( mbedtls_md2_context *ctx );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          MD2 context setup
+ *
+ * \deprecated     Superseded by mbedtls_md2_starts_ret() in 2.7.0
+ *
+ * \param ctx      context to be initialized
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_md2_starts( mbedtls_md2_context *ctx );
+MBEDTLS_DEPRECATED static inline void mbedtls_md2_starts(
+                                                    mbedtls_md2_context *ctx )
+{
+    mbedtls_md2_starts_ret( ctx );
+}
 
 /**
  * \brief          MD2 process buffer
  *
+ * \deprecated     Superseded by mbedtls_md2_update_ret() in 2.7.0
+ *
  * \param ctx      MD2 context
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_md2_update( mbedtls_md2_context *ctx, const unsigned char *input, size_t ilen );
+MBEDTLS_DEPRECATED static inline void mbedtls_md2_update(
+                                                mbedtls_md2_context *ctx,
+                                                const unsigned char *input,
+                                                size_t ilen )
+{
+    mbedtls_md2_update_ret( ctx, input, ilen );
+}
 
 /**
  * \brief          MD2 final digest
  *
+ * \deprecated     Superseded by mbedtls_md2_finish_ret() in 2.7.0
+ *
  * \param ctx      MD2 context
  * \param output   MD2 checksum result
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_md2_finish( mbedtls_md2_context *ctx, unsigned char output[16] );
+MBEDTLS_DEPRECATED static inline void mbedtls_md2_finish(
+                                                    mbedtls_md2_context *ctx,
+                                                    unsigned char output[16] )
+{
+    mbedtls_md2_finish_ret( ctx, output );
+}
+
+/**
+ * \brief          MD2 process data block (internal use only)
+ *
+ * \deprecated     Superseded by mbedtls_internal_md2_process() in 2.7.0
+ *
+ * \param ctx      MD2 context
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+MBEDTLS_DEPRECATED static inline void mbedtls_md2_process(
+                                                    mbedtls_md2_context *ctx )
+{
+    mbedtls_internal_md2_process( ctx );
+}
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 #ifdef __cplusplus
 }
@@ -113,22 +271,61 @@ extern "C" {
 /**
  * \brief          Output = MD2( input buffer )
  *
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ * \param output   MD2 checksum result
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md2_ret( const unsigned char *input,
+                     size_t ilen,
+                     unsigned char output[16] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          Output = MD2( input buffer )
+ *
+ * \deprecated     Superseded by mbedtls_md2_ret() in 2.7.0
+ *
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
  * \param output   MD2 checksum result
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_md2( const unsigned char *input, size_t ilen, unsigned char output[16] );
+MBEDTLS_DEPRECATED static inline void mbedtls_md2( const unsigned char *input,
+                                                   size_t ilen,
+                                                   unsigned char output[16] )
+{
+    mbedtls_md2_ret( input, ilen, output );
+}
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 /**
  * \brief          Checkup routine
  *
  * \return         0 if successful, or 1 if the test failed
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 int mbedtls_md2_self_test( int verbose );
 
-/* Internal use */
-void mbedtls_md2_process( mbedtls_md2_context *ctx );
-
 #ifdef __cplusplus
 }
 #endif

+ 211 - 9
app/include/mbedtls/md4.h

@@ -3,6 +3,11 @@
  *
  * \brief MD4 message digest algorithm (hash function)
  *
+ * \warning MD4 is considered a weak message digest and its use constitutes a
+ *          security risk. We recommend considering stronger message digests
+ *          instead.
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -19,6 +24,7 @@
  *  limitations under the License.
  *
  *  This file is part of mbed TLS (https://tls.mbed.org)
+ *
  */
 #ifndef MBEDTLS_MD4_H
 #define MBEDTLS_MD4_H
@@ -32,6 +38,13 @@
 #include <stddef.h>
 #include <stdint.h>
 
+#define MBEDTLS_ERR_MD4_HW_ACCEL_FAILED                   -0x002D  /**< MD4 hardware accelerator failed */
+
+#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
+    !defined(inline) && !defined(__cplusplus)
+#define inline __inline
+#endif
+
 #if !defined(MBEDTLS_MD4_ALT)
 // Regular implementation
 //
@@ -42,6 +55,11 @@ extern "C" {
 
 /**
  * \brief          MD4 context structure
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 typedef struct
 {
@@ -55,6 +73,11 @@ mbedtls_md4_context;
  * \brief          Initialize MD4 context
  *
  * \param ctx      MD4 context to be initialized
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 void mbedtls_md4_init( mbedtls_md4_context *ctx );
 
@@ -62,6 +85,11 @@ void mbedtls_md4_init( mbedtls_md4_context *ctx );
  * \brief          Clear MD4 context
  *
  * \param ctx      MD4 context to be cleared
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 void mbedtls_md4_free( mbedtls_md4_context *ctx );
 
@@ -70,6 +98,11 @@ void mbedtls_md4_free( mbedtls_md4_context *ctx );
  *
  * \param dst      The destination context
  * \param src      The context to be cloned
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 void mbedtls_md4_clone( mbedtls_md4_context *dst,
                         const mbedtls_md4_context *src );
@@ -78,25 +111,153 @@ void mbedtls_md4_clone( mbedtls_md4_context *dst,
  * \brief          MD4 context setup
  *
  * \param ctx      context to be initialized
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ */
+int mbedtls_md4_starts_ret( mbedtls_md4_context *ctx );
+
+/**
+ * \brief          MD4 process buffer
+ *
+ * \param ctx      MD4 context
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md4_update_ret( mbedtls_md4_context *ctx,
+                            const unsigned char *input,
+                            size_t ilen );
+
+/**
+ * \brief          MD4 final digest
+ *
+ * \param ctx      MD4 context
+ * \param output   MD4 checksum result
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md4_finish_ret( mbedtls_md4_context *ctx,
+                            unsigned char output[16] );
+
+/**
+ * \brief          MD4 process data block (internal use only)
+ *
+ * \param ctx      MD4 context
+ * \param data     buffer holding one block of data
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_internal_md4_process( mbedtls_md4_context *ctx,
+                                  const unsigned char data[64] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          MD4 context setup
+ *
+ * \deprecated     Superseded by mbedtls_md4_starts_ret() in 2.7.0
+ *
+ * \param ctx      context to be initialized
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_md4_starts( mbedtls_md4_context *ctx );
+MBEDTLS_DEPRECATED static inline void mbedtls_md4_starts(
+                                                    mbedtls_md4_context *ctx )
+{
+    mbedtls_md4_starts_ret( ctx );
+}
 
 /**
  * \brief          MD4 process buffer
  *
+ * \deprecated     Superseded by mbedtls_md4_update_ret() in 2.7.0
+ *
  * \param ctx      MD4 context
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_md4_update( mbedtls_md4_context *ctx, const unsigned char *input, size_t ilen );
+MBEDTLS_DEPRECATED static inline void mbedtls_md4_update(
+                                                    mbedtls_md4_context *ctx,
+                                                    const unsigned char *input,
+                                                    size_t ilen )
+{
+    mbedtls_md4_update_ret( ctx, input, ilen );
+}
 
 /**
  * \brief          MD4 final digest
  *
+ * \deprecated     Superseded by mbedtls_md4_finish_ret() in 2.7.0
+ *
  * \param ctx      MD4 context
  * \param output   MD4 checksum result
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_md4_finish( mbedtls_md4_context *ctx, unsigned char output[16] );
+MBEDTLS_DEPRECATED static inline void mbedtls_md4_finish(
+                                                    mbedtls_md4_context *ctx,
+                                                    unsigned char output[16] )
+{
+    mbedtls_md4_finish_ret( ctx, output );
+}
+
+/**
+ * \brief          MD4 process data block (internal use only)
+ *
+ * \deprecated     Superseded by mbedtls_internal_md4_process() in 2.7.0
+ *
+ * \param ctx      MD4 context
+ * \param data     buffer holding one block of data
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+MBEDTLS_DEPRECATED static inline void mbedtls_md4_process(
+                                                mbedtls_md4_context *ctx,
+                                                const unsigned char data[64] )
+{
+    mbedtls_internal_md4_process( ctx, data );
+}
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 #ifdef __cplusplus
 }
@@ -113,22 +274,63 @@ extern "C" {
 /**
  * \brief          Output = MD4( input buffer )
  *
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ * \param output   MD4 checksum result
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md4_ret( const unsigned char *input,
+                     size_t ilen,
+                     unsigned char output[16] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          Output = MD4( input buffer )
+ *
+ * \deprecated     Superseded by mbedtls_md4_ret() in 2.7.0
+ *
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
  * \param output   MD4 checksum result
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_md4( const unsigned char *input, size_t ilen, unsigned char output[16] );
+MBEDTLS_DEPRECATED static inline void mbedtls_md4( const unsigned char *input,
+                                                   size_t ilen,
+                                                   unsigned char output[16] )
+{
+    mbedtls_md4_ret( input, ilen, output );
+}
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 /**
  * \brief          Checkup routine
  *
  * \return         0 if successful, or 1 if the test failed
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 int mbedtls_md4_self_test( int verbose );
 
-/* Internal use */
-void mbedtls_md4_process( mbedtls_md4_context *ctx, const unsigned char data[64] );
-
 #ifdef __cplusplus
 }
 #endif

+ 210 - 8
app/include/mbedtls/md5.h

@@ -3,6 +3,11 @@
  *
  * \brief MD5 message digest algorithm (hash function)
  *
+ * \warning   MD5 is considered a weak message digest and its use constitutes a
+ *            security risk. We recommend considering stronger message
+ *            digests instead.
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -32,16 +37,28 @@
 #include <stddef.h>
 #include <stdint.h>
 
+#define MBEDTLS_ERR_MD5_HW_ACCEL_FAILED                   -0x002F  /**< MD5 hardware accelerator failed */
+
 #if !defined(MBEDTLS_MD5_ALT)
 // Regular implementation
 //
 
+#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
+    !defined(inline) && !defined(__cplusplus)
+#define inline __inline
+#endif
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
 /**
  * \brief          MD5 context structure
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 typedef struct
 {
@@ -55,6 +72,11 @@ mbedtls_md5_context;
  * \brief          Initialize MD5 context
  *
  * \param ctx      MD5 context to be initialized
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 void mbedtls_md5_init( mbedtls_md5_context *ctx );
 
@@ -62,6 +84,11 @@ void mbedtls_md5_init( mbedtls_md5_context *ctx );
  * \brief          Clear MD5 context
  *
  * \param ctx      MD5 context to be cleared
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 void mbedtls_md5_free( mbedtls_md5_context *ctx );
 
@@ -70,6 +97,11 @@ void mbedtls_md5_free( mbedtls_md5_context *ctx );
  *
  * \param dst      The destination context
  * \param src      The context to be cloned
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 void mbedtls_md5_clone( mbedtls_md5_context *dst,
                         const mbedtls_md5_context *src );
@@ -78,28 +110,154 @@ void mbedtls_md5_clone( mbedtls_md5_context *dst,
  * \brief          MD5 context setup
  *
  * \param ctx      context to be initialized
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md5_starts_ret( mbedtls_md5_context *ctx );
+
+/**
+ * \brief          MD5 process buffer
+ *
+ * \param ctx      MD5 context
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md5_update_ret( mbedtls_md5_context *ctx,
+                            const unsigned char *input,
+                            size_t ilen );
+
+/**
+ * \brief          MD5 final digest
+ *
+ * \param ctx      MD5 context
+ * \param output   MD5 checksum result
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md5_finish_ret( mbedtls_md5_context *ctx,
+                            unsigned char output[16] );
+
+/**
+ * \brief          MD5 process data block (internal use only)
+ *
+ * \param ctx      MD5 context
+ * \param data     buffer holding one block of data
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_internal_md5_process( mbedtls_md5_context *ctx,
+                                  const unsigned char data[64] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          MD5 context setup
+ *
+ * \deprecated     Superseded by mbedtls_md5_starts_ret() in 2.7.0
+ *
+ * \param ctx      context to be initialized
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_md5_starts( mbedtls_md5_context *ctx );
+MBEDTLS_DEPRECATED static inline void mbedtls_md5_starts(
+                                                    mbedtls_md5_context *ctx )
+{
+    mbedtls_md5_starts_ret( ctx );
+}
 
 /**
  * \brief          MD5 process buffer
  *
+ * \deprecated     Superseded by mbedtls_md5_update_ret() in 2.7.0
+ *
  * \param ctx      MD5 context
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_md5_update( mbedtls_md5_context *ctx, const unsigned char *input, size_t ilen );
+MBEDTLS_DEPRECATED static inline void mbedtls_md5_update(
+                                                    mbedtls_md5_context *ctx,
+                                                    const unsigned char *input,
+                                                    size_t ilen )
+{
+    mbedtls_md5_update_ret( ctx, input, ilen );
+}
 
 /**
  * \brief          MD5 final digest
  *
+ * \deprecated     Superseded by mbedtls_md5_finish_ret() in 2.7.0
+ *
  * \param ctx      MD5 context
  * \param output   MD5 checksum result
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+MBEDTLS_DEPRECATED static inline void mbedtls_md5_finish(
+                                                    mbedtls_md5_context *ctx,
+                                                    unsigned char output[16] )
+{
+    mbedtls_md5_finish_ret( ctx, output );
+}
+
+/**
+ * \brief          MD5 process data block (internal use only)
+ *
+ * \deprecated     Superseded by mbedtls_internal_md5_process() in 2.7.0
+ *
+ * \param ctx      MD5 context
+ * \param data     buffer holding one block of data
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_md5_finish( mbedtls_md5_context *ctx, unsigned char output[16] );
+MBEDTLS_DEPRECATED static inline void mbedtls_md5_process(
+                                                mbedtls_md5_context *ctx,
+                                                const unsigned char data[64] )
+{
+    mbedtls_internal_md5_process( ctx, data );
+}
 
-/* Internal use */
-void mbedtls_md5_process( mbedtls_md5_context *ctx, const unsigned char data[64] );
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 #ifdef __cplusplus
 }
@@ -116,16 +274,60 @@ extern "C" {
 /**
  * \brief          Output = MD5( input buffer )
  *
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ * \param output   MD5 checksum result
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md5_ret( const unsigned char *input,
+                     size_t ilen,
+                     unsigned char output[16] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          Output = MD5( input buffer )
+ *
+ * \deprecated     Superseded by mbedtls_md5_ret() in 2.7.0
+ *
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
  * \param output   MD5 checksum result
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_md5( const unsigned char *input, size_t ilen, unsigned char output[16] );
+MBEDTLS_DEPRECATED static inline void mbedtls_md5( const unsigned char *input,
+                                                   size_t ilen,
+                                                   unsigned char output[16] )
+{
+    mbedtls_md5_ret( input, ilen, output );
+}
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 /**
  * \brief          Checkup routine
  *
  * \return         0 if successful, or 1 if the test failed
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 int mbedtls_md5_self_test( int verbose );
 

+ 8 - 7
app/include/mbedtls/md_internal.h

@@ -6,7 +6,8 @@
  * \warning This in an internal header. Do not include directly.
  *
  * \author Adriaan de Jong <dejong@fox-it.com>
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -58,17 +59,17 @@ struct mbedtls_md_info_t
     int block_size;
 
     /** Digest initialisation function */
-    void (*starts_func)( void *ctx );
+    int (*starts_func)( void *ctx );
 
     /** Digest update function */
-    void (*update_func)( void *ctx, const unsigned char *input, size_t ilen );
+    int (*update_func)( void *ctx, const unsigned char *input, size_t ilen );
 
     /** Digest finalisation function */
-    void (*finish_func)( void *ctx, unsigned char *output );
+    int (*finish_func)( void *ctx, unsigned char *output );
 
     /** Generic digest function */
-    void (*digest_func)( const unsigned char *input, size_t ilen,
-                         unsigned char *output );
+    int (*digest_func)( const unsigned char *input, size_t ilen,
+                        unsigned char *output );
 
     /** Allocate a new context */
     void * (*ctx_alloc_func)( void );
@@ -80,7 +81,7 @@ struct mbedtls_md_info_t
     void (*clone_func)( void *dst, const void *src );
 
     /** Internal use only */
-    void (*process_func)( void *ctx, const unsigned char *input );
+    int (*process_func)( void *ctx, const unsigned char *input );
 };
 
 #if defined(MBEDTLS_MD2_C)

+ 10 - 5
app/include/mbedtls/memory_buffer_alloc.h

@@ -2,7 +2,8 @@
  * \file memory_buffer_alloc.h
  *
  * \brief Buffer-based memory allocator
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -98,8 +99,10 @@ void mbedtls_memory_buffer_alloc_status( void );
 /**
  * \brief   Get the peak heap usage so far
  *
- * \param max_used      Peak number of bytes reauested by the application
- * \param max_blocks    Peak number of blocks reauested by the application
+ * \param max_used      Peak number of bytes in use or committed. This
+ *                      includes bytes in allocated blocks too small to split
+ *                      into smaller blocks but larger than the requested size.
+ * \param max_blocks    Peak number of blocks in use, including free and used
  */
 void mbedtls_memory_buffer_alloc_max_get( size_t *max_used, size_t *max_blocks );
 
@@ -111,8 +114,10 @@ void mbedtls_memory_buffer_alloc_max_reset( void );
 /**
  * \brief   Get the current heap usage
  *
- * \param cur_used      Number of bytes reauested by the application
- * \param cur_blocks    Number of blocks reauested by the application
+ * \param cur_used      Current number of bytes in use or committed. This
+ *                      includes bytes in allocated blocks too small to split
+ *                      into smaller blocks but larger than the requested size.
+ * \param cur_blocks    Current number of blocks in use, including free and used
  */
 void mbedtls_memory_buffer_alloc_cur_get( size_t *cur_used, size_t *cur_blocks );
 #endif /* MBEDTLS_MEMORY_DEBUG */

+ 11 - 204
app/include/mbedtls/net.h

@@ -1,9 +1,12 @@
 /**
  * \file net.h
  *
- * \brief Network communication functions
+ * \brief Deprecated header file that includes mbedtls/net_sockets.h
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * \deprecated Superseded by mbedtls/net_sockets.h
+ */
+/*
+ *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -20,206 +23,10 @@
  *
  *  This file is part of mbed TLS (https://tls.mbed.org)
  */
-#ifndef MBEDTLS_NET_H
-#define MBEDTLS_NET_H
-
-#if !defined(MBEDTLS_CONFIG_FILE)
-#include "config.h"
-#else
-#include MBEDTLS_CONFIG_FILE
-#endif
-
-#include "ssl.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#define MBEDTLS_ERR_NET_SOCKET_FAILED                     -0x0042  /**< Failed to open a socket. */
-#define MBEDTLS_ERR_NET_CONNECT_FAILED                    -0x0044  /**< The connection to the given server / port failed. */
-#define MBEDTLS_ERR_NET_BIND_FAILED                       -0x0046  /**< Binding of the socket failed. */
-#define MBEDTLS_ERR_NET_LISTEN_FAILED                     -0x0048  /**< Could not listen on the socket. */
-#define MBEDTLS_ERR_NET_ACCEPT_FAILED                     -0x004A  /**< Could not accept the incoming connection. */
-#define MBEDTLS_ERR_NET_RECV_FAILED                       -0x004C  /**< Reading information from the socket failed. */
-#define MBEDTLS_ERR_NET_SEND_FAILED                       -0x004E  /**< Sending information through the socket failed. */
-#define MBEDTLS_ERR_NET_CONN_RESET                        -0x0050  /**< Connection was reset by peer. */
-#define MBEDTLS_ERR_NET_UNKNOWN_HOST                      -0x0052  /**< Failed to get an IP address for the given hostname. */
-#define MBEDTLS_ERR_NET_BUFFER_TOO_SMALL                  -0x0043  /**< Buffer is too small to hold the data. */
-#define MBEDTLS_ERR_NET_INVALID_CONTEXT                   -0x0045  /**< The context is invalid, eg because it was free()ed. */
-
-#define MBEDTLS_NET_LISTEN_BACKLOG         10 /**< The backlog that listen() should use. */
-
-#define MBEDTLS_NET_PROTO_TCP 0 /**< The TCP transport protocol */
-#define MBEDTLS_NET_PROTO_UDP 1 /**< The UDP transport protocol */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Wrapper type for sockets.
- *
- * Currently backed by just a file descriptor, but might be more in the future
- * (eg two file descriptors for combined IPv4 + IPv6 support, or additional
- * structures for hand-made UDP demultiplexing).
- */
-typedef struct
-{
-    int fd;             /**< The underlying file descriptor                 */
-}
-mbedtls_net_context;
-
-/**
- * \brief          Initialize a context
- *                 Just makes the context ready to be used or freed safely.
- *
- * \param ctx      Context to initialize
- */
-void mbedtls_net_init( mbedtls_net_context *ctx );
-
-/**
- * \brief          Initiate a connection with host:port in the given protocol
- *
- * \param ctx      Socket to use
- * \param host     Host to connect to
- * \param port     Port to connect to
- * \param proto    Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP
- *
- * \return         0 if successful, or one of:
- *                      MBEDTLS_ERR_NET_SOCKET_FAILED,
- *                      MBEDTLS_ERR_NET_UNKNOWN_HOST,
- *                      MBEDTLS_ERR_NET_CONNECT_FAILED
- *
- * \note           Sets the socket in connected mode even with UDP.
- */
-int mbedtls_net_connect( mbedtls_net_context *ctx, const char *host, const char *port, int proto );
-
-/**
- * \brief          Create a receiving socket on bind_ip:port in the chosen
- *                 protocol. If bind_ip == NULL, all interfaces are bound.
- *
- * \param ctx      Socket to use
- * \param bind_ip  IP to bind to, can be NULL
- * \param port     Port number to use
- * \param proto    Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP
- *
- * \return         0 if successful, or one of:
- *                      MBEDTLS_ERR_NET_SOCKET_FAILED,
- *                      MBEDTLS_ERR_NET_BIND_FAILED,
- *                      MBEDTLS_ERR_NET_LISTEN_FAILED
- *
- * \note           Regardless of the protocol, opens the sockets and binds it.
- *                 In addition, make the socket listening if protocol is TCP.
- */
-int mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto );
-
-/**
- * \brief           Accept a connection from a remote client
- *
- * \param bind_ctx  Relevant socket
- * \param client_ctx Will contain the connected client socket
- * \param client_ip Will contain the client IP address
- * \param buf_size  Size of the client_ip buffer
- * \param ip_len    Will receive the size of the client IP written
- *
- * \return          0 if successful, or
- *                  MBEDTLS_ERR_NET_ACCEPT_FAILED, or
- *                  MBEDTLS_ERR_NET_BUFFER_TOO_SMALL if buf_size is too small,
- *                  MBEDTLS_ERR_SSL_WANT_READ if bind_fd was set to
- *                  non-blocking and accept() would block.
- */
-int mbedtls_net_accept( mbedtls_net_context *bind_ctx,
-                        mbedtls_net_context *client_ctx,
-                        void *client_ip, size_t buf_size, size_t *ip_len );
-
-/**
- * \brief          Set the socket blocking
- *
- * \param ctx      Socket to set
- *
- * \return         0 if successful, or a non-zero error code
- */
-int mbedtls_net_set_block( mbedtls_net_context *ctx );
-
-/**
- * \brief          Set the socket non-blocking
- *
- * \param ctx      Socket to set
- *
- * \return         0 if successful, or a non-zero error code
- */
-int mbedtls_net_set_nonblock( mbedtls_net_context *ctx );
-
-/**
- * \brief          Portable usleep helper
- *
- * \param usec     Amount of microseconds to sleep
- *
- * \note           Real amount of time slept will not be less than
- *                 select()'s timeout granularity (typically, 10ms).
- */
-void mbedtls_net_usleep( unsigned long usec );
-
-/**
- * \brief          Read at most 'len' characters. If no error occurs,
- *                 the actual amount read is returned.
- *
- * \param ctx      Socket
- * \param buf      The buffer to write to
- * \param len      Maximum length of the buffer
- *
- * \return         the number of bytes received,
- *                 or a non-zero error code; with a non-blocking socket,
- *                 MBEDTLS_ERR_SSL_WANT_READ indicates read() would block.
- */
-int mbedtls_net_recv( void *ctx, unsigned char *buf, size_t len );
-
-/**
- * \brief          Write at most 'len' characters. If no error occurs,
- *                 the actual amount read is returned.
- *
- * \param ctx      Socket
- * \param buf      The buffer to read from
- * \param len      The length of the buffer
- *
- * \return         the number of bytes sent,
- *                 or a non-zero error code; with a non-blocking socket,
- *                 MBEDTLS_ERR_SSL_WANT_WRITE indicates write() would block.
- */
-int mbedtls_net_send( void *ctx, const unsigned char *buf, size_t len );
-
-/**
- * \brief          Read at most 'len' characters, blocking for at most
- *                 'timeout' seconds. If no error occurs, the actual amount
- *                 read is returned.
- *
- * \param ctx      Socket
- * \param buf      The buffer to write to
- * \param len      Maximum length of the buffer
- * \param timeout  Maximum number of milliseconds to wait for data
- *                 0 means no timeout (wait forever)
- *
- * \return         the number of bytes received,
- *                 or a non-zero error code:
- *                 MBEDTLS_ERR_SSL_TIMEOUT if the operation timed out,
- *                 MBEDTLS_ERR_SSL_WANT_READ if interrupted by a signal.
- *
- * \note           This function will block (until data becomes available or
- *                 timeout is reached) even if the socket is set to
- *                 non-blocking. Handling timeouts with non-blocking reads
- *                 requires a different strategy.
- */
-int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf, size_t len,
-                      uint32_t timeout );
-
-/**
- * \brief          Gracefully shutdown the connection and free associated data
- *
- * \param ctx      The context to free
- */
-void mbedtls_net_free( mbedtls_net_context *ctx );
-
-#ifdef __cplusplus
-}
-#endif
 
-#endif /* net.h */
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#include "mbedtls/net_sockets.h"
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#warning "Deprecated header file: Superseded by mbedtls/net_sockets.h"
+#endif /* MBEDTLS_DEPRECATED_WARNING */
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */

+ 226 - 0
app/include/mbedtls/net_sockets.h

@@ -0,0 +1,226 @@
+/**
+ * \file net_sockets.h
+ *
+ * \brief Network communication functions
+ */
+/*
+ *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ *  SPDX-License-Identifier: Apache-2.0
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License"); you may
+ *  not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ *  This file is part of mbed TLS (https://tls.mbed.org)
+ */
+#ifndef MBEDTLS_NET_SOCKETS_H
+#define MBEDTLS_NET_SOCKETS_H
+
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
+#include "ssl.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+#define MBEDTLS_ERR_NET_SOCKET_FAILED                     -0x0042  /**< Failed to open a socket. */
+#define MBEDTLS_ERR_NET_CONNECT_FAILED                    -0x0044  /**< The connection to the given server / port failed. */
+#define MBEDTLS_ERR_NET_BIND_FAILED                       -0x0046  /**< Binding of the socket failed. */
+#define MBEDTLS_ERR_NET_LISTEN_FAILED                     -0x0048  /**< Could not listen on the socket. */
+#define MBEDTLS_ERR_NET_ACCEPT_FAILED                     -0x004A  /**< Could not accept the incoming connection. */
+#define MBEDTLS_ERR_NET_RECV_FAILED                       -0x004C  /**< Reading information from the socket failed. */
+#define MBEDTLS_ERR_NET_SEND_FAILED                       -0x004E  /**< Sending information through the socket failed. */
+#define MBEDTLS_ERR_NET_CONN_RESET                        -0x0050  /**< Connection was reset by peer. */
+#define MBEDTLS_ERR_NET_UNKNOWN_HOST                      -0x0052  /**< Failed to get an IP address for the given hostname. */
+#define MBEDTLS_ERR_NET_BUFFER_TOO_SMALL                  -0x0043  /**< Buffer is too small to hold the data. */
+#define MBEDTLS_ERR_NET_INVALID_CONTEXT                   -0x0045  /**< The context is invalid, eg because it was free()ed. */
+
+#define MBEDTLS_NET_LISTEN_BACKLOG         10 /**< The backlog that listen() should use. */
+
+#define MBEDTLS_NET_PROTO_TCP 0 /**< The TCP transport protocol */
+#define MBEDTLS_NET_PROTO_UDP 1 /**< The UDP transport protocol */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Wrapper type for sockets.
+ *
+ * Currently backed by just a file descriptor, but might be more in the future
+ * (eg two file descriptors for combined IPv4 + IPv6 support, or additional
+ * structures for hand-made UDP demultiplexing).
+ */
+typedef struct
+{
+    int fd;             /**< The underlying file descriptor                 */
+}
+mbedtls_net_context;
+
+/**
+ * \brief          Initialize a context
+ *                 Just makes the context ready to be used or freed safely.
+ *
+ * \param ctx      Context to initialize
+ */
+void mbedtls_net_init( mbedtls_net_context *ctx );
+
+/**
+ * \brief          Initiate a connection with host:port in the given protocol
+ *
+ * \param ctx      Socket to use
+ * \param host     Host to connect to
+ * \param port     Port to connect to
+ * \param proto    Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP
+ *
+ * \return         0 if successful, or one of:
+ *                      MBEDTLS_ERR_NET_SOCKET_FAILED,
+ *                      MBEDTLS_ERR_NET_UNKNOWN_HOST,
+ *                      MBEDTLS_ERR_NET_CONNECT_FAILED
+ *
+ * \note           Sets the socket in connected mode even with UDP.
+ */
+int mbedtls_net_connect( mbedtls_net_context *ctx, const char *host, const char *port, int proto );
+
+/**
+ * \brief          Create a receiving socket on bind_ip:port in the chosen
+ *                 protocol. If bind_ip == NULL, all interfaces are bound.
+ *
+ * \param ctx      Socket to use
+ * \param bind_ip  IP to bind to, can be NULL
+ * \param port     Port number to use
+ * \param proto    Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP
+ *
+ * \return         0 if successful, or one of:
+ *                      MBEDTLS_ERR_NET_SOCKET_FAILED,
+ *                      MBEDTLS_ERR_NET_BIND_FAILED,
+ *                      MBEDTLS_ERR_NET_LISTEN_FAILED
+ *
+ * \note           Regardless of the protocol, opens the sockets and binds it.
+ *                 In addition, make the socket listening if protocol is TCP.
+ */
+int mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto );
+
+/**
+ * \brief           Accept a connection from a remote client
+ *
+ * \param bind_ctx  Relevant socket
+ * \param client_ctx Will contain the connected client socket
+ * \param client_ip Will contain the client IP address
+ * \param buf_size  Size of the client_ip buffer
+ * \param ip_len    Will receive the size of the client IP written
+ *
+ * \return          0 if successful, or
+ *                  MBEDTLS_ERR_NET_ACCEPT_FAILED, or
+ *                  MBEDTLS_ERR_NET_BUFFER_TOO_SMALL if buf_size is too small,
+ *                  MBEDTLS_ERR_SSL_WANT_READ if bind_fd was set to
+ *                  non-blocking and accept() would block.
+ */
+int mbedtls_net_accept( mbedtls_net_context *bind_ctx,
+                        mbedtls_net_context *client_ctx,
+                        void *client_ip, size_t buf_size, size_t *ip_len );
+
+/**
+ * \brief          Set the socket blocking
+ *
+ * \param ctx      Socket to set
+ *
+ * \return         0 if successful, or a non-zero error code
+ */
+int mbedtls_net_set_block( mbedtls_net_context *ctx );
+
+/**
+ * \brief          Set the socket non-blocking
+ *
+ * \param ctx      Socket to set
+ *
+ * \return         0 if successful, or a non-zero error code
+ */
+int mbedtls_net_set_nonblock( mbedtls_net_context *ctx );
+
+/**
+ * \brief          Portable usleep helper
+ *
+ * \param usec     Amount of microseconds to sleep
+ *
+ * \note           Real amount of time slept will not be less than
+ *                 select()'s timeout granularity (typically, 10ms).
+ */
+void mbedtls_net_usleep( unsigned long usec );
+
+/**
+ * \brief          Read at most 'len' characters. If no error occurs,
+ *                 the actual amount read is returned.
+ *
+ * \param ctx      Socket
+ * \param buf      The buffer to write to
+ * \param len      Maximum length of the buffer
+ *
+ * \return         the number of bytes received,
+ *                 or a non-zero error code; with a non-blocking socket,
+ *                 MBEDTLS_ERR_SSL_WANT_READ indicates read() would block.
+ */
+int mbedtls_net_recv( void *ctx, unsigned char *buf, size_t len );
+
+/**
+ * \brief          Write at most 'len' characters. If no error occurs,
+ *                 the actual amount read is returned.
+ *
+ * \param ctx      Socket
+ * \param buf      The buffer to read from
+ * \param len      The length of the buffer
+ *
+ * \return         the number of bytes sent,
+ *                 or a non-zero error code; with a non-blocking socket,
+ *                 MBEDTLS_ERR_SSL_WANT_WRITE indicates write() would block.
+ */
+int mbedtls_net_send( void *ctx, const unsigned char *buf, size_t len );
+
+/**
+ * \brief          Read at most 'len' characters, blocking for at most
+ *                 'timeout' seconds. If no error occurs, the actual amount
+ *                 read is returned.
+ *
+ * \param ctx      Socket
+ * \param buf      The buffer to write to
+ * \param len      Maximum length of the buffer
+ * \param timeout  Maximum number of milliseconds to wait for data
+ *                 0 means no timeout (wait forever)
+ *
+ * \return         the number of bytes received,
+ *                 or a non-zero error code:
+ *                 MBEDTLS_ERR_SSL_TIMEOUT if the operation timed out,
+ *                 MBEDTLS_ERR_SSL_WANT_READ if interrupted by a signal.
+ *
+ * \note           This function will block (until data becomes available or
+ *                 timeout is reached) even if the socket is set to
+ *                 non-blocking. Handling timeouts with non-blocking reads
+ *                 requires a different strategy.
+ */
+int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf, size_t len,
+                      uint32_t timeout );
+
+/**
+ * \brief          Gracefully shutdown the connection and free associated data
+ *
+ * \param ctx      The context to free
+ */
+void mbedtls_net_free( mbedtls_net_context *ctx );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* net_sockets.h */

+ 2 - 1
app/include/mbedtls/oid.h

@@ -2,7 +2,8 @@
  * \file oid.h
  *
  * \brief Object Identifier (OID) database
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 2 - 1
app/include/mbedtls/padlock.h

@@ -3,7 +3,8 @@
  *
  * \brief VIA PadLock ACE for HW encryption/decryption supported by some
  *        processors
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 2 - 1
app/include/mbedtls/pem.h

@@ -2,7 +2,8 @@
  * \file pem.h
  *
  * \brief Privacy Enhanced Mail (PEM) decoding
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 7 - 4
app/include/mbedtls/pk.h

@@ -2,7 +2,8 @@
  * \file pk.h
  *
  * \brief Public Key abstraction layer
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -63,6 +64,7 @@
 #define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00  /**< Elliptic curve is unsupported (only NIST curves are supported). */
 #define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980  /**< Unavailable feature, e.g. RSA disabled for RSA key. */
 #define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH    -0x3900  /**< The signature is valid but its length is less than expected. */
+#define MBEDTLS_ERR_PK_HW_ACCEL_FAILED     -0x3880  /**< PK hardware accelerator failed. */
 
 #ifdef __cplusplus
 extern "C" {
@@ -496,11 +498,12 @@ int mbedtls_pk_parse_keyfile( mbedtls_pk_context *ctx,
  * \brief           Load and parse a public key
  *
  * \param ctx       key to be initialized
- * \param path      filename to read the private key from
+ * \param path      filename to read the public key from
  *
  * \note            On entry, ctx must be empty, either freshly initialised
- *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
- *                  specific key type, check the result with mbedtls_pk_can_do().
+ *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If
+ *                  you need a specific key type, check the result with
+ *                  mbedtls_pk_can_do().
  *
  * \note            The key is also checked for correctness.
  *

+ 3 - 2
app/include/mbedtls/pk_internal.h

@@ -1,8 +1,9 @@
 /**
- * \file pk.h
+ * \file pk_internal.h
  *
  * \brief Public Key abstraction layer: wrapper functions
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 2 - 1
app/include/mbedtls/pkcs11.h

@@ -4,7 +4,8 @@
  * \brief Wrapper for PKCS#11 library libpkcs11-helper
  *
  * \author Adriaan de Jong <dejong@fox-it.com>
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 2 - 1
app/include/mbedtls/pkcs12.h

@@ -2,7 +2,8 @@
  * \file pkcs12.h
  *
  * \brief PKCS#12 Personal Information Exchange Syntax
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 2 - 1
app/include/mbedtls/pkcs5.h

@@ -4,7 +4,8 @@
  * \brief PKCS#5 functions
  *
  * \author Mathias Olsson <mathias@kompetensum.com>
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 168 - 35
app/include/mbedtls/platform.h

@@ -1,9 +1,10 @@
 /**
  * \file platform.h
  *
- * \brief mbed TLS Platform abstraction layer
- *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * \brief The Mbed TLS platform abstraction layer.
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,7 +19,7 @@
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *
- *  This file is part of mbed TLS (https://tls.mbed.org)
+ *  This file is part of Mbed TLS (https://tls.mbed.org)
  */
 #ifndef MBEDTLS_PLATFORM_H
 #define MBEDTLS_PLATFORM_H
@@ -29,6 +30,10 @@
 #include MBEDTLS_CONFIG_FILE
 #endif
 
+#if defined(MBEDTLS_HAVE_TIME)
+#include "mbedtls/platform_time.h"
+#endif
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -40,41 +45,60 @@ extern "C" {
  * Either change them in config.h or define them on the compiler command line.
  * \{
  */
-extern int ets_snprintf(char *buf, unsigned int size, const char *format, ...);
-extern void *pvPortCalloc(unsigned int count, unsigned int size);
-extern void vPortFree( void *pv );
-#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS
+
 #if !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS)
 #include <stdio.h>
 #include <stdlib.h>
+#include <time.h>
 #if !defined(MBEDTLS_PLATFORM_STD_SNPRINTF)
 #if defined(_WIN32)
-#define MBEDTLS_PLATFORM_STD_SNPRINTF   mbedtls_platform_win32_snprintf /**< Default snprintf to use  */
+#define MBEDTLS_PLATFORM_STD_SNPRINTF   mbedtls_platform_win32_snprintf /**< The default \c snprintf function to use.  */
 #else
-#define MBEDTLS_PLATFORM_STD_SNPRINTF   ets_snprintf /**< Default snprintf to use  */
+#define MBEDTLS_PLATFORM_STD_SNPRINTF   snprintf /**< The default \c snprintf function to use.  */
 #endif
 #endif
 #if !defined(MBEDTLS_PLATFORM_STD_PRINTF)
-#define MBEDTLS_PLATFORM_STD_PRINTF   printf /**< Default printf to use  */
+#define MBEDTLS_PLATFORM_STD_PRINTF   printf /**< The default \c printf function to use. */
 #endif
 #if !defined(MBEDTLS_PLATFORM_STD_FPRINTF)
-#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< Default fprintf to use */
+#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< The default \c fprintf function to use. */
 #endif
 #if !defined(MBEDTLS_PLATFORM_STD_CALLOC)
-#define MBEDTLS_PLATFORM_STD_CALLOC   pvPortCalloc /**< Default allocator to use */
+#define MBEDTLS_PLATFORM_STD_CALLOC   calloc /**< The default \c calloc function to use. */
 #endif
 #if !defined(MBEDTLS_PLATFORM_STD_FREE)
-#define MBEDTLS_PLATFORM_STD_FREE       vPortFree /**< Default free to use */
+#define MBEDTLS_PLATFORM_STD_FREE       free /**< The default \c free function to use. */
 #endif
 #if !defined(MBEDTLS_PLATFORM_STD_EXIT)
-#define MBEDTLS_PLATFORM_STD_EXIT      exit /**< Default free to use */
+#define MBEDTLS_PLATFORM_STD_EXIT      exit /**< The default \c exit function to use. */
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_TIME)
+#define MBEDTLS_PLATFORM_STD_TIME       time    /**< The default \c time function to use. */
 #endif
+#if !defined(MBEDTLS_PLATFORM_STD_EXIT_SUCCESS)
+#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS  EXIT_SUCCESS /**< The default exit value to use. */
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_EXIT_FAILURE)
+#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE  EXIT_FAILURE /**< The default exit value to use. */
+#endif
+#if defined(MBEDTLS_FS_IO)
+#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ)
+#define MBEDTLS_PLATFORM_STD_NV_SEED_READ   mbedtls_platform_std_nv_seed_read
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE)
+#define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE  mbedtls_platform_std_nv_seed_write
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_FILE)
+#define MBEDTLS_PLATFORM_STD_NV_SEED_FILE   "seedfile"
+#endif
+#endif /* MBEDTLS_FS_IO */
 #else /* MBEDTLS_PLATFORM_NO_STD_FUNCTIONS */
 #if defined(MBEDTLS_PLATFORM_STD_MEM_HDR)
 #include MBEDTLS_PLATFORM_STD_MEM_HDR
 #endif
 #endif /* MBEDTLS_PLATFORM_NO_STD_FUNCTIONS */
 
+
 /* \} name SECTION: Module settings */
 
 /*
@@ -92,19 +116,19 @@ extern void * (*mbedtls_calloc)( size_t n, size_t size );
 extern void (*mbedtls_free)( void *ptr );
 
 /**
- * \brief   Set your own memory implementation function pointers
+ * \brief   This function allows configuring custom memory-management functions.
  *
- * \param calloc_func   the calloc function implementation
- * \param free_func     the free function implementation
+ * \param calloc_func   The \c calloc function implementation.
+ * \param free_func     The \c free function implementation.
  *
- * \return              0 if successful
+ * \return              \c 0.
  */
 int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),
                               void (*free_func)( void * ) );
 #endif /* MBEDTLS_PLATFORM_FREE_MACRO && MBEDTLS_PLATFORM_CALLOC_MACRO */
 #else /* !MBEDTLS_PLATFORM_MEMORY */
-#define mbedtls_free       vPortFree
-#define mbedtls_calloc     pvPortCalloc
+#define mbedtls_free       free
+#define mbedtls_calloc     calloc
 #endif /* MBEDTLS_PLATFORM_MEMORY && !MBEDTLS_PLATFORM_{FREE,CALLOC}_MACRO */
 
 /*
@@ -116,11 +140,11 @@ int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),
 extern int (*mbedtls_fprintf)( FILE *stream, const char *format, ... );
 
 /**
- * \brief   Set your own fprintf function pointer
+ * \brief   This function allows configuring a custom \p fprintf function pointer.
  *
- * \param fprintf_func   the fprintf function implementation
+ * \param fprintf_func   The \c fprintf function implementation.
  *
- * \return              0
+ * \return               \c 0.
  */
 int mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *stream, const char *,
                                                ... ) );
@@ -139,18 +163,19 @@ int mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *stream, const char
 extern int (*mbedtls_printf)( const char *format, ... );
 
 /**
- * \brief   Set your own printf function pointer
+ * \brief    This function allows configuring a custom \c printf function
+ *           pointer.
  *
- * \param printf_func   the printf function implementation
+ * \param printf_func   The \c printf function implementation.
  *
- * \return              0
+ * \return              \c 0 on success.
  */
 int mbedtls_platform_set_printf( int (*printf_func)( const char *, ... ) );
 #else /* !MBEDTLS_PLATFORM_PRINTF_ALT */
 #if defined(MBEDTLS_PLATFORM_PRINTF_MACRO)
 #define mbedtls_printf     MBEDTLS_PLATFORM_PRINTF_MACRO
 #else
-#define mbedtls_printf     os_printf
+#define mbedtls_printf     printf
 #endif /* MBEDTLS_PLATFORM_PRINTF_MACRO */
 #endif /* MBEDTLS_PLATFORM_PRINTF_ALT */
 
@@ -172,19 +197,22 @@ int mbedtls_platform_win32_snprintf( char *s, size_t n, const char *fmt, ... );
 extern int (*mbedtls_snprintf)( char * s, size_t n, const char * format, ... );
 
 /**
- * \brief   Set your own snprintf function pointer
+ * \brief   This function allows configuring a custom \c snprintf function
+ *          pointer.
  *
- * \param snprintf_func   the snprintf function implementation
+ * \param snprintf_func   The \c snprintf function implementation.
  *
- * \return              0
+ * \return    \c 0 on success.
  */
 int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n,
                                                  const char * format, ... ) );
 #else /* MBEDTLS_PLATFORM_SNPRINTF_ALT */
 #if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO)
 #define mbedtls_snprintf   MBEDTLS_PLATFORM_SNPRINTF_MACRO
+#define mbedtls_vsnprintf  MBEDTLS_PLATFORM_VSNPRINTF_MACRO
 #else
-#define mbedtls_snprintf   ets_snprintf
+#define mbedtls_snprintf   snprintf
+#define mbedtls_vsnprintf  vsnprintf
 #endif /* MBEDTLS_PLATFORM_SNPRINTF_MACRO */
 #endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */
 
@@ -195,11 +223,12 @@ int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n,
 extern void (*mbedtls_exit)( int status );
 
 /**
- * \brief   Set your own exit function pointer
+ * \brief   This function allows configuring a custom \c exit function
+ *          pointer.
  *
- * \param exit_func   the exit function implementation
+ * \param exit_func   The \c exit function implementation.
  *
- * \return              0
+ * \return  \c 0 on success.
  */
 int mbedtls_platform_set_exit( void (*exit_func)( int status ) );
 #else
@@ -210,6 +239,110 @@ int mbedtls_platform_set_exit( void (*exit_func)( int status ) );
 #endif /* MBEDTLS_PLATFORM_EXIT_MACRO */
 #endif /* MBEDTLS_PLATFORM_EXIT_ALT */
 
+/*
+ * The default exit values
+ */
+#if defined(MBEDTLS_PLATFORM_STD_EXIT_SUCCESS)
+#define MBEDTLS_EXIT_SUCCESS MBEDTLS_PLATFORM_STD_EXIT_SUCCESS
+#else
+#define MBEDTLS_EXIT_SUCCESS 0
+#endif
+#if defined(MBEDTLS_PLATFORM_STD_EXIT_FAILURE)
+#define MBEDTLS_EXIT_FAILURE MBEDTLS_PLATFORM_STD_EXIT_FAILURE
+#else
+#define MBEDTLS_EXIT_FAILURE 1
+#endif
+
+/*
+ * The function pointers for reading from and writing a seed file to
+ * Non-Volatile storage (NV) in a platform-independent way
+ *
+ * Only enabled when the NV seed entropy source is enabled
+ */
+#if defined(MBEDTLS_ENTROPY_NV_SEED)
+#if !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS) && defined(MBEDTLS_FS_IO)
+/* Internal standard platform definitions */
+int mbedtls_platform_std_nv_seed_read( unsigned char *buf, size_t buf_len );
+int mbedtls_platform_std_nv_seed_write( unsigned char *buf, size_t buf_len );
+#endif
+
+#if defined(MBEDTLS_PLATFORM_NV_SEED_ALT)
+extern int (*mbedtls_nv_seed_read)( unsigned char *buf, size_t buf_len );
+extern int (*mbedtls_nv_seed_write)( unsigned char *buf, size_t buf_len );
+
+/**
+ * \brief   This function allows configuring custom seed file writing and
+ *          reading functions.
+ *
+ * \param   nv_seed_read_func   The seed reading function implementation.
+ * \param   nv_seed_write_func  The seed writing function implementation.
+ *
+ * \return  \c 0 on success.
+ */
+int mbedtls_platform_set_nv_seed(
+            int (*nv_seed_read_func)( unsigned char *buf, size_t buf_len ),
+            int (*nv_seed_write_func)( unsigned char *buf, size_t buf_len )
+            );
+#else
+#if defined(MBEDTLS_PLATFORM_NV_SEED_READ_MACRO) && \
+    defined(MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO)
+#define mbedtls_nv_seed_read    MBEDTLS_PLATFORM_NV_SEED_READ_MACRO
+#define mbedtls_nv_seed_write   MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO
+#else
+#define mbedtls_nv_seed_read    mbedtls_platform_std_nv_seed_read
+#define mbedtls_nv_seed_write   mbedtls_platform_std_nv_seed_write
+#endif
+#endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */
+#endif /* MBEDTLS_ENTROPY_NV_SEED */
+
+#if !defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT)
+
+/**
+ * \brief   The platform context structure.
+ *
+ * \note    This structure may be used to assist platform-specific
+ *          setup or teardown operations.
+ */
+typedef struct {
+    char dummy; /**< Placeholder member, as empty structs are not portable. */
+}
+mbedtls_platform_context;
+
+#else
+#include "platform_alt.h"
+#endif /* !MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */
+
+/**
+ * \brief   This function performs any platform initialization operations.
+ *
+ * \param   ctx     The Mbed TLS context.
+ *
+ * \return  \c 0 on success.
+ *
+ * \note    This function is intended to allow platform-specific initialization,
+ *          and should be called before any other library functions. Its
+ *          implementation is platform-specific, and unless
+ *          platform-specific code is provided, it does nothing.
+ *
+ *          Its use and whether it is necessary to call it is dependent on the
+ *          platform.
+ */
+int mbedtls_platform_setup( mbedtls_platform_context *ctx );
+/**
+ * \brief   This function performs any platform teardown operations.
+ *
+ * \param   ctx     The Mbed TLS context.
+ *
+ * \note    This function should be called after every other Mbed TLS module
+ *          has been correctly freed using the appropriate free function.
+ *          Its implementation is platform-specific, and unless
+ *          platform-specific code is provided, it does nothing.
+ *
+ *          Its use and whether it is necessary to call it is dependent on the
+ *          platform.
+ */
+void mbedtls_platform_teardown( mbedtls_platform_context *ctx );
+
 #ifdef __cplusplus
 }
 #endif

+ 82 - 0
app/include/mbedtls/platform_time.h

@@ -0,0 +1,82 @@
+/**
+ * \file platform_time.h
+ *
+ * \brief mbed TLS Platform time abstraction
+ */
+/*
+ *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
+ *  SPDX-License-Identifier: Apache-2.0
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License"); you may
+ *  not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ *  This file is part of mbed TLS (https://tls.mbed.org)
+ */
+#ifndef MBEDTLS_PLATFORM_TIME_H
+#define MBEDTLS_PLATFORM_TIME_H
+
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \name SECTION: Module settings
+ *
+ * The configuration options you can set for this module are in this section.
+ * Either change them in config.h or define them on the compiler command line.
+ * \{
+ */
+
+/*
+ * The time_t datatype
+ */
+#if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO)
+typedef MBEDTLS_PLATFORM_TIME_TYPE_MACRO mbedtls_time_t;
+#else
+/* For time_t */
+#include <time.h>
+typedef time_t mbedtls_time_t;
+#endif /* MBEDTLS_PLATFORM_TIME_TYPE_MACRO */
+
+/*
+ * The function pointers for time
+ */
+#if defined(MBEDTLS_PLATFORM_TIME_ALT)
+extern mbedtls_time_t (*mbedtls_time)( mbedtls_time_t* time );
+
+/**
+ * \brief   Set your own time function pointer
+ *
+ * \param   time_func   the time function implementation
+ *
+ * \return              0
+ */
+int mbedtls_platform_set_time( mbedtls_time_t (*time_func)( mbedtls_time_t* time ) );
+#else
+#if defined(MBEDTLS_PLATFORM_TIME_MACRO)
+#define mbedtls_time    MBEDTLS_PLATFORM_TIME_MACRO
+#else
+#define mbedtls_time   time
+#endif /* MBEDTLS_PLATFORM_TIME_MACRO */
+#endif /* MBEDTLS_PLATFORM_TIME_ALT */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* platform_time.h */

+ 134 - 12
app/include/mbedtls/ripemd160.h

@@ -2,7 +2,8 @@
  * \file ripemd160.h
  *
  * \brief RIPE MD-160 message digest
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -32,6 +33,13 @@
 #include <stddef.h>
 #include <stdint.h>
 
+#define MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED             -0x0031  /**< RIPEMD160 hardware accelerator failed */
+
+#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
+    !defined(inline) && !defined(__cplusplus)
+#define inline __inline
+#endif
+
 #if !defined(MBEDTLS_RIPEMD160_ALT)
 // Regular implementation
 //
@@ -78,36 +86,121 @@ void mbedtls_ripemd160_clone( mbedtls_ripemd160_context *dst,
  * \brief          RIPEMD-160 context setup
  *
  * \param ctx      context to be initialized
+ *
+ * \return         0 if successful
  */
-void mbedtls_ripemd160_starts( mbedtls_ripemd160_context *ctx );
+int mbedtls_ripemd160_starts_ret( mbedtls_ripemd160_context *ctx );
 
 /**
  * \brief          RIPEMD-160 process buffer
  *
  * \param ctx      RIPEMD-160 context
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
+ *
+ * \return         0 if successful
  */
-void mbedtls_ripemd160_update( mbedtls_ripemd160_context *ctx,
-                       const unsigned char *input, size_t ilen );
+int mbedtls_ripemd160_update_ret( mbedtls_ripemd160_context *ctx,
+                                  const unsigned char *input,
+                                  size_t ilen );
 
 /**
  * \brief          RIPEMD-160 final digest
  *
  * \param ctx      RIPEMD-160 context
  * \param output   RIPEMD-160 checksum result
+ *
+ * \return         0 if successful
+ */
+int mbedtls_ripemd160_finish_ret( mbedtls_ripemd160_context *ctx,
+                                  unsigned char output[20] );
+
+/**
+ * \brief          RIPEMD-160 process data block (internal use only)
+ *
+ * \param ctx      RIPEMD-160 context
+ * \param data     buffer holding one block of data
+ *
+ * \return         0 if successful
+ */
+int mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx,
+                                        const unsigned char data[64] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          RIPEMD-160 context setup
+ *
+ * \deprecated     Superseded by mbedtls_ripemd160_starts_ret() in 2.7.0
+ *
+ * \param ctx      context to be initialized
  */
-void mbedtls_ripemd160_finish( mbedtls_ripemd160_context *ctx, unsigned char output[20] );
+MBEDTLS_DEPRECATED static inline void mbedtls_ripemd160_starts(
+                                            mbedtls_ripemd160_context *ctx )
+{
+    mbedtls_ripemd160_starts_ret( ctx );
+}
 
-/* Internal use */
-void mbedtls_ripemd160_process( mbedtls_ripemd160_context *ctx, const unsigned char data[64] );
+/**
+ * \brief          RIPEMD-160 process buffer
+ *
+ * \deprecated     Superseded by mbedtls_ripemd160_update_ret() in 2.7.0
+ *
+ * \param ctx      RIPEMD-160 context
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ */
+MBEDTLS_DEPRECATED static inline void mbedtls_ripemd160_update(
+                                                mbedtls_ripemd160_context *ctx,
+                                                const unsigned char *input,
+                                                size_t ilen )
+{
+    mbedtls_ripemd160_update_ret( ctx, input, ilen );
+}
+
+/**
+ * \brief          RIPEMD-160 final digest
+ *
+ * \deprecated     Superseded by mbedtls_ripemd160_finish_ret() in 2.7.0
+ *
+ * \param ctx      RIPEMD-160 context
+ * \param output   RIPEMD-160 checksum result
+ */
+MBEDTLS_DEPRECATED static inline void mbedtls_ripemd160_finish(
+                                                mbedtls_ripemd160_context *ctx,
+                                                unsigned char output[20] )
+{
+    mbedtls_ripemd160_finish_ret( ctx, output );
+}
+
+/**
+ * \brief          RIPEMD-160 process data block (internal use only)
+ *
+ * \deprecated     Superseded by mbedtls_internal_ripemd160_process() in 2.7.0
+ *
+ * \param ctx      RIPEMD-160 context
+ * \param data     buffer holding one block of data
+ */
+MBEDTLS_DEPRECATED static inline void mbedtls_ripemd160_process(
+                                            mbedtls_ripemd160_context *ctx,
+                                            const unsigned char data[64] )
+{
+    mbedtls_internal_ripemd160_process( ctx, data );
+}
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 #ifdef __cplusplus
 }
 #endif
 
 #else  /* MBEDTLS_RIPEMD160_ALT */
-#include "ripemd160.h"
+#include "ripemd160_alt.h"
 #endif /* MBEDTLS_RIPEMD160_ALT */
 
 #ifdef __cplusplus
@@ -117,12 +210,41 @@ extern "C" {
 /**
  * \brief          Output = RIPEMD-160( input buffer )
  *
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ * \param output   RIPEMD-160 checksum result
+ *
+ * \return         0 if successful
+ */
+int mbedtls_ripemd160_ret( const unsigned char *input,
+                           size_t ilen,
+                           unsigned char output[20] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          Output = RIPEMD-160( input buffer )
+ *
+ * \deprecated     Superseded by mbedtls_ripemd160_ret() in 2.7.0
+ *
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
  * \param output   RIPEMD-160 checksum result
  */
-void mbedtls_ripemd160( const unsigned char *input, size_t ilen,
-                unsigned char output[20] );
+MBEDTLS_DEPRECATED static inline void mbedtls_ripemd160(
+                                                    const unsigned char *input,
+                                                    size_t ilen,
+                                                    unsigned char output[20] )
+{
+    mbedtls_ripemd160_ret( input, ilen, output );
+}
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 /**
  * \brief          Checkup routine

File diff suppressed because it is too large
+ 632 - 229
app/include/mbedtls/rsa.h


+ 216 - 0
app/include/mbedtls/rsa_internal.h

@@ -0,0 +1,216 @@
+/**
+ * \file rsa_internal.h
+ *
+ * \brief Context-independent RSA helper functions
+ */
+/*
+ *  Copyright (C) 2006-2017, ARM Limited, All Rights Reserved
+ *  SPDX-License-Identifier: Apache-2.0
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License"); you may
+ *  not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ *  This file is part of mbed TLS (https://tls.mbed.org)
+ *
+ *
+ *  This file declares some RSA-related helper functions useful when
+ *  implementing the RSA interface. They are public and provided in a
+ *  separate compilation unit in order to make it easy for designers of
+ *  alternative RSA implementations to use them in their code, as it is
+ *  conceived that the functionality they provide will be necessary
+ *  for most complete implementations.
+ *
+ *  End-users of Mbed TLS not intending to re-implement the RSA functionality
+ *  are not expected to get into the need of making use of these functions directly,
+ *  but instead should be able to use the functions declared in rsa.h.
+ *
+ *  There are two classes of helper functions:
+ *  (1) Parameter-generating helpers. These are:
+ *      - mbedtls_rsa_deduce_primes
+ *      - mbedtls_rsa_deduce_private_exponent
+ *      - mbedtls_rsa_deduce_crt
+ *       Each of these functions takes a set of core RSA parameters
+ *       and generates some other, or CRT related parameters.
+ *  (2) Parameter-checking helpers. These are:
+ *      - mbedtls_rsa_validate_params
+ *      - mbedtls_rsa_validate_crt
+ *      They take a set of core or CRT related RSA parameters
+ *      and check their validity.
+ *
+ */
+
+#ifndef MBEDTLS_RSA_INTERNAL_H
+#define MBEDTLS_RSA_INTERNAL_H
+
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
+#include "bignum.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/**
+ * \brief          Compute RSA prime moduli P, Q from public modulus N=PQ
+ *                 and a pair of private and public key.
+ *
+ * \note           This is a 'static' helper function not operating on
+ *                 an RSA context. Alternative implementations need not
+ *                 overwrite it.
+ *
+ * \param N        RSA modulus N = PQ, with P, Q to be found
+ * \param E        RSA public exponent
+ * \param D        RSA private exponent
+ * \param P        Pointer to MPI holding first prime factor of N on success
+ * \param Q        Pointer to MPI holding second prime factor of N on success
+ *
+ * \return
+ *                 - 0 if successful. In this case, P and Q constitute a
+ *                   factorization of N.
+ *                 - A non-zero error code otherwise.
+ *
+ * \note           It is neither checked that P, Q are prime nor that
+ *                 D, E are modular inverses wrt. P-1 and Q-1. For that,
+ *                 use the helper function \c mbedtls_rsa_validate_params.
+ *
+ */
+int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N, mbedtls_mpi const *E,
+                               mbedtls_mpi const *D,
+                               mbedtls_mpi *P, mbedtls_mpi *Q );
+
+/**
+ * \brief          Compute RSA private exponent from
+ *                 prime moduli and public key.
+ *
+ * \note           This is a 'static' helper function not operating on
+ *                 an RSA context. Alternative implementations need not
+ *                 overwrite it.
+ *
+ * \param P        First prime factor of RSA modulus
+ * \param Q        Second prime factor of RSA modulus
+ * \param E        RSA public exponent
+ * \param D        Pointer to MPI holding the private exponent on success.
+ *
+ * \return
+ *                 - 0 if successful. In this case, D is set to a simultaneous
+ *                   modular inverse of E modulo both P-1 and Q-1.
+ *                 - A non-zero error code otherwise.
+ *
+ * \note           This function does not check whether P and Q are primes.
+ *
+ */
+int mbedtls_rsa_deduce_private_exponent( mbedtls_mpi const *P,
+                                         mbedtls_mpi const *Q,
+                                         mbedtls_mpi const *E,
+                                         mbedtls_mpi *D );
+
+
+/**
+ * \brief          Generate RSA-CRT parameters
+ *
+ * \note           This is a 'static' helper function not operating on
+ *                 an RSA context. Alternative implementations need not
+ *                 overwrite it.
+ *
+ * \param P        First prime factor of N
+ * \param Q        Second prime factor of N
+ * \param D        RSA private exponent
+ * \param DP       Output variable for D modulo P-1
+ * \param DQ       Output variable for D modulo Q-1
+ * \param QP       Output variable for the modular inverse of Q modulo P.
+ *
+ * \return         0 on success, non-zero error code otherwise.
+ *
+ * \note           This function does not check whether P, Q are
+ *                 prime and whether D is a valid private exponent.
+ *
+ */
+int mbedtls_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,
+                            const mbedtls_mpi *D, mbedtls_mpi *DP,
+                            mbedtls_mpi *DQ, mbedtls_mpi *QP );
+
+
+/**
+ * \brief          Check validity of core RSA parameters
+ *
+ * \note           This is a 'static' helper function not operating on
+ *                 an RSA context. Alternative implementations need not
+ *                 overwrite it.
+ *
+ * \param N        RSA modulus N = PQ
+ * \param P        First prime factor of N
+ * \param Q        Second prime factor of N
+ * \param D        RSA private exponent
+ * \param E        RSA public exponent
+ * \param f_rng    PRNG to be used for primality check, or NULL
+ * \param p_rng    PRNG context for f_rng, or NULL
+ *
+ * \return
+ *                 - 0 if the following conditions are satisfied
+ *                   if all relevant parameters are provided:
+ *                    - P prime if f_rng != NULL (%)
+ *                    - Q prime if f_rng != NULL (%)
+ *                    - 1 < N = P * Q
+ *                    - 1 < D, E < N
+ *                    - D and E are modular inverses modulo P-1 and Q-1
+ *                   (%) This is only done if MBEDTLS_GENPRIME is defined.
+ *                 - A non-zero error code otherwise.
+ *
+ * \note           The function can be used with a restricted set of arguments
+ *                 to perform specific checks only. E.g., calling it with
+ *                 (-,P,-,-,-) and a PRNG amounts to a primality check for P.
+ */
+int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P,
+                                 const mbedtls_mpi *Q, const mbedtls_mpi *D,
+                                 const mbedtls_mpi *E,
+                                 int (*f_rng)(void *, unsigned char *, size_t),
+                                 void *p_rng );
+
+/**
+ * \brief          Check validity of RSA CRT parameters
+ *
+ * \note           This is a 'static' helper function not operating on
+ *                 an RSA context. Alternative implementations need not
+ *                 overwrite it.
+ *
+ * \param P        First prime factor of RSA modulus
+ * \param Q        Second prime factor of RSA modulus
+ * \param D        RSA private exponent
+ * \param DP       MPI to check for D modulo P-1
+ * \param DQ       MPI to check for D modulo P-1
+ * \param QP       MPI to check for the modular inverse of Q modulo P.
+ *
+ * \return
+ *                 - 0 if the following conditions are satisfied:
+ *                    - D = DP mod P-1 if P, D, DP != NULL
+ *                    - Q = DQ mod P-1 if P, D, DQ != NULL
+ *                    - QP = Q^-1 mod P if P, Q, QP != NULL
+ *                 - \c MBEDTLS_ERR_RSA_KEY_CHECK_FAILED if check failed,
+ *                   potentially including \c MBEDTLS_ERR_MPI_XXX if some
+ *                   MPI calculations failed.
+ *                 - \c MBEDTLS_ERR_RSA_BAD_INPUT_DATA if insufficient
+ *                   data was provided to check DP, DQ or QP.
+ *
+ * \note           The function can be used with a restricted set of arguments
+ *                 to perform specific checks only. E.g., calling it with the
+ *                 parameters (P, -, D, DP, -, -) will check DP = D mod P-1.
+ */
+int mbedtls_rsa_validate_crt( const mbedtls_mpi *P,  const mbedtls_mpi *Q,
+                              const mbedtls_mpi *D,  const mbedtls_mpi *DP,
+                              const mbedtls_mpi *DQ, const mbedtls_mpi *QP );
+
+#endif /* rsa_internal.h */

+ 241 - 31
app/include/mbedtls/sha1.h

@@ -1,9 +1,14 @@
 /**
  * \file sha1.h
  *
- * \brief SHA-1 cryptographic hash function
+ * \brief The SHA-1 cryptographic hash function.
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * \warning   SHA-1 is considered a weak message digest and its use constitutes
+ *            a security risk. We recommend considering stronger message
+ *            digests instead.
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,7 +23,7 @@
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *
- *  This file is part of mbed TLS (https://tls.mbed.org)
+ *  This file is part of Mbed TLS (https://tls.mbed.org)
  */
 #ifndef MBEDTLS_SHA1_H
 #define MBEDTLS_SHA1_H
@@ -32,6 +37,13 @@
 #include <stddef.h>
 #include <stdint.h>
 
+#define MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED                  -0x0035  /**< SHA-1 hardware accelerator failed */
+
+#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
+    !defined(inline) && !defined(__cplusplus)
+#define inline __inline
+#endif
+
 #if !defined(MBEDTLS_SHA1_ALT)
 // Regular implementation
 //
@@ -41,65 +53,213 @@ extern "C" {
 #endif
 
 /**
- * \brief          SHA-1 context structure
+ * \brief          The SHA-1 context structure.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
 typedef struct
 {
-    uint32_t total[2];          /*!< number of bytes processed  */
-    uint32_t state[5];          /*!< intermediate digest state  */
-    unsigned char buffer[64];   /*!< data block being processed */
+    uint32_t total[2];          /*!< The number of Bytes processed.  */
+    uint32_t state[5];          /*!< The intermediate digest state.  */
+    unsigned char buffer[64];   /*!< The data block being processed. */
 }
 mbedtls_sha1_context;
 
 /**
- * \brief          Initialize SHA-1 context
+ * \brief          This function initializes a SHA-1 context.
+ *
+ * \param ctx      The SHA-1 context to initialize.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
  *
- * \param ctx      SHA-1 context to be initialized
  */
 void mbedtls_sha1_init( mbedtls_sha1_context *ctx );
 
 /**
- * \brief          Clear SHA-1 context
+ * \brief          This function clears a SHA-1 context.
+ *
+ * \param ctx      The SHA-1 context to clear.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
  *
- * \param ctx      SHA-1 context to be cleared
  */
 void mbedtls_sha1_free( mbedtls_sha1_context *ctx );
 
 /**
- * \brief          Clone (the state of) a SHA-1 context
+ * \brief          This function clones the state of a SHA-1 context.
+ *
+ * \param dst      The destination context.
+ * \param src      The context to clone.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
  *
- * \param dst      The destination context
- * \param src      The context to be cloned
  */
 void mbedtls_sha1_clone( mbedtls_sha1_context *dst,
                          const mbedtls_sha1_context *src );
 
+/**
+ * \brief          This function starts a SHA-1 checksum calculation.
+ *
+ * \param ctx      The context to initialize.
+ *
+ * \return         \c 0 if successful
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_sha1_starts_ret( mbedtls_sha1_context *ctx );
+
+/**
+ * \brief          This function feeds an input buffer into an ongoing SHA-1
+ *                 checksum calculation.
+ *
+ * \param ctx      The SHA-1 context.
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
+ *
+ * \return         \c 0 if successful
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_sha1_update_ret( mbedtls_sha1_context *ctx,
+                             const unsigned char *input,
+                             size_t ilen );
+
+/**
+ * \brief          This function finishes the SHA-1 operation, and writes
+ *                 the result to the output buffer.
+ *
+ * \param ctx      The SHA-1 context.
+ * \param output   The SHA-1 checksum result.
+ *
+ * \return         \c 0 if successful
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_sha1_finish_ret( mbedtls_sha1_context *ctx,
+                             unsigned char output[20] );
+
+/**
+ * \brief          SHA-1 process data block (internal use only)
+ *
+ * \param ctx      SHA-1 context
+ * \param data     The data block being processed.
+ *
+ * \return         \c 0 if successful
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx,
+                                   const unsigned char data[64] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
 /**
  * \brief          SHA-1 context setup
  *
- * \param ctx      context to be initialized
+ * \deprecated     Superseded by mbedtls_sha1_starts_ret() in 2.7.0
+ *
+ * \param ctx      The SHA-1 context to be initialized.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_sha1_starts( mbedtls_sha1_context *ctx );
+MBEDTLS_DEPRECATED static inline void mbedtls_sha1_starts(
+                                                mbedtls_sha1_context *ctx )
+{
+    mbedtls_sha1_starts_ret( ctx );
+}
 
 /**
  * \brief          SHA-1 process buffer
  *
- * \param ctx      SHA-1 context
- * \param input    buffer holding the  data
- * \param ilen     length of the input data
+ * \deprecated     Superseded by mbedtls_sha1_update_ret() in 2.7.0
+ *
+ * \param ctx      The SHA-1 context.
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_sha1_update( mbedtls_sha1_context *ctx, const unsigned char *input, size_t ilen );
+MBEDTLS_DEPRECATED static inline void mbedtls_sha1_update(
+                                                mbedtls_sha1_context *ctx,
+                                                const unsigned char *input,
+                                                size_t ilen )
+{
+    mbedtls_sha1_update_ret( ctx, input, ilen );
+}
 
 /**
  * \brief          SHA-1 final digest
  *
- * \param ctx      SHA-1 context
- * \param output   SHA-1 checksum result
+ * \deprecated     Superseded by mbedtls_sha1_finish_ret() in 2.7.0
+ *
+ * \param ctx      The SHA-1 context.
+ * \param output   The SHA-1 checksum result.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+MBEDTLS_DEPRECATED static inline void mbedtls_sha1_finish(
+                                                mbedtls_sha1_context *ctx,
+                                                unsigned char output[20] )
+{
+    mbedtls_sha1_finish_ret( ctx, output );
+}
+
+/**
+ * \brief          SHA-1 process data block (internal use only)
+ *
+ * \deprecated     Superseded by mbedtls_internal_sha1_process() in 2.7.0
+ *
+ * \param ctx      The SHA-1 context.
+ * \param data     The data block being processed.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_sha1_finish( mbedtls_sha1_context *ctx, unsigned char output[20] );
+MBEDTLS_DEPRECATED static inline void mbedtls_sha1_process(
+                                                mbedtls_sha1_context *ctx,
+                                                const unsigned char data[64] )
+{
+    mbedtls_internal_sha1_process( ctx, data );
+}
 
-/* Internal use */
-void mbedtls_sha1_process( mbedtls_sha1_context *ctx, const unsigned char data[64] );
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 #ifdef __cplusplus
 }
@@ -113,19 +273,69 @@ void mbedtls_sha1_process( mbedtls_sha1_context *ctx, const unsigned char data[6
 extern "C" {
 #endif
 
+/**
+ * \brief          This function calculates the SHA-1 checksum of a buffer.
+ *
+ *                 The function allocates the context, performs the
+ *                 calculation, and frees the context.
+ *
+ *                 The SHA-1 result is calculated as
+ *                 output = SHA-1(input buffer).
+ *
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
+ * \param output   The SHA-1 checksum result.
+ *
+ * \return         \c 0 if successful
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_sha1_ret( const unsigned char *input,
+                      size_t ilen,
+                      unsigned char output[20] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
 /**
  * \brief          Output = SHA-1( input buffer )
  *
- * \param input    buffer holding the  data
- * \param ilen     length of the input data
- * \param output   SHA-1 checksum result
+ * \deprecated     Superseded by mbedtls_sha1_ret() in 2.7.0
+ *
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
+ * \param output   The SHA-1 checksum result.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
-void mbedtls_sha1( const unsigned char *input, size_t ilen, unsigned char output[20] );
+MBEDTLS_DEPRECATED static inline void mbedtls_sha1( const unsigned char *input,
+                                                    size_t ilen,
+                                                    unsigned char output[20] )
+{
+    mbedtls_sha1_ret( input, ilen, output );
+}
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 /**
- * \brief          Checkup routine
+ * \brief          The SHA-1 checkup routine.
+ *
+ * \return         \c 0 on success, or \c 1 on failure.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
  *
- * \return         0 if successful, or 1 if the test failed
  */
 int mbedtls_sha1_self_test( int verbose );
 

+ 200 - 39
app/include/mbedtls/sha256.h

@@ -1,9 +1,10 @@
 /**
  * \file sha256.h
  *
- * \brief SHA-224 and SHA-256 cryptographic hash function
- *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * \brief The SHA-224 and SHA-256 cryptographic hash function.
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,7 +19,7 @@
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *
- *  This file is part of mbed TLS (https://tls.mbed.org)
+ *  This file is part of Mbed TLS (https://tls.mbed.org)
  */
 #ifndef MBEDTLS_SHA256_H
 #define MBEDTLS_SHA256_H
@@ -32,6 +33,12 @@
 #include <stddef.h>
 #include <stdint.h>
 
+#define MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED                -0x0037  /**< SHA-256 hardware accelerator failed */
+
+#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
+    !defined(inline) && !defined(__cplusplus)
+#define inline __inline
+#endif
 #if !defined(MBEDTLS_SHA256_ALT)
 // Regular implementation
 //
@@ -41,69 +48,174 @@ extern "C" {
 #endif
 
 /**
- * \brief          SHA-256 context structure
+ * \brief          The SHA-256 context structure.
+ *
+ *                 The structure is used both for SHA-256 and for SHA-224
+ *                 checksum calculations. The choice between these two is
+ *                 made in the call to mbedtls_sha256_starts_ret().
  */
 typedef struct
 {
-    uint32_t total[2];          /*!< number of bytes processed  */
-    uint32_t state[8];          /*!< intermediate digest state  */
-    unsigned char buffer[64];   /*!< data block being processed */
-    int is224;                  /*!< 0 => SHA-256, else SHA-224 */
+    uint32_t total[2];          /*!< The number of Bytes processed.  */
+    uint32_t state[8];          /*!< The intermediate digest state.  */
+    unsigned char buffer[64];   /*!< The data block being processed. */
+    int is224;                  /*!< Determines which function to use.
+                                     <ul><li>0: Use SHA-256.</li>
+                                     <li>1: Use SHA-224.</li></ul> */
 }
 mbedtls_sha256_context;
 
 /**
- * \brief          Initialize SHA-256 context
+ * \brief          This function initializes a SHA-256 context.
  *
- * \param ctx      SHA-256 context to be initialized
+ * \param ctx      The SHA-256 context to initialize.
  */
 void mbedtls_sha256_init( mbedtls_sha256_context *ctx );
 
 /**
- * \brief          Clear SHA-256 context
+ * \brief          This function clears a SHA-256 context.
  *
- * \param ctx      SHA-256 context to be cleared
+ * \param ctx      The SHA-256 context to clear.
  */
 void mbedtls_sha256_free( mbedtls_sha256_context *ctx );
 
 /**
- * \brief          Clone (the state of) a SHA-256 context
+ * \brief          This function clones the state of a SHA-256 context.
  *
- * \param dst      The destination context
- * \param src      The context to be cloned
+ * \param dst      The destination context.
+ * \param src      The context to clone.
  */
 void mbedtls_sha256_clone( mbedtls_sha256_context *dst,
                            const mbedtls_sha256_context *src );
 
 /**
- * \brief          SHA-256 context setup
+ * \brief          This function starts a SHA-224 or SHA-256 checksum
+ *                 calculation.
+ *
+ * \param ctx      The context to initialize.
+ * \param is224    Determines which function to use.
+ *                 <ul><li>0: Use SHA-256.</li>
+ *                 <li>1: Use SHA-224.</li></ul>
  *
- * \param ctx      context to be initialized
- * \param is224    0 = use SHA256, 1 = use SHA224
+ * \return         \c 0 on success.
  */
-void mbedtls_sha256_starts( mbedtls_sha256_context *ctx, int is224 );
+int mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 );
 
 /**
- * \brief          SHA-256 process buffer
+ * \brief          This function feeds an input buffer into an ongoing
+ *                 SHA-256 checksum calculation.
  *
  * \param ctx      SHA-256 context
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
+ *
+ * \return         \c 0 on success.
  */
-void mbedtls_sha256_update( mbedtls_sha256_context *ctx, const unsigned char *input,
-                    size_t ilen );
+int mbedtls_sha256_update_ret( mbedtls_sha256_context *ctx,
+                               const unsigned char *input,
+                               size_t ilen );
 
 /**
- * \brief          SHA-256 final digest
+ * \brief          This function finishes the SHA-256 operation, and writes
+ *                 the result to the output buffer.
  *
- * \param ctx      SHA-256 context
- * \param output   SHA-224/256 checksum result
+ * \param ctx      The SHA-256 context.
+ * \param output   The SHA-224 or SHA-256 checksum result.
+ *
+ * \return         \c 0 on success.
+ */
+int mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx,
+                               unsigned char output[32] );
+
+/**
+ * \brief          This function processes a single data block within
+ *                 the ongoing SHA-256 computation. This function is for
+ *                 internal use only.
+ *
+ * \param ctx      The SHA-256 context.
+ * \param data     The buffer holding one block of data.
+ *
+ * \return         \c 0 on success.
+ */
+int mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx,
+                                     const unsigned char data[64] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          This function starts a SHA-256 checksum calculation.
+ *
+ * \deprecated     Superseded by mbedtls_sha256_starts_ret() in 2.7.0.
+ *
+ * \param ctx      The SHA-256 context to initialize.
+ * \param is224    Determines which function to use.
+ *                 <ul><li>0: Use SHA-256.</li>
+ *                 <li>1: Use SHA-224.</li></ul>
  */
-void mbedtls_sha256_finish( mbedtls_sha256_context *ctx, unsigned char output[32] );
+MBEDTLS_DEPRECATED static inline void mbedtls_sha256_starts(
+                                                mbedtls_sha256_context *ctx,
+                                                int is224 )
+{
+    mbedtls_sha256_starts_ret( ctx, is224 );
+}
 
-/* Internal use */
-void mbedtls_sha256_process( mbedtls_sha256_context *ctx, const unsigned char data[64] );
+/**
+ * \brief          This function feeds an input buffer into an ongoing
+ *                 SHA-256 checksum calculation.
+ *
+ * \deprecated     Superseded by mbedtls_sha256_update_ret() in 2.7.0.
+ *
+ * \param ctx      The SHA-256 context to initialize.
+ * \param input    The buffer holding the data.
+ * \param ilen     The length of the input data.
+ */
+MBEDTLS_DEPRECATED static inline void mbedtls_sha256_update(
+                                                mbedtls_sha256_context *ctx,
+                                                const unsigned char *input,
+                                                size_t ilen )
+{
+    mbedtls_sha256_update_ret( ctx, input, ilen );
+}
 
+/**
+ * \brief          This function finishes the SHA-256 operation, and writes
+ *                 the result to the output buffer.
+ *
+ * \deprecated     Superseded by mbedtls_sha256_finish_ret() in 2.7.0.
+ *
+ * \param ctx      The SHA-256 context.
+ * \param output   The SHA-224or SHA-256 checksum result.
+ */
+MBEDTLS_DEPRECATED static inline void mbedtls_sha256_finish(
+                                                mbedtls_sha256_context *ctx,
+                                                unsigned char output[32] )
+{
+    mbedtls_sha256_finish_ret( ctx, output );
+}
+
+/**
+ * \brief          This function processes a single data block within
+ *                 the ongoing SHA-256 computation. This function is for
+ *                 internal use only.
+ *
+ * \deprecated     Superseded by mbedtls_internal_sha256_process() in 2.7.0.
+ *
+ * \param ctx      The SHA-256 context.
+ * \param data     The buffer holding one block of data.
+ */
+MBEDTLS_DEPRECATED static inline void mbedtls_sha256_process(
+                                                mbedtls_sha256_context *ctx,
+                                                const unsigned char data[64] )
+{
+    mbedtls_internal_sha256_process( ctx, data );
+}
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 #ifdef __cplusplus
 }
 #endif
@@ -117,20 +229,69 @@ extern "C" {
 #endif
 
 /**
- * \brief          Output = SHA-256( input buffer )
+ * \brief          This function calculates the SHA-224 or SHA-256
+ *                 checksum of a buffer.
  *
- * \param input    buffer holding the  data
- * \param ilen     length of the input data
- * \param output   SHA-224/256 checksum result
- * \param is224    0 = use SHA256, 1 = use SHA224
+ *                 The function allocates the context, performs the
+ *                 calculation, and frees the context.
+ *
+ *                 The SHA-256 result is calculated as
+ *                 output = SHA-256(input buffer).
+ *
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
+ * \param output   The SHA-224 or SHA-256 checksum result.
+ * \param is224    Determines which function to use.
+ *                 <ul><li>0: Use SHA-256.</li>
+ *                 <li>1: Use SHA-224.</li></ul>
+ */
+int mbedtls_sha256_ret( const unsigned char *input,
+                        size_t ilen,
+                        unsigned char output[32],
+                        int is224 );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+
+/**
+ * \brief          This function calculates the SHA-224 or SHA-256 checksum
+ *                 of a buffer.
+ *
+ *                 The function allocates the context, performs the
+ *                 calculation, and frees the context.
+ *
+ *                 The SHA-256 result is calculated as
+ *                 output = SHA-256(input buffer).
+ *
+ * \deprecated     Superseded by mbedtls_sha256_ret() in 2.7.0.
+ *
+ * \param input    The buffer holding the data.
+ * \param ilen     The length of the input data.
+ * \param output   The SHA-224 or SHA-256 checksum result.
+ * \param is224    Determines which function to use.
+ *                 <ul><li>0: Use SHA-256.</li>
+ *                 <li>1: Use SHA-224.</li></ul>
  */
-void mbedtls_sha256( const unsigned char *input, size_t ilen,
-           unsigned char output[32], int is224 );
+MBEDTLS_DEPRECATED static inline void mbedtls_sha256(
+                                                    const unsigned char *input,
+                                                    size_t ilen,
+                                                    unsigned char output[32],
+                                                    int is224 )
+{
+    mbedtls_sha256_ret( input, ilen, output, is224 );
+}
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 /**
- * \brief          Checkup routine
+ * \brief          The SHA-224 and SHA-256 checkup routine.
  *
- * \return         0 if successful, or 1 if the test failed
+ * \return         \c 0 on success, or \c 1 on failure.
  */
 int mbedtls_sha256_self_test( int verbose );
 

+ 203 - 41
app/include/mbedtls/sha512.h

@@ -1,9 +1,10 @@
 /**
  * \file sha512.h
  *
- * \brief SHA-384 and SHA-512 cryptographic hash function
- *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * \brief The SHA-384 and SHA-512 cryptographic hash function.
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,7 +19,7 @@
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *
- *  This file is part of mbed TLS (https://tls.mbed.org)
+ *  This file is part of Mbed TLS (https://tls.mbed.org)
  */
 #ifndef MBEDTLS_SHA512_H
 #define MBEDTLS_SHA512_H
@@ -32,6 +33,12 @@
 #include <stddef.h>
 #include <stdint.h>
 
+#define MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED                -0x0039  /**< SHA-512 hardware accelerator failed */
+
+#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
+    !defined(inline) && !defined(__cplusplus)
+#define inline __inline
+#endif
 #if !defined(MBEDTLS_SHA512_ALT)
 // Regular implementation
 //
@@ -41,65 +48,174 @@ extern "C" {
 #endif
 
 /**
- * \brief          SHA-512 context structure
+ * \brief          The SHA-512 context structure.
+ *
+ *                 The structure is used both for SHA-384 and for SHA-512
+ *                 checksum calculations. The choice between these two is
+ *                 made in the call to mbedtls_sha512_starts_ret().
  */
 typedef struct
 {
-    uint64_t total[2];          /*!< number of bytes processed  */
-    uint64_t state[8];          /*!< intermediate digest state  */
-    unsigned char buffer[128];  /*!< data block being processed */
-    int is384;                  /*!< 0 => SHA-512, else SHA-384 */
+    uint64_t total[2];          /*!< The number of Bytes processed. */
+    uint64_t state[8];          /*!< The intermediate digest state. */
+    unsigned char buffer[128];  /*!< The data block being processed. */
+    int is384;                  /*!< Determines which function to use.
+                                 *   <ul><li>0: Use SHA-512.</li>
+                                 *   <li>1: Use SHA-384.</li></ul> */
 }
 mbedtls_sha512_context;
 
 /**
- * \brief          Initialize SHA-512 context
+ * \brief          This function initializes a SHA-512 context.
  *
- * \param ctx      SHA-512 context to be initialized
+ * \param ctx      The SHA-512 context to initialize.
  */
 void mbedtls_sha512_init( mbedtls_sha512_context *ctx );
 
 /**
- * \brief          Clear SHA-512 context
+ * \brief          This function clears a SHA-512 context.
  *
- * \param ctx      SHA-512 context to be cleared
+ * \param ctx      The SHA-512 context to clear.
  */
 void mbedtls_sha512_free( mbedtls_sha512_context *ctx );
 
 /**
- * \brief          Clone (the state of) a SHA-512 context
+ * \brief          This function clones the state of a SHA-512 context.
  *
- * \param dst      The destination context
- * \param src      The context to be cloned
+ * \param dst      The destination context.
+ * \param src      The context to clone.
  */
 void mbedtls_sha512_clone( mbedtls_sha512_context *dst,
                            const mbedtls_sha512_context *src );
 
 /**
- * \brief          SHA-512 context setup
+ * \brief          This function starts a SHA-384 or SHA-512 checksum
+ *                 calculation.
+ *
+ * \param ctx      The SHA-512 context to initialize.
+ * \param is384    Determines which function to use.
+ *                 <ul><li>0: Use SHA-512.</li>
+ *                 <li>1: Use SHA-384.</li></ul>
  *
- * \param ctx      context to be initialized
- * \param is384    0 = use SHA512, 1 = use SHA384
+ * \return         \c 0 on success.
  */
-void mbedtls_sha512_starts( mbedtls_sha512_context *ctx, int is384 );
+int mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 );
 
 /**
- * \brief          SHA-512 process buffer
+ * \brief          This function feeds an input buffer into an ongoing
+ *                 SHA-512 checksum calculation.
  *
- * \param ctx      SHA-512 context
- * \param input    buffer holding the  data
- * \param ilen     length of the input data
+ * \param ctx      The SHA-512 context.
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
+ *
+ * \return         \c 0 on success.
  */
-void mbedtls_sha512_update( mbedtls_sha512_context *ctx, const unsigned char *input,
+int mbedtls_sha512_update_ret( mbedtls_sha512_context *ctx,
+                    const unsigned char *input,
                     size_t ilen );
 
 /**
- * \brief          SHA-512 final digest
+ * \brief          This function finishes the SHA-512 operation, and writes
+ *                 the result to the output buffer. This function is for
+ *                 internal use only.
+ *
+ * \param ctx      The SHA-512 context.
+ * \param output   The SHA-384 or SHA-512 checksum result.
  *
- * \param ctx      SHA-512 context
- * \param output   SHA-384/512 checksum result
+ * \return         \c 0 on success.
  */
-void mbedtls_sha512_finish( mbedtls_sha512_context *ctx, unsigned char output[64] );
+int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx,
+                               unsigned char output[64] );
+
+/**
+ * \brief          This function processes a single data block within
+ *                 the ongoing SHA-512 computation.
+ *
+ * \param ctx      The SHA-512 context.
+ * \param data     The buffer holding one block of data.
+ *
+ * \return         \c 0 on success.
+ */
+int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx,
+                                     const unsigned char data[128] );
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          This function starts a SHA-384 or SHA-512 checksum
+ *                 calculation.
+ *
+ * \deprecated     Superseded by mbedtls_sha512_starts_ret() in 2.7.0
+ *
+ * \param ctx      The SHA-512 context to initialize.
+ * \param is384    Determines which function to use.
+ *                 <ul><li>0: Use SHA-512.</li>
+ *                 <li>1: Use SHA-384.</li></ul>
+ */
+MBEDTLS_DEPRECATED static inline void mbedtls_sha512_starts(
+                                                mbedtls_sha512_context *ctx,
+                                                int is384 )
+{
+    mbedtls_sha512_starts_ret( ctx, is384 );
+}
+
+/**
+ * \brief          This function feeds an input buffer into an ongoing
+ *                 SHA-512 checksum calculation.
+ *
+ * \deprecated     Superseded by mbedtls_sha512_update_ret() in 2.7.0
+ *
+ * \param ctx      The SHA-512 context.
+ * \param input    The buffer holding the data.
+ * \param ilen     The length of the input data.
+ */
+MBEDTLS_DEPRECATED static inline void mbedtls_sha512_update(
+                                                mbedtls_sha512_context *ctx,
+                                                const unsigned char *input,
+                                                size_t ilen )
+{
+    mbedtls_sha512_update_ret( ctx, input, ilen );
+}
+
+/**
+ * \brief          This function finishes the SHA-512 operation, and writes
+ *                 the result to the output buffer.
+ *
+ * \deprecated     Superseded by mbedtls_sha512_finish_ret() in 2.7.0
+ *
+ * \param ctx      The SHA-512 context.
+ * \param output   The SHA-384 or SHA-512 checksum result.
+ */
+MBEDTLS_DEPRECATED static inline void mbedtls_sha512_finish(
+                                                mbedtls_sha512_context *ctx,
+                                                unsigned char output[64] )
+{
+    mbedtls_sha512_finish_ret( ctx, output );
+}
+
+/**
+ * \brief          This function processes a single data block within
+ *                 the ongoing SHA-512 computation. This function is for
+ *                 internal use only.
+ *
+ * \deprecated     Superseded by mbedtls_internal_sha512_process() in 2.7.0
+ *
+ * \param ctx      The SHA-512 context.
+ * \param data     The buffer holding one block of data.
+ */
+MBEDTLS_DEPRECATED static inline void mbedtls_sha512_process(
+                                            mbedtls_sha512_context *ctx,
+                                            const unsigned char data[128] )
+{
+    mbedtls_internal_sha512_process( ctx, data );
+}
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 #ifdef __cplusplus
 }
@@ -114,25 +230,71 @@ extern "C" {
 #endif
 
 /**
- * \brief          Output = SHA-512( input buffer )
+ * \brief          This function calculates the SHA-512 or SHA-384
+ *                 checksum of a buffer.
  *
- * \param input    buffer holding the  data
- * \param ilen     length of the input data
- * \param output   SHA-384/512 checksum result
- * \param is384    0 = use SHA512, 1 = use SHA384
+ *                 The function allocates the context, performs the
+ *                 calculation, and frees the context.
+ *
+ *                 The SHA-512 result is calculated as
+ *                 output = SHA-512(input buffer).
+ *
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
+ * \param output   The SHA-384 or SHA-512 checksum result.
+ * \param is384    Determines which function to use.
+ *                 <ul><li>0: Use SHA-512.</li>
+ *                 <li>1: Use SHA-384.</li></ul>
+ *
+ * \return         \c 0 on success.
  */
-void mbedtls_sha512( const unsigned char *input, size_t ilen,
-             unsigned char output[64], int is384 );
+int mbedtls_sha512_ret( const unsigned char *input,
+                        size_t ilen,
+                        unsigned char output[64],
+                        int is384 );
 
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
 /**
- * \brief          Checkup routine
+ * \brief          This function calculates the SHA-512 or SHA-384
+ *                 checksum of a buffer.
+ *
+ *                 The function allocates the context, performs the
+ *                 calculation, and frees the context.
+ *
+ *                 The SHA-512 result is calculated as
+ *                 output = SHA-512(input buffer).
  *
- * \return         0 if successful, or 1 if the test failed
+ * \deprecated     Superseded by mbedtls_sha512_ret() in 2.7.0
+ *
+ * \param input    The buffer holding the data.
+ * \param ilen     The length of the input data.
+ * \param output   The SHA-384 or SHA-512 checksum result.
+ * \param is384    Determines which function to use.
+ *                 <ul><li>0: Use SHA-512.</li>
+ *                 <li>1: Use SHA-384.</li></ul>
  */
-int mbedtls_sha512_self_test( int verbose );
+MBEDTLS_DEPRECATED static inline void mbedtls_sha512(
+                                                    const unsigned char *input,
+                                                    size_t ilen,
+                                                    unsigned char output[64],
+                                                    int is384 )
+{
+    mbedtls_sha512_ret( input, ilen, output, is384 );
+}
 
-/* Internal use */
-void mbedtls_sha512_process( mbedtls_sha512_context *ctx, const unsigned char data[128] );
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
+ /**
+ * \brief          The SHA-384 or SHA-512 checkup routine.
+ *
+ * \return         \c 0 on success, or \c 1 on failure.
+ */
+int mbedtls_sha512_self_test( int verbose );
 
 #ifdef __cplusplus
 }

+ 294 - 64
app/include/mbedtls/ssl.h

@@ -2,7 +2,8 @@
  * \file ssl.h
  *
  * \brief SSL/TLS functions.
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -52,7 +53,7 @@
 #endif
 
 #if defined(MBEDTLS_HAVE_TIME)
-#include <time.h>
+#include "mbedtls/platform_time.h"
 #endif
 
 /*
@@ -107,6 +108,8 @@
 #define MBEDTLS_ERR_SSL_TIMEOUT                           -0x6800  /**< The operation timed out. */
 #define MBEDTLS_ERR_SSL_CLIENT_RECONNECT                  -0x6780  /**< The client initiated a reconnect from the same port. */
 #define MBEDTLS_ERR_SSL_UNEXPECTED_RECORD                 -0x6700  /**< Record header looks valid but is not expected. */
+#define MBEDTLS_ERR_SSL_NON_FATAL                         -0x6680  /**< The alert message received indicates a non-fatal error. */
+#define MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH               -0x6600  /**< Couldn't set the hash for verifying CertificateVerify */
 
 /*
  * Various constants
@@ -183,6 +186,9 @@
 #define MBEDTLS_SSL_PRESET_DEFAULT              0
 #define MBEDTLS_SSL_PRESET_SUITEB               2
 
+#define MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED       1
+#define MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED      0
+
 /*
  * Default range for DTLS retransmission timer value, in milliseconds.
  * RFC 6347 4.2.4.1 says from 1 second to 60 seconds.
@@ -232,7 +238,7 @@
  * Signaling ciphersuite values (SCSV)
  */
 #define MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO    0xFF   /**< renegotiation info ext */
-#define MBEDTLS_SSL_FALLBACK_SCSV_VALUE         0x5600 /**< draft-ietf-tls-downgrade-scsv-00 */
+#define MBEDTLS_SSL_FALLBACK_SCSV_VALUE         0x5600 /**< RFC 7507 section 2 */
 
 /*
  * Supported Signature and Hash algorithms (For TLS 1.2)
@@ -411,6 +417,116 @@ typedef enum
 }
 mbedtls_ssl_states;
 
+/**
+ * \brief          Callback type: send data on the network.
+ *
+ * \note           That callback may be either blocking or non-blocking.
+ *
+ * \param ctx      Context for the send callback (typically a file descriptor)
+ * \param buf      Buffer holding the data to send
+ * \param len      Length of the data to send
+ *
+ * \return         The callback must return the number of bytes sent if any,
+ *                 or a non-zero error code.
+ *                 If performing non-blocking I/O, \c MBEDTLS_ERR_SSL_WANT_WRITE
+ *                 must be returned when the operation would block.
+ *
+ * \note           The callback is allowed to send fewer bytes than requested.
+ *                 It must always return the number of bytes actually sent.
+ */
+typedef int mbedtls_ssl_send_t( void *ctx,
+                                const unsigned char *buf,
+                                size_t len );
+
+/**
+ * \brief          Callback type: receive data from the network.
+ *
+ * \note           That callback may be either blocking or non-blocking.
+ *
+ * \param ctx      Context for the receive callback (typically a file
+ *                 descriptor)
+ * \param buf      Buffer to write the received data to
+ * \param len      Length of the receive buffer
+ *
+ * \return         The callback must return the number of bytes received,
+ *                 or a non-zero error code.
+ *                 If performing non-blocking I/O, \c MBEDTLS_ERR_SSL_WANT_READ
+ *                 must be returned when the operation would block.
+ *
+ * \note           The callback may receive fewer bytes than the length of the
+ *                 buffer. It must always return the number of bytes actually
+ *                 received and written to the buffer.
+ */
+typedef int mbedtls_ssl_recv_t( void *ctx,
+                                unsigned char *buf,
+                                size_t len );
+
+/**
+ * \brief          Callback type: receive data from the network, with timeout
+ *
+ * \note           That callback must block until data is received, or the
+ *                 timeout delay expires, or the operation is interrupted by a
+ *                 signal.
+ *
+ * \param ctx      Context for the receive callback (typically a file descriptor)
+ * \param buf      Buffer to write the received data to
+ * \param len      Length of the receive buffer
+ * \param timeout  Maximum nomber of millisecondes to wait for data
+ *                 0 means no timeout (potentially waiting forever)
+ *
+ * \return         The callback must return the number of bytes received,
+ *                 or a non-zero error code:
+ *                 \c MBEDTLS_ERR_SSL_TIMEOUT if the operation timed out,
+ *                 \c MBEDTLS_ERR_SSL_WANT_READ if interrupted by a signal.
+ *
+ * \note           The callback may receive fewer bytes than the length of the
+ *                 buffer. It must always return the number of bytes actually
+ *                 received and written to the buffer.
+ */
+typedef int mbedtls_ssl_recv_timeout_t( void *ctx,
+                                        unsigned char *buf,
+                                        size_t len,
+                                        uint32_t timeout );
+/**
+ * \brief          Callback type: set a pair of timers/delays to watch
+ *
+ * \param ctx      Context pointer
+ * \param int_ms   Intermediate delay in milliseconds
+ * \param fin_ms   Final delay in milliseconds
+ *                 0 cancels the current timer.
+ *
+ * \note           This callback must at least store the necessary information
+ *                 for the associated \c mbedtls_ssl_get_timer_t callback to
+ *                 return correct information.
+ *
+ * \note           If using a event-driven style of programming, an event must
+ *                 be generated when the final delay is passed. The event must
+ *                 cause a call to \c mbedtls_ssl_handshake() with the proper
+ *                 SSL context to be scheduled. Care must be taken to ensure
+ *                 that at most one such call happens at a time.
+ *
+ * \note           Only one timer at a time must be running. Calling this
+ *                 function while a timer is running must cancel it. Cancelled
+ *                 timers must not generate any event.
+ */
+typedef void mbedtls_ssl_set_timer_t( void * ctx,
+                                      uint32_t int_ms,
+                                      uint32_t fin_ms );
+
+/**
+ * \brief          Callback type: get status of timers/delays
+ *
+ * \param ctx      Context pointer
+ *
+ * \return         This callback must return:
+ *                 -1 if cancelled (fin_ms == 0),
+ *                  0 if none of the delays have passed,
+ *                  1 if only the intermediate delay has passed,
+ *                  2 if the final delay has passed.
+ */
+typedef int mbedtls_ssl_get_timer_t( void * ctx );
+
+
 /* Defined below */
 typedef struct mbedtls_ssl_session mbedtls_ssl_session;
 typedef struct mbedtls_ssl_context mbedtls_ssl_context;
@@ -419,6 +535,7 @@ typedef struct mbedtls_ssl_config  mbedtls_ssl_config;
 /* Defined in ssl_internal.h */
 typedef struct mbedtls_ssl_transform mbedtls_ssl_transform;
 typedef struct mbedtls_ssl_handshake_params mbedtls_ssl_handshake_params;
+typedef struct mbedtls_ssl_sig_hash_set_t mbedtls_ssl_sig_hash_set_t;
 #if defined(MBEDTLS_X509_CRT_PARSE_C)
 typedef struct mbedtls_ssl_key_cert mbedtls_ssl_key_cert;
 #endif
@@ -432,7 +549,7 @@ typedef struct mbedtls_ssl_flight_item mbedtls_ssl_flight_item;
 struct mbedtls_ssl_session
 {
 #if defined(MBEDTLS_HAVE_TIME)
-    time_t start;               /*!< starting time      */
+    mbedtls_time_t start;       /*!< starting time      */
 #endif
     int ciphersuite;            /*!< chosen ciphersuite */
     int compression;            /*!< chosen compression */
@@ -637,6 +754,10 @@ struct mbedtls_ssl_config
 #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)
     unsigned int fallback : 1;      /*!< is this a fallback?                */
 #endif
+#if defined(MBEDTLS_SSL_SRV_C)
+    unsigned int cert_req_ca_list : 1;  /*!< enable sending CA list in
+                                          Certificate Request messages?     */
+#endif
 };
 
 
@@ -662,12 +783,11 @@ struct mbedtls_ssl_context
     unsigned badmac_seen;       /*!< records with a bad MAC received    */
 #endif
 
-    /*
-     * Callbacks
-     */
-    int (*f_send)(void *, const unsigned char *, size_t);
-    int (*f_recv)(void *, unsigned char *, size_t);
-    int (*f_recv_timeout)(void *, unsigned char *, size_t, uint32_t);
+    mbedtls_ssl_send_t *f_send; /*!< Callback for network send */
+    mbedtls_ssl_recv_t *f_recv; /*!< Callback for network receive */
+    mbedtls_ssl_recv_timeout_t *f_recv_timeout;
+                                /*!< Callback for network receive with timeout */
+
     void *p_bio;                /*!< context for I/O operations   */
 
     /*
@@ -693,8 +813,9 @@ struct mbedtls_ssl_context
      * Timers
      */
     void *p_timer;              /*!< context for the timer callbacks */
-    void (*f_set_timer)(void *, uint32_t, uint32_t); /*!< set timer callback */
-    int (*f_get_timer)(void *); /*!< get timer callback             */
+
+    mbedtls_ssl_set_timer_t *f_set_timer;       /*!< set timer callback */
+    mbedtls_ssl_get_timer_t *f_get_timer;       /*!< get timer callback */
 
     /*
      * Record layer (incoming data)
@@ -725,7 +846,9 @@ struct mbedtls_ssl_context
     size_t in_hslen;            /*!< current handshake message length,
                                      including the handshake header   */
     int nb_zero;                /*!< # of 0-length encrypted messages */
-    int record_read;            /*!< record is already present        */
+
+    int keep_current_message;   /*!< drop or reuse current message
+                                     on next call to record layer? */
 
     /*
      * Record layer (outgoing data)
@@ -848,7 +971,7 @@ void mbedtls_ssl_init( mbedtls_ssl_context *ssl );
  * \note           No copy of the configuration context is made, it can be
  *                 shared by many mbedtls_ssl_context structures.
  *
- * \warning        Modifying the conf structure after is has been used in this
+ * \warning        Modifying the conf structure after it has been used in this
  *                 function is unsupported!
  *
  * \param ssl      SSL context
@@ -866,7 +989,7 @@ int mbedtls_ssl_setup( mbedtls_ssl_context *ssl,
  *                 pointers and data.
  *
  * \param ssl      SSL context
- * \return         0 if successful, or POLASSL_ERR_SSL_MALLOC_FAILED,
+ * \return         0 if successful, or MBEDTLS_ERR_SSL_ALLOC_FAILED,
                    MBEDTLS_ERR_SSL_HW_ACCEL_FAILED or
  *                 MBEDTLS_ERR_SSL_COMPRESSION_FAILED
  */
@@ -914,6 +1037,7 @@ void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport );
  *
  *  MBEDTLS_SSL_VERIFY_REQUIRED:  peer *must* present a valid certificate,
  *                        handshake is aborted if verification failed.
+ *                        (default on client)
  *
  * \note On client, MBEDTLS_SSL_VERIFY_REQUIRED is the recommended mode.
  * With MBEDTLS_SSL_VERIFY_OPTIONAL, the user needs to call mbedtls_ssl_get_verify_result() at
@@ -929,7 +1053,7 @@ void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode );
  *
  *                 If set, the verify callback is called for each
  *                 certificate in the chain. For implementation
- *                 information, please see \c x509parse_verify()
+ *                 information, please see \c mbedtls_x509_crt_verify()
  *
  * \param conf     SSL configuration
  * \param f_vrfy   verification function
@@ -978,8 +1102,6 @@ void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,
  * \param f_send   write callback
  * \param f_recv   read callback
  * \param f_recv_timeout blocking read callback with timeout.
- *                 The last argument is the timeout in milliseconds,
- *                 0 means no timeout (block forever until a message comes)
  *
  * \note           One of f_recv or f_recv_timeout can be NULL, in which case
  *                 the other is used. If both are non-NULL, f_recv_timeout is
@@ -991,12 +1113,21 @@ void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,
  *
  * \note           For DTLS, you need to provide either a non-NULL
  *                 f_recv_timeout callback, or a f_recv that doesn't block.
+ *
+ * \note           See the documentations of \c mbedtls_ssl_sent_t,
+ *                 \c mbedtls_ssl_recv_t and \c mbedtls_ssl_recv_timeout_t for
+ *                 the conventions those callbacks must follow.
+ *
+ * \note           On some platforms, net_sockets.c provides
+ *                 \c mbedtls_net_send(), \c mbedtls_net_recv() and
+ *                 \c mbedtls_net_recv_timeout() that are suitable to be used
+ *                 here.
  */
 void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,
-        void *p_bio,
-        int (*f_send)(void *, const unsigned char *, size_t),
-        int (*f_recv)(void *, unsigned char *, size_t),
-        int (*f_recv_timeout)(void *, unsigned char *, size_t, uint32_t) );
+                          void *p_bio,
+                          mbedtls_ssl_send_t *f_send,
+                          mbedtls_ssl_recv_t *f_recv,
+                          mbedtls_ssl_recv_timeout_t *f_recv_timeout );
 
 /**
  * \brief          Set the timeout period for mbedtls_ssl_read()
@@ -1017,37 +1148,42 @@ void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,
 void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout );
 
 /**
- * \brief          Set the timer callbacks
- *                 (Mandatory for DTLS.)
+ * \brief          Set the timer callbacks (Mandatory for DTLS.)
  *
  * \param ssl      SSL context
- * \param p_timer  parameter (context) shared by timer callback
+ * \param p_timer  parameter (context) shared by timer callbacks
  * \param f_set_timer   set timer callback
- *                 Accepts an intermediate and a final delay in milliseconcs
- *                 If the final delay is 0, cancels the running timer.
  * \param f_get_timer   get timer callback. Must return:
- *                 -1 if cancelled
- *                 0 if none of the delays is expired
- *                 1 if the intermediate delay only is expired
- *                 2 if the final delay is expired
+ *
+ * \note           See the documentation of \c mbedtls_ssl_set_timer_t and
+ *                 \c mbedtls_ssl_get_timer_t for the conventions this pair of
+ *                 callbacks must follow.
+ *
+ * \note           On some platforms, timing.c provides
+ *                 \c mbedtls_timing_set_delay() and
+ *                 \c mbedtls_timing_get_delay() that are suitable for using
+ *                 here, except if using an event-driven style.
+ *
+ * \note           See also the "DTLS tutorial" article in our knowledge base.
+ *                 https://tls.mbed.org/kb/how-to/dtls-tutorial
  */
 void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl,
                                void *p_timer,
-                               void (*f_set_timer)(void *, uint32_t int_ms, uint32_t fin_ms),
-                               int (*f_get_timer)(void *) );
+                               mbedtls_ssl_set_timer_t *f_set_timer,
+                               mbedtls_ssl_get_timer_t *f_get_timer );
 
 /**
  * \brief           Callback type: generate and write session ticket
  *
  * \note            This describes what a callback implementation should do.
- *                  This callback should generate and encrypted and
+ *                  This callback should generate an encrypted and
  *                  authenticated ticket for the session and write it to the
  *                  output buffer. Here, ticket means the opaque ticket part
  *                  of the NewSessionTicket structure of RFC 5077.
  *
  * \param p_ticket  Context for the callback
- * \param session   SSL session to bo written in the ticket
- * \param start     Start of the outpur buffer
+ * \param session   SSL session to be written in the ticket
+ * \param start     Start of the output buffer
  * \param end       End of the output buffer
  * \param tlen      On exit, holds the length written
  * \param lifetime  On exit, holds the lifetime of the ticket in seconds
@@ -1298,7 +1434,7 @@ void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limi
 
 #if defined(MBEDTLS_SSL_PROTO_DTLS)
 /**
- * \brief          Set retransmit timeout values for the DTLS handshale.
+ * \brief          Set retransmit timeout values for the DTLS handshake.
  *                 (DTLS only, no effect on TLS.)
  *
  * \param conf     SSL configuration
@@ -1309,9 +1445,24 @@ void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limi
  *
  * \note           Default values are from RFC 6347 section 4.2.4.1.
  *
- * \note           Higher values for initial timeout may increase average
- *                 handshake latency. Lower values may increase the risk of
- *                 network congestion by causing more retransmissions.
+ * \note           The 'min' value should typically be slightly above the
+ *                 expected round-trip time to your peer, plus whatever time
+ *                 it takes for the peer to process the message. For example,
+ *                 if your RTT is about 600ms and you peer needs up to 1s to
+ *                 do the cryptographic operations in the handshake, then you
+ *                 should set 'min' slightly above 1600. Lower values of 'min'
+ *                 might cause spurious resends which waste network resources,
+ *                 while larger value of 'min' will increase overall latency
+ *                 on unreliable network links.
+ *
+ * \note           The more unreliable your network connection is, the larger
+ *                 your max / min ratio needs to be in order to achieve
+ *                 reliable handshakes.
+ *
+ * \note           Messages are retransmitted up to log2(ceil(max/min)) times.
+ *                 For example, if min = 1s and max = 5s, the retransmit plan
+ *                 goes: send ... 1s -> resend ... 2s -> resend ... 4s ->
+ *                 resend ... 5s -> give up and return a timeout error.
  */
 void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf, uint32_t min, uint32_t max );
 #endif /* MBEDTLS_SSL_PROTO_DTLS */
@@ -1381,7 +1532,7 @@ int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session
 /**
  * \brief               Set the list of allowed ciphersuites and the preference
  *                      order. First in the list has the highest preference.
- *                      (Overrides all version specific lists)
+ *                      (Overrides all version-specific lists)
  *
  *                      The ciphersuites array is not copied, and must remain
  *                      valid for the lifetime of the ssl_config.
@@ -1459,7 +1610,12 @@ void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,
  *                 adequate, preference is given to the one set by the first
  *                 call to this function, then second, etc.
  *
- * \note           On client, only the first call has any effect.
+ * \note           On client, only the first call has any effect. That is,
+ *                 only one client certificate can be provisioned. The
+ *                 server's preferences in its CertficateRequest message will
+ *                 be ignored and our only cert will be sent regardless of
+ *                 whether it matches those preferences - the server can then
+ *                 decide what it wants to do with it.
  *
  * \param conf     SSL configuration
  * \param own_cert own public certificate chain
@@ -1479,6 +1635,12 @@ int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
  * \note           This is mainly useful for clients. Servers will usually
  *                 want to use \c mbedtls_ssl_conf_psk_cb() instead.
  *
+ * \note           Currently clients can only register one pre-shared key.
+ *                 In other words, the servers' identity hint is ignored.
+ *                 Support for setting multiple PSKs on clients and selecting
+ *                 one based on the identity hint is not a planned feature but
+ *                 feedback is welcomed.
+ *
  * \param conf     SSL configuration
  * \param psk      pointer to the pre-shared key
  * \param psk_len  pre-shared key length
@@ -1538,18 +1700,50 @@ void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,
 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
 
 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED    __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+
 /**
  * \brief          Set the Diffie-Hellman public P and G values,
  *                 read as hexadecimal strings (server-side only)
- *                 (Default: MBEDTLS_DHM_RFC5114_MODP_2048_[PG])
+ *                 (Default values: MBEDTLS_DHM_RFC3526_MODP_2048_[PG])
  *
  * \param conf     SSL configuration
  * \param dhm_P    Diffie-Hellman-Merkle modulus
  * \param dhm_G    Diffie-Hellman-Merkle generator
  *
+ * \deprecated     Superseded by \c mbedtls_ssl_conf_dh_param_bin.
+ *
+ * \return         0 if successful
+ */
+MBEDTLS_DEPRECATED int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf,
+                                                  const char *dhm_P,
+                                                  const char *dhm_G );
+
+#endif /* MBEDTLS_DEPRECATED_REMOVED */
+
+/**
+ * \brief          Set the Diffie-Hellman public P and G values
+ *                 from big-endian binary presentations.
+ *                 (Default values: MBEDTLS_DHM_RFC3526_MODP_2048_[PG]_BIN)
+ *
+ * \param conf     SSL configuration
+ * \param dhm_P    Diffie-Hellman-Merkle modulus in big-endian binary form
+ * \param P_len    Length of DHM modulus
+ * \param dhm_G    Diffie-Hellman-Merkle generator in big-endian binary form
+ * \param G_len    Length of DHM generator
+ *
  * \return         0 if successful
  */
-int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G );
+int mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf,
+                                   const unsigned char *dhm_P, size_t P_len,
+                                   const unsigned char *dhm_G,  size_t G_len );
 
 /**
  * \brief          Set the Diffie-Hellman public P and G values,
@@ -1633,14 +1827,22 @@ void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
 
 #if defined(MBEDTLS_X509_CRT_PARSE_C)
 /**
- * \brief          Set hostname for ServerName TLS extension
- *                 (client-side only)
- *
+ * \brief          Set or reset the hostname to check against the received 
+ *                 server certificate. It sets the ServerName TLS extension, 
+ *                 too, if that extension is enabled. (client-side only)
  *
  * \param ssl      SSL context
- * \param hostname the server hostname
+ * \param hostname the server hostname, may be NULL to clear hostname
+ 
+ * \note           Maximum hostname length MBEDTLS_SSL_MAX_HOST_NAME_LEN.
  *
- * \return         0 if successful or MBEDTLS_ERR_SSL_ALLOC_FAILED
+ * \return         0 if successful, MBEDTLS_ERR_SSL_ALLOC_FAILED on 
+ *                 allocation failure, MBEDTLS_ERR_SSL_BAD_INPUT_DATA on 
+ *                 too long input hostname.
+ *
+ *                 Hostname set to the one provided on success (cleared
+ *                 when NULL). On allocation failure hostname is cleared. 
+ *                 On too long input failure, old hostname is unchanged.
  */
 int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname );
 #endif /* MBEDTLS_X509_CRT_PARSE_C */
@@ -1747,8 +1949,11 @@ int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,
  * \brief          Set the supported Application Layer Protocols.
  *
  * \param conf     SSL configuration
- * \param protos   NULL-terminated list of supported protocols,
- *                 in decreasing preference order.
+ * \param protos   Pointer to a NULL-terminated list of supported protocols,
+ *                 in decreasing preference order. The pointer to the list is
+ *                 recorded by the library for later reference as required, so
+ *                 the lifetime of the table must be atleast as long as the
+ *                 lifetime of the SSL configuration structure.
  *
  * \return         0 on success, or MBEDTLS_ERR_SSL_BAD_INPUT_DATA.
  */
@@ -1862,11 +2067,13 @@ void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems
  * \brief          Disable or enable support for RC4
  *                 (Default: MBEDTLS_SSL_ARC4_DISABLED)
  *
- * \warning        Use of RC4 in (D)TLS has been prohibited by RFC ????
- *                 for security reasons. Use at your own risks.
+ * \warning        Use of RC4 in DTLS/TLS has been prohibited by RFC 7465
+ *                 for security reasons. Use at your own risk.
  *
- * \note           This function will likely be removed in future versions as
- *                 RC4 will then be disabled by default at compile time.
+ * \note           This function is deprecated and will likely be removed in
+ *                 a future version of the library.
+ *                 RC4 is disabled by default at compile time and needs to be
+ *                 actively enabled for use with legacy systems.
  *
  * \param conf     SSL configuration
  * \param arc4     MBEDTLS_SSL_ARC4_ENABLED or MBEDTLS_SSL_ARC4_DISABLED
@@ -1874,6 +2081,20 @@ void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems
 void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 );
 #endif /* MBEDTLS_ARC4_C */
 
+#if defined(MBEDTLS_SSL_SRV_C)
+/**
+ * \brief          Whether to send a list of acceptable CAs in
+ *                 CertificateRequest messages.
+ *                 (Default: do send)
+ *
+ * \param conf     SSL configuration
+ * \param cert_req_ca_list   MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED or
+ *                          MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED
+ */
+void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf,
+                                          char cert_req_ca_list );
+#endif /* MBEDTLS_SSL_SRV_C */
+
 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
 /**
  * \brief          Set the maximum fragment length to emit and/or negotiate
@@ -1942,7 +2163,7 @@ void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets
  *
  * \warning        It is recommended to always disable renegotation unless you
  *                 know you need it and you know what you're doing. In the
- *                 past, there has been several issues associated with
+ *                 past, there have been several issues associated with
  *                 renegotiation or a poor understanding of its properties.
  *
  * \note           Server-side, enabling renegotiation also makes the server
@@ -2026,7 +2247,7 @@ void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_
 
 /**
  * \brief          Set record counter threshold for periodic renegotiation.
- *                 (Default: 2^64 - 256.)
+ *                 (Default: 2^48 - 1)
  *
  *                 Renegotiation is automatically triggered when a record
  *                 counter (outgoing or ingoing) crosses the defined
@@ -2037,9 +2258,17 @@ void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_
  *                 Lower values can be used to enforce policies such as "keys
  *                 must be refreshed every N packets with cipher X".
  *
+ *                 The renegotiation period can be disabled by setting
+ *                 conf->disable_renegotiation to
+ *                 MBEDTLS_SSL_RENEGOTIATION_DISABLED.
+ *
+ * \note           When the configured transport is
+ *                 MBEDTLS_SSL_TRANSPORT_DATAGRAM the maximum renegotiation
+ *                 period is 2^48 - 1, and for MBEDTLS_SSL_TRANSPORT_STREAM,
+ *                 the maximum renegotiation period is 2^64 - 1.
+ *
  * \param conf     SSL configuration
  * \param period   The threshold value: a big-endian 64-bit number.
- *                 Set to 2^64 - 1 to disable periodic renegotiation
  */
 void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,
                                    const unsigned char period[8] );
@@ -2182,8 +2411,8 @@ int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl );
  * \brief          Perform a single step of the SSL handshake
  *
  * \note           The state of the context (ssl->state) will be at
- *                 the following state after execution of this function.
- *                 Do not call this function if state is MBEDTLS_SSL_HANDSHAKE_OVER.
+ *                 the next state after execution of this function. Do not
+ *                 call this function if state is MBEDTLS_SSL_HANDSHAKE_OVER.
  *
  * \note           If this function returns something other than 0 or
  *                 MBEDTLS_ERR_SSL_WANT_READ/WRITE, then the ssl context
@@ -2204,11 +2433,13 @@ int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl );
  * \brief          Initiate an SSL renegotiation on the running connection.
  *                 Client: perform the renegotiation right now.
  *                 Server: request renegotiation, which will be performed
- *                 during the next call to mbedtls_ssl_read() if honored by client.
+ *                 during the next call to mbedtls_ssl_read() if honored by
+ *                 client.
  *
  * \param ssl      SSL context
  *
- * \return         0 if successful, or any mbedtls_ssl_handshake() return value.
+ * \return         0 if successful, or any mbedtls_ssl_handshake() return
+ *                 value.
  *
  * \note           If this function returns something other than 0 or
  *                 MBEDTLS_ERR_SSL_WANT_READ/WRITE, then the ssl context
@@ -2269,7 +2500,7 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
  * \param len      how many bytes must be written
  *
  * \return         the number of bytes actually written (may be less than len),
- *                 or MBEDTLS_ERR_SSL_WANT_WRITE of MBEDTLS_ERR_SSL_WANT_READ,
+ *                 or MBEDTLS_ERR_SSL_WANT_WRITE or MBEDTLS_ERR_SSL_WANT_READ,
  *                 or another negative error code.
  *
  * \note           If this function returns something other than a positive
@@ -2354,7 +2585,6 @@ void mbedtls_ssl_config_init( mbedtls_ssl_config *conf );
  * \param transport MBEDTLS_SSL_TRANSPORT_STREAM for TLS, or
  *                  MBEDTLS_SSL_TRANSPORT_DATAGRAM for DTLS
  * \param preset   a MBEDTLS_SSL_PRESET_XXX value
- *                 (currently unused).
  *
  * \note           See \c mbedtls_ssl_conf_transport() for notes on DTLS.
  *

+ 3 - 2
app/include/mbedtls/ssl_cache.h

@@ -2,7 +2,8 @@
  * \file ssl_cache.h
  *
  * \brief SSL session cache implementation
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -60,7 +61,7 @@ typedef struct mbedtls_ssl_cache_entry mbedtls_ssl_cache_entry;
 struct mbedtls_ssl_cache_entry
 {
 #if defined(MBEDTLS_HAVE_TIME)
-    time_t timestamp;           /*!< entry timestamp    */
+    mbedtls_time_t timestamp;           /*!< entry timestamp    */
 #endif
     mbedtls_ssl_session session;        /*!< entry session      */
 #if defined(MBEDTLS_X509_CRT_PARSE_C)

+ 167 - 2
app/include/mbedtls/ssl_ciphersuites.h

@@ -2,7 +2,8 @@
  * \file ssl_ciphersuites.h
  *
  * \brief SSL Ciphersuites for mbed TLS
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -260,6 +261,47 @@ typedef enum {
 #define MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED
 #endif
 
+/* Key exchanges allowing client certificate requests */
+#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)           ||       \
+    defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)       ||       \
+    defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)      ||       \
+    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)     ||       \
+    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)    ||       \
+    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) 
+#define MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED
+#endif
+
+/* Key exchanges involving server signature in ServerKeyExchange */
+#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)       || \
+    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)     || \
+    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED
+#endif
+
+/* Key exchanges using ECDH */
+#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)      || \
+    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED
+#endif
+
+/* Key exchanges that don't involve ephemeral keys */
+#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)           || \
+    defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)           || \
+    defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)       || \
+    defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED
+#endif
+
+/* Key exchanges that involve ephemeral keys */
+#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)       || \
+    defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)       || \
+    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)     || \
+    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)     || \
+    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)   || \
+    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED
+#endif
+
 /* Key exchanges using a PSK */
 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)           || \
     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)       || \
@@ -268,7 +310,13 @@ typedef enum {
 #define MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
 #endif
 
-/* Key exchanges using a ECDHE */
+/* Key exchanges using DHE */
+#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)       || \
+    defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED
+#endif
+
+/* Key exchanges using ECDHE */
 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)     || \
     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)   || \
     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
@@ -309,11 +357,128 @@ const mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_id( int ciphersuit
 
 #if defined(MBEDTLS_PK_C)
 mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_pk_alg( const mbedtls_ssl_ciphersuite_t *info );
+mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg( const mbedtls_ssl_ciphersuite_t *info );
 #endif
 
 int mbedtls_ssl_ciphersuite_uses_ec( const mbedtls_ssl_ciphersuite_t *info );
 int mbedtls_ssl_ciphersuite_uses_psk( const mbedtls_ssl_ciphersuite_t *info );
 
+#if defined(MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED)
+static inline int mbedtls_ssl_ciphersuite_has_pfs( const mbedtls_ssl_ciphersuite_t *info )
+{
+    switch( info->key_exchange )
+    {
+        case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
+        case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
+        case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
+        case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
+        case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
+        case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
+            return( 1 );
+
+        default:
+            return( 0 );
+    }
+}
+#endif /* MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED */
+
+#if defined(MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED)
+static inline int mbedtls_ssl_ciphersuite_no_pfs( const mbedtls_ssl_ciphersuite_t *info )
+{
+    switch( info->key_exchange )
+    {
+        case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
+        case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
+        case MBEDTLS_KEY_EXCHANGE_RSA:
+        case MBEDTLS_KEY_EXCHANGE_PSK:
+        case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
+            return( 1 );
+
+        default:
+            return( 0 );
+    }
+}
+#endif /* MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED */
+
+#if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED)
+static inline int mbedtls_ssl_ciphersuite_uses_ecdh( const mbedtls_ssl_ciphersuite_t *info )
+{
+    switch( info->key_exchange )
+    {
+        case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
+        case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
+            return( 1 );
+
+        default:
+            return( 0 );
+    }
+}
+#endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED */
+
+static inline int mbedtls_ssl_ciphersuite_cert_req_allowed( const mbedtls_ssl_ciphersuite_t *info )
+{
+    switch( info->key_exchange )
+    {
+        case MBEDTLS_KEY_EXCHANGE_RSA:
+        case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
+        case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
+        case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
+        case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
+        case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
+            return( 1 );
+
+        default:
+            return( 0 );
+    }
+}
+
+#if defined(MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED)
+static inline int mbedtls_ssl_ciphersuite_uses_dhe( const mbedtls_ssl_ciphersuite_t *info )
+{
+    switch( info->key_exchange )
+    {
+        case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
+        case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
+            return( 1 );
+
+        default:
+            return( 0 );
+    }
+}
+#endif /* MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED) */
+
+#if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED)
+static inline int mbedtls_ssl_ciphersuite_uses_ecdhe( const mbedtls_ssl_ciphersuite_t *info )
+{
+    switch( info->key_exchange )
+    {
+        case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
+        case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
+        case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
+            return( 1 );
+
+        default:
+            return( 0 );
+    }
+}
+#endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED) */
+
+#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
+static inline int mbedtls_ssl_ciphersuite_uses_server_signature( const mbedtls_ssl_ciphersuite_t *info )
+{
+    switch( info->key_exchange )
+    {
+        case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
+        case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
+        case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
+            return( 1 );
+
+        default:
+            return( 0 );
+    }
+}
+#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
+
 #ifdef __cplusplus
 }
 #endif

+ 2 - 1
app/include/mbedtls/ssl_cookie.h

@@ -2,7 +2,8 @@
  * \file ssl_cookie.h
  *
  * \brief DTLS cookie callbacks implementation
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 177 - 16
app/include/mbedtls/ssl_internal.h

@@ -1,8 +1,9 @@
 /**
- * \file ssl_ticket.h
+ * \file ssl_internal.h
  *
  * \brief Internal functions shared by the SSL modules
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -24,6 +25,7 @@
 #define MBEDTLS_SSL_INTERNAL_H
 
 #include "ssl.h"
+#include "cipher.h"
 
 #if defined(MBEDTLS_MD5_C)
 #include "md5.h"
@@ -138,13 +140,33 @@
 #define MBEDTLS_SSL_PADDING_ADD              0
 #endif
 
-#define MBEDTLS_SSL_BUFFER_LEN  ( MBEDTLS_SSL_MAX_CONTENT_LEN               \
-                        + MBEDTLS_SSL_COMPRESSION_ADD               \
-                        + 29 /* counter + header + IV */    \
-                        + MBEDTLS_SSL_MAC_ADD                       \
-                        + MBEDTLS_SSL_PADDING_ADD                   \
+#define MBEDTLS_SSL_PAYLOAD_LEN ( MBEDTLS_SSL_MAX_CONTENT_LEN    \
+                        + MBEDTLS_SSL_COMPRESSION_ADD            \
+                        + MBEDTLS_MAX_IV_LENGTH                  \
+                        + MBEDTLS_SSL_MAC_ADD                    \
+                        + MBEDTLS_SSL_PADDING_ADD                \
                         )
 
+/*
+ * Check that we obey the standard's message size bounds
+ */
+
+#if MBEDTLS_SSL_MAX_CONTENT_LEN > 16384
+#error Bad configuration - record content too large.
+#endif
+
+#if MBEDTLS_SSL_PAYLOAD_LEN > 16384 + 2048
+#error Bad configuration - protected record payload too large.
+#endif
+
+/* Note: Even though the TLS record header is only 5 bytes
+   long, we're internally using 8 bytes to store the
+   implicit sequence number. */
+#define MBEDTLS_SSL_HEADER_LEN 13
+
+#define MBEDTLS_SSL_BUFFER_LEN  \
+    ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_PAYLOAD_LEN ) )
+
 /*
  * TLS extension flags (for extensions with outgoing ServerHello content
  * that need it (e.g. for RENEGOTIATION_INFO the server already knows because
@@ -157,6 +179,24 @@
 extern "C" {
 #endif
 
+#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
+    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
+/*
+ * Abstraction for a grid of allowed signature-hash-algorithm pairs.
+ */
+struct mbedtls_ssl_sig_hash_set_t
+{
+    /* At the moment, we only need to remember a single suitable
+     * hash algorithm per signature algorithm. As long as that's
+     * the case - and we don't need a general lookup function -
+     * we can implement the sig-hash-set as a map from signatures
+     * to hash algorithms. */
+    mbedtls_md_type_t rsa;
+    mbedtls_md_type_t ecdsa;
+};
+#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
+          MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
+
 /*
  * This structure contains the parameters only needed during handshake.
  */
@@ -165,9 +205,11 @@ struct mbedtls_ssl_handshake_params
     /*
      * Handshake specific crypto variables
      */
-    int sig_alg;                        /*!<  Hash algorithm for signature   */
-    int cert_type;                      /*!<  Requested cert type            */
-    int verify_sig_alg;                 /*!<  Signature algorithm for verify */
+
+#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
+    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
+    mbedtls_ssl_sig_hash_set_t hash_algs;             /*!<  Set of suitable sig-hash pairs */
+#endif
 #if defined(MBEDTLS_DHM_C)
     mbedtls_dhm_context dhm_ctx;                /*!<  DHM key exchange        */
 #endif
@@ -180,7 +222,7 @@ struct mbedtls_ssl_handshake_params
     unsigned char *ecjpake_cache;               /*!< Cache for ClientHello ext */
     size_t ecjpake_cache_len;                   /*!< Length of cached data */
 #endif
-#endif
+#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
     const mbedtls_ecp_curve_info **curves;      /*!<  Supported elliptic curves */
@@ -196,7 +238,7 @@ struct mbedtls_ssl_handshake_params
     mbedtls_ssl_key_cert *sni_key_cert; /*!< key/cert list from SNI         */
     mbedtls_x509_crt *sni_ca_chain;     /*!< trusted CAs from SNI callback  */
     mbedtls_x509_crl *sni_ca_crl;       /*!< trusted CAs CRLs from SNI      */
-#endif
+#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
 #endif /* MBEDTLS_X509_CRT_PARSE_C */
 #if defined(MBEDTLS_SSL_PROTO_DTLS)
     unsigned int out_msg_seq;           /*!<  Outgoing handshake sequence number */
@@ -219,7 +261,7 @@ struct mbedtls_ssl_handshake_params
                                               resending messages             */
     unsigned char alt_out_ctr[8];       /*!<  Alternative record epoch/counter
                                               for resending messages         */
-#endif
+#endif /* MBEDTLS_SSL_PROTO_DTLS */
 
     /*
      * Checksum contexts
@@ -330,6 +372,28 @@ struct mbedtls_ssl_flight_item
 };
 #endif /* MBEDTLS_SSL_PROTO_DTLS */
 
+#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
+    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
+
+/* Find an entry in a signature-hash set matching a given hash algorithm. */
+mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set,
+                                                 mbedtls_pk_type_t sig_alg );
+/* Add a signature-hash-pair to a signature-hash set */
+void mbedtls_ssl_sig_hash_set_add( mbedtls_ssl_sig_hash_set_t *set,
+                                   mbedtls_pk_type_t sig_alg,
+                                   mbedtls_md_type_t md_alg );
+/* Allow exactly one hash algorithm for each signature. */
+void mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set,
+                                          mbedtls_md_type_t md_alg );
+
+/* Setup an empty signature-hash set */
+static inline void mbedtls_ssl_sig_hash_set_init( mbedtls_ssl_sig_hash_set_t *set )
+{
+    mbedtls_ssl_sig_hash_set_const_hash( set, MBEDTLS_MD_NONE );
+}
+
+#endif /* MBEDTLS_SSL_PROTO_TLS1_2) &&
+          MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
 
 /**
  * \brief           Free referenced items in an SSL transform context and clear
@@ -356,6 +420,84 @@ int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl );
 void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl );
 int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl );
 
+int mbedtls_ssl_read_record_layer( mbedtls_ssl_context *ssl );
+int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl );
+int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl );
+void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl );
+
+/**
+ * \brief       Update record layer
+ *
+ *              This function roughly separates the implementation
+ *              of the logic of (D)TLS from the implementation
+ *              of the secure transport.
+ *
+ * \param  ssl  SSL context to use
+ *
+ * \return      0 or non-zero error code.
+ *
+ * \note        A clarification on what is called 'record layer' here
+ *              is in order, as many sensible definitions are possible:
+ *
+ *              The record layer takes as input an untrusted underlying
+ *              transport (stream or datagram) and transforms it into
+ *              a serially multiplexed, secure transport, which
+ *              conceptually provides the following:
+ *
+ *              (1) Three datagram based, content-agnostic transports
+ *                  for handshake, alert and CCS messages.
+ *              (2) One stream- or datagram-based transport
+ *                  for application data.
+ *              (3) Functionality for changing the underlying transform
+ *                  securing the contents.
+ *
+ *              The interface to this functionality is given as follows:
+ *
+ *              a Updating
+ *                [Currently implemented by mbedtls_ssl_read_record]
+ *
+ *                Check if and on which of the four 'ports' data is pending:
+ *                Nothing, a controlling datagram of type (1), or application
+ *                data (2). In any case data is present, internal buffers
+ *                provide access to the data for the user to process it.
+ *                Consumption of type (1) datagrams is done automatically
+ *                on the next update, invalidating that the internal buffers
+ *                for previous datagrams, while consumption of application
+ *                data (2) is user-controlled.
+ *
+ *              b Reading of application data
+ *                [Currently manual adaption of ssl->in_offt pointer]
+ *
+ *                As mentioned in the last paragraph, consumption of data
+ *                is different from the automatic consumption of control
+ *                datagrams (1) because application data is treated as a stream.
+ *
+ *              c Tracking availability of application data
+ *                [Currently manually through decreasing ssl->in_msglen]
+ *
+ *                For efficiency and to retain datagram semantics for
+ *                application data in case of DTLS, the record layer
+ *                provides functionality for checking how much application
+ *                data is still available in the internal buffer.
+ *
+ *              d Changing the transformation securing the communication.
+ *
+ *              Given an opaque implementation of the record layer in the
+ *              above sense, it should be possible to implement the logic
+ *              of (D)TLS on top of it without the need to know anything
+ *              about the record layer's internals. This is done e.g.
+ *              in all the handshake handling functions, and in the
+ *              application data reading function mbedtls_ssl_read.
+ *
+ * \note        The above tries to give a conceptual picture of the
+ *              record layer, but the current implementation deviates
+ *              from it in some places. For example, our implementation of
+ *              the update functionality through mbedtls_ssl_read_record
+ *              discards datagrams depending on the current state, which
+ *              wouldn't fall under the record layer's responsibility
+ *              following the above definition.
+ *
+ */
 int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl );
 int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want );
 
@@ -380,11 +522,13 @@ int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exch
 
 #if defined(MBEDTLS_PK_C)
 unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk );
+unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type );
 mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig );
 #endif
 
 mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash );
 unsigned char mbedtls_ssl_hash_from_md_alg( int md );
+int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md );
 
 #if defined(MBEDTLS_ECP_C)
 int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id );
@@ -478,9 +622,9 @@ void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl );
 static inline int mbedtls_ssl_safer_memcmp( const void *a, const void *b, size_t n )
 {
     size_t i;
-    const unsigned char *A = (const unsigned char *) a;
-    const unsigned char *B = (const unsigned char *) b;
-    unsigned char diff = 0;
+    volatile const unsigned char *A = (volatile const unsigned char *) a;
+    volatile const unsigned char *B = (volatile const unsigned char *) b;
+    volatile unsigned char diff = 0;
 
     for( i = 0; i < n; i++ )
         diff |= A[i] ^ B[i];
@@ -488,6 +632,23 @@ static inline int mbedtls_ssl_safer_memcmp( const void *a, const void *b, size_t
     return( diff );
 }
 
+#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
+    defined(MBEDTLS_SSL_PROTO_TLS1_1)
+int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl,
+                                        unsigned char *output,
+                                        unsigned char *data, size_t data_len );
+#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
+          MBEDTLS_SSL_PROTO_TLS1_1 */
+
+#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
+    defined(MBEDTLS_SSL_PROTO_TLS1_2)
+int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,
+                                        unsigned char *output,
+                                        unsigned char *data, size_t data_len,
+                                        mbedtls_md_type_t md_alg );
+#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
+          MBEDTLS_SSL_PROTO_TLS1_2 */
+
 #ifdef __cplusplus
 }
 #endif

+ 2 - 1
app/include/mbedtls/ssl_ticket.h

@@ -2,7 +2,8 @@
  * \file ssl_ticket.h
  *
  * \brief TLS server ticket callbacks implementation
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 4 - 1
app/include/mbedtls/threading.h

@@ -2,7 +2,8 @@
  * \file threading.h
  *
  * \brief Threading abstraction layer
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -81,6 +82,7 @@ void mbedtls_threading_set_alt( void (*mutex_init)( mbedtls_threading_mutex_t *
 void mbedtls_threading_free_alt( void );
 #endif /* MBEDTLS_THREADING_ALT */
 
+#if defined(MBEDTLS_THREADING_C)
 /*
  * The function pointers for mutex_init, mutex_free, mutex_ and mutex_unlock
  *
@@ -96,6 +98,7 @@ extern int (*mbedtls_mutex_unlock)( mbedtls_threading_mutex_t *mutex );
  */
 extern mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex;
 extern mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex;
+#endif /* MBEDTLS_THREADING_C */
 
 #ifdef __cplusplus
 }

+ 25 - 5
app/include/mbedtls/timing.h

@@ -1,8 +1,9 @@
 /**
  * \file timing.h
  *
- * \brief Portable interface to the CPU cycle counter
- *
+ * \brief Portable interface to timeouts and to the CPU cycle counter
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -65,6 +66,9 @@ extern volatile int mbedtls_timing_alarmed;
  * \warning        This is only a best effort! Do not rely on this!
  *                 In particular, it is known to be unreliable on virtual
  *                 machines.
+ *
+ * \note           This value starts at an unspecified origin and
+ *                 may wrap around.
  */
 unsigned long mbedtls_timing_hardclock( void );
 
@@ -72,7 +76,18 @@ unsigned long mbedtls_timing_hardclock( void );
  * \brief          Return the elapsed time in milliseconds
  *
  * \param val      points to a timer structure
- * \param reset    if set to 1, the timer is restarted
+ * \param reset    If 0, query the elapsed time. Otherwise (re)start the timer.
+ *
+ * \return         Elapsed time since the previous reset in ms. When
+ *                 restarting, this is always 0.
+ *
+ * \note           To initialize a timer, call this function with reset=1.
+ *
+ *                 Determining the elapsed time and resetting the timer is not
+ *                 atomic on all platforms, so after the sequence
+ *                 `{ get_timer(1); ...; time1 = get_timer(1); ...; time2 =
+ *                 get_timer(0) }` the value time1+time2 is only approximately
+ *                 the delay since the first reset.
  */
 unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset );
 
@@ -80,6 +95,7 @@ unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int
  * \brief          Setup an alarm clock
  *
  * \param seconds  delay before the "mbedtls_timing_alarmed" flag is set
+ *                 (must be >=0)
  *
  * \warning        Only one alarm at a time  is supported. In a threaded
  *                 context, this means one for the whole process, not one per
@@ -91,11 +107,15 @@ void mbedtls_set_alarm( int seconds );
  * \brief          Set a pair of delays to watch
  *                 (See \c mbedtls_timing_get_delay().)
  *
- * \param data     Pointer to timing data
+ * \param data     Pointer to timing data.
  *                 Must point to a valid \c mbedtls_timing_delay_context struct.
  * \param int_ms   First (intermediate) delay in milliseconds.
+ *                 The effect if int_ms > fin_ms is unspecified.
  * \param fin_ms   Second (final) delay in milliseconds.
  *                 Pass 0 to cancel the current delay.
+ *
+ * \note           To set a single delay, either use \c mbedtls_timing_set_timer
+ *                 directly or use this function with int_ms == fin_ms.
  */
 void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms );
 
@@ -106,7 +126,7 @@ void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms );
  * \param data     Pointer to timing data
  *                 Must point to a valid \c mbedtls_timing_delay_context struct.
  *
- * \return         -1 if cancelled (fin_ms = 0)
+ * \return         -1 if cancelled (fin_ms = 0),
  *                  0 if none of the delays are passed,
  *                  1 if only the intermediate delay is passed,
  *                  2 if the final delay is passed.

+ 7 - 6
app/include/mbedtls/version.h

@@ -2,7 +2,8 @@
  * \file version.h
  *
  * \brief Run-time version information
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -38,17 +39,17 @@
  * Major, Minor, Patchlevel
  */
 #define MBEDTLS_VERSION_MAJOR  2
-#define MBEDTLS_VERSION_MINOR  2
-#define MBEDTLS_VERSION_PATCH  1
+#define MBEDTLS_VERSION_MINOR  7
+#define MBEDTLS_VERSION_PATCH  0
 
 /**
  * The single version number has the following structure:
  *    MMNNPP00
  *    Major version | Minor version | Patch version
  */
-#define MBEDTLS_VERSION_NUMBER         0x02020100
-#define MBEDTLS_VERSION_STRING         "2.2.1"
-#define MBEDTLS_VERSION_STRING_FULL    "mbed TLS 2.2.1"
+#define MBEDTLS_VERSION_NUMBER         0x02070000
+#define MBEDTLS_VERSION_STRING         "2.7.0"
+#define MBEDTLS_VERSION_STRING_FULL    "mbed TLS 2.7.0"
 
 #if defined(MBEDTLS_VERSION_C)
 

+ 9 - 7
app/include/mbedtls/x509.h

@@ -2,7 +2,8 @@
  * \file x509.h
  *
  * \brief X.509 generic defines and structures
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -76,6 +77,7 @@
 #define MBEDTLS_ERR_X509_ALLOC_FAILED                     -0x2880  /**< Allocation of memory failed. */
 #define MBEDTLS_ERR_X509_FILE_IO_ERROR                    -0x2900  /**< Read/write of file failed. */
 #define MBEDTLS_ERR_X509_BUFFER_TOO_SMALL                 -0x2980  /**< Destination buffer is too small. */
+#define MBEDTLS_ERR_X509_FATAL_ERROR                      -0x3000  /**< A fatal error occured, eg the chain is too long or the vrfy callback failed. */
 /* \} name */
 
 /**
@@ -157,7 +159,7 @@
 #define MBEDTLS_X509_EXT_INIHIBIT_ANYPOLICY          (1 << 13)
 #define MBEDTLS_X509_EXT_FRESHEST_CRL                (1 << 14)
 
-#define MBEDTLS_X509_EXT_NS_CERT_TYPE                (1 << 16)   /* Parsed (and then ?) */
+#define MBEDTLS_X509_EXT_NS_CERT_TYPE                (1 << 16)
 
 /*
  * Storage format identifiers
@@ -246,12 +248,12 @@ int mbedtls_x509_serial_gets( char *buf, size_t size, const mbedtls_x509_buf *se
  * \note           Intended usage is "if( is_past( valid_to ) ) ERROR".
  *                 Hence the return value of 1 if on internal errors.
  *
- * \param time     mbedtls_x509_time to check
+ * \param to       mbedtls_x509_time to check
  *
  * \return         1 if the given time is in the past or an error occured,
  *                 0 otherwise.
  */
-int mbedtls_x509_time_is_past( const mbedtls_x509_time *time );
+int mbedtls_x509_time_is_past( const mbedtls_x509_time *to );
 
 /**
  * \brief          Check a given mbedtls_x509_time against the system time
@@ -260,12 +262,12 @@ int mbedtls_x509_time_is_past( const mbedtls_x509_time *time );
  * \note           Intended usage is "if( is_future( valid_from ) ) ERROR".
  *                 Hence the return value of 1 if on internal errors.
  *
- * \param time     mbedtls_x509_time to check
+ * \param from     mbedtls_x509_time to check
  *
  * \return         1 if the given time is in the future or an error occured,
  *                 0 otherwise.
  */
-int mbedtls_x509_time_is_future( const mbedtls_x509_time *time );
+int mbedtls_x509_time_is_future( const mbedtls_x509_time *from );
 
 /**
  * \brief          Checkup routine
@@ -294,7 +296,7 @@ int mbedtls_x509_get_sig_alg( const mbedtls_x509_buf *sig_oid, const mbedtls_x50
                       mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg,
                       void **sig_opts );
 int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end,
-                   mbedtls_x509_time *time );
+                   mbedtls_x509_time *t );
 int mbedtls_x509_get_serial( unsigned char **p, const unsigned char *end,
                      mbedtls_x509_buf *serial );
 int mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end,

+ 2 - 1
app/include/mbedtls/x509_crl.h

@@ -2,7 +2,8 @@
  * \file x509_crl.h
  *
  * \brief X.509 certificate revocation list parsing
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *

+ 41 - 23
app/include/mbedtls/x509_crt.h

@@ -2,7 +2,8 @@
  * \file x509_crt.h
  *
  * \brief X.509 certificate parsing and writing
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -120,6 +121,10 @@ mbedtls_x509_crt_profile;
 #define MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN 32
 #define MBEDTLS_X509_RFC5280_UTC_TIME_LEN   15
 
+#if !defined( MBEDTLS_X509_MAX_FILE_PATH_LEN )
+#define MBEDTLS_X509_MAX_FILE_PATH_LEN 512
+#endif
+
 /**
  * Container for writing a certificate (CRT)
  */
@@ -263,7 +268,13 @@ int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
  *
  *                 All flags left after returning from the callback
  *                 are also returned to the application. The function should
- *                 return 0 for anything but a fatal error.
+ *                 return 0 for anything (including invalid certificates)
+ *                 other than fatal error, as a non-zero return code
+ *                 immediately aborts the verification process. For fatal
+ *                 errors, a specific error code should be used (different
+ *                 from MBEDTLS_ERR_X509_CERT_VERIFY_FAILED which should not
+ *                 be returned at this point), or MBEDTLS_ERR_X509_FATAL_ERROR
+ *                 can be used if no better code is available.
  *
  * \note           In case verification failed, the results can be displayed
  *                 using \c mbedtls_x509_crt_verify_info()
@@ -271,21 +282,27 @@ int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
  * \note           Same as \c mbedtls_x509_crt_verify_with_profile() with the
  *                 default security profile.
  *
- * \param crt      a certificate to be verified
- * \param trust_ca the trusted CA chain
- * \param ca_crl   the CRL chain for trusted CA's
+ * \note           It is your responsibility to provide up-to-date CRLs for
+ *                 all trusted CAs. If no CRL is provided for the CA that was
+ *                 used to sign the certificate, CRL verification is skipped
+ *                 silently, that is *without* setting any flag.
+ *
+ * \param crt      a certificate (chain) to be verified
+ * \param trust_ca the list of trusted CAs
+ * \param ca_crl   the list of CRLs for trusted CAs (see note above)
  * \param cn       expected Common Name (can be set to
  *                 NULL if the CN must not be verified)
  * \param flags    result of the verification
  * \param f_vrfy   verification function
  * \param p_vrfy   verification parameter
  *
- * \return         0 if successful or MBEDTLS_ERR_X509_CERT_VERIFY_FAILED
- *                 in which case *flags will have one or more
- *                 MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX flags
- *                 set,
- *                 or another error in case of a fatal error encountered
- *                 during the verification process.
+ * \return         0 (and flags set to 0) if the chain was verified and valid,
+ *                 MBEDTLS_ERR_X509_CERT_VERIFY_FAILED if the chain was verified
+ *                 but found to be invalid, in which case *flags will have one
+ *                 or more MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX
+ *                 flags set, or another error (and flags set to 0xffffffff)
+ *                 in case of a fatal error encountered during the
+ *                 verification process.
  */
 int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
                      mbedtls_x509_crt *trust_ca,
@@ -304,9 +321,9 @@ int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
  *                 for ECDSA) apply to all certificates: trusted root,
  *                 intermediate CAs if any, and end entity certificate.
  *
- * \param crt      a certificate to be verified
- * \param trust_ca the trusted CA chain
- * \param ca_crl   the CRL chain for trusted CA's
+ * \param crt      a certificate (chain) to be verified
+ * \param trust_ca the list of trusted CAs
+ * \param ca_crl   the list of CRLs for trusted CAs
  * \param profile  security profile for verification
  * \param cn       expected Common Name (can be set to
  *                 NULL if the CN must not be verified)
@@ -357,21 +374,22 @@ int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
 
 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
 /**
- * \brief          Check usage of certificate against extentedJeyUsage.
+ * \brief           Check usage of certificate against extendedKeyUsage.
  *
- * \param crt      Leaf certificate used.
- * \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or MBEDTLS_OID_CLIENT_AUTH).
+ * \param crt       Leaf certificate used.
+ * \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or
+ *                  MBEDTLS_OID_CLIENT_AUTH).
  * \param usage_len Length of usage_oid (eg given by MBEDTLS_OID_SIZE()).
  *
- * \return         0 if this use of the certificate is allowed,
- *                 MBEDTLS_ERR_X509_BAD_INPUT_DATA if not.
+ * \return          0 if this use of the certificate is allowed,
+ *                  MBEDTLS_ERR_X509_BAD_INPUT_DATA if not.
  *
- * \note           Usually only makes sense on leaf certificates.
+ * \note            Usually only makes sense on leaf certificates.
  */
 int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
-                                       const char *usage_oid,
-                                       size_t usage_len );
-#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) */
+                                               const char *usage_oid,
+                                               size_t usage_len );
+#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
 
 #if defined(MBEDTLS_X509_CRL_PARSE_C)
 /**

+ 9 - 2
app/include/mbedtls/x509_csr.h

@@ -2,7 +2,8 @@
  * \file x509_csr.h
  *
  * \brief X.509 certificate signing request parsing and writing
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -83,6 +84,8 @@ mbedtls_x509write_csr;
 /**
  * \brief          Load a Certificate Signing Request (CSR) in DER format
  *
+ * \note           CSR attributes (if any) are currently silently ignored.
+ *
  * \param csr      CSR context to fill
  * \param buf      buffer holding the CRL data
  * \param buflen   size of the buffer
@@ -95,6 +98,8 @@ int mbedtls_x509_csr_parse_der( mbedtls_x509_csr *csr,
 /**
  * \brief          Load a Certificate Signing Request (CSR), DER or PEM format
  *
+ * \note           See notes for \c mbedtls_x509_csr_parse_der()
+ *
  * \param csr      CSR context to fill
  * \param buf      buffer holding the CRL data
  * \param buflen   size of the buffer
@@ -108,6 +113,8 @@ int mbedtls_x509_csr_parse( mbedtls_x509_csr *csr, const unsigned char *buf, siz
 /**
  * \brief          Load a Certificate Signing Request (CSR)
  *
+ * \note           See notes for \c mbedtls_x509_csr_parse()
+ *
  * \param csr      CSR context to fill
  * \param path     filename to read the CSR from
  *
@@ -276,7 +283,7 @@ int mbedtls_x509write_csr_der( mbedtls_x509write_csr *ctx, unsigned char *buf, s
  *
  * \note            f_rng may be NULL if RSA is used for signature and the
  *                  signature is made offline (otherwise f_rng is desirable
- *                  for couermeasures against timing attacks).
+ *                  for countermeasures against timing attacks).
  *                  ECDSA signatures always require a non-NULL f_rng.
  */
 int mbedtls_x509write_csr_pem( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size,

+ 3 - 1
app/include/mbedtls/xtea.h

@@ -2,7 +2,8 @@
  * \file xtea.h
  *
  * \brief XTEA block cipher (32-bit)
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -36,6 +37,7 @@
 #define MBEDTLS_XTEA_DECRYPT     0
 
 #define MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH             -0x0028  /**< The data input has an invalid length. */
+#define MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED                  -0x0029  /**< XTEA hardware accelerator failed. */
 
 #if !defined(MBEDTLS_XTEA_ALT)
 // Regular implementation

+ 35 - 28
app/include/rtc/rtctime_internal.h

@@ -187,8 +187,9 @@
 #define CPU_BOOTUP_MHZ    52
 
 #ifdef RTC_DEBUG_ENABLED
+#warn this does not really work....
 #define RTC_DBG(...)         do { if (rtc_dbg_enabled == 'R') { dbg_printf(__VA_ARGS__); } } while (0)
-static bool rtc_dbg_enabled;
+static char rtc_dbg_enabled;
 #define RTC_DBG_ENABLED()   rtc_dbg_enabled = 'R'
 #define RTC_DBG_NOT_ENABLED()   rtc_dbg_enabled = 0
 #else
@@ -197,6 +198,8 @@ static bool rtc_dbg_enabled;
 #define RTC_DBG_NOT_ENABLED()
 #endif
 
+#define NOINIT_ATTR __attribute__((section(".noinit")))
+
 // RTCTIME storage
 #define RTC_TIME_MAGIC_POS       (RTC_TIME_BASE+0)
 #define RTC_CYCLEOFFSETL_POS     (RTC_TIME_BASE+1)
@@ -210,18 +213,18 @@ static bool rtc_dbg_enabled;
 //#define RTC_LASTTODUS_POS        (RTC_TIME_BASE+9)
 #define RTC_USRATE_POS		 (RTC_TIME_BASE+8)
 
-static uint32_t rtc_time_magic;
-static uint64_t rtc_cycleoffset;
-static uint32_t rtc_lastsourceval;
-static uint32_t rtc_sourcecycleunits;
-static uint32_t rtc_calibration;
-static uint32_t rtc_sleeptotalus;
-static uint32_t rtc_sleeptotalcycles;
-static uint64_t rtc_usatlastrate;
-static uint64_t rtc_rateadjustedus;
-static uint32_t rtc_todoffsetus;
-static uint32_t rtc_lasttodus;
-static uint32_t rtc_usrate;
+NOINIT_ATTR uint32_t rtc_time_magic;
+NOINIT_ATTR uint64_t rtc_cycleoffset;
+NOINIT_ATTR uint32_t rtc_lastsourceval;
+NOINIT_ATTR uint32_t rtc_sourcecycleunits;
+NOINIT_ATTR uint32_t rtc_calibration;
+NOINIT_ATTR uint32_t rtc_sleeptotalus;
+NOINIT_ATTR uint32_t rtc_sleeptotalcycles;
+NOINIT_ATTR uint64_t rtc_usatlastrate;
+NOINIT_ATTR uint64_t rtc_rateadjustedus;
+NOINIT_ATTR uint32_t rtc_todoffsetus;
+NOINIT_ATTR uint32_t rtc_lasttodus;
+NOINIT_ATTR uint32_t rtc_usrate;
 
 
 struct rtc_timeval
@@ -503,11 +506,6 @@ extern void rtc_time_enter_deep_sleep_final(void);
 
 static void rtc_time_enter_deep_sleep_us(uint32_t us)
 {
-  if (rtc_time_check_wake_magic())
-    rtc_time_set_sleep_magic();
-  else 
-    bbram_save();
-
   rtc_reg_write(0,0);
   rtc_reg_write(0,rtc_reg_read(0)&0xffffbfff);
   rtc_reg_write(0,rtc_reg_read(0)|0x30);
@@ -533,6 +531,11 @@ static void rtc_time_enter_deep_sleep_us(uint32_t us)
   uint32_t cycles=rtc_time_us_to_ticks(us);
   rtc_time_add_sleep_tracking(us,cycles);
 
+  if (rtc_time_check_wake_magic())
+    rtc_time_set_sleep_magic();
+  else 
+    bbram_save();
+
   rtc_reg_write(RTC_TARGET_ADDR,rtc_time_read_raw()+cycles);
   rtc_reg_write(0x9c,17);
   rtc_reg_write(0xa0,3);
@@ -744,17 +747,15 @@ static void rtc_time_register_bootup(void)
     if (reset_reason!=2)  // This was *not* a proper wakeup from a deep sleep. All our time keeping is f*cked!
       rtc_time_reset(erase_calibration); // Possibly keep the calibration, it should still be good
     rtc_time_select_ccount_source(CPU_BOOTUP_MHZ,true);
-    rtc_rateadjustedus = rtc_usatlastrate = rtc_time_get_now_us_adjusted();
     rtc_todoffsetus = 0;
+    rtc_rateadjustedus = rtc_usatlastrate = rtc_time_get_now_us_adjusted();
     RTC_DBG_ENABLED();
     return;
   }
 
-  if (rtc_time_check_magic())
-  {
-    // We did not go to sleep properly. All our time keeping is f*cked!
-    rtc_time_reset(erase_calibration); // Possibly keep the calibration, it should still be good
-  }
+  // We did not go to sleep properly. All our time keeping is f*cked!
+  rtc_time_reset(erase_calibration); // Possibly keep the calibration, it should still be good
+
   RTC_DBG_ENABLED();
 }
 
@@ -778,6 +779,10 @@ static inline void rtc_time_prepare(void)
   rtc_time_select_frc2_source();
 }
 
+static int32_t rtc_time_adjust_delta_by_rate(int32_t delta) {
+  return (delta * ((1ull << 32) + (int) rtc_usrate)) >> 32;
+}
+
 static uint64_t rtc_time_adjust_us_by_rate(uint64_t us, int force) {
   uint64_t usoff = us - rtc_usatlastrate; 
   uint64_t usadj = (usoff * ((1ull << 32) + (int) rtc_usrate)) >> 32;
@@ -856,7 +861,8 @@ static void rtc_time_settimeofday(const struct rtc_timeval* tv)
 
   // calibrate sleep period based on difference between expected time and actual time
   if (sleep_us>0 && sleep_us<0xffffffff &&
-      sleep_cycles>0 && sleep_cycles<0xffffffff)
+      sleep_cycles>0 && sleep_cycles<0xffffffff &&
+      tv->tv_sec)
   {
     uint64_t actual_sleep_us=sleep_us-diff_us;
     uint32_t cali=(actual_sleep_us<<12)/sleep_cycles;
@@ -872,14 +878,15 @@ static void rtc_time_settimeofday(const struct rtc_timeval* tv)
   rtc_usrate = 0;
 
   // Deal with time adjustment if necessary
-  if (diff_us>0) // Time went backwards. Avoid that....
+  if (diff_us>0 && tv->tv_sec) // Time went backwards. Avoid that....
   {
     if (diff_us>0xffffffffULL)
       diff_us=0xffffffffULL;
     now_ntp_us+=diff_us;
-  }
-  else
+  } else {
     diff_us=0;
+  }
+
   rtc_todoffsetus = diff_us;
 
   uint32_t now_s=now_ntp_us/1000000;

+ 1 - 1
app/include/sys/espconn_mbedtls.h

@@ -31,7 +31,7 @@
 
 #if !defined(ESPCONN_MBEDTLS)
 
-#include "mbedtls/net.h"
+#include "mbedtls/net_sockets.h"
 #include "mbedtls/debug.h"
 #include "mbedtls/ssl.h"
 #include "mbedtls/entropy.h"

+ 98 - 0
app/include/sys/network_80211.h

@@ -0,0 +1,98 @@
+#define FRAME_TYPE_MANAGEMENT 0
+#define FRAME_TYPE_CONTROL 1
+#define FRAME_TYPE_DATA 2
+#define FRAME_SUBTYPE_ASSOC_REQUEST 0x00
+#define FRAME_SUBTYPE_ASSOC_RESPONSE 0x01
+#define FRAME_SUBTYPE_REASSOC_REQUEST 0x02
+#define FRAME_SUBTYPE_REASSOC_RESPONSE 0x03
+#define FRAME_SUBTYPE_PROBE_REQUEST 0x04
+#define FRAME_SUBTYPE_PROBE_RESPONSE 0x05
+#define FRAME_SUBTYPE_BEACON 0x08
+#define FRAME_SUBTYPE_ATIM 0x09
+#define FRAME_SUBTYPE_DISASSOCIATION 0x0a
+#define FRAME_SUBTYPE_AUTHENTICATION 0x0b
+#define FRAME_SUBTYPE_DEAUTHENTICATION 0x0c
+#define FRAME_SUBTYPE_DATA 0x14
+typedef struct framectrl_80211
+{
+    //buf[0]
+    u8 Protocol:2;
+    u8 Type:2;
+    u8 Subtype:4;
+    //buf[1]
+    u8 ToDS:1;
+    u8 FromDS:1;
+    u8 MoreFlag:1;
+    u8 Retry:1;
+    u8 PwrMgmt:1;
+    u8 MoreData:1;
+    u8 Protectedframe:1;
+    u8 Order:1;
+} framectrl_80211,*lpframectrl_80211;
+
+typedef struct management_80211
+{
+	struct framectrl_80211 framectrl;
+	uint16 duration;
+	uint8 rdaddr[6];
+	uint8 tsaddr[6];
+	uint8 bssid[6];
+	uint16 number;
+} management_request_t;
+
+typedef struct
+{
+	management_request_t hdr;
+        uint8 timestamp[8];
+	uint16 beacon_interval;
+	uint16 capability_info;
+} wifi_beacon_t;
+
+typedef struct tagged_parameter
+{
+	/* SSID parameter */
+	uint8 tag_number;
+	uint8 tag_length;
+} tagged_parameter, *ptagged_parameter;
+
+struct RxControl {
+    signed rssi:8;//表示该包的信号强度
+    unsigned rate:4;
+    unsigned is_group:1;
+    unsigned:1;
+    unsigned sig_mode:2;//表示该包是否是11n的包,0表示非11n,非0表示11n
+    unsigned legacy_length:12;//如果不是11n的包,它表示包的长度
+    unsigned damatch0:1;
+    unsigned damatch1:1;
+    unsigned bssidmatch0:1;
+    unsigned bssidmatch1:1;
+    unsigned MCS:7;//如果是11n的包,它表示包的调制编码序列,有效值:0-76
+    unsigned CWB:1;//如果是11n的包,它表示是否为HT40的包
+    unsigned HT_length:16;//如果是11n的包,它表示包的长度
+    unsigned Smoothing:1;
+    unsigned Not_Sounding:1;
+    unsigned:1;
+    unsigned Aggregation:1;
+    unsigned STBC:2;
+    unsigned FEC_CODING:1;//如果是11n的包,它表示是否为LDPC的包
+    unsigned SGI:1;
+    unsigned rxend_state:8;
+    unsigned ampdu_cnt:8;
+    unsigned channel:4;//表示该包所在的信道
+    unsigned:12;
+};
+
+struct sniffer_buf2{
+	struct RxControl rx_ctrl;
+	u8 buf[112];//包含ieee80211包头
+	u16 cnt;//包的个数
+	u16 len[1];//包的长度
+};
+
+struct sniffer_buf{
+	struct RxControl rx_ctrl;
+	u8 buf[48];//包含ieee80211包头
+	u16 cnt;//包的个数
+	u16 len[1];//包的长度
+};
+

+ 35 - 18
app/include/user_mbedtls.h

@@ -1,12 +1,15 @@
 #include "c_types.h"
 
+#include "user_config.h"
+
 #undef MBEDTLS_HAVE_ASM
 #undef MBEDTLS_HAVE_SSE2
 
-#define MBEDTLS_HAVE_TIME
-#define MBEDTLS_HAVE_TIME_DATE
+// These are disabled until we have a real, working RTC-based gettimeofday
+#undef MBEDTLS_HAVE_TIME
+#undef MBEDTLS_HAVE_TIME_DATE
 
-#undef MBEDTLS_PLATFORM_MEMORY
+#define MBEDTLS_PLATFORM_MEMORY
 #undef MBEDTLS_PLATFORM_NO_STD_FUNCTIONS
 
 #undef MBEDTLS_PLATFORM_EXIT_ALT
@@ -126,8 +129,6 @@
 
 #define MBEDTLS_SHA256_SMALLER
 
-#undef MBEDTLS_SSL_AEAD_RANDOM_IV
-
 #define MBEDTLS_SSL_ALL_ALERT_MESSAGES
 #undef MBEDTLS_SSL_DEBUG_ALL
 
@@ -149,13 +150,13 @@
 #define MBEDTLS_SSL_PROTO_TLS1
 #define MBEDTLS_SSL_PROTO_TLS1_1
 #define MBEDTLS_SSL_PROTO_TLS1_2
-#define MBEDTLS_SSL_PROTO_DTLS
+#undef MBEDTLS_SSL_PROTO_DTLS
 
 #define MBEDTLS_SSL_ALPN
-#define MBEDTLS_SSL_DTLS_ANTI_REPLAY
-#define MBEDTLS_SSL_DTLS_HELLO_VERIFY
-#define MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE
-#define MBEDTLS_SSL_DTLS_BADMAC_LIMIT
+#undef MBEDTLS_SSL_DTLS_ANTI_REPLAY
+#undef MBEDTLS_SSL_DTLS_HELLO_VERIFY
+#undef MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE
+#undef MBEDTLS_SSL_DTLS_BADMAC_LIMIT
 #define MBEDTLS_SSL_SESSION_TICKETS
 #define MBEDTLS_SSL_EXPORT_KEYS
 #define MBEDTLS_SSL_SERVER_NAME_INDICATION
@@ -187,6 +188,7 @@
 #define MBEDTLS_CCM_C
 #undef MBEDTLS_CERTS_C
 #define MBEDTLS_CIPHER_C
+#define MBEDTLS_CMAC_C
 #define MBEDTLS_CTR_DRBG_C
 #undef MBEDTLS_DEBUG_C
 #define MBEDTLS_DES_C
@@ -260,13 +262,14 @@
 
 //#define MBEDTLS_ENTROPY_MAX_SOURCES                20 /**< Maximum number of sources supported */
 //#define MBEDTLS_ENTROPY_MAX_GATHER                128 /**< Maximum amount requested from entropy sources */
+//#define MBEDTLS_ENTROPY_MIN_HARDWARE               32 /**< Default minimum number of bytes required for the hardware entropy source mbedtls_hardware_poll() before entropy is released */
 //#define MBEDTLS_MEMORY_ALIGN_MULTIPLE      4 /**< Align on multiples of this value */
 
 //#define MBEDTLS_PLATFORM_STD_MEM_HDR   <stdlib.h> /**< Header to include if MBEDTLS_PLATFORM_NO_STD_FUNCTIONS is defined. Don't define if no header is needed. */
-//#define MBEDTLS_PLATFORM_STD_CALLOC        calloc /**< Default allocator to use, can be undefined */
-//#define MBEDTLS_PLATFORM_STD_FREE            free /**< Default free to use, can be undefined */
+#define MBEDTLS_PLATFORM_STD_CALLOC        pvPortCalloc /**< Default allocator to use, can be undefined */
+#define MBEDTLS_PLATFORM_STD_FREE            vPortFree /**< Default free to use, can be undefined */
 //#define MBEDTLS_PLATFORM_STD_EXIT            exit /**< Default exit to use, can be undefined */
-//#define MBEDTLS_PLATFORM_STD_TIME            time /**< Default time to use, can be undefined */
+//#define MBEDTLS_PLATFORM_STD_TIME            time /**< Default time to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */
 //#define MBEDTLS_PLATFORM_STD_FPRINTF      fprintf /**< Default fprintf to use, can be undefined */
 //#define MBEDTLS_PLATFORM_STD_PRINTF        printf /**< Default printf to use, can be undefined */
 //#define MBEDTLS_PLATFORM_STD_SNPRINTF    snprintf /**< Default snprintf to use, can be undefined */
@@ -278,19 +281,33 @@
 //#define MBEDTLS_PLATFORM_CALLOC_MACRO        calloc /**< Default allocator macro to use, can be undefined */
 //#define MBEDTLS_PLATFORM_FREE_MACRO            free /**< Default free macro to use, can be undefined */
 //#define MBEDTLS_PLATFORM_EXIT_MACRO            exit /**< Default exit macro to use, can be undefined */
-//#define MBEDTLS_PLATFORM_TIME_MACRO            time /**< Default time macro to use, can be undefined */
-//#define MBEDTLS_PLATFORM_TIME_TYPE_MACRO       time_t /**< Default time macro to use, can be undefined */
+//#define MBEDTLS_PLATFORM_TIME_MACRO            time /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */
+//#define MBEDTLS_PLATFORM_TIME_TYPE_MACRO       time_t /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */
 //#define MBEDTLS_PLATFORM_FPRINTF_MACRO      fprintf /**< Default fprintf macro to use, can be undefined */
-//#define MBEDTLS_PLATFORM_PRINTF_MACRO        printf /**< Default printf macro to use, can be undefined */
-//#define MBEDTLS_PLATFORM_SNPRINTF_MACRO    snprintf /**< Default snprintf macro to use, can be undefined */
+#define MBEDTLS_PLATFORM_PRINTF_MACRO        ets_printf /**< Default printf macro to use, can be undefined */
+#define MBEDTLS_PLATFORM_SNPRINTF_MACRO    ets_snprintf /**< Default snprintf macro to use, can be undefined */
+#define MBEDTLS_PLATFORM_VSNPRINTF_MACRO    ets_vsnprintf /**< Default vsnprintf macro to use, can be undefined */
 //#define MBEDTLS_PLATFORM_NV_SEED_READ_MACRO   mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */
 //#define MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO  mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */
 //#define MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT       86400 /**< 1 day  */
 //#define MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES      50 /**< Maximum entries in cache */
-#define MBEDTLS_SSL_MAX_CONTENT_LEN             4096 /**< Maxium fragment length in bytes, determines the size of each of the two internal I/O buffers */
+
+#if 0
+// dynamic buffer sizing with espconn_secure_set_size()
+extern unsigned int max_content_len;
+#define MBEDTLS_SSL_MAX_CONTENT_LEN             max_content_len;
+#else
+// the current mbedtls integration doesn't allow to set the buffer size dynamically:
+//   MBEDTLS_SSL_MAX_FRAGMENT_LENGTH feature and dynamic sizing are mutually exclusive
+//   due to non-constant initializer element in app/mbedtls/library/ssl_tls.c:150 
+// the buffer size is hardcoded here and value is taken from SSL_BUFFER_SIZE (user_config.h)
+#define MBEDTLS_SSL_MAX_CONTENT_LEN             SSL_BUFFER_SIZE /**< Maxium fragment length in bytes, determines the size of each of the two internal I/O buffers */
+#endif
+
 //#define MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME     86400 /**< Lifetime of session tickets (if enabled) */
 //#define MBEDTLS_PSK_MAX_LEN               32 /**< Max size of TLS pre-shared keys, in bytes (default 256 bits) */
 //#define MBEDTLS_SSL_COOKIE_TIMEOUT        60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */
 
 //#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
 #define MBEDTLS_X509_MAX_INTERMEDIATE_CA   3   /**< Maximum number of intermediate CAs in a verification chain. */
+//#define MBEDTLS_X509_MAX_FILE_PATH_LEN     512 /**< Maximum length of a path/filename string in bytes including the null terminator character ('\0'). */

+ 7 - 0
app/include/user_modules.h

@@ -23,9 +23,12 @@
 //#define LUA_USE_MODULES_AM2320
 //#define LUA_USE_MODULES_APA102
 #define LUA_USE_MODULES_BIT
+//#define LUA_USE_MODULES_BLOOM
 //#define LUA_USE_MODULES_BMP085
 //#define LUA_USE_MODULES_BME280
+//#define LUA_USE_MODULES_BME680
 //#define LUA_USE_MODULES_COAP
+//#define LUA_USE_MODULES_COLOR_UTILS
 //#define LUA_USE_MODULES_CRON
 //#define LUA_USE_MODULES_CRYPTO
 #define LUA_USE_MODULES_DHT
@@ -35,6 +38,7 @@
 #define LUA_USE_MODULES_FILE
 //#define LUA_USE_MODULES_GDBSTUB
 #define LUA_USE_MODULES_GPIO
+//#define LUA_USE_MODULES_GPIO_PULSE
 //#define LUA_USE_MODULES_HDC1080
 //#define LUA_USE_MODULES_HMC5883L
 //#define LUA_USE_MODULES_HTTP
@@ -62,6 +66,7 @@
 //#define LUA_USE_MODULES_SNTP
 //#define LUA_USE_MODULES_SOMFY
 #define LUA_USE_MODULES_SPI
+//#define LUA_USE_MODULES_SQLITE3
 //#define LUA_USE_MODULES_STRUCT
 //#define LUA_USE_MODULES_SWITEC
 // #define LUA_USE_MODULES_TCS34725
@@ -74,9 +79,11 @@
 //#define LUA_USE_MODULES_UCG
 //#define LUA_USE_MODULES_WEBSOCKET
 #define LUA_USE_MODULES_WIFI
+//#define LUA_USE_MODULES_WIFI_MONITOR
 //#define LUA_USE_MODULES_WPS
 //#define LUA_USE_MODULES_WS2801
 //#define LUA_USE_MODULES_WS2812
+//#define LUA_USE_MODULES_WS2812_EFFECTS
 //#define LUA_USE_MODULES_XPT2046
 
 #endif  /* LUA_CROSS_COMPILER */

+ 12 - 6
app/include/user_version.h

@@ -1,14 +1,20 @@
 #ifndef __USER_VERSION_H__
 #define __USER_VERSION_H__
 
-#define NODE_VERSION_MAJOR		2U
-#define NODE_VERSION_MINOR		1U
-#define NODE_VERSION_REVISION	0U
-#define NODE_VERSION_INTERNAL   0U
+#include "version.h"	/* ESP firmware header */
+
+#define NODE_VERSION_MAJOR	ESP_SDK_VERSION_MAJOR
+#define NODE_VERSION_MINOR	ESP_SDK_VERSION_MINOR
+#define NODE_VERSION_REVISION	ESP_SDK_VERSION_PATCH
+#define NODE_VERSION_INTERNAL   0
+
+#define NODE_VERSION_STR(x)	#x
+#define NODE_VERSION_XSTR(x)	NODE_VERSION_STR(x)
+
+#define NODE_VERSION		"NodeMCU " ESP_SDK_VERSION_STRING "." NODE_VERSION_XSTR(NODE_VERSION_INTERNAL)
 
-#define NODE_VERSION	"NodeMCU 2.1.0"
 #ifndef BUILD_DATE
-#define BUILD_DATE	  "unspecified"
+#define BUILD_DATE		"unspecified"
 #endif
 
 extern char SDK_VERSION[];

+ 3 - 0
app/lua/ldo.c

@@ -144,8 +144,11 @@ static void correctstack (lua_State *L, TValue *oldstack) {
 void luaD_reallocstack (lua_State *L, int newsize) {
   TValue *oldstack = L->stack;
   int realsize = newsize + 1 + EXTRA_STACK;
+  int block_status = is_block_gc(L);
   lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1);
+  set_block_gc(L);       /* The GC MUST be blocked during stack reallocaiton */
   luaM_reallocvector(L, L->stack, L->stacksize, realsize, TValue);
+  if (!block_status) unset_block_gc(L);  /* Honour the previous block status */
   L->stacksize = realsize;
   L->stack_last = L->stack+newsize;
   correctstack(L, oldstack);

+ 6 - 2
app/lua/lua.c

@@ -468,8 +468,11 @@ int lua_main (int argc, char **argv) {
 
 void lua_handle_input (bool force)
 {
-  if (gLoad.L && (force || readline (&gLoad)))
+  while (gLoad.L && (force || readline (&gLoad)))
+  {
     dojob (&gLoad);
+    force = false;
+  }
 }
 
 void donejob(lua_Load *load){
@@ -599,11 +602,12 @@ static bool readline(lua_Load *load){
         {
           /* Get a empty line, then go to get a new line */
           c_puts(load->prmt);
+          continue;
         } else {
           load->done = 1;
           need_dojob = true;
+          break;
         }
-        continue;
       }
 
       /* other control character or not an acsii character */

+ 5 - 2
app/lwip/app/espconn.c

@@ -441,6 +441,7 @@ sint16 ICACHE_FLASH_ATTR espconn_recv(struct espconn *espconn, void *mem, size_t
 	espconn_msg *pnode = NULL;
 	bool value = false;
 	int bytes_used = 0;
+	struct tcp_pcb *tpcb = NULL;
 	if (espconn == NULL || mem == NULL || len == 0)
 		return ESPCONN_ARG;
 
@@ -454,13 +455,15 @@ sint16 ICACHE_FLASH_ATTR espconn_recv(struct espconn *espconn, void *mem, size_t
 					len = bytes_used;
 				}
 				ringbuf_memcpy_from(mem, pnode->readbuf, len);
-				espconn_recv_unhold(pnode->pespconn);
+				tpcb = pnode->pcommon.pcb;
+				if (tpcb && tpcb->state == ESTABLISHED)
+				    tcp_recved(pnode->pcommon.pcb, len);
 				return len;
 			} else {
 				return ESPCONN_OK;
 			}
 		} else{
-			return ESPCONN_OK;
+			return ESPCONN_MEM;
 		}
 	} else{
 		return ESPCONN_ARG;

+ 76 - 2
app/lwip/app/espconn_tcp.c

@@ -231,6 +231,10 @@ void ICACHE_FLASH_ATTR espconn_tcp_memp_free(espconn_msg *pmemp)
 	if (pmemp == NULL)
 		return;
 
+	/*Enable block option for fetches the data proactive*/
+    if (espconn_manual_recv_disabled(pmemp))
+        espconn_list_delete(&plink_active, pmemp);
+
 	if (pmemp->espconn_mode == ESPCONN_TCPSERVER_MODE){
 		if (pmemp->pespconn != NULL && pmemp->pespconn->proto.tcp != NULL)
 			os_free(pmemp->pespconn->proto.tcp);
@@ -431,11 +435,13 @@ espconn_Task(os_event_t *events)
 			case SIG_ESPCONN_ERRER:
 				/*remove the node from the client's active connection list*/
 				espconn_list_delete(&plink_active, task_msg);
-				espconn_tcp_reconnect(task_msg);
+			    if (espconn_manual_recv_enabled(task_msg))
+			        espconn_list_delete(&plink_active, task_msg);
 				break;
 			case SIG_ESPCONN_CLOSE:
 				/*remove the node from the client's active connection list*/
-				espconn_list_delete(&plink_active, task_msg);
+			    if (espconn_manual_recv_enabled(task_msg))
+			        espconn_list_delete(&plink_active, task_msg);
 				espconn_tcp_disconnect_successful(task_msg);
 				break;
 			default:
@@ -538,6 +544,66 @@ void ICACHE_FLASH_ATTR espconn_tcp_disconnect(espconn_msg *pdiscon,u8 type)
 	}
 }
 
+/******************************************************************************
+ * FunctionName : espconn_tcp_recv
+ * Description  : Data has been received on this pcb.
+ * Parameters   : arg -- Additional argument to pass to the callback function
+ *                pcb -- The connection pcb which received data
+ *                p -- The received data (or NULL when the connection has been closed!)
+ *                err -- An error code if there has been an error receiving
+ * Returns      : ERR_ABRT: if you have called tcp_abort from within the function!
+*******************************************************************************/
+static err_t ICACHE_FLASH_ATTR
+espconn_tcp_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
+{
+    espconn_msg *precv_cb = arg;
+    struct pbuf *pthis = NULL;
+    uint8_t *ring = NULL;
+    size_t  bytes_used = 0;
+
+    tcp_arg(pcb, arg);
+
+    if (precv_cb->readbuf == NULL) {
+        precv_cb->readbuf = ringbuf_new(TCP_WND);
+        if (precv_cb->readbuf == NULL)
+            return ESPCONN_MEM;
+    }
+
+    if (err == ERR_OK) {
+        precv_cb->pcommon.recv_check = 0;
+        if (p != NULL) {
+            /*store the data to the adapter for application fetches it proactive*/
+            for (pthis = p; pthis != NULL ; pthis = pthis->next) {
+                ring = ringbuf_memcpy_into(precv_cb->readbuf, pthis->payload, pthis->len);
+                if (ring)
+                    pbuf_free(pthis);
+                else
+                    break;
+            }
+            bytes_used = ringbuf_bytes_used(precv_cb->readbuf);
+
+            /*switch the state of espconn for application process*/
+            precv_cb->pespconn->state = ESPCONN_READ;
+            precv_cb->pcommon.pcb = pcb;
+            if (precv_cb->pespconn->recv_callback != NULL) {
+                precv_cb->pespconn->recv_callback(precv_cb->pespconn, NULL, bytes_used);
+            }
+
+            /*switch the state of espconn for next packet copy*/
+            if (pcb->state == ESTABLISHED)
+                precv_cb->pespconn->state = ESPCONN_CONNECT;
+        } else {
+            if (precv_cb->preverse) {
+                espconn_server_close(precv_cb, pcb, 0);
+            } else {
+                espconn_client_close(precv_cb, pcb, 0);
+            }
+        }
+    }
+
+    return ERR_OK;
+}
+
 ///////////////////////////////client function/////////////////////////////////
 /******************************************************************************
  * FunctionName : espconn_client_close
@@ -933,6 +999,10 @@ espconn_client_connect(void *arg, struct tcp_pcb *tpcb, err_t err)
 			pcon->pespconn->proto.tcp->connect_callback(pcon->pespconn);
 		}
 
+		/*Enable block option for fetches the data proactive*/
+        if (espconn_manual_recv_disabled(pcon))
+            tcp_recv(tpcb, espconn_tcp_recv);
+
 		/*Enable keep alive option*/
 		if (espconn_keepalive_disabled(pcon))
 			espconn_keepalive_enable(tpcb);
@@ -1358,6 +1428,10 @@ espconn_tcp_accept(void *arg, struct tcp_pcb *pcb, err_t err)
 		paccept->pespconn->proto.tcp->connect_callback(paccept->pespconn);
 	}
 
+	/*Enable block option for fetches the data proactive*/
+	if (espconn_manual_recv_disabled(paccept))
+	    tcp_recv(pcb, espconn_tcp_recv);
+
 	/*Enable keep alive option*/
 	if (espconn_keepalive_disabled(paccept))
 		espconn_keepalive_enable(pcb);

+ 4 - 3
app/lwip/app/espconn_udp.c

@@ -237,9 +237,10 @@ espconn_udp_sendto(void *arg, uint8 *psent, uint16 length)
 
     if(wifi_get_opmode() == ESPCONN_AP_STA && default_interface == ESPCONN_AP_STA && sta_netif != NULL && ap_netif != NULL)
 	{
-		if(netif_is_up(sta_netif) && netif_is_up(ap_netif) && \
-			ip_addr_isbroadcast(&upcb->remote_ip, sta_netif) && \
-			ip_addr_isbroadcast(&upcb->remote_ip, ap_netif)) {
+		if( netif_is_up(sta_netif) && \
+            netif_is_up(ap_netif) && \
+            ip_addr_isbroadcast(&dst_ip, sta_netif) && \
+            ip_addr_isbroadcast(&dst_ip, ap_netif)) {
 
 		  p_temp = pbuf_alloc(PBUF_TRANSPORT, datalen, PBUF_RAM);
 		  if (pbuf_copy (p_temp,p) != ERR_OK) {

+ 0 - 1185
app/lwip/core/sntp.c

@@ -1,1185 +0,0 @@
-/**
- * @file
- * SNTP client module
- *
- * This is simple "SNTP" client for the lwIP raw API.
- * It is a minimal implementation of SNTPv4 as specified in RFC 4330.
- * 
- * For a list of some public NTP servers, see this link :
- * http://support.ntp.org/bin/view/Servers/NTPPoolServers
- *
- * @todo:
- * - set/change servers at runtime
- * - complete SNTP_CHECK_RESPONSE checks 3 and 4
- * - support broadcast/multicast mode?
- */
-
-/*
- * Redistribution and use in source and binary forms, with or without modification, 
- * are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- *    this list of conditions and the following disclaimer.
- * 2. 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.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission. 
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 is part of the lwIP TCP/IP stack.
- * 
- * Author: Simon Goldschmidt (lwIP raw API part)
- */
-
-#include "lwip/sntp.h"
-#include "osapi.h"
-#include "os_type.h"
-#include "lwip/opt.h"
-#include "lwip/timers.h"
-#include "lwip/udp.h"
-#include "lwip/dns.h"
-#include "lwip/ip_addr.h"
-#include "lwip/pbuf.h"
-#include "lwip/app/time.h"
-//#include <string.h>
-#if LWIP_UDP
-
-/**
- * SNTP_DEBUG: Enable debugging for SNTP.
- */
-#ifndef SNTP_DEBUG
-#define SNTP_DEBUG                  LWIP_DBG_ON
-#endif
-
-/** SNTP server port */
-#ifndef SNTP_PORT
-#define SNTP_PORT                   123
-#endif
-
-/** Set this to 1 to allow config of SNTP server(s) by DNS name */
-#ifndef SNTP_SERVER_DNS
-#define SNTP_SERVER_DNS             0
-#endif
-
-/** Handle support for more than one server via NTP_MAX_SERVERS,
- * but catch legacy style of setting SNTP_SUPPORT_MULTIPLE_SERVERS, probably outside of this file
- */
-#ifndef SNTP_SUPPORT_MULTIPLE_SERVERS
-#if SNTP_MAX_SERVERS > 1
-#define SNTP_SUPPORT_MULTIPLE_SERVERS 1
-#else /* NTP_MAX_SERVERS > 1 */
-#define SNTP_SUPPORT_MULTIPLE_SERVERS 0
-#endif /* NTP_MAX_SERVERS > 1 */
-#else /* SNTP_SUPPORT_MULTIPLE_SERVERS */
-/* The developer has defined SNTP_SUPPORT_MULTIPLE_SERVERS, probably from old code */
-#if SNTP_MAX_SERVERS <= 1
-#error "SNTP_MAX_SERVERS needs to be defined to the max amount of servers if SNTP_SUPPORT_MULTIPLE_SERVERS is defined"
-#endif /* SNTP_MAX_SERVERS <= 1 */
-#endif /* SNTP_SUPPORT_MULTIPLE_SERVERS */
-
-
-/** Sanity check:
- * Define this to
- * - 0 to turn off sanity checks (default; smaller code)
- * - >= 1 to check address and port of the response packet to ensure the
- *        response comes from the server we sent the request to.
- * - >= 2 to check returned Originate Timestamp against Transmit Timestamp
- *        sent to the server (to ensure response to older request).
- * - >= 3 @todo: discard reply if any of the LI, Stratum, or Transmit Timestamp
- *        fields is 0 or the Mode field is not 4 (unicast) or 5 (broadcast).
- * - >= 4 @todo: to check that the Root Delay and Root Dispersion fields are each
- *        greater than or equal to 0 and less than infinity, where infinity is
- *        currently a cozy number like one second. This check avoids using a
- *        server whose synchronization source has expired for a very long time.
- */
-#ifndef SNTP_CHECK_RESPONSE
-#define SNTP_CHECK_RESPONSE         0
-#endif
-
-/** According to the RFC, this shall be a random delay
- * between 1 and 5 minutes (in milliseconds) to prevent load peaks.
- * This can be defined to a random generation function,
- * which must return the delay in milliseconds as u32_t.
- * Turned off by default.
- */
-#ifndef SNTP_STARTUP_DELAY
-#define SNTP_STARTUP_DELAY          0
-#endif
-
-/** If you want the startup delay to be a function, define this
- * to a function (including the brackets) and define SNTP_STARTUP_DELAY to 1.
- */
-#ifndef SNTP_STARTUP_DELAY_FUNC
-#define SNTP_STARTUP_DELAY_FUNC     SNTP_STARTUP_DELAY
-#endif
-
-/** SNTP receive timeout - in milliseconds
- * Also used as retry timeout - this shouldn't be too low.
- * Default is 3 seconds.
- */
-#ifndef SNTP_RECV_TIMEOUT
-#define SNTP_RECV_TIMEOUT           3000
-#endif
-
-/** SNTP update delay - in milliseconds
- * Default is 1 hour.
- */
-#ifndef SNTP_UPDATE_DELAY
-#define SNTP_UPDATE_DELAY           3600000
-#endif
-#if (SNTP_UPDATE_DELAY < 15000) && !SNTP_SUPPRESS_DELAY_CHECK
-#error "SNTPv4 RFC 4330 enforces a minimum update time of 15 seconds!"
-#endif
-
-/** SNTP macro to change system time and/or the update the RTC clock */
-#ifndef SNTP_SET_SYSTEM_TIME
-#define SNTP_SET_SYSTEM_TIME(sec) ((void)sec)
-#endif
-
-/** SNTP macro to change system time including microseconds */
-uint8 sntp_receive_time_size = 1;
-#define SNTP_RECEIVE_TIME_SIZE      sntp_receive_time_size
-#define SNTP_SET_SYSTEM_TIME_US(sec, us)	sntp_update_rtc(sec, us)
-//#ifdef SNTP_SET_SYSTEM_TIME_US
-//#define SNTP_SET_SYSTEM_TIME_US(sec, us)	sntp_update_rtc(sec, us)
-//#define SNTP_CALC_TIME_US           1
-//#define SNTP_RECEIVE_TIME_SIZE      2
-//#else
-//#define SNTP_SET_SYSTEM_TIME_US(sec, us)
-//#define SNTP_CALC_TIME_US           0
-//#define SNTP_RECEIVE_TIME_SIZE      sntp_receive_time_size
-//#endif
-
-/** SNTP macro to get system time, used with SNTP_CHECK_RESPONSE >= 2
- * to send in request and compare in response.
- */
-#ifndef SNTP_GET_SYSTEM_TIME
-#define SNTP_GET_SYSTEM_TIME(sec, us)     do { (sec) = 0; (us) = 0; } while(0)
-#endif
-
-/** Default retry timeout (in milliseconds) if the response
- * received is invalid.
- * This is doubled with each retry until SNTP_RETRY_TIMEOUT_MAX is reached.
- */
-#ifndef SNTP_RETRY_TIMEOUT
-#define SNTP_RETRY_TIMEOUT          SNTP_RECV_TIMEOUT
-#endif
-
-/** Maximum retry timeout (in milliseconds). */
-#ifndef SNTP_RETRY_TIMEOUT_MAX
-#define SNTP_RETRY_TIMEOUT_MAX      (SNTP_RETRY_TIMEOUT * 10)
-#endif
-
-/** Increase retry timeout with every retry sent
- * Default is on to conform to RFC.
- */
-#ifndef SNTP_RETRY_TIMEOUT_EXP
-#define SNTP_RETRY_TIMEOUT_EXP      1
-#endif
-
-/* the various debug levels for this file */
-#define SNTP_DEBUG_TRACE        (SNTP_DEBUG | LWIP_DBG_TRACE)
-#define SNTP_DEBUG_STATE        (SNTP_DEBUG | LWIP_DBG_STATE)
-#define SNTP_DEBUG_WARN         (SNTP_DEBUG | LWIP_DBG_LEVEL_WARNING)
-#define SNTP_DEBUG_WARN_STATE   (SNTP_DEBUG | LWIP_DBG_LEVEL_WARNING | LWIP_DBG_STATE)
-#define SNTP_DEBUG_SERIOUS      (SNTP_DEBUG | LWIP_DBG_LEVEL_SERIOUS)
-
-#define SNTP_ERR_KOD                1
-
-/* SNTP protocol defines */
-#define SNTP_MSG_LEN                48
-
-#define SNTP_OFFSET_LI_VN_MODE      0
-#define SNTP_LI_MASK                0xC0
-#define SNTP_LI_NO_WARNING          0x00
-#define SNTP_LI_LAST_MINUTE_61_SEC  0x01
-#define SNTP_LI_LAST_MINUTE_59_SEC  0x02
-#define SNTP_LI_ALARM_CONDITION     0x03 /* (clock not synchronized) */
-
-#define SNTP_VERSION_MASK           0x38
-#define SNTP_VERSION                (4/* NTP Version 4*/<<3) 
-
-#define SNTP_MODE_MASK              0x07
-#define SNTP_MODE_CLIENT            0x03
-#define SNTP_MODE_SERVER            0x04
-#define SNTP_MODE_BROADCAST         0x05
-
-#define SNTP_OFFSET_STRATUM         1
-#define SNTP_STRATUM_KOD            0x00
-
-#define SNTP_OFFSET_ORIGINATE_TIME  24
-#define SNTP_OFFSET_RECEIVE_TIME    32
-#define SNTP_OFFSET_TRANSMIT_TIME   40
-
-/* number of seconds between 1900 and 1970 */
-#define DIFF_SEC_1900_1970         (2208988800UL)
-
-/**
- * SNTP packet format (without optional fields)
- * Timestamps are coded as 64 bits:
- * - 32 bits seconds since Jan 01, 1970, 00:00
- * - 32 bits seconds fraction (0-padded)
- * For future use, if the MSB in the seconds part is set, seconds are based
- * on Feb 07, 2036, 06:28:16.
- */
-#ifdef PACK_STRUCT_USE_INCLUDES
-#  include "arch/bpstruct.h"
-#endif
-PACK_STRUCT_BEGIN
-#define PACK_STRUCT_FLD_8 PACK_STRUCT_FIELD
-struct sntp_msg {
-  PACK_STRUCT_FLD_8(u8_t           li_vn_mode);
-  PACK_STRUCT_FLD_8(u8_t           stratum);
-  PACK_STRUCT_FLD_8(u8_t           poll);
-  PACK_STRUCT_FLD_8(u8_t           precision);
-  PACK_STRUCT_FIELD(u32_t          root_delay);
-  PACK_STRUCT_FIELD(u32_t          root_dispersion);
-  PACK_STRUCT_FIELD(u32_t          reference_identifier);
-  PACK_STRUCT_FIELD(u32_t          reference_timestamp[2]);
-  PACK_STRUCT_FIELD(u32_t          originate_timestamp[2]);
-  PACK_STRUCT_FIELD(u32_t          receive_timestamp[2]);
-  PACK_STRUCT_FIELD(u32_t          transmit_timestamp[2]);
-} PACK_STRUCT_STRUCT;
-PACK_STRUCT_END
-#ifdef PACK_STRUCT_USE_INCLUDES
-#  include "arch/epstruct.h"
-#endif
-
-/* function prototypes */
-static void sntp_request(void *arg);
-
-/** The UDP pcb used by the SNTP client */
-static struct udp_pcb* sntp_pcb;
-
-sint8 time_zone = 8;
-/** Names/Addresses of servers */
-struct sntp_server {
-#if SNTP_SERVER_DNS
-  char* name;
-#endif /* SNTP_SERVER_DNS */
-  ip_addr_t addr;
-};
-static struct sntp_server sntp_servers[SNTP_MAX_SERVERS];
-
-static u8_t sntp_set_servers_from_dhcp;
-#if SNTP_SUPPORT_MULTIPLE_SERVERS
-/** The currently used server (initialized to 0) */
-static u8_t sntp_current_server;
-#else /* SNTP_SUPPORT_MULTIPLE_SERVERS */
-#define sntp_current_server 0
-#endif /* SNTP_SUPPORT_MULTIPLE_SERVERS */
-
-#if SNTP_RETRY_TIMEOUT_EXP
-#define SNTP_RESET_RETRY_TIMEOUT() sntp_retry_timeout = SNTP_RETRY_TIMEOUT
-/** Retry time, initialized with SNTP_RETRY_TIMEOUT and doubled with each retry. */
-static u32_t sntp_retry_timeout;
-#else /* SNTP_RETRY_TIMEOUT_EXP */
-#define SNTP_RESET_RETRY_TIMEOUT()
-#define sntp_retry_timeout SNTP_RETRY_TIMEOUT
-#endif /* SNTP_RETRY_TIMEOUT_EXP */
-
-#if SNTP_CHECK_RESPONSE >= 1
-/** Saves the last server address to compare with response */
-static ip_addr_t sntp_last_server_address;
-#endif /* SNTP_CHECK_RESPONSE >= 1 */
-
-#if SNTP_CHECK_RESPONSE >= 2
-/** Saves the last timestamp sent (which is sent back by the server)
- * to compare against in response */
-static u32_t sntp_last_timestamp_sent[2];
-#endif /* SNTP_CHECK_RESPONSE >= 2 */
-
-//uint32 current_stamp_1 = 0;
-//uint32 current_stamp_2 = 0;
-static bool sntp_time_flag = false;
-static uint32 sntp_update_delay = SNTP_UPDATE_DELAY;
-static uint32 realtime_stamp = 0;
-LOCAL os_timer_t sntp_timer;
-/*****************************************/
-#define SECSPERMIN	60L
-#define MINSPERHOUR	60L
-#define HOURSPERDAY	24L
-#define SECSPERHOUR	(SECSPERMIN * MINSPERHOUR)
-#define SECSPERDAY	(SECSPERHOUR * HOURSPERDAY)
-#define DAYSPERWEEK	7
-#define MONSPERYEAR	12
-
-#define YEAR_BASE	1900
-#define EPOCH_YEAR      1970
-#define EPOCH_WDAY      4
-#define EPOCH_YEARS_SINCE_LEAP 2
-#define EPOCH_YEARS_SINCE_CENTURY 70
-#define EPOCH_YEARS_SINCE_LEAP_CENTURY 370
-
-#define isleap(y) ((((y) % 4) == 0 && ((y) % 100) != 0) || ((y) % 400) == 0)
-
-int __tznorth;
-int __tzyear;
-char reult[100];
-static const int mon_lengths[2][12] = {
-  {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
-  {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
-} ;
-
-static const int year_lengths[2] = {
-  365,
-  366
-} ;
-struct tm
-{
-  int	tm_sec;
-  int	tm_min;
-  int	tm_hour;
-  int	tm_mday;
-  int	tm_mon;
-  int	tm_year;
-  int	tm_wday;
-  int	tm_yday;
-  int	tm_isdst;
-};
-
-struct tm res_buf;
-typedef struct __tzrule_struct
-{
-  char ch;
-  int m;
-  int n;
-  int d;
-  int s;
-  time_t change;
-  int offset;
-} __tzrule_type;
-
-__tzrule_type sntp__tzrule[2];
-struct tm * ICACHE_FLASH_ATTR
-sntp_mktm_r(const time_t * tim_p ,struct tm *res ,int is_gmtime)
-{
-  long days, rem;
-  time_t lcltime;
-  int i;
-  int y;
-  int yleap;
-  const int *ip;
-
-  /* base decision about std/dst time on current time */
-  lcltime = *tim_p;
-
-  days = ((long)lcltime) / SECSPERDAY;
-  rem = ((long)lcltime) % SECSPERDAY;
-  while (rem < 0)
-    {
-      rem += SECSPERDAY;
-      --days;
-    }
-  while (rem >= SECSPERDAY)
-    {
-      rem -= SECSPERDAY;
-      ++days;
-    }
-
-  /* compute hour, min, and sec */
-  res->tm_hour = (int) (rem / SECSPERHOUR);
-  rem %= SECSPERHOUR;
-  res->tm_min = (int) (rem / SECSPERMIN);
-  res->tm_sec = (int) (rem % SECSPERMIN);
-
-  /* compute day of week */
-  if ((res->tm_wday = ((EPOCH_WDAY + days) % DAYSPERWEEK)) < 0)
-    res->tm_wday += DAYSPERWEEK;
-
-  /* compute year & day of year */
-  y = EPOCH_YEAR;
-  if (days >= 0)
-    {
-      for (;;)
-	{
-	  yleap = isleap(y);
-	  if (days < year_lengths[yleap])
-	    break;
-	  y++;
-	  days -= year_lengths[yleap];
-	}
-    }
-  else
-    {
-      do
-	{
-	  --y;
-	  yleap = isleap(y);
-	  days += year_lengths[yleap];
-	} while (days < 0);
-    }
-
-  res->tm_year = y - YEAR_BASE;
-  res->tm_yday = days;
-  ip = mon_lengths[yleap];
-  for (res->tm_mon = 0; days >= ip[res->tm_mon]; ++res->tm_mon)
-    days -= ip[res->tm_mon];
-  res->tm_mday = days + 1;
-
-  if (!is_gmtime)
-    {
-      int offset;
-      int hours, mins, secs;
-
-//      TZ_LOCK;
-//      if (_daylight)
-//	{
-//	  if (y == __tzyear || __tzcalc_limits (y))
-//	    res->tm_isdst = (__tznorth
-//			     ? (*tim_p >= __tzrule[0].change && *tim_p < __tzrule[1].change)
-//			     : (*tim_p >= __tzrule[0].change || *tim_p < __tzrule[1].change));
-//	  else
-//	    res->tm_isdst = -1;
-//	}
-//      else
-	res->tm_isdst = 0;
-
-      offset = (res->tm_isdst == 1 ? sntp__tzrule[1].offset : sntp__tzrule[0].offset);
-
-      hours = offset / SECSPERHOUR;
-      offset = offset % SECSPERHOUR;
-
-      mins = offset / SECSPERMIN;
-      secs = offset % SECSPERMIN;
-
-      res->tm_sec -= secs;
-      res->tm_min -= mins;
-      res->tm_hour -= hours;
-
-      if (res->tm_sec >= SECSPERMIN)
-	{
-	  res->tm_min += 1;
-	  res->tm_sec -= SECSPERMIN;
-	}
-      else if (res->tm_sec < 0)
-	{
-	  res->tm_min -= 1;
-	  res->tm_sec += SECSPERMIN;
-	}
-      if (res->tm_min >= MINSPERHOUR)
-	{
-	  res->tm_hour += 1;
-	  res->tm_min -= MINSPERHOUR;
-	}
-      else if (res->tm_min < 0)
-	{
-	  res->tm_hour -= 1;
-	  res->tm_min += MINSPERHOUR;
-	}
-      if (res->tm_hour >= HOURSPERDAY)
-	{
-	  ++res->tm_yday;
-	  ++res->tm_wday;
-	  if (res->tm_wday > 6)
-	    res->tm_wday = 0;
-	  ++res->tm_mday;
-	  res->tm_hour -= HOURSPERDAY;
-	  if (res->tm_mday > ip[res->tm_mon])
-	    {
-	      res->tm_mday -= ip[res->tm_mon];
-	      res->tm_mon += 1;
-	      if (res->tm_mon == 12)
-		{
-		  res->tm_mon = 0;
-		  res->tm_year += 1;
-		  res->tm_yday = 0;
-		}
-	    }
-	}
-       else if (res->tm_hour < 0)
-	{
-	  res->tm_yday -= 1;
-	  res->tm_wday -= 1;
-	  if (res->tm_wday < 0)
-	    res->tm_wday = 6;
-	  res->tm_mday -= 1;
-	  res->tm_hour += 24;
-	  if (res->tm_mday == 0)
-	    {
-	      res->tm_mon -= 1;
-	      if (res->tm_mon < 0)
-		{
-		  res->tm_mon = 11;
-		  res->tm_year -= 1;
-		  res->tm_yday = 365 + isleap(res->tm_year);
-		}
-	      res->tm_mday = ip[res->tm_mon];
-	    }
-	}
-//      TZ_UNLOCK;
-    }
-  else
-    res->tm_isdst = 0;
-//  os_printf("res %d %d %d %d %d\n",res->tm_year,res->tm_mon,res->tm_mday,res->tm_yday,res->tm_hour);
-  return (res);
-}
-struct tm * ICACHE_FLASH_ATTR
-sntp_localtime_r(const time_t * tim_p ,
-		struct tm *res)
-{
-  return sntp_mktm_r (tim_p, res, 0);
-}
-
-struct tm * ICACHE_FLASH_ATTR
-sntp_localtime(const time_t * tim_p)
-{
-  return sntp_localtime_r (tim_p, &res_buf);
-}
-
-
-int ICACHE_FLASH_ATTR
-sntp__tzcalc_limits(int year)
-{
-  int days, year_days, years;
-  int i, j;
-
-  if (year < EPOCH_YEAR)
-    return 0;
-
-  __tzyear = year;
-
-  years = (year - EPOCH_YEAR);
-
-  year_days = years * 365 +
-    (years - 1 + EPOCH_YEARS_SINCE_LEAP) / 4 - (years - 1 + EPOCH_YEARS_SINCE_CENTURY) / 100 +
-    (years - 1 + EPOCH_YEARS_SINCE_LEAP_CENTURY) / 400;
-
-  for (i = 0; i < 2; ++i)
-    {
-      if (sntp__tzrule[i].ch == 'J')
-	days = year_days + sntp__tzrule[i].d + (isleap(year) && sntp__tzrule[i].d >= 60);
-      else if (sntp__tzrule[i].ch == 'D')
-	days = year_days + sntp__tzrule[i].d;
-      else
-	{
-	  int yleap = isleap(year);
-	  int m_day, m_wday, wday_diff;
-	  const int *ip = mon_lengths[yleap];
-
-	  days = year_days;
-
-	  for (j = 1; j < sntp__tzrule[i].m; ++j)
-	    days += ip[j-1];
-
-	  m_wday = (EPOCH_WDAY + days) % DAYSPERWEEK;
-
-	  wday_diff = sntp__tzrule[i].d - m_wday;
-	  if (wday_diff < 0)
-	    wday_diff += DAYSPERWEEK;
-	  m_day = (sntp__tzrule[i].n - 1) * DAYSPERWEEK + wday_diff;
-
-	  while (m_day >= ip[j-1])
-	    m_day -= DAYSPERWEEK;
-
-	  days += m_day;
-	}
-
-      /* store the change-over time in GMT form by adding offset */
-      sntp__tzrule[i].change = days * SECSPERDAY + sntp__tzrule[i].s + sntp__tzrule[i].offset;
-    }
-
-  __tznorth = (sntp__tzrule[0].change < sntp__tzrule[1].change);
-
-  return 1;
-}
-
-char * ICACHE_FLASH_ATTR
-sntp_asctime_r(struct tm *tim_p ,char *result)
-{
-  static const char day_name[7][4] = {
-	"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
-  };
-  static const char mon_name[12][4] = {
-	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
-	"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
-  };
-  os_sprintf (result, "%s %s %02d %02d:%02d:%02d %02d\n",
-	   day_name[tim_p->tm_wday],
-	   mon_name[tim_p->tm_mon],
-	   tim_p->tm_mday, tim_p->tm_hour, tim_p->tm_min,
-	   tim_p->tm_sec, 1900 + tim_p->tm_year);
-  return result;
-}
-char *ICACHE_FLASH_ATTR
-sntp_asctime(struct tm *tim_p)
-{
-
-    return sntp_asctime_r (tim_p, reult);
-}
-
-uint32 sntp_get_current_timestamp()
-{
-	if(realtime_stamp == 0){
-		os_printf("please start sntp first !\n");
-		return 0;
-	} else {
-		return realtime_stamp;
-	}
-}
-
-char* sntp_get_real_time(time_t t)
-{
-	return sntp_asctime(sntp_localtime (&t));
-}
-/**
- * SNTP get time_zone default GMT + 8
- */
-sint8 ICACHE_FLASH_ATTR
-sntp_get_timezone(void)
-{
-	return time_zone;
-}
-/**
- * SNTP set time_zone default GMT + 8
- */
-
-bool ICACHE_FLASH_ATTR
-sntp_set_timezone(sint8 timezone)
-{
-	if(timezone >= -11 || timezone <= 13) {
-		if (sntp_get_timetype()){
-			RTC_TZ_SET(time_zone);
-		} else
-			time_zone = timezone;
-		return true;
-	} else {
-		return false;
-	}
-
-}
-
-void ICACHE_FLASH_ATTR sntp_set_daylight(int daylight)
-{
-	if (sntp_get_timetype()){
-		RTC_DST_SET(daylight);
-	}
-}
-
-void ICACHE_FLASH_ATTR
-sntp_time_inc(void)
-{
-	realtime_stamp++;
-}
-/**
- * SNTP processing of received timestamp
- */
-static void ICACHE_FLASH_ATTR
-sntp_process(u32_t *receive_timestamp)
-{
-  /* convert SNTP time (1900-based) to unix GMT time (1970-based)
-   * @todo: if MSB is 1, SNTP time is 2036-based!
-   */
-  time_t t = (ntohl(receive_timestamp[0]) - DIFF_SEC_1900_1970);
-  if (sntp_get_timetype()){
-	  u32_t us = ntohl(receive_timestamp[1]) / 4295;
-	    SNTP_SET_SYSTEM_TIME_US(t, us);
-	    /* display local time from GMT time */
-	    LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp_process: %s, %"U32_F" us", ctime(&t), us));
-  } else{
-	  /* change system time and/or the update the RTC clock */
-	    SNTP_SET_SYSTEM_TIME(t);
-	    /* display local time from GMT time */
-	    t += time_zone * 60 * 60;// format GMT + time_zone TIME ZONE
-	    realtime_stamp = t;
-	    os_timer_disarm(&sntp_timer);
-	    os_timer_setfn(&sntp_timer, (os_timer_func_t *)sntp_time_inc, NULL);
-	    os_timer_arm(&sntp_timer, 1000, 1);
-  }
-#if 0
-#if SNTP_CALC_TIME_US
-  u32_t us = ntohl(receive_timestamp[1]) / 4295;
-  SNTP_SET_SYSTEM_TIME_US(t, us);
-  /* display local time from GMT time */
-  LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp_process: %s, %"U32_F" us", ctime(&t), us));
-
-#else /* SNTP_CALC_TIME_US */
-
-  /* change system time and/or the update the RTC clock */
-  SNTP_SET_SYSTEM_TIME(t);
-  /* display local time from GMT time */
-  t += time_zone * 60 * 60;// format GMT + time_zone TIME ZONE
-  realtime_stamp = t;
-  os_timer_disarm(&sntp_timer);
-  os_timer_setfn(&sntp_timer, (os_timer_func_t *)sntp_time_inc, NULL);
-  os_timer_arm(&sntp_timer, 1000, 1);
-#endif /* SNTP_CALC_TIME_US */
-#endif
-}
-
-/**
- * Initialize request struct to be sent to server.
- */
-static void ICACHE_FLASH_ATTR
-sntp_initialize_request(struct sntp_msg *req)
-{
-  os_memset(req, 0, SNTP_MSG_LEN);
-  req->li_vn_mode = SNTP_LI_NO_WARNING | SNTP_VERSION | SNTP_MODE_CLIENT;
-
-#if SNTP_CHECK_RESPONSE >= 2
-  {
-    u32_t sntp_time_sec, sntp_time_us;
-    /* fill in transmit timestamp and save it in 'sntp_last_timestamp_sent' */
-    SNTP_GET_SYSTEM_TIME(sntp_time_sec, sntp_time_us);
-    sntp_last_timestamp_sent[0] = htonl(sntp_time_sec + DIFF_SEC_1900_1970);
-    req->transmit_timestamp[0] = sntp_last_timestamp_sent[0];
-    /* we send/save us instead of fraction to be faster... */
-    sntp_last_timestamp_sent[1] = htonl(sntp_time_us);
-    req->transmit_timestamp[1] = sntp_last_timestamp_sent[1];
-  }
-#endif /* SNTP_CHECK_RESPONSE >= 2 */
-}
-
-/**
- * Retry: send a new request (and increase retry timeout).
- *
- * @param arg is unused (only necessary to conform to sys_timeout)
- */
-static void ICACHE_FLASH_ATTR
-sntp_retry(void* arg)
-{
-  LWIP_UNUSED_ARG(arg);
-
-  LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_retry: Next request will be sent in %"U32_F" ms\n",
-    sntp_retry_timeout));
-
-  /* set up a timer to send a retry and increase the retry delay */
-  sys_timeout(sntp_retry_timeout, sntp_request, NULL);
-
-#if SNTP_RETRY_TIMEOUT_EXP
-  {
-    u32_t new_retry_timeout;
-    /* increase the timeout for next retry */
-    new_retry_timeout = sntp_retry_timeout << 1;
-    /* limit to maximum timeout and prevent overflow */
-    if ((new_retry_timeout <= SNTP_RETRY_TIMEOUT_MAX) &&
-        (new_retry_timeout > sntp_retry_timeout)) {
-      sntp_retry_timeout = new_retry_timeout;
-    }
-  }
-#endif /* SNTP_RETRY_TIMEOUT_EXP */
-}
-
-#if SNTP_SUPPORT_MULTIPLE_SERVERS
-/**
- * If Kiss-of-Death is received (or another packet parsing error),
- * try the next server or retry the current server and increase the retry
- * timeout if only one server is available.
- * (implicitly, SNTP_MAX_SERVERS > 1)
- *
- * @param arg is unused (only necessary to conform to sys_timeout)
- */
-static void
-sntp_try_next_server(void* arg)
-{
-  u8_t old_server, i;
-  LWIP_UNUSED_ARG(arg);
-
-  old_server = sntp_current_server;
-  for (i = 0; i < SNTP_MAX_SERVERS - 1; i++) {
-    sntp_current_server++;
-    if (sntp_current_server >= SNTP_MAX_SERVERS) {
-      sntp_current_server = 0;
-    }
-    if (!ip_addr_isany(&sntp_servers[sntp_current_server].addr)
-#if SNTP_SERVER_DNS
-        || (sntp_servers[sntp_current_server].name != NULL)
-#endif
-        ) {
-      LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_try_next_server: Sending request to server %"U16_F"\n",
-        (u16_t)sntp_current_server));
-      /* new server: reset retry timeout */
-      SNTP_RESET_RETRY_TIMEOUT();
-      /* instantly send a request to the next server */
-      sntp_request(NULL);
-      return;
-    }
-  }
-  /* no other valid server found */
-  sntp_current_server = old_server;
-  sntp_retry(NULL);
-}
-#else /* SNTP_SUPPORT_MULTIPLE_SERVERS */
-/* Always retry on error if only one server is supported */
-#define sntp_try_next_server    sntp_retry
-#endif /* SNTP_SUPPORT_MULTIPLE_SERVERS */
-
-/** UDP recv callback for the sntp pcb */
-static void ICACHE_FLASH_ATTR
-sntp_recv(void *arg, struct udp_pcb* pcb, struct pbuf *p, ip_addr_t *addr, u16_t port)
-{
-  u8_t mode;
-  u8_t stratum;
-  u32_t receive_timestamp[SNTP_RECEIVE_TIME_SIZE];
-  err_t err;
-//os_printf("sntp_recv\n");
-  LWIP_UNUSED_ARG(arg);
-  LWIP_UNUSED_ARG(pcb);
-
-  /* packet received: stop retry timeout  */
-  sys_untimeout(sntp_try_next_server, NULL);
-  sys_untimeout(sntp_request, NULL);
-
-  err = ERR_ARG;
-#if SNTP_CHECK_RESPONSE >= 1
-  /* check server address and port */
-  if (ip_addr_cmp(addr, &sntp_last_server_address) &&
-    (port == SNTP_PORT))
-#else /* SNTP_CHECK_RESPONSE >= 1 */
-  LWIP_UNUSED_ARG(addr);
-  LWIP_UNUSED_ARG(port);
-#endif /* SNTP_CHECK_RESPONSE >= 1 */
-  {
-    /* process the response */
-    if (p->tot_len == SNTP_MSG_LEN) {
-      pbuf_copy_partial(p, &mode, 1, SNTP_OFFSET_LI_VN_MODE);
-      mode &= SNTP_MODE_MASK;
-      /* if this is a SNTP response... */
-      if ((mode == SNTP_MODE_SERVER) ||
-          (mode == SNTP_MODE_BROADCAST)) {
-        pbuf_copy_partial(p, &stratum, 1, SNTP_OFFSET_STRATUM);
-        if (stratum == SNTP_STRATUM_KOD) {
-          /* Kiss-of-death packet. Use another server or increase UPDATE_DELAY. */
-          err = SNTP_ERR_KOD;
-          LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_recv: Received Kiss-of-Death\n"));
-        } else {
-#if SNTP_CHECK_RESPONSE >= 2
-          /* check originate_timetamp against sntp_last_timestamp_sent */
-          u32_t originate_timestamp[2];
-          pbuf_copy_partial(p, &originate_timestamp, 8, SNTP_OFFSET_ORIGINATE_TIME);
-          if ((originate_timestamp[0] != sntp_last_timestamp_sent[0]) ||
-              (originate_timestamp[1] != sntp_last_timestamp_sent[1]))
-          {
-            LWIP_DEBUGF(SNTP_DEBUG_WARN, ("sntp_recv: Invalid originate timestamp in response\n"));
-          } else
-#endif /* SNTP_CHECK_RESPONSE >= 2 */
-          /* @todo: add code for SNTP_CHECK_RESPONSE >= 3 and >= 4 here */
-          {
-            /* correct answer */
-            err = ERR_OK;
-            pbuf_copy_partial(p, &receive_timestamp, SNTP_RECEIVE_TIME_SIZE * 4, SNTP_OFFSET_RECEIVE_TIME);
-          }
-        }
-      } else {
-        LWIP_DEBUGF(SNTP_DEBUG_WARN, ("sntp_recv: Invalid mode in response: %"U16_F"\n", (u16_t)mode));
-      }
-    } else {
-      LWIP_DEBUGF(SNTP_DEBUG_WARN, ("sntp_recv: Invalid packet length: %"U16_F"\n", p->tot_len));
-    }
-  }
-  pbuf_free(p);
-  if (err == ERR_OK) {
-    /* Correct response, reset retry timeout */
-    SNTP_RESET_RETRY_TIMEOUT();
-
-    sntp_process(receive_timestamp);
-
-    /* Set up timeout for next request */
-    sys_timeout((u32_t)sntp_update_delay, sntp_request, NULL);
-    LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_recv: Scheduled next time request: %"U32_F" ms\n",
-      (u32_t)sntp_update_delay));
-  } else if (err == SNTP_ERR_KOD) {
-    /* Kiss-of-death packet. Use another server or increase UPDATE_DELAY. */
-    sntp_try_next_server(NULL);
-  } else {
-    /* another error, try the same server again */
-    sntp_retry(NULL);
-  }
-}
-
-/** Actually send an sntp request to a server.
- *
- * @param server_addr resolved IP address of the SNTP server
- */
-static void ICACHE_FLASH_ATTR
-sntp_send_request(ip_addr_t *server_addr)
-{
-  struct pbuf* p;
-//  os_printf("sntp_send_request\n");
-  p = pbuf_alloc(PBUF_TRANSPORT, SNTP_MSG_LEN, PBUF_RAM);
-  if (p != NULL) {
-    struct sntp_msg *sntpmsg = (struct sntp_msg *)p->payload;
-    LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_send_request: Sending request to server\n"));
-    /* initialize request message */
-    sntp_initialize_request(sntpmsg);
-    /* send request */
-    udp_sendto(sntp_pcb, p, server_addr, SNTP_PORT);
-    /* free the pbuf after sending it */
-    pbuf_free(p);
-    /* set up receive timeout: try next server or retry on timeout */
-    sys_timeout((u32_t)SNTP_RECV_TIMEOUT, sntp_try_next_server, NULL);
-#if SNTP_CHECK_RESPONSE >= 1
-    /* save server address to verify it in sntp_recv */ 
-    ip_addr_set(&sntp_last_server_address, server_addr);
-#endif /* SNTP_CHECK_RESPONSE >= 1 */
-  } else {
-    LWIP_DEBUGF(SNTP_DEBUG_SERIOUS, ("sntp_send_request: Out of memory, trying again in %"U32_F" ms\n",
-      (u32_t)SNTP_RETRY_TIMEOUT));
-    /* out of memory: set up a timer to send a retry */
-    sys_timeout((u32_t)SNTP_RETRY_TIMEOUT, sntp_request, NULL);
-  }
-}
-
-#if SNTP_SERVER_DNS
-/**
- * DNS found callback when using DNS names as server address.
- */
-static void
-sntp_dns_found(const char* hostname, ip_addr_t *ipaddr, void *arg)
-{
-  LWIP_UNUSED_ARG(hostname);
-  LWIP_UNUSED_ARG(arg);
-
-  if (ipaddr != NULL) {
-    /* Address resolved, send request */
-    LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_dns_found: Server address resolved, sending request\n"));
-    sntp_send_request(ipaddr);
-  } else {
-    /* DNS resolving failed -> try another server */
-    LWIP_DEBUGF(SNTP_DEBUG_WARN_STATE, ("sntp_dns_found: Failed to resolve server address resolved, trying next server\n"));
-    sntp_try_next_server(NULL);
-  }
-}
-#endif /* SNTP_SERVER_DNS */
-
-/**
- * Send out an sntp request.
- *
- * @param arg is unused (only necessary to conform to sys_timeout)
- */
-static void ICACHE_FLASH_ATTR
-sntp_request(void *arg)
-{
-  ip_addr_t sntp_server_address;
-  err_t err;
-
-  LWIP_UNUSED_ARG(arg);
-
-  /* initialize SNTP server address */
-#if SNTP_SERVER_DNS
-
-  if (sntp_servers[sntp_current_server].name) {
-    /* always resolve the name and rely on dns-internal caching & timeout */
-    ip_addr_set_any(&sntp_servers[sntp_current_server].addr);
-    err = dns_gethostbyname(sntp_servers[sntp_current_server].name, &sntp_server_address,
-      sntp_dns_found, NULL);
-    if (err == ERR_INPROGRESS) {
-      /* DNS request sent, wait for sntp_dns_found being called */
-      LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_request: Waiting for server address to be resolved.\n"));
-      return;
-    } else if (err == ERR_OK) {
-      sntp_servers[sntp_current_server].addr = sntp_server_address;
-    }
-  } else
-#endif /* SNTP_SERVER_DNS */
-  {
-    sntp_server_address = sntp_servers[sntp_current_server].addr;
-//    os_printf("sntp_server_address ip %d\n",sntp_server_address.addr);
-    err = (ip_addr_isany(&sntp_server_address)) ? ERR_ARG : ERR_OK;
-  }
-
-  if (err == ERR_OK) {
-    LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp_request: current server address is %u.%u.%u.%u\n",
-      ip4_addr1(&sntp_server_address), ip4_addr2(&sntp_server_address), ip4_addr3(&sntp_server_address), ip4_addr4(&sntp_server_address)));
-    sntp_send_request(&sntp_server_address);
-  } else {
-    /* address conversion failed, try another server */
-    LWIP_DEBUGF(SNTP_DEBUG_WARN_STATE, ("sntp_request: Invalid server address, trying next server.\n"));
-    sys_timeout((u32_t)SNTP_RETRY_TIMEOUT, sntp_try_next_server, NULL);
-  }
-}
-
-/**
- * Initialize this module.
- * Send out request instantly or after SNTP_STARTUP_DELAY(_FUNC).
- */
-void ICACHE_FLASH_ATTR
-sntp_init(void)
-{
-#ifdef SNTP_SERVER_ADDRESS
-#if SNTP_SERVER_DNS
-  sntp_setservername(0, SNTP_SERVER_ADDRESS);
-#else
-#error SNTP_SERVER_ADDRESS string not supported SNTP_SERVER_DNS==0
-#endif
-#endif /* SNTP_SERVER_ADDRESS */
-
-  if (sntp_pcb == NULL) {
-    SNTP_RESET_RETRY_TIMEOUT();
-    sntp_pcb = udp_new();
-    LWIP_ASSERT("Failed to allocate udp pcb for sntp client", sntp_pcb != NULL);
-    if (sntp_pcb != NULL) {
-      udp_recv(sntp_pcb, sntp_recv, NULL);
-#if SNTP_STARTUP_DELAY
-      sys_timeout((u32_t)SNTP_STARTUP_DELAY_FUNC, sntp_request, NULL);
-#else
-      sntp_request(NULL);
-#endif
-    }
-  }
-}
-
-/**
- * Stop this module.
- */
-void ICACHE_FLASH_ATTR
-sntp_stop(void)
-{
-  if (sntp_pcb != NULL) {
-    sys_untimeout(sntp_request, NULL);
-    udp_remove(sntp_pcb);
-    sntp_pcb = NULL;
-  }
-  os_timer_disarm(&sntp_timer);
-  realtime_stamp = 0;
-}
-
-#if SNTP_GET_SERVERS_FROM_DHCP
-/**
- * Config SNTP server handling by IP address, name, or DHCP; clear table
- * @param set_servers_from_dhcp enable or disable getting server addresses from dhcp
- */
-void
-sntp_servermode_dhcp(int set_servers_from_dhcp)
-{
-  u8_t new_mode = set_servers_from_dhcp ? 1 : 0;
-  if (sntp_set_servers_from_dhcp != new_mode) {
-    sntp_set_servers_from_dhcp = new_mode;
-  }
-}
-#endif /* SNTP_GET_SERVERS_FROM_DHCP */
-
-/**
- * Initialize one of the NTP servers by IP address
- *
- * @param numdns the index of the NTP server to set must be < SNTP_MAX_SERVERS
- * @param dnsserver IP address of the NTP server to set
- */
-void ICACHE_FLASH_ATTR
-sntp_setserver(u8_t idx, ip_addr_t *server)
-{
-  if (idx < SNTP_MAX_SERVERS) {
-    if (server != NULL) {
-      sntp_servers[idx].addr = (*server);
-//      os_printf("server ip %d\n",server->addr);
-    } else {
-      ip_addr_set_any(&sntp_servers[idx].addr);
-    }
-#if SNTP_SERVER_DNS
-    sntp_servers[idx].name = NULL;
-#endif
-  }
-}
-
-#if LWIP_DHCP && SNTP_GET_SERVERS_FROM_DHCP
-/**
- * Initialize one of the NTP servers by IP address, required by DHCP
- *
- * @param numdns the index of the NTP server to set must be < SNTP_MAX_SERVERS
- * @param dnsserver IP address of the NTP server to set
- */
-void
-dhcp_set_ntp_servers(u8_t num, ip_addr_t *server)
-{
-  LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp: %s %u.%u.%u.%u as NTP server #%u via DHCP\n",
-    (sntp_set_servers_from_dhcp ? "Got" : "Rejected"),
-    ip4_addr1(server), ip4_addr2(server), ip4_addr3(server), ip4_addr4(server), num));
-  if (sntp_set_servers_from_dhcp && num) {
-    u8_t i;
-    for (i = 0; (i < num) && (i < SNTP_MAX_SERVERS); i++) {
-      sntp_setserver(i, &server[i]);
-    }
-    for (i = num; i < SNTP_MAX_SERVERS; i++) {
-      sntp_setserver(i, NULL);
-    }
-  }
-}
-#endif /* LWIP_DHCP && SNTP_GET_SERVERS_FROM_DHCP */
-
-/**
- * Obtain one of the currently configured by IP address (or DHCP) NTP servers 
- *
- * @param numdns the index of the NTP server
- * @return IP address of the indexed NTP server or "ip_addr_any" if the NTP
- *         server has not been configured by address (or at all).
- */
-ip_addr_t ICACHE_FLASH_ATTR
-sntp_getserver(u8_t idx)
-{
-  if (idx < SNTP_MAX_SERVERS) {
-    return sntp_servers[idx].addr;
-  }
-  return *IP_ADDR_ANY;
-}
-
-#if SNTP_SERVER_DNS
-/**
- * Initialize one of the NTP servers by name
- *
- * @param numdns the index of the NTP server to set must be < SNTP_MAX_SERVERS
- * @param dnsserver DNS name of the NTP server to set, to be resolved at contact time
- */
-void ICACHE_FLASH_ATTR
-sntp_setservername(u8_t idx, char *server)
-{
-  if (idx < SNTP_MAX_SERVERS) {
-    sntp_servers[idx].name = server;
-  }
-}
-
-/**
- * Obtain one of the currently configured by name NTP servers.
- *
- * @param numdns the index of the NTP server
- * @return IP address of the indexed NTP server or NULL if the NTP
- *         server has not been configured by name (or at all)
- */
-char * ICACHE_FLASH_ATTR
-sntp_getservername(u8_t idx)
-{
-  if (idx < SNTP_MAX_SERVERS) {
-    return sntp_servers[idx].name;
-  }
-  return NULL;
-}
-#endif /* SNTP_SERVER_DNS */
-
-void ICACHE_FLASH_ATTR
-sntp_set_update_delay(uint32 ms)
-{
-	sntp_update_delay = ms > 15000?ms:15000;
-}
-
-void ICACHE_FLASH_ATTR
-sntp_set_timetype(bool type)
-{
-	sntp_time_flag = type;
-}
-
-bool sntp_get_timetype(void)
-{
-	return sntp_time_flag;
-}
-
-void ICACHE_FLASH_ATTR
-sntp_set_receive_time_size(void)
-{
-	if (sntp_get_timetype()){
-		sntp_receive_time_size = 2;
-	} else{
-		sntp_receive_time_size = 1;
-	}
-}
-
-#endif /* LWIP_UDP */

+ 1 - 1
app/lwip/core/tcp_in.c

@@ -500,7 +500,7 @@ tcp_listen_input(struct tcp_pcb_listen *pcb)
     /* For incoming segments with the ACK flag set, respond with a
        RST. */
     LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_listen_input: ACK in LISTEN, sending reset\n"));
-    tcp_rst(ackno + 1, seqno + tcplen,
+    tcp_rst(ackno, seqno + tcplen,
       ip_current_dest_addr(), ip_current_src_addr(),
       tcphdr->dest, tcphdr->src);
   } else if (flags & TCP_SYN) {//�յ�SYN����

+ 8 - 0
app/lwip/core/tcp_out.c

@@ -461,6 +461,7 @@ tcp_write(struct tcp_pcb *pcb, const void *arg, u16_t len, u8_t apiflags)
       return ERR_MEM;
     }
 
+#if !LWIP_NETIF_TX_SINGLE_PBUF
    /*
      * Phase 2: Chain a new pbuf to the end of pcb->unsent.
      *
@@ -510,6 +511,7 @@ tcp_write(struct tcp_pcb *pcb, const void *arg, u16_t len, u8_t apiflags)
       pos += seglen;
       queuelen += pbuf_clen(concat_p);
     }
+#endif /* !LWIP_NETIF_TX_SINGLE_PBUF */
   } else {
 #if TCP_OVERSIZE
     LWIP_ASSERT("unsent_oversize mismatch (pcb->unsent is NULL)",
@@ -1336,6 +1338,12 @@ tcp_rexmit(struct tcp_pcb *pcb)
   }
   seg->next = *cur_seg;
   *cur_seg = seg;
+#if TCP_OVERSIZE
+  if (seg->next == NULL) {
+    /* the retransmitted segment is last in unsent, so reset unsent_oversize */
+    pcb->unsent_oversize = 0;
+  }
+#endif /* TCP_OVERSIZE */
 
   ++pcb->nrtx;
 

Some files were not shown because too many files changed in this diff