Add Zephyr support for bundled mbed-tls ASN1 parser

When using EC256 for signing, Zephyr now uses the bundled tinycrypt
and mbed-tls ASN1 parser instead of relying on the one provided by
the OS.

Signed-off-by: Fabio Utzig <utzig@apache.org>
diff --git a/boot/zephyr/CMakeLists.txt b/boot/zephyr/CMakeLists.txt
index e303421..8c623be 100644
--- a/boot/zephyr/CMakeLists.txt
+++ b/boot/zephyr/CMakeLists.txt
@@ -131,12 +131,18 @@
 get_filename_component(MCUBOOT_DIR ${BOOT_DIR} DIRECTORY)
 # Path to tinycrypt library source subdirectory of MCUBOOT_DIR.
 set(TINYCRYPT_DIR "${MCUBOOT_DIR}/ext/tinycrypt/lib")
-
-# Zephyr's mbedTLS needs this.
-zephyr_include_directories(include)
+# Path to mbed-tls' asn1 parser library.
+set(MBEDTLS_ASN1_DIR "${MCUBOOT_DIR}/ext/mbedtls")
 
 # Zephyr application include directories.
-target_include_directories(app PRIVATE $ENV{ZEPHYR_BASE}/ext/lib/crypto/mbedtls/include)
+if (NOT NEED_TINYCRYPT)
+  # Zephyr's mbedTLS needs this.
+  zephyr_include_directories(include)
+
+  # Use full mbedtls provided by OS for RSA
+  target_include_directories(app PRIVATE $ENV{ZEPHYR_BASE}/ext/lib/crypto/mbedtls/include)
+endif()
+
 target_include_directories(app PRIVATE include)
 target_include_directories(app PRIVATE targets)
 if(EXISTS "${APPLICATION_SOURCE_DIR}/targets/${BOARD}.h")
@@ -164,12 +170,16 @@
 
 # Tinycrypt sources and includes, if needed.
 if (NEED_TINYCRYPT)
+  target_include_directories(app PRIVATE "${BOOT_DIR}/zephyr/include")
   target_include_directories(app PRIVATE "${TINYCRYPT_DIR}/include")
+  target_include_directories(app PRIVATE "${MBEDTLS_ASN1_DIR}/include")
 
   target_sources(app PRIVATE "${TINYCRYPT_DIR}/source/ecc.c")
   target_sources(app PRIVATE "${TINYCRYPT_DIR}/source/ecc_dsa.c")
   target_sources(app PRIVATE "${TINYCRYPT_DIR}/source/sha256.c")
   target_sources(app PRIVATE "${TINYCRYPT_DIR}/source/utils.c")
+
+  target_sources(app PRIVATE "${MBEDTLS_ASN1_DIR}/src/asn1parse.c")
 endif()
 
 if (CONFIG_MCUBOOT_SERIAL)
diff --git a/boot/zephyr/os.c b/boot/zephyr/os.c
index 2f1c036..f913268 100644
--- a/boot/zephyr/os.c
+++ b/boot/zephyr/os.c
@@ -22,11 +22,12 @@
 
 #include "os/os_heap.h"
 
+#ifdef MCUBOOT_USE_MBED_TLS
+
 #define MBEDTLS_CONFIG_FILE CONFIG_MBEDTLS_CFG_FILE
 #include <mbedtls/platform.h>
 #include <mbedtls/memory_buffer_alloc.h>
 
-#ifdef MCUBOOT_USE_MBED_TLS
 /*
  * This is the heap for mbed TLS.  The value needed depends on the key
  * size and algorithm used.  For RSA-2048, 6144 bytes seems to be
diff --git a/boot/zephyr/prj-p256.conf b/boot/zephyr/prj-p256.conf
index 8879bf4..c9cac66 100644
--- a/boot/zephyr/prj-p256.conf
+++ b/boot/zephyr/prj-p256.conf
@@ -5,7 +5,7 @@
 
 CONFIG_MAIN_STACK_SIZE=10240
 CONFIG_MBEDTLS=y
-CONFIG_MBEDTLS_BUILTIN=y
+CONFIG_MBEDTLS_BUILTIN=n
 CONFIG_MBEDTLS_CFG_FILE="config-asn1.h"
 # CONFIG_TINYCRYPT is not set
 # CONFIG_TINYCRYPT_ECC_DSA is not set