tls_interface.c 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. /**
  2. * Copyright (c) 2016 - 2020, Nordic Semiconductor ASA
  3. *
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without modification,
  7. * are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form, except as embedded into a Nordic
  13. * Semiconductor ASA integrated circuit in a product or a software update for
  14. * such product, must reproduce the above copyright notice, this list of
  15. * conditions and the following disclaimer in the documentation and/or other
  16. * materials provided with the distribution.
  17. *
  18. * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
  19. * contributors may be used to endorse or promote products derived from this
  20. * software without specific prior written permission.
  21. *
  22. * 4. This software, with or without modification, must only be used with a
  23. * Nordic Semiconductor ASA integrated circuit.
  24. *
  25. * 5. Any software provided in binary form under this license must not be reverse
  26. * engineered, decompiled, modified and/or disassembled.
  27. *
  28. * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
  29. * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  30. * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
  31. * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
  32. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  33. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  34. * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  35. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  36. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  37. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  38. *
  39. */
  40. #include <stdint.h>
  41. #include <stdbool.h>
  42. #include "nrf_error.h"
  43. #include "nrf_drv_rng.h"
  44. #include "app_fifo.h"
  45. #include "mem_manager.h"
  46. #include "mbedtls/ssl.h"
  47. #include "mbedtls/platform.h"
  48. #include "mbedtls/sha256.h"
  49. #include "mbedtls/debug.h"
  50. #include "nrf_tls.h"
  51. #include "nrf_assert.h"
  52. #include "iot_timer.h"
  53. #include "iot_errors.h"
  54. #if TLS_CONFIG_LOG_ENABLED
  55. #define NRF_LOG_MODULE_NAME TLS
  56. #define NRF_LOG_LEVEL TLS_CONFIG_LOG_LEVEL
  57. #define NRF_LOG_INFO_COLOR TLS_CONFIG_INFO_COLOR
  58. #define NRF_LOG_DEBUG_COLOR TLS_CONFIG_DEBUG_COLOR
  59. #include "nrf_log.h"
  60. NRF_LOG_MODULE_REGISTER();
  61. #define TLS_LOG NRF_LOG_INFO /**< Used for getting trace of execution in the module. */
  62. #define TLS_ERR NRF_LOG_ERROR /**< Used for logging errors in the module. */
  63. #define TLS_DUMP NRF_LOG_HEXDUMP_DEBUG /**< Used for dumping octet information to get details of bond information etc. */
  64. #define TLS_ENTRY() TLS_TRC(">> %s", __func__)
  65. #define TLS_EXIT() TLS_TRC("<< %s", __func__)
  66. #else // TLS_CONFIG_LOG_ENABLED
  67. #define TLS_LOG(...) /**< Disables traces. */
  68. #define TLS_DUMP(...) /**< Disables dumping of octet streams. */
  69. #define TLS_ERR(...) /**< Disables error logs. */
  70. #define TLS_ENTRY(...)
  71. #define TLS_EXIT(...)
  72. #endif // TLS_CONFIG_LOG_ENABLED
  73. #define TIME_PERIOD_INVALID 0xFFFFFFFF /**< Identifier for invalid time period. Used for timer functions. */
  74. #define TLS_MUTEX_LOCK() SDK_MUTEX_LOCK(m_tls_mutex) /**< Lock module using mutex */
  75. #define TLS_MUTEX_UNLOCK() SDK_MUTEX_UNLOCK(m_tls_mutex) /**< Unlock module using mutex */
  76. /**
  77. * @brief This macro is used for developer debugging.
  78. *
  79. * @note Not enabled normally as too many logs result and this level of detail is needed
  80. * less frequently.
  81. */
  82. #define TLS_TRC(...)
  83. /**@brief TLS interface. */
  84. typedef struct
  85. {
  86. uint32_t transport_id; /**< Transport identifier provided by the application to map the TLS instance with associated transport. Set by the application on allocation. */
  87. nrf_tls_output_t output_fn; /**< Output function registered by the application to write TLS data on the transport. */
  88. app_fifo_t input_fifo; /**< Input FIFO used for queueing up data received from the transport. Data on the transport us*/
  89. app_fifo_t output_fifo; /**< Output FIFO used for queueing up decrypted data received on the TLS interface. */
  90. mbedtls_ssl_context context; /**< SSL context used by mBedTLS for managing the TLS instance. */
  91. mbedtls_ssl_config conf; /**< Pointer to the configuration paramaters used for the instance. Memory is allocated on nrf_tls_alloc. */
  92. #ifdef MBEDTLS_X509_CRT_PARSE_C
  93. mbedtls_pk_context pkey; /**< Private key information. Used only when own certificate is provided. */
  94. mbedtls_x509_crt * p_owncert; /**< Own parsed certificate. */
  95. mbedtls_x509_crt * p_cacert; /**< CA's parsed certificate. */
  96. #endif // MBEDTLS_X509_CRT_PARSE_C
  97. /**@brief Timer management used to provide timeouts to the TLS library. */
  98. uint32_t start_tick; /**< Indicator (in milliseconds) of when the timeout was requested. */
  99. uint32_t intrmediate_delay; /**< Period indicating intermediate timeout period in milliseconds. */
  100. uint32_t final_delay; /**< Final timeout period in milliseconds. */
  101. } interface_t;
  102. #ifdef MBEDTLS_X509_CRT_PARSE_C
  103. /**@brief Input buffer size used for the input FIFO.
  104. *
  105. * @note For ECDHE-RSA, though the context length is set to a value smaller than 3072, a buffer size
  106. * of 4k is needed for the cloud sends a certificate that does not fit the size.
  107. * Also configuration of input FIFO is possible in powers of 2 therefore tuning this value to
  108. * a smaller FIFO size to exactly the size of certificate size is not possible.
  109. */
  110. #define INPUT_BUFFER_SIZE 4096
  111. #endif // MBEDTLS_X509_CRT_PARSE_C
  112. /**@brief Input buffer size when certificates are not used. */
  113. #ifndef INPUT_BUFFER_SIZE
  114. #define INPUT_BUFFER_SIZE MBEDTLS_SSL_MAX_CONTENT_LEN
  115. #endif // INPUT_BUFFER_SIZE
  116. /**@brief Output buffer size.
  117. *
  118. * @note Limiting to 1024 instead of MBEDTLS_SSL_MAX_CONTENT_LEN due to RAM constraints.
  119. */
  120. #define OUTPUT_BUFFER_SIZE 1024
  121. static interface_t * m_interface[NRF_TLS_MAX_INSTANCE_COUNT]; /**< Interface table to manage the interfaces. */
  122. static uint8_t m_input_buffer[INPUT_BUFFER_SIZE * NRF_TLS_MAX_INSTANCE_COUNT]; /**< Input buffer that is statically reserved. */
  123. SDK_MUTEX_DEFINE(m_tls_mutex) /**< Mutex variable. Currently unused, this declaration does not occupy any space in RAM. */
  124. /**@brief Initializes the interface.
  125. *
  126. * @param[in] index Identifies instance in m_interface table to be initialized.
  127. */
  128. static __INLINE void interface_init(uint32_t index)
  129. {
  130. m_interface[index] = NULL;
  131. }
  132. /**@brief Wrapper function to avoid GCC errors with incompatible parameters.
  133. *
  134. * @param[in] n Number of blocks to be allocated.
  135. * @param[in] s Size of each block to be assigned.
  136. *
  137. * @retval Pointer to memory block if procedure succeeded.
  138. * @retval NULL if procedure failed.
  139. */
  140. static __INLINE void * wrapper_calloc(size_t n, size_t s)
  141. {
  142. return nrf_calloc(n,s);
  143. }
  144. /**@brief Frees an allocated interface instance.
  145. *
  146. * @param[in] p_instance Identifies the interface instance to be freed.
  147. */
  148. static void interface_free(uint32_t index)
  149. {
  150. interface_t * const p_interface = m_interface[index];
  151. if (p_interface != NULL)
  152. {
  153. nrf_free(p_interface->input_fifo.p_buf);
  154. nrf_free(p_interface->output_fifo.p_buf);
  155. #ifdef MBEDTLS_X509_CRT_PARSE_C
  156. nrf_free(p_interface->p_cacert);
  157. nrf_free(p_interface->p_owncert);
  158. #endif // MBEDTLS_X509_CRT_PARSE_C
  159. mbedtls_ssl_config_free(&p_interface->conf);
  160. mbedtls_ssl_config_init(&p_interface->conf);
  161. mbedtls_ssl_free(&p_interface->context);
  162. nrf_free(p_interface);
  163. }
  164. interface_init(index);
  165. }
  166. /**@brief Allocates an interface instance.
  167. *
  168. * @param[inout] p_instance Provides transport identifier for the TLS instance.
  169. * And if procedure was successful, will conatin allocated TLS instance identifier.
  170. * @param[in] p_options TLS options to be used for the instance.
  171. *
  172. * @retval NRF_SUCCESS if the procedure was successful, else an error code indicating reason
  173. ( for failure.
  174. */
  175. static uint32_t interface_alloc(nrf_tls_instance_t * p_instance,
  176. nrf_tls_options_t const * p_options)
  177. {
  178. uint32_t index;
  179. uint32_t err_code = NRF_TLS_NO_FREE_INSTANCE;
  180. interface_t * p_interface = NULL;
  181. TLS_ENTRY();
  182. // Allocate memory for the TLS instance.
  183. for (index = 0; index < NRF_TLS_MAX_INSTANCE_COUNT; index++)
  184. {
  185. if (m_interface[index] == NULL)
  186. {
  187. err_code = (NRF_ERROR_NO_MEM | IOT_TLS_ERR_BASE);
  188. // Check if we have space to book keep the instance information.
  189. p_interface = nrf_malloc(sizeof(interface_t));
  190. m_interface[index] = p_interface;
  191. break;
  192. }
  193. }
  194. if ((index < NRF_TLS_MAX_INSTANCE_COUNT) && (p_interface != NULL))
  195. {
  196. // Initialize the memory holding the structure.
  197. memset(p_interface, 0, sizeof(interface_t));
  198. p_interface->output_fn = p_options->output_fn;
  199. // Found free instance. Allocate memory for input and output queues.
  200. uint8_t * p_input_memory = &m_input_buffer[INPUT_BUFFER_SIZE * index];
  201. uint8_t * p_output_memory = (uint8_t *)nrf_malloc(OUTPUT_BUFFER_SIZE);
  202. TLS_LOG("Input memory address %p", p_input_memory);
  203. TLS_LOG("Output memory address %p", p_output_memory);
  204. if (p_output_memory != NULL)
  205. {
  206. // Initialize the instance.
  207. err_code = app_fifo_init(&p_interface->input_fifo,
  208. p_input_memory,
  209. INPUT_BUFFER_SIZE);
  210. TLS_LOG("Input FIFO init result %08lx", err_code);
  211. if (err_code == NRF_SUCCESS)
  212. {
  213. err_code = app_fifo_init(&p_interface->output_fifo,
  214. p_output_memory,
  215. OUTPUT_BUFFER_SIZE);
  216. TLS_LOG("Output FIFO init result %08lx", err_code);
  217. }
  218. if (err_code == NRF_SUCCESS)
  219. {
  220. // All prerequisites for using the instance met.
  221. // Procedure was successful.
  222. p_interface->transport_id = p_instance->transport_id;
  223. p_instance->instance_id = index;
  224. }
  225. else
  226. {
  227. err_code = (NRF_ERROR_INTERNAL | IOT_TLS_ERR_BASE);
  228. }
  229. }
  230. if (err_code != NRF_SUCCESS)
  231. {
  232. TLS_ERR("Allocation failed - Initialization procedures.");
  233. interface_free(index);
  234. }
  235. }
  236. else
  237. {
  238. TLS_ERR("Allocation failed - Inadequate memory.");
  239. }
  240. return err_code;
  241. }
  242. /**@brief Transport read function registered with the TLS library.
  243. *
  244. * @details Data read on the transport is fed to the interface using the nrf_tls_input function.
  245. * The TLS library requests the data based on state of SSL connection.
  246. *
  247. * @param[in] p_ctx Context registered with the library on creation of the TLS instance.
  248. * @param[out] p_buffer Buffer where read data is fetched.
  249. * @param[in] size Size to be read.
  250. *
  251. * @retval size of data read if procedure was successful.
  252. * @retval MBEDTLS_ERR_SSL_CONN_EOF indicating there is not enough data received on the transport.
  253. */
  254. static int interface_transport_read(void * p_ctx,
  255. unsigned char * p_buffer,
  256. size_t buffer_size)
  257. {
  258. uint32_t err_code;
  259. uint32_t length = buffer_size;
  260. interface_t * const p_interface = m_interface[(uint32_t)p_ctx];
  261. uint32_t available_size = 0;
  262. TLS_MUTEX_LOCK();
  263. TLS_TRC("[%p]: interface_transport_read requested %08x",
  264. p_interface,
  265. buffer_size);
  266. // Verify how much data is available in the queue.
  267. err_code = app_fifo_read(&p_interface->input_fifo, NULL, &available_size);
  268. TLS_TRC("[%p]: interface_transport_read, app_fifo_read result %ld",
  269. p_interface,
  270. err_code);
  271. // For datagram connection, read all that is available.
  272. // For stream sockets, read only if available data is at least as much as requested.
  273. if (( (p_interface->conf.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) &&
  274. (available_size > 0) )||
  275. ( (p_interface->conf.transport == MBEDTLS_SSL_TRANSPORT_STREAM) &&
  276. (available_size >= buffer_size)) )
  277. {
  278. TLS_TRC("[%p]: interface_transport_read requested 0x%08x, available %08lx.",
  279. p_interface,
  280. buffer_size,
  281. available_size);
  282. err_code = app_fifo_read(&p_interface->input_fifo, p_buffer, &length);
  283. if (err_code == NRF_SUCCESS)
  284. {
  285. TLS_TRC("[%p]: interface_transport_read success, length 0x%08lx.",
  286. p_interface,
  287. length);
  288. TLS_TRC("[NRF TLS]: ---------------- SSL Read data --------------");
  289. TLS_DUMP(p_buffer, length);
  290. TLS_TRC("[NRF TLS]: -------------------- End ------------------");
  291. TLS_MUTEX_UNLOCK();
  292. return length;
  293. }
  294. }
  295. else
  296. {
  297. TLS_TRC("[%p]: interface_transport_read requested size 0x%08x, "
  298. "available 0x%08lx.",
  299. p_interface,
  300. buffer_size,
  301. available_size);
  302. }
  303. TLS_MUTEX_UNLOCK();
  304. return MBEDTLS_ERR_SSL_CONN_EOF;
  305. }
  306. /**@brief Write function that the TLS library calls to write on the transport.
  307. *
  308. * @param[in] p_ctx Context registered with the library on creation of the TLS instance.
  309. * @param[in] p_buf Buffer containing data to be written on the transport.
  310. * @param[in] len Length of data to be written.
  311. *
  312. * @retval length of data written on the transport if the procedure was successful.
  313. * @retval MBEDTLS_ERR_SSL_CONN_EOF in case the procedure failed.
  314. */
  315. static int interface_transport_write(void * p_ctx,
  316. const unsigned char * p_buf,
  317. size_t len)
  318. {
  319. int op_len = len;
  320. interface_t * const p_interface = m_interface[(uint32_t)p_ctx];
  321. TLS_MUTEX_LOCK();
  322. const nrf_tls_instance_t handle = {
  323. .transport_id = p_interface->transport_id,
  324. .instance_id = (uint32_t)p_ctx
  325. };
  326. TLS_TRC("[%p]: interface_transport_write requested 0x%08x",
  327. p_interface, len);
  328. TLS_MUTEX_UNLOCK();
  329. uint32_t err_code = p_interface->output_fn(&handle, (uint8_t *)p_buf, len);
  330. TLS_MUTEX_LOCK();
  331. if (err_code != NRF_SUCCESS)
  332. {
  333. op_len = MBEDTLS_ERR_SSL_CONN_EOF;
  334. }
  335. TLS_MUTEX_UNLOCK();
  336. return op_len;
  337. }
  338. /**
  339. * @brief Random number generator registered with the TLS library to create random numbers
  340. * when needed.
  341. *
  342. * @param[in] p_ctx Context registered with the library on creation of the TLS instance.
  343. * @param[out] p_buffer Buffer where generated random vector is to be fetched.
  344. * @param[in] size Requested size of the random vector.
  345. *
  346. * @retval 0 when procedure is successful.
  347. *
  348. * @note This loop is time critical when available is less than requested size.
  349. */
  350. static int random_vector_generate(void * p_ctx,
  351. unsigned char * p_buffer,
  352. size_t size)
  353. {
  354. uint8_t available = 0;
  355. ASSERT(size <= RNG_CONFIG_POOL_SIZE);
  356. while (available < size)
  357. {
  358. nrf_drv_rng_bytes_available(&available);
  359. TLS_TRC(">> random_vector_generate, requested 0x%08lx, available 0x%08x",
  360. size,
  361. available);
  362. }
  363. UNUSED_RETURN_VALUE(nrf_drv_rng_rand(p_buffer, size));
  364. return 0;
  365. }
  366. /**@brief Routine called periodically to advance the SSL context state.
  367. *
  368. * @param[in] p_instance Provides transport identifier for the TLS instance.
  369. */
  370. static void interface_continue(interface_t * p_interface)
  371. {
  372. uint8_t * data = nrf_malloc(OUTPUT_BUFFER_SIZE);
  373. if (data != NULL)
  374. {
  375. int len;
  376. TLS_MUTEX_UNLOCK();
  377. len = mbedtls_ssl_read(&p_interface->context, &data[0], OUTPUT_BUFFER_SIZE);
  378. TLS_MUTEX_LOCK();
  379. TLS_TRC("[%p]: mbedtls_ssl_read result(len) 0x%08lx",
  380. p_interface,
  381. len);
  382. if (len > 0)
  383. {
  384. uint32_t write_len = len;
  385. uint32_t err_code = app_fifo_write(&p_interface->output_fifo, data, &write_len);
  386. if (err_code != NRF_SUCCESS)
  387. {
  388. TLS_LOG("Failed to write decrypted data.");
  389. }
  390. }
  391. nrf_free(data);
  392. }
  393. }
  394. /**@brief Debug log funciton registered with the TLS library.
  395. *
  396. * @param[in] p_ctx Context registered with the library on creation of the TLS instance.
  397. * @param[in] level Debug level of the log.
  398. * @param[in] p_file File requesting the log.
  399. * @param[in] line Line number in the file requesting the log.
  400. * @param[in] p_str String containing the log message.
  401. */
  402. static void mbedtls_log(void * p_ctx,
  403. int level,
  404. const char * p_file,
  405. int line,
  406. const char * p_str)
  407. {
  408. TLS_LOG("[%s]:[%d]: %s", &p_file[strlen(p_file)-12], line, p_str);
  409. }
  410. /**@brief Function registered with TLS library to set (start/stop) timer.
  411. *
  412. * @param[in] p_ctx Context registered with the library on creation of the TLS instance.
  413. * @param[in] int_ms Intermediate timeout period in milliseconds.
  414. * @param[in] fin_ms Finaly timout period in milliseconds.
  415. * Value of zero indicates a request to stop the timer.
  416. */
  417. static void tls_set_timer(void * p_ctx,
  418. uint32_t int_ms,
  419. uint32_t fin_ms)
  420. {
  421. TLS_MUTEX_LOCK();
  422. interface_t * const p_interface = m_interface[(uint32_t)p_ctx];
  423. if (fin_ms > 0)
  424. {
  425. TLS_TRC("[%p]: set_timer, start %d, final %d, intermediate %d",
  426. p_interface,
  427. p_interface->start_tick,
  428. p_interface->final_delay,
  429. p_interface->intrmediate_delay);
  430. uint32_t err_code = iot_timer_wall_clock_get(&p_interface->start_tick);
  431. if (err_code == NRF_SUCCESS)
  432. {
  433. p_interface->final_delay = fin_ms;
  434. p_interface->intrmediate_delay = int_ms;
  435. }
  436. }
  437. else
  438. {
  439. p_interface->start_tick = TIME_PERIOD_INVALID;
  440. p_interface->final_delay = TIME_PERIOD_INVALID;
  441. p_interface->intrmediate_delay = 0;
  442. }
  443. TLS_MUTEX_UNLOCK();
  444. }
  445. /**@brief Function registered with TLS library to get the status of the timer.
  446. *
  447. * @param[in] p_ctx Context registered with the library on creation of the TLS instance.
  448. *
  449. * @retval -1 if timer is cancelled
  450. * @retval 0 if none of the delays is expired
  451. * @retval 1 if the intermediate delay only is expired
  452. * @retval 2 if the final delay is expired
  453. */
  454. static int tls_get_timer(void * p_ctx)
  455. {
  456. int retval = 0;
  457. TLS_MUTEX_LOCK();
  458. iot_timer_time_in_ms_t elapsed_time;
  459. interface_t * const p_interface = m_interface[(uint32_t)p_ctx];
  460. uint32_t err_code = iot_timer_wall_clock_delta_get(&p_interface->start_tick, &elapsed_time);
  461. TLS_TRC("[%p]: get_timer, start %d, final %d, intermediate %d, elapsed %d",
  462. p_interface,
  463. p_interface->start_tick,
  464. p_interface->final_delay,
  465. p_interface->intrmediate_delay,
  466. elapsed_time);
  467. if (err_code == NRF_SUCCESS)
  468. {
  469. if (p_interface->final_delay <= elapsed_time)
  470. {
  471. retval = 2;
  472. }
  473. else if (p_interface->intrmediate_delay <= elapsed_time)
  474. {
  475. retval = 1;
  476. }
  477. else if ((p_interface->intrmediate_delay == TIME_PERIOD_INVALID) &&
  478. (p_interface->final_delay == TIME_PERIOD_INVALID))
  479. {
  480. retval = -1;
  481. }
  482. }
  483. TLS_MUTEX_UNLOCK();
  484. return retval;
  485. }
  486. /**@brief Prints/displays the configuration of the interface. Used for debugging purposes.
  487. *
  488. * @param[in] p_interface Identifies the instance whose ssl configuration is to be printed.
  489. */
  490. static void interface_conf_debug_print(interface_t * p_interface)
  491. {
  492. TLS_TRC("[%p] SSL Conf", p_interface);
  493. for (int i = 0; i < 4; i++)
  494. {
  495. TLS_TRC("\t Cipger Suites : %02d", i);
  496. TLS_TRC("\t\t\tCiphersuite[0] = %02d", p_interface->conf.ciphersuite_list[i][0]);
  497. TLS_TRC("\t\t\tCiphersuite[1] = %02d", p_interface->conf.ciphersuite_list[i][1]);
  498. TLS_TRC("\t\t\tCiphersuite[2] = %02d", p_interface->conf.ciphersuite_list[i][2]);
  499. TLS_TRC("\t\t\tCiphersuite[3] = %02d", p_interface->conf.ciphersuite_list[i][3]);
  500. }
  501. TLS_TRC("\t\tf_dbg = %p", p_interface->conf.f_dbg);
  502. TLS_TRC("\t\tp_dbg = %p", p_interface->conf.p_dbg);
  503. TLS_TRC("\t\tf_rng = %p", p_interface->conf.f_rng);
  504. TLS_TRC("\t\tp_rng = %p", p_interface->conf.p_rng);
  505. TLS_TRC("\t\tf_get_cache = %p", p_interface->conf.f_get_cache);
  506. TLS_TRC("\t\tf_set_cache = %p", p_interface->conf.f_set_cache);
  507. TLS_TRC("\t\tf_set_cache = %p", p_interface->conf.p_cache);
  508. TLS_TRC("\t\tf_vrfy = %p", p_interface->conf.f_vrfy);
  509. TLS_TRC("\t\tp_vrfy = %p", p_interface->conf.p_vrfy);
  510. TLS_TRC("\t\tcert_profile = %p", p_interface->conf.cert_profile);
  511. TLS_TRC("\t\tkey_cert = %p", p_interface->conf.key_cert);
  512. TLS_TRC("\t\tca_chain = %p", p_interface->conf.ca_chain);
  513. TLS_TRC("\t\tca_crl = %p", p_interface->conf.ca_crl);
  514. TLS_TRC("\t\tmax_major_ver = %2d", p_interface->conf.max_major_ver);
  515. TLS_TRC("\t\tmax_minor_ver = %2d", p_interface->conf.max_minor_ver);
  516. TLS_TRC("\t\tmin_major_ver = %2d", p_interface->conf.min_major_ver);
  517. TLS_TRC("\t\tmax_major_ver = %2d", p_interface->conf.max_major_ver);
  518. }
  519. /**@brief Sets up own certificate on the interface instance.
  520. *
  521. * @param[in] p_interface TLS interface instance for which the procedure is requested.
  522. * @param[in] p_own Supplies own certifcate setup information.
  523. *
  524. * @retval NRF_SUCCESS if the procedure was successful, else an error code indicating reason for
  525. * failure.
  526. */
  527. static uint32_t own_certificate_set(interface_t * const p_interface,
  528. nrf_tls_certificate_t const * p_own)
  529. {
  530. #ifdef MBEDTLS_X509_CRT_PARSE_C
  531. uint32_t error_code = (NRF_ERROR_NO_MEM | IOT_TLS_ERR_BASE);
  532. int result;
  533. p_interface->p_owncert = nrf_malloc(sizeof(mbedtls_x509_crt));
  534. if (p_interface->p_owncert)
  535. {
  536. mbedtls_x509_crt_init(p_interface->p_owncert);
  537. result = mbedtls_x509_crt_parse(p_interface->p_owncert,
  538. p_own->p_certificate,
  539. p_own->certificate_len);
  540. if (result == 0)
  541. {
  542. mbedtls_pk_init(&p_interface->pkey);
  543. result = mbedtls_pk_parse_key(&p_interface->pkey,
  544. p_own->p_private_key,
  545. p_own->private_key_len,
  546. NULL,
  547. 0 );
  548. result = mbedtls_ssl_conf_own_cert(&p_interface->conf,
  549. p_interface->p_owncert,
  550. &p_interface->pkey);
  551. if (result == 0)
  552. {
  553. error_code = NRF_SUCCESS;
  554. }
  555. else
  556. {
  557. error_code = NRF_TLS_OWN_CERT_SETUP_FAILED;
  558. }
  559. }
  560. else
  561. {
  562. error_code = NRF_TLS_OWN_CERT_SETUP_FAILED;
  563. }
  564. }
  565. return error_code;
  566. #else
  567. return NRF_SUCCESS;
  568. #endif // MBEDTLS_X509_CRT_PARSE_C
  569. }
  570. /**@brief Sets up verification option for the interfce,
  571. *
  572. * @param[in] p_interface TLS interface instance for which the procedure is requested.
  573. * @param[in] p_settings Key setting supplying CA PEM file.
  574. *
  575. * @retval NRF_SUCCESS if the procedure was successful, else an error code indicating reason for
  576. * failure.
  577. */
  578. static uint32_t verify_options_set(interface_t * const p_interface,
  579. nrf_tls_key_settings_t const * p_settings)
  580. {
  581. uint32_t err_code = NRF_SUCCESS;
  582. #ifdef MBEDTLS_X509_CRT_PARSE_C
  583. if ((p_settings != NULL) && (p_settings->p_ca_cert_pem != NULL))
  584. {
  585. mbedtls_ssl_conf_authmode(&p_interface->conf, MBEDTLS_SSL_VERIFY_REQUIRED );
  586. p_interface->p_cacert = nrf_malloc(sizeof(mbedtls_x509_crt));
  587. if (p_interface->p_cacert != NULL)
  588. {
  589. // Initialize ca certificate.
  590. mbedtls_x509_crt_init(p_interface->p_cacert);
  591. int result = mbedtls_x509_crt_parse(p_interface->p_cacert,
  592. p_settings->p_ca_cert_pem,
  593. p_settings->ca_cert_pem_len);
  594. if (result >= 0)
  595. {
  596. mbedtls_ssl_conf_ca_chain(&p_interface->conf, p_interface->p_cacert, NULL);
  597. }
  598. else
  599. {
  600. err_code = NRF_TLS_INVALID_CA_CERTIFICATE;
  601. }
  602. }
  603. else
  604. {
  605. err_code = (NRF_ERROR_NO_MEM | IOT_TLS_ERR_BASE);
  606. }
  607. }
  608. else
  609. #endif // MBEDTLS_X509_CRT_PARSE_C
  610. {
  611. mbedtls_ssl_conf_authmode(&p_interface->conf, MBEDTLS_SSL_VERIFY_NONE);
  612. }
  613. return err_code;
  614. }
  615. /**@brief Sets up the configuration for SSL context according to the options specificed.
  616. *
  617. * @param[in] instance_id Identifies the TLS instance for which the procedure is requested.
  618. * @param[in] p_options Supplies options to be used for the configuration.
  619. *
  620. * @retval NRF_SUCCESS if the procedure was successful, else an error indicating reason
  621. * for failure.
  622. */
  623. static uint32_t interface_conf_setup(uint32_t instance_id,
  624. nrf_tls_options_t const * p_options)
  625. {
  626. int result;
  627. interface_t * p_interface = m_interface[instance_id];
  628. uint32_t err_code = NRF_TLS_CONFIGURATION_FAILED;
  629. mbedtls_ssl_config_init(&p_interface->conf);
  630. result = mbedtls_ssl_config_defaults(&p_interface->conf,
  631. p_options->role,
  632. p_options->transport_type,
  633. MBEDTLS_SSL_PRESET_DEFAULT);
  634. mbedtls_ssl_conf_rng(&p_interface->conf, random_vector_generate, NULL);
  635. mbedtls_ssl_conf_dbg(&p_interface->conf, mbedtls_log, NULL);
  636. TLS_TRC("[%p]: mbedtls_ssl_config_defaults result %08lx", p_interface, result);
  637. #ifdef MBEDTLS_KEY_EXCHANGE_PSK_ENABLED
  638. if (result == 0)
  639. {
  640. if ((p_options->p_key_settings != NULL) && (p_options->p_key_settings->p_psk != NULL))
  641. {
  642. result = mbedtls_ssl_conf_psk(&p_interface->conf,
  643. p_options->p_key_settings->p_psk->p_secret_key,
  644. p_options->p_key_settings->p_psk->secret_key_len,
  645. p_options->p_key_settings->p_psk->p_identity,
  646. p_options->p_key_settings->p_psk->identity_len);
  647. }
  648. }
  649. #endif // MBEDTLS_KEY_EXCHANGE_PSK_ENABLED
  650. if (result == 0)
  651. {
  652. if (p_options->p_key_settings->p_own_certificate != NULL)
  653. {
  654. err_code = own_certificate_set(p_interface,
  655. p_options->p_key_settings->p_own_certificate);
  656. }
  657. else
  658. {
  659. err_code = NRF_SUCCESS;
  660. }
  661. }
  662. if (err_code == NRF_SUCCESS)
  663. {
  664. err_code = verify_options_set(p_interface, p_options->p_key_settings);
  665. }
  666. #ifdef MBEDTLS_SSL_PROTO_DTLS
  667. if (err_code == NRF_SUCCESS)
  668. {
  669. if (p_interface->conf.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM)
  670. {
  671. mbedtls_ssl_conf_min_version(&p_interface->conf,
  672. MBEDTLS_SSL_MAJOR_VERSION_3,
  673. MBEDTLS_SSL_MINOR_VERSION_3);
  674. mbedtls_ssl_conf_max_version(&p_interface->conf,
  675. MBEDTLS_SSL_MAJOR_VERSION_3,
  676. MBEDTLS_SSL_MINOR_VERSION_3);
  677. if (p_options->transport_type == MBEDTLS_SSL_TRANSPORT_DATAGRAM)
  678. {
  679. mbedtls_ssl_conf_handshake_timeout(&p_interface->conf,
  680. (MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN * 2),
  681. (MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN * 2));
  682. }
  683. }
  684. }
  685. #endif // MBEDTLS_SSL_PROTO_DTLS
  686. interface_conf_debug_print(p_interface);
  687. return err_code;
  688. }
  689. /**@brief Sets up the SSL context according to the options specificed.
  690. *
  691. * @param[in] instance_id Identifies the TLS instance for which the procedure is requested.
  692. *
  693. * @retval NRF_SUCCESS if the procedure was successful, else an error indicating reason for
  694. * failure.
  695. *
  696. * @note For client roles, handshake prcoedure is initiated here.
  697. */
  698. static uint32_t interface_ssl_context_setup(uint32_t instance_id)
  699. {
  700. int result;
  701. interface_t * p_interface = m_interface[instance_id];
  702. TLS_TRC("[%p]: Major number: 0x%08lx Minor number: 0x%08lx",
  703. p_interface->conf,
  704. p_interface->conf.min_major_ver,
  705. p_interface->conf.min_minor_ver);
  706. mbedtls_ssl_init(&p_interface->context);
  707. result = mbedtls_ssl_setup(&p_interface->context, &p_interface->conf);
  708. TLS_LOG("mbedtls_ssl_setup result %d",result);
  709. if (result == 0)
  710. {
  711. //ssl_set_ciphersuites(&p_interface->context, default_ciphers);
  712. mbedtls_ssl_set_bio(&p_interface->context,
  713. (void *)instance_id,
  714. interface_transport_write,
  715. interface_transport_read,
  716. NULL);
  717. if (p_interface->conf.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM)
  718. {
  719. mbedtls_ssl_set_timer_cb(&p_interface->context,
  720. (void *)instance_id,
  721. tls_set_timer,
  722. tls_get_timer);
  723. }
  724. TLS_MUTEX_UNLOCK();
  725. result = mbedtls_ssl_handshake(&p_interface->context);
  726. TLS_MUTEX_LOCK();
  727. TLS_LOG("mbedtls_ssl_handshake result %d", result);
  728. if (result == MBEDTLS_ERR_SSL_CONN_EOF)
  729. {
  730. result = 0;
  731. }
  732. }
  733. return (result ? (NRF_ERROR_INTERNAL | IOT_TLS_ERR_BASE) : NRF_SUCCESS);
  734. }
  735. uint32_t nrf_tls_init(void)
  736. {
  737. uint32_t index = 0;
  738. SDK_MUTEX_INIT(m_tls_mutex);
  739. for (index = 0; index < NRF_TLS_MAX_INSTANCE_COUNT; index++)
  740. {
  741. interface_init(index);
  742. }
  743. UNUSED_RETURN_VALUE(mbedtls_platform_set_calloc_free(wrapper_calloc, nrf_free));
  744. #ifdef MBEDTLS_DEBUG_C
  745. mbedtls_debug_set_threshold(2);
  746. #endif // MBEDTLS_DEBUG_C
  747. UNUSED_RETURN_VALUE(nrf_drv_rng_init(NULL));
  748. return NRF_SUCCESS;
  749. }
  750. uint32_t nrf_tls_alloc(nrf_tls_instance_t * p_instance,
  751. nrf_tls_options_t const * p_options)
  752. {
  753. uint32_t err_code = (NRF_ERROR_NO_MEM | IOT_TLS_ERR_BASE);
  754. TLS_MUTEX_LOCK();
  755. err_code = interface_alloc(p_instance, p_options);
  756. if (err_code == NRF_SUCCESS)
  757. {
  758. err_code = interface_conf_setup(p_instance->instance_id, p_options);
  759. }
  760. if (err_code == NRF_SUCCESS)
  761. {
  762. err_code = interface_ssl_context_setup(p_instance->instance_id);
  763. }
  764. if (err_code != NRF_SUCCESS)
  765. {
  766. interface_free(p_instance->instance_id);
  767. }
  768. TLS_MUTEX_UNLOCK();
  769. return err_code;
  770. }
  771. uint32_t nrf_tls_input(nrf_tls_instance_t const * p_instance,
  772. uint8_t const * p_data,
  773. uint32_t datalen)
  774. {
  775. uint32_t actual_size = 0;
  776. uint32_t err_code = (NRF_ERROR_NOT_FOUND | IOT_TLS_ERR_BASE);
  777. TLS_MUTEX_LOCK();
  778. if ((p_instance->instance_id < NRF_TLS_MAX_INSTANCE_COUNT) &&
  779. (m_interface[p_instance->instance_id] != NULL))
  780. {
  781. interface_t * const p_interface = m_interface[p_instance->instance_id];
  782. // Verify all data can be queued in the FIFO.
  783. err_code = app_fifo_write(&p_interface->input_fifo, NULL, &actual_size);
  784. if (err_code == NRF_SUCCESS)
  785. {
  786. // Avoid partial write.
  787. if (datalen <= actual_size)
  788. {
  789. actual_size = datalen;
  790. err_code = app_fifo_write(&p_interface->input_fifo, p_data, &actual_size);
  791. TLS_TRC("[%p]: >> nrf_tls_input datalen 0x%08lx result 0x%08lx",
  792. p_interface,
  793. datalen,
  794. err_code);
  795. }
  796. else
  797. {
  798. TLS_LOG("[%p]: Failed to queue input. "
  799. "Available 0x%08lx, requested 0x%08lx",
  800. p_interface,
  801. actual_size,
  802. datalen);
  803. }
  804. interface_continue(p_interface);
  805. }
  806. else
  807. {
  808. // Not enough room in the FIFO, indicate error.
  809. err_code = (NRF_ERROR_NO_MEM | IOT_TLS_ERR_BASE);
  810. }
  811. }
  812. TLS_MUTEX_UNLOCK();
  813. return err_code;
  814. }
  815. uint32_t nrf_tls_read(nrf_tls_instance_t const * p_instance,
  816. uint8_t * p_data,
  817. uint32_t * p_datalen)
  818. {
  819. uint32_t err_code = (NRF_ERROR_NOT_FOUND | IOT_TLS_ERR_BASE);
  820. TLS_MUTEX_LOCK();
  821. if ((p_instance->instance_id < NRF_TLS_MAX_INSTANCE_COUNT) &&
  822. (m_interface[p_instance->instance_id] != NULL))
  823. {
  824. interface_t * const p_interface = m_interface[p_instance->instance_id];
  825. err_code = app_fifo_read(&p_interface->output_fifo, p_data, p_datalen);
  826. }
  827. TLS_MUTEX_UNLOCK();
  828. return err_code;
  829. }
  830. uint32_t nrf_tls_write(nrf_tls_instance_t const * p_instance,
  831. uint8_t const * p_data,
  832. uint32_t * p_datalen)
  833. {
  834. uint32_t err_code = (NRF_ERROR_NOT_FOUND | IOT_TLS_ERR_BASE);
  835. TLS_MUTEX_LOCK();
  836. if ((p_instance->instance_id < NRF_TLS_MAX_INSTANCE_COUNT) &&
  837. (m_interface[p_instance->instance_id] != NULL))
  838. {
  839. interface_t * const p_interface = m_interface[p_instance->instance_id];
  840. int actual_len = (*p_datalen);
  841. TLS_MUTEX_UNLOCK();
  842. actual_len = mbedtls_ssl_write(&p_interface->context, p_data, actual_len);
  843. TLS_MUTEX_LOCK();
  844. if (actual_len < 0)
  845. {
  846. err_code = (NRF_ERROR_INTERNAL | IOT_TLS_ERR_BASE);
  847. if (actual_len == MBEDTLS_ERR_SSL_CONN_EOF)
  848. {
  849. if (p_interface->context.state < MBEDTLS_SSL_HANDSHAKE_OVER)
  850. {
  851. err_code = NRF_TLS_HANDSHAKE_IN_PROGRESS;
  852. }
  853. }
  854. }
  855. else
  856. {
  857. (* p_datalen) = actual_len;
  858. err_code = NRF_SUCCESS;
  859. }
  860. }
  861. TLS_MUTEX_UNLOCK();
  862. return err_code;
  863. }
  864. uint32_t nrf_tls_free(nrf_tls_instance_t const * p_instance)
  865. {
  866. uint32_t err_code = (NRF_ERROR_NOT_FOUND | IOT_TLS_ERR_BASE);
  867. TLS_MUTEX_LOCK();
  868. if ((p_instance->instance_id < NRF_TLS_MAX_INSTANCE_COUNT) &&
  869. (m_interface[p_instance->instance_id] != NULL))
  870. {
  871. interface_free(p_instance->instance_id);
  872. err_code = NRF_SUCCESS;
  873. }
  874. TLS_MUTEX_UNLOCK();
  875. return err_code;
  876. }
  877. void nrf_tls_process(void)
  878. {
  879. uint32_t index;
  880. TLS_MUTEX_LOCK();
  881. for (index = 0; index < NRF_TLS_MAX_INSTANCE_COUNT; index++)
  882. {
  883. if (m_interface[index] != NULL)
  884. {
  885. interface_continue(m_interface[index]);
  886. }
  887. }
  888. TLS_MUTEX_UNLOCK();
  889. }