tls_interface.c 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  1. /**
  2. * Copyright (c) 2016 - 2019, 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 nromally 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 and 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] TLS options to be used for the instamce.
  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 = 0;
  179. uint32_t err_code = NRF_TLS_NO_FREE_INSTANCE;
  180. interface_t * p_interface = NULL;
  181. TLS_ENTRY();
  182. // allocate meory 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 sturcture.
  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. if (err_code == NRF_SUCCESS)
  218. {
  219. // All pre-requisites for using the instance met.
  220. // Procedure was successful.
  221. TLS_LOG("Ind");
  222. p_interface->transport_id = p_instance->transport_id;
  223. p_instance->instance_id = index;
  224. }
  225. }
  226. if (err_code != NRF_SUCCESS)
  227. {
  228. err_code = (NRF_ERROR_INTERNAL | IOT_TLS_ERR_BASE);
  229. }
  230. }
  231. if (err_code != NRF_SUCCESS)
  232. {
  233. TLS_ERR("Allocation failed - Initialization procedures.");
  234. interface_free(index);
  235. }
  236. }
  237. else
  238. {
  239. TLS_ERR("Allocation failed - Inadequate memory.");
  240. }
  241. return err_code;
  242. }
  243. /**@brief Transport read function registered with the TLS library.
  244. *
  245. * @details Data read on the transport is fed to the interface using the nrf_tls_input function.
  246. * The TLS library requests the data based on state of SSL connection.
  247. *
  248. * @param[in] p_ctx Context registered with the library on creation of the TLS instance.
  249. * @param[out] p_buffer Buffer where read data is fetched.
  250. * @param[in] size Size to be read.
  251. *
  252. * @retval size of data read if procedure was successful.
  253. * @retval MBEDTLS_ERR_SSL_CONN_EOF indicating there is not enough data received on the transport.
  254. */
  255. static int interface_transport_read(void * p_ctx, unsigned char * p_buffer, size_t buffer_size)
  256. {
  257. uint32_t err;
  258. uint32_t length = buffer_size;
  259. interface_t * const p_interface = m_interface[(uint32_t)p_ctx];
  260. uint32_t available_size = 0;
  261. TLS_MUTEX_LOCK();
  262. TLS_TRC("[%p]: interface_transport_read requested %08x",
  263. p_interface,
  264. buffer_size);
  265. // Verify how much data is available in the queue.
  266. err = app_fifo_read(&p_interface->input_fifo, NULL, &available_size);
  267. TLS_TRC("[%p]: interface_transport_read, app_fifo_read result %ld",
  268. p_interface,
  269. err);
  270. // For datagram connection, read all that is available.
  271. // For stream sockets, read only if available data is at least as much as requested.
  272. if (( (p_interface->conf.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) &&
  273. (available_size > 0) )||
  274. ( (p_interface->conf.transport == MBEDTLS_SSL_TRANSPORT_STREAM) &&
  275. (available_size >= buffer_size)) )
  276. {
  277. TLS_TRC("[%p]: interface_transport_read requested 0x%08x, available %08lx.",
  278. p_interface,
  279. buffer_size,
  280. available_size);
  281. err = app_fifo_read(&p_interface->input_fifo, p_buffer, &length);
  282. if (err == NRF_SUCCESS)
  283. {
  284. TLS_TRC("[%p]: interface_transport_read success, length 0x%08lx.",
  285. p_interface,
  286. length);
  287. TLS_TRC("[NRF TLS]: ---------------- SSL Read data --------------");
  288. TLS_DUMP(p_buffer, length);
  289. TLS_TRC("[NRF TLS]: -------------------- End ------------------");
  290. return length;
  291. }
  292. }
  293. else
  294. {
  295. TLS_TRC("[%p]: interface_transport_read requested size 0x%08x, "
  296. "available 0x%08lx.",
  297. p_interface,
  298. buffer_size,
  299. available_size);
  300. }
  301. TLS_MUTEX_UNLOCK();
  302. return MBEDTLS_ERR_SSL_CONN_EOF;
  303. }
  304. /**@brief Write function that the TLS library calls to write on the transport.
  305. *
  306. * @param[in] p_ctx Context registered with the library on creation of the TLS instance.
  307. * @param[in] p_buf Buffer containing data to be written on the transport.
  308. * @param[in] len Length of data to be written.
  309. *
  310. * @retval length of data written on the transport if the procedure was successful.
  311. * @retval MBEDTLS_ERR_SSL_CONN_EOF in case the procedure failed.
  312. */
  313. static int interface_transport_write(void * p_ctx, const unsigned char * p_buf, size_t len)
  314. {
  315. int op_len = len;
  316. interface_t * const p_interface = m_interface[(uint32_t)p_ctx];
  317. TLS_MUTEX_LOCK();
  318. const nrf_tls_instance_t handle = {
  319. .transport_id = p_interface->transport_id,
  320. .instance_id = (uint32_t)p_ctx
  321. };
  322. TLS_LOG("[%p]: interface_transport_write requested 0x%08x",
  323. p_interface, len);
  324. TLS_MUTEX_UNLOCK();
  325. uint32_t err_code = p_interface->output_fn(&handle, (uint8_t *)p_buf, len);
  326. TLS_MUTEX_LOCK();
  327. if (err_code != NRF_SUCCESS)
  328. {
  329. op_len = MBEDTLS_ERR_SSL_CONN_EOF;
  330. }
  331. TLS_MUTEX_UNLOCK();
  332. return op_len;
  333. }
  334. /**
  335. * @brief Random number generator registered with the TLS library to create random numbers
  336. * when needed.
  337. *
  338. * @param[in] p_ctx Context registered with the library on creation of the TLS instance.
  339. * @param[out] p_buffer Buffer where generated random vector is to be fetched.
  340. * @param[in] size Requested size of the random vector.
  341. *
  342. * @retval 0 when procedure is successful.
  343. *
  344. * @note This loop is time critical when available is less than requested size.
  345. */
  346. static int random_vector_generate(void * p_ctx, unsigned char * p_buffer, size_t size)
  347. {
  348. uint8_t available = 0;
  349. ASSERT(size <= RNG_CONFIG_POOL_SIZE);
  350. while (available < size)
  351. {
  352. nrf_drv_rng_bytes_available(&available);
  353. TLS_TRC(">> random_vector_generate, requested 0x%08lx, available 0x%08x",
  354. size,
  355. available);
  356. }
  357. UNUSED_RETURN_VALUE(nrf_drv_rng_rand(p_buffer, size));
  358. return 0;
  359. }
  360. /**@brief Routine called periodically to adavnce the SSL context state.
  361. *
  362. * @param[in] index Identifies the instance in m_interface to be serviced.
  363. */
  364. static void interface_continue(interface_t * p_interface)
  365. {
  366. uint8_t * data = nrf_malloc(OUTPUT_BUFFER_SIZE);
  367. if (data != NULL)
  368. {
  369. int len;
  370. TLS_MUTEX_UNLOCK();
  371. len = mbedtls_ssl_read(&p_interface->context, &data[0], OUTPUT_BUFFER_SIZE);
  372. TLS_MUTEX_LOCK();
  373. TLS_TRC("[%p]:[0x%08lx]mbedtls_ssl_read result(len) 0x%08lx",
  374. p_interface,
  375. index,
  376. len);
  377. if (len > 0)
  378. {
  379. uint32_t write_len = len;
  380. uint32_t err_code = app_fifo_write(&p_interface->output_fifo, data, &write_len);
  381. if (err_code != NRF_SUCCESS)
  382. {
  383. TLS_LOG("Failed to write decrypted data.");
  384. }
  385. }
  386. nrf_free(data);
  387. }
  388. }
  389. /**@brief Debug log funciton registered with the TLS library.
  390. *
  391. * @param[in] p_ctx Context registered with the library on creation of the TLS instance.
  392. * @param[in] level Debug level of the log.
  393. * @param[in] p_file File requesting the log.
  394. * @param[in] line Line number in the file requesting the log.
  395. * @param[in] p_str String containing the log message.
  396. */
  397. static void mbedtls_log(void * p_ctx,
  398. int level,
  399. const char * p_file,
  400. int line,
  401. const char * p_str)
  402. {
  403. TLS_LOG("[%s]:[%d]: %s", &p_file[strlen(p_file)-12], line, p_str);
  404. }
  405. /**@brief Function registered with TLS library to set (start/stop) timer.
  406. *
  407. * @param[in] p_ctx Context registered with the library on creation of the TLS instance.
  408. * @param[in] int_ms Intermediate timeout period in milliseconds.
  409. * @param[in] fin_ms Finaly timout period in milliseconds.
  410. * Value of zero indicates a request to stop the timer.
  411. */
  412. static void tls_set_timer (void * p_ctx, uint32_t int_ms, uint32_t fin_ms)
  413. {
  414. TLS_MUTEX_LOCK();
  415. interface_t * const p_interface = m_interface[(uint32_t)p_ctx];
  416. if (fin_ms > 0)
  417. {
  418. TLS_TRC("[%p]: set_timer, start %d, final %d, intermediate %d",
  419. p_interface,
  420. p_interface->start_tick,
  421. p_interface->final_delay,
  422. p_interface->intrmediate_delay);
  423. uint32_t err_code = iot_timer_wall_clock_get(&p_interface->start_tick);
  424. if (err_code == NRF_SUCCESS)
  425. {
  426. p_interface->final_delay = fin_ms;
  427. p_interface->intrmediate_delay = int_ms;
  428. }
  429. }
  430. else
  431. {
  432. p_interface->start_tick = TIME_PERIOD_INVALID;
  433. p_interface->final_delay = TIME_PERIOD_INVALID;
  434. p_interface->intrmediate_delay = 0;
  435. }
  436. TLS_MUTEX_UNLOCK();
  437. }
  438. /**@brief Function registered with TLS library to get the status of the timer.
  439. *
  440. * @param[in] p_ctx Context registered with the library on creation of the TLS instance.
  441. *
  442. * @retval -1 if timer is cancelled
  443. * @retval 0 if none of the delays is expired
  444. * @retval 1 if the intermediate delay only is expired
  445. * @retval 2 if the final delay is expired
  446. */
  447. static int tls_get_timer (void * p_ctx)
  448. {
  449. TLS_MUTEX_LOCK();
  450. iot_timer_time_in_ms_t elapsed_time;
  451. interface_t * const p_interface = m_interface[(uint32_t)p_ctx];
  452. uint32_t err_code = iot_timer_wall_clock_delta_get(&p_interface->start_tick, &elapsed_time);
  453. TLS_TRC("[%p]:get_timer, start %d, final %d, intermediate %d, elapsed %d",
  454. p_interface,
  455. p_interface->start_tick,
  456. p_interface->final_delay,
  457. p_interface->intrmediate_delay,
  458. elapsed_time);
  459. if (err_code == NRF_SUCCESS)
  460. {
  461. if (p_interface->final_delay <= elapsed_time)
  462. {
  463. return 2;
  464. }
  465. else if (p_interface->intrmediate_delay <= elapsed_time)
  466. {
  467. return 1;
  468. }
  469. else
  470. {
  471. if ((p_interface->intrmediate_delay == TIME_PERIOD_INVALID) &&
  472. (p_interface->final_delay == TIME_PERIOD_INVALID))
  473. {
  474. return -1;
  475. }
  476. }
  477. }
  478. TLS_MUTEX_UNLOCK();
  479. return 0;
  480. }
  481. /**@brief Prints/displays the configuration of the interface. Used for debugging purposes.
  482. *
  483. * @param[in] p_interface Identifies the instance whose ssl configuration is to be printed.
  484. */
  485. static void interface_conf_debug_print(interface_t * p_interface)
  486. {
  487. TLS_TRC("[%p] SSL Conf", p_interface);
  488. for (int i = 0; i < 4; i++)
  489. {
  490. TLS_TRC("\t Cipger Suites : %02d", i);
  491. TLS_TRC("\t\t\tCiphersuite[0] = %02d", p_interface->conf.ciphersuite_list[i][0]);
  492. TLS_TRC("\t\t\tCiphersuite[1] = %02d", p_interface->conf.ciphersuite_list[i][1]);
  493. TLS_TRC("\t\t\tCiphersuite[2] = %02d", p_interface->conf.ciphersuite_list[i][2]);
  494. TLS_TRC("\t\t\tCiphersuite[3] = %02d", p_interface->conf.ciphersuite_list[i][3]);
  495. }
  496. TLS_TRC("\t\tf_dbg = %p", p_interface->conf.f_dbg);
  497. TLS_TRC("\t\tp_dbg = %p", p_interface->conf.p_dbg);
  498. TLS_TRC("\t\tf_rng = %p", p_interface->conf.f_rng);
  499. TLS_TRC("\t\tp_rng = %p", p_interface->conf.p_rng);
  500. TLS_TRC("\t\tf_get_cache = %p", p_interface->conf.f_get_cache);
  501. TLS_TRC("\t\tf_set_cache = %p", p_interface->conf.f_set_cache);
  502. TLS_TRC("\t\tf_set_cache = %p", p_interface->conf.p_cache);
  503. TLS_TRC("\t\tf_vrfy = %p", p_interface->conf.f_vrfy);
  504. TLS_TRC("\t\tp_vrfy = %p", p_interface->conf.p_vrfy);
  505. TLS_TRC("\t\tcert_profile = %p", p_interface->conf.cert_profile);
  506. TLS_TRC("\t\tkey_cert = %p", p_interface->conf.key_cert);
  507. TLS_TRC("\t\tca_chain = %p", p_interface->conf.ca_chain);
  508. TLS_TRC("\t\tca_crl = %p", p_interface->conf.ca_crl);
  509. TLS_TRC("\t\tmax_major_ver = %2d", p_interface->conf.max_major_ver);
  510. TLS_TRC("\t\tmax_minor_ver = %2d", p_interface->conf.max_minor_ver);
  511. TLS_TRC("\t\tmin_major_ver = %2d", p_interface->conf.min_major_ver);
  512. TLS_TRC("\t\tmax_major_ver = %2d", p_interface->conf.max_major_ver);
  513. }
  514. /**@brief Sets up own certificate on the interface instance.
  515. *
  516. * @param[in] p_interface TLS interface instance for which the procedure is requested.
  517. * @param[in] p_own Supplies own certifcate setup information.
  518. *
  519. * @retval NRF_SUCCESS if the procedure was successful, else an error code indicating reason for
  520. * failure.
  521. */
  522. static uint32_t own_certificate_set(interface_t * const p_interface,
  523. nrf_tls_certificate_t const * p_own)
  524. {
  525. #ifdef MBEDTLS_X509_CRT_PARSE_C
  526. uint32_t error_code = (NRF_ERROR_NO_MEM | IOT_TLS_ERR_BASE);
  527. int result;
  528. p_interface->p_owncert = nrf_malloc(sizeof(mbedtls_x509_crt));
  529. if (p_interface->p_owncert)
  530. {
  531. mbedtls_x509_crt_init(p_interface->p_owncert);
  532. result = mbedtls_x509_crt_parse(p_interface->p_owncert,
  533. p_own->p_certificate,
  534. p_own->certificate_len);
  535. if ( result == 0 )
  536. {
  537. mbedtls_pk_init( &p_interface->pkey );
  538. result = mbedtls_pk_parse_key(&p_interface->pkey,
  539. p_own->p_private_key,
  540. p_own->private_key_len,
  541. NULL,
  542. 0 );
  543. result = mbedtls_ssl_conf_own_cert(&p_interface->conf,
  544. p_interface->p_owncert,
  545. &p_interface->pkey);
  546. if (result != 0)
  547. {
  548. error_code = NRF_TLS_OWN_CERT_SETUP_FAILED;
  549. }
  550. else
  551. {
  552. error_code = NRF_SUCCESS;
  553. }
  554. }
  555. else
  556. {
  557. error_code = NRF_TLS_OWN_CERT_SETUP_FAILED;
  558. }
  559. }
  560. return error_code;
  561. #else
  562. return NRF_SUCCESS;
  563. #endif // MBEDTLS_X509_CRT_PARSE_C
  564. }
  565. /**@brief Sets up verification option for the interfce,
  566. *
  567. * @param[in] p_interface TLS interface instance for which the procedure is requested.
  568. * @param[in] p_settings Key setting supplying CA PEM file.
  569. *
  570. * @retval NRF_SUCCESS if the procedure was successful, else an error code indicating reason for
  571. * failure.
  572. */
  573. static uint32_t verify_options_set(interface_t * const p_interface,
  574. nrf_tls_key_settings_t const * p_settings)
  575. {
  576. uint32_t err_code = NRF_SUCCESS;
  577. #ifdef MBEDTLS_X509_CRT_PARSE_C
  578. if ((p_settings != NULL) && (p_settings->p_ca_cert_pem != NULL))
  579. {
  580. mbedtls_ssl_conf_authmode(&p_interface->conf, MBEDTLS_SSL_VERIFY_REQUIRED );
  581. p_interface->p_cacert = nrf_malloc(sizeof(mbedtls_x509_crt));
  582. if (p_interface->p_cacert != NULL)
  583. {
  584. // Initialize ca certificate.
  585. mbedtls_x509_crt_init(p_interface->p_cacert);
  586. int result = mbedtls_x509_crt_parse(p_interface->p_cacert,
  587. p_settings->p_ca_cert_pem,
  588. p_settings->ca_cert_pem_len);
  589. if ( result < 0 )
  590. {
  591. err_code = NRF_TLS_INVALID_CA_CERTIFICATE;
  592. }
  593. else
  594. {
  595. mbedtls_ssl_conf_ca_chain(&p_interface->conf, p_interface->p_cacert, NULL);
  596. }
  597. }
  598. else
  599. {
  600. err_code = (NRF_ERROR_NO_MEM | IOT_TLS_ERR_BASE);
  601. }
  602. }
  603. else
  604. #endif // MBEDTLS_X509_CRT_PARSE_C
  605. {
  606. mbedtls_ssl_conf_authmode(&p_interface->conf, MBEDTLS_SSL_VERIFY_NONE);
  607. }
  608. return err_code;
  609. }
  610. /**@brief Sets up the configuration for SSL context according to the options specificed.
  611. *
  612. * @param[in] instance_id Identifies the TLS instance for which the procedure is requested.
  613. * @param[in] p_options Supplies options to be used for the configuration.
  614. *
  615. * @retval NRF_SUCCESS if the procedure was successful, else an error indicating reason
  616. * for failure.
  617. */
  618. static uint32_t interface_conf_setup(uint32_t instance_id, nrf_tls_options_t const * p_options)
  619. {
  620. int result = 0;
  621. interface_t * p_interface = m_interface[instance_id];
  622. uint32_t err_code = NRF_TLS_CONFIGURATION_FAILED;
  623. mbedtls_ssl_config_init(&p_interface->conf);
  624. result = mbedtls_ssl_config_defaults(&p_interface->conf,
  625. p_options->role,
  626. p_options->transport_type,
  627. MBEDTLS_SSL_PRESET_DEFAULT);
  628. mbedtls_ssl_conf_rng(&p_interface->conf, random_vector_generate, NULL);
  629. mbedtls_ssl_conf_dbg(&p_interface->conf, mbedtls_log, NULL);
  630. TLS_TRC("[%p]: mbedtls_ssl_config_defaults result %08lx", p_conf, result);
  631. #ifdef MBEDTLS_KEY_EXCHANGE_PSK_ENABLED
  632. if (result == 0)
  633. {
  634. if ((p_options->p_key_settings != NULL) && (p_options->p_key_settings->p_psk != NULL))
  635. {
  636. result = mbedtls_ssl_conf_psk(&p_interface->conf,
  637. p_options->p_key_settings->p_psk->p_secret_key,
  638. p_options->p_key_settings->p_psk->secret_key_len,
  639. p_options->p_key_settings->p_psk->p_identity,
  640. p_options->p_key_settings->p_psk->identity_len);
  641. }
  642. }
  643. #endif // MBEDTLS_KEY_EXCHANGE_PSK_ENABLED
  644. if (result == 0)
  645. {
  646. if (p_options->p_key_settings->p_own_certificate != NULL)
  647. {
  648. err_code = own_certificate_set(p_interface,
  649. p_options->p_key_settings->p_own_certificate);
  650. }
  651. else
  652. {
  653. err_code = NRF_SUCCESS;
  654. }
  655. }
  656. if (err_code == NRF_SUCCESS)
  657. {
  658. err_code = verify_options_set(p_interface, p_options->p_key_settings);
  659. }
  660. #ifdef MBEDTLS_SSL_PROTO_DTLS
  661. if (err_code == NRF_SUCCESS)
  662. {
  663. if (p_interface->conf.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM)
  664. {
  665. mbedtls_ssl_conf_min_version(&p_interface->conf,
  666. MBEDTLS_SSL_MAJOR_VERSION_3,
  667. MBEDTLS_SSL_MINOR_VERSION_3);
  668. mbedtls_ssl_conf_max_version(&p_interface->conf,
  669. MBEDTLS_SSL_MAJOR_VERSION_3,
  670. MBEDTLS_SSL_MINOR_VERSION_3);
  671. if (p_options->transport_type == MBEDTLS_SSL_TRANSPORT_DATAGRAM)
  672. {
  673. mbedtls_ssl_conf_handshake_timeout(&p_interface->conf,
  674. (MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN * 2),
  675. (MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN * 2));
  676. }
  677. }
  678. }
  679. #endif // MBEDTLS_SSL_PROTO_DTLS
  680. interface_conf_debug_print(p_interface);
  681. return err_code;
  682. }
  683. /**@brief Sets up the SSL context according to the options specificed.
  684. *
  685. * @param[in] instance_id Identifies the TLS instance for which the procedure is requested.
  686. *
  687. * @retval NRF_SUCCESS if the procedure was successful, else an error indicating reason for
  688. * failure.
  689. *
  690. * @note For client roles, handshake prcoedure is initiated here.
  691. */
  692. static uint32_t interface_ssl_context_setup(uint32_t instance_id)
  693. {
  694. int result = 0;
  695. interface_t * p_interface = m_interface[instance_id];
  696. TLS_TRC("[%p]: Major number: 0x%08lx Minor number: 0x%08lx",
  697. p_conf,
  698. p_conf->min_major_ver,
  699. p_conf->min_minor_ver);
  700. mbedtls_ssl_init(&p_interface->context);
  701. result = mbedtls_ssl_setup(&p_interface->context, &p_interface->conf);
  702. TLS_LOG("mbedtls_ssl_setup result %d",result);
  703. if (result == 0)
  704. {
  705. //ssl_set_ciphersuites(&p_interface->context, default_ciphers);
  706. mbedtls_ssl_set_bio(&p_interface->context,
  707. (void *)instance_id,
  708. interface_transport_write,
  709. interface_transport_read,
  710. NULL);
  711. if (p_interface->conf.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM)
  712. {
  713. mbedtls_ssl_set_timer_cb(&p_interface->context,
  714. (void *)instance_id,
  715. tls_set_timer,
  716. tls_get_timer);
  717. }
  718. TLS_MUTEX_UNLOCK();
  719. result = mbedtls_ssl_handshake(&p_interface->context);
  720. TLS_MUTEX_LOCK();
  721. TLS_LOG("mbedtls_ssl_handshake result %d", result);
  722. if (result == MBEDTLS_ERR_SSL_CONN_EOF)
  723. {
  724. result = 0;
  725. }
  726. }
  727. return (result ? (NRF_ERROR_INTERNAL | IOT_TLS_ERR_BASE) : NRF_SUCCESS);
  728. }
  729. uint32_t nrf_tls_init(void)
  730. {
  731. uint32_t index = 0;
  732. SDK_MUTEX_INIT(m_tls_mutex);
  733. do
  734. {
  735. interface_init(index);
  736. index++;
  737. } while (index < NRF_TLS_MAX_INSTANCE_COUNT);
  738. UNUSED_RETURN_VALUE(mbedtls_platform_set_calloc_free(wrapper_calloc, nrf_free));
  739. #ifdef MBEDTLS_DEBUG_C
  740. mbedtls_debug_set_threshold(2);
  741. #endif // MBEDTLS_DEBUG_C
  742. UNUSED_RETURN_VALUE(nrf_drv_rng_init(NULL));
  743. return NRF_SUCCESS;
  744. }
  745. uint32_t nrf_tls_alloc(nrf_tls_instance_t * p_instance,
  746. nrf_tls_options_t const * p_options)
  747. {
  748. uint32_t err_code = (NRF_ERROR_NO_MEM | IOT_TLS_ERR_BASE);
  749. TLS_MUTEX_LOCK();
  750. err_code = interface_alloc(p_instance, p_options);
  751. if (err_code == NRF_SUCCESS)
  752. {
  753. err_code = interface_conf_setup(p_instance->instance_id, p_options);
  754. }
  755. if (err_code == NRF_SUCCESS)
  756. {
  757. err_code = interface_ssl_context_setup(p_instance->instance_id);
  758. }
  759. if (err_code != NRF_SUCCESS)
  760. {
  761. interface_free(p_instance->instance_id);
  762. }
  763. TLS_MUTEX_UNLOCK();
  764. return err_code;
  765. }
  766. uint32_t nrf_tls_input(nrf_tls_instance_t const * p_instance,
  767. uint8_t const * p_data,
  768. uint32_t datalen)
  769. {
  770. uint32_t actual_size = 0;
  771. uint32_t err_code = (NRF_ERROR_NOT_FOUND | IOT_TLS_ERR_BASE);
  772. TLS_MUTEX_LOCK();
  773. if ((p_instance->instance_id < NRF_TLS_MAX_INSTANCE_COUNT) &&
  774. (m_interface[p_instance->instance_id] != NULL))
  775. {
  776. interface_t * const p_interface = m_interface[p_instance->instance_id];
  777. // Verify all data can be queued in the FIFO.
  778. err_code = app_fifo_write(&p_interface->input_fifo, NULL, &actual_size);
  779. if (err_code == NRF_SUCCESS)
  780. {
  781. // Avoid partial write.
  782. if (datalen <= actual_size)
  783. {
  784. actual_size = datalen;
  785. err_code = app_fifo_write(&p_interface->input_fifo, p_data, &actual_size);
  786. TLS_TRC("[%p]: >> nrf_tls_input datalen 0x%08lx result 0x%08lx",
  787. p_interface,
  788. datalen,
  789. retval);
  790. }
  791. else
  792. {
  793. TLS_LOG("[%p]: Failed to queue input. "
  794. "Available 0x%08lx, requested 0x%08lx",
  795. p_interface,
  796. actual_size,
  797. datalen);
  798. }
  799. interface_continue(p_interface);
  800. }
  801. else
  802. {
  803. // Not enough room in the FIFO, indicate error.
  804. return (NRF_ERROR_NO_MEM | IOT_TLS_ERR_BASE);
  805. }
  806. }
  807. TLS_MUTEX_UNLOCK();
  808. return err_code;
  809. }
  810. uint32_t nrf_tls_read(nrf_tls_instance_t const * p_instance,
  811. uint8_t * p_data,
  812. uint32_t * p_datalen)
  813. {
  814. uint32_t err_code = (NRF_ERROR_NOT_FOUND | IOT_TLS_ERR_BASE);
  815. TLS_MUTEX_LOCK();
  816. if ((p_instance->instance_id < NRF_TLS_MAX_INSTANCE_COUNT) &&
  817. (m_interface[p_instance->instance_id] != NULL))
  818. {
  819. interface_t * const p_interface = m_interface[p_instance->instance_id];
  820. err_code = app_fifo_read(&p_interface->output_fifo, p_data, p_datalen);
  821. }
  822. TLS_MUTEX_UNLOCK();
  823. return err_code;
  824. }
  825. uint32_t nrf_tls_write(nrf_tls_instance_t const * p_instance,
  826. uint8_t const * p_data,
  827. uint32_t * p_datalen)
  828. {
  829. uint32_t err_code = (NRF_ERROR_NOT_FOUND | IOT_TLS_ERR_BASE);
  830. TLS_MUTEX_LOCK();
  831. if ((p_instance->instance_id < NRF_TLS_MAX_INSTANCE_COUNT) &&
  832. (m_interface[p_instance->instance_id] != NULL))
  833. {
  834. interface_t * const p_interface = m_interface[p_instance->instance_id];
  835. int actual_len = (*p_datalen);
  836. TLS_MUTEX_UNLOCK();
  837. actual_len = mbedtls_ssl_write(&p_interface->context, p_data, actual_len);
  838. TLS_MUTEX_LOCK();
  839. if (actual_len < 0)
  840. {
  841. err_code = (NRF_ERROR_INTERNAL | IOT_TLS_ERR_BASE);
  842. if (actual_len == MBEDTLS_ERR_SSL_CONN_EOF)
  843. {
  844. if (p_interface->context.state < MBEDTLS_SSL_HANDSHAKE_OVER)
  845. {
  846. err_code = NRF_TLS_HANDSHAKE_IN_PROGRESS;
  847. }
  848. }
  849. }
  850. else
  851. {
  852. (* p_datalen) = actual_len;
  853. err_code = NRF_SUCCESS;
  854. }
  855. }
  856. TLS_MUTEX_UNLOCK();
  857. return err_code;
  858. }
  859. uint32_t nrf_tls_free(nrf_tls_instance_t const * p_instance)
  860. {
  861. uint32_t err_code = (NRF_ERROR_NOT_FOUND | IOT_TLS_ERR_BASE);
  862. TLS_MUTEX_LOCK();
  863. if ((p_instance->instance_id < NRF_TLS_MAX_INSTANCE_COUNT) &&
  864. (m_interface[p_instance->instance_id] != NULL))
  865. {
  866. interface_free(p_instance->instance_id);
  867. err_code = NRF_SUCCESS;
  868. }
  869. TLS_MUTEX_UNLOCK();
  870. return err_code;
  871. }
  872. void nrf_tls_process(void)
  873. {
  874. uint32_t index;
  875. TLS_MUTEX_LOCK();
  876. for (index = 0; index < NRF_TLS_MAX_INSTANCE_COUNT; index++)
  877. {
  878. if (m_interface[index] != NULL)
  879. {
  880. interface_continue(m_interface[index]);
  881. }
  882. }
  883. TLS_MUTEX_UNLOCK();
  884. }