d8a7a8953cca04bbf56fc9a7f275df821d6b47fd
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / adapter_util / ca_adapter_net_ssl.c
1 /******************************************************************
2  *
3  * Copyright 2016 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20
21
22 #include "iotivity_config.h"
23
24 #define _GNU_SOURCE
25
26 #include <stddef.h>
27 #include <stdbool.h>
28 #include "ca_adapter_net_ssl.h"
29 #include "cacommon.h"
30 #include "caipinterface.h"
31 #include "oic_malloc.h"
32 #include "ocrandom.h"
33 #include "byte_array.h"
34 #include "octhread.h"
35 #include "timer.h"
36
37 // headers required for mbed TLS
38 #include "mbedtls/platform.h"
39 #include "mbedtls/ssl.h"
40 #include "mbedtls/entropy.h"
41 #include "mbedtls/ctr_drbg.h"
42 #include "mbedtls/pkcs12.h"
43 #include "mbedtls/ssl_internal.h"
44 #include "mbedtls/net_sockets.h"
45 #ifdef __WITH_DTLS__
46 #include "mbedtls/timing.h"
47 #include "mbedtls/ssl_cookie.h"
48 #endif
49
50 #if !defined(NDEBUG) || defined(TB_LOG)
51 #include "mbedtls/debug.h"
52 #include "mbedtls/version.h"
53 #endif
54
55 #ifdef HAVE_SYS_TYPES_H
56 #include <sys/types.h>
57 #endif
58 #ifdef HAVE_SYS_STAT_H
59 #include <sys/stat.h>
60 #endif
61 #ifdef HAVE_FCNTL_H
62 #include <fcntl.h>
63 #endif
64 #ifdef HAVE_UNISTD_H
65 #include <unistd.h>
66 #endif
67
68
69 /**
70  * @def MBED_TLS_VERSION_LEN
71  * @brief mbedTLS version string length
72  */
73 #define MBED_TLS_VERSION_LEN (16)
74  /**
75  * @def PERSONALIZATION_STRING
76  * @brief Personalization string for the mbedtls RNG
77  */
78 #define PERSONALIZATION_STRING "IOTIVITY_RND"
79 /**
80  * @def UUID_PREFIX
81  * @brief uuid prefix in certificate subject field
82  */
83 #define UUID_PREFIX "uuid:"
84 /**
85  * @def USERID_PREFIX
86  * @brief userid prefix in certificate alternative subject name field
87  */
88 #define USERID_PREFIX "userid:"
89
90 /**
91  * @def NET_SSL_TAG
92  * @brief Logging tag for module name
93  */
94 #define NET_SSL_TAG "OIC_CA_NET_SSL"
95 /**
96  * @def MBED_TLS_TAG
97  * @brief Logging tag for mbedTLS library
98  */
99 #define MBED_TLS_TAG "MBED_TLS"
100 /**
101  * @def MMBED_TLS_DEBUG_LEVEL
102  * @brief Logging level for mbedTLS library
103  */
104 #define MBED_TLS_DEBUG_LEVEL (4)
105
106 /**
107  * @def TLS_MSG_BUF_LEN
108  * @brief Buffer size for TLS record. A single TLS record may be up to 16384 octets in length
109  */
110
111 #define TLS_MSG_BUF_LEN (16384)
112 /**
113  * @def PSK_LENGTH
114  * @brief PSK keys max length
115  */
116 #define PSK_LENGTH (256/8)
117 /**
118  * @def UUID_LENGTHPSK_LENGTH
119  * @brief Identity max length
120  */
121 #define UUID_LENGTH (128/8)
122 /**
123  * @def MASTER_SECRET_LEN
124  * @brief TLS master secret length
125  */
126 #define MASTER_SECRET_LEN (48)
127 /**
128  * @def RANDOM_LEN
129  * @brief TLS client and server random bytes length
130  */
131 #define RANDOM_LEN (32)
132 /**
133  * @def SHA384_MAC_KEY_LENGTH
134  * @brief MAC key length for SHA384 cipher suites
135  */
136 #define SHA384_MAC_KEY_LENGTH (48)
137 /**
138  * @def SHA256_MAC_KEY_LENGTH
139  * @brief MAC key length for SHA256 cipher suites
140  */
141 #define SHA256_MAC_KEY_LENGTH (32)
142 /**
143  * @def CCM_MAC_KEY_LENGTH
144  * @brief MAC key length for CCM cipher suites
145  */
146 #define CCM_MAC_KEY_LENGTH (0)
147 /**
148  * @def AES256_KEY_LENGTH
149  * @brief key material length for AES256 cipher suites
150  */
151 #define AES256_KEY_LENGTH (32)
152 /**
153  * @def AES128_KEY_LENGTH
154  * @brief key material length for AES128 cipher suites
155  */
156 #define AES128_KEY_LENGTH (16)
157 /**
158  * @def GCM_IV_LENGTH
159  * @brief length of nonce for GCM cipher suites
160  */
161 #define GCM_IV_LENGTH (12)
162 /**
163  * @def CCM_IV_LENGTH
164  * @brief length of nonce for CCM cipher suites
165  */
166 #define CCM_IV_LENGTH (4)
167 /**
168  * @def CBC_IV_LENGTH
169  * @brief length of nonce for CBC cipher suites
170  */
171 #define CBC_IV_LENGTH (0)
172
173 /**
174  * @var RETRANSMISSION_TIME
175  * @brief Maximum timeout value (in seconds) to start DTLS retransmission.
176  */
177 #define RETRANSMISSION_TIME 1
178
179 /**@def SSL_CLOSE_NOTIFY(peer, ret)
180  *
181  * Notifies of existing \a peer about closing TLS connection.
182  *
183  * @param[in] peer remote peer
184  * @param[in] ret used internaly
185  */
186 #define SSL_CLOSE_NOTIFY(peer, ret)                                                                \
187 do                                                                                                 \
188 {                                                                                                  \
189     (ret) = mbedtls_ssl_close_notify(&(peer)->ssl);                                                \
190 } while (MBEDTLS_ERR_SSL_WANT_WRITE == (ret))
191
192 /**@def SSL_RES(peer, status)
193  *
194  * Sets SSL result for callback.
195  *
196  * @param[in] peer remote peer
197  */
198 #define SSL_RES(peer, status)                                                                      \
199 if (g_sslCallback)                                                                                 \
200 {                                                                                                  \
201     CAErrorInfo_t errorInfo;                                                                       \
202     errorInfo.result = (status);                                                                   \
203     g_sslCallback(&(peer)->sep.endpoint, &errorInfo);                                              \
204 }
205 /**@def SSL_CHECK_FAIL(peer, ret, str, mutex, error, msg)
206  *
207  * Checks handshake result and send alert if needed.
208  *
209  * @param[in] peer remote peer
210  * @param[in] ret error code
211  * @param[in] str debug string
212  * @param[in] mutex ca mutex
213  * @param[in] if code does not equal to -1 returns error code
214  * @param[in] msg allert message
215  */
216 #define SSL_CHECK_FAIL(peer, ret, str, mutex, error, msg)                                          \
217 if (0 != (ret) && MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY != (int) (ret) &&                              \
218     MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED != (int) (ret) &&                                        \
219     MBEDTLS_ERR_SSL_WANT_READ != (int) (ret) &&                                                    \
220     MBEDTLS_ERR_SSL_WANT_WRITE != (int) (ret) &&                                                   \
221     MBEDTLS_ERR_SSL_NON_FATAL != (int) (ret) &&                                                    \
222     MBEDTLS_SSL_ALERT_MSG_USER_CANCELED != (int) (ret) &&                                          \
223     MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION != (int) (ret) &&                                       \
224     MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT != (int) (ret) &&                                        \
225     MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY != (int) (ret) &&                                           \
226     MBEDTLS_SSL_ALERT_MSG_NO_CERT != (int) (ret) &&                                                \
227     MBEDTLS_SSL_ALERT_MSG_BAD_CERT != (int) (ret) &&                                               \
228     MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT != (int) (ret) &&                                       \
229     MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED != (int) (ret) &&                                           \
230     MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED != (int) (ret) &&                                           \
231     MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN != (int) (ret) &&                                           \
232     MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK != (int) (ret) &&                                  \
233     MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME != (int) (ret) &&                                      \
234     MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY != (int) (ret) &&                                   \
235     MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL != (int) (ret))                                  \
236 {                                                                                                  \
237     OIC_LOG_V(ERROR, NET_SSL_TAG, "%s: -0x%x", (str), -(ret));                                     \
238     if ((int) MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE != (int) (ret) &&                                \
239         (int) MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO != (int) (ret))                                  \
240     {                                                                                              \
241         mbedtls_ssl_send_alert_message(&(peer)->ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, (msg));        \
242     }                                                                                              \
243     RemovePeerFromList(&(peer)->sep.endpoint);                                                     \
244     if (mutex)                                                                                     \
245     {                                                                                              \
246         oc_mutex_unlock(g_sslContextMutex);                                                        \
247     }                                                                                              \
248     if ((int) MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO != (int)(ret))                                   \
249     {                                                                                              \
250         SSL_RES((peer), CA_DTLS_AUTHENTICATION_FAILURE);                                           \
251     }                                                                                              \
252     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);                                             \
253     if (-1 != error)                                                                               \
254     {                                                                                              \
255         return (error);                                                                            \
256     }                                                                                              \
257 }
258 /**@def CONF_SSL(clientConf, serverConf, fn, ...)
259  *
260  * Calls \a fn for \a clientConf and \a serverConf.
261  *
262  */
263 #define CONF_SSL(clientConf, serverConf, fn, ...) do {                                             \
264 fn((clientConf), __VA_ARGS__);                                                                     \
265 fn((serverConf), __VA_ARGS__);                                                                     \
266 } while (0)
267
268 /** @def CHECK_MBEDTLS_RET(f, ...)
269  * A macro that checks \a f function return code
270  *
271  * If function returns error code it goes to error processing.
272  *
273  * **IMPORTANT:** Any time CHECK_MBEDTLS_RET is used an `exit:` goto label must
274  *                be present to handle error processing.
275  *
276  * @param[in] f  Function to call
277  */
278 #define CHECK_MBEDTLS_RET(f, ...) do {                                                             \
279 int ret = (f)(__VA_ARGS__);                                                                        \
280 if (0 != ret) {                                                                                    \
281     OIC_LOG_V(ERROR, NET_SSL_TAG, "%s returned -0x%04x\n", __func__, -(ret));                      \
282     goto exit;                                                                                     \
283 } } while (0)
284
285 typedef enum
286 {
287     SSL_RSA_WITH_AES_256_CBC_SHA256,
288     SSL_RSA_WITH_AES_128_GCM_SHA256,
289     SSL_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
290     SSL_ECDHE_ECDSA_WITH_AES_128_CCM_8,
291     SSL_ECDHE_ECDSA_WITH_AES_128_CCM,
292     SSL_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
293     SSL_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
294     SSL_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
295     SSL_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
296     SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
297     SSL_ECDH_ANON_WITH_AES_128_CBC_SHA256,
298     SSL_CIPHER_MAX
299 } SslCipher_t;
300
301 typedef enum
302 {
303     ADAPTER_CURVE_SECP256R1,
304     ADAPTER_CURVE_MAX
305 } AdapterCurve_t;
306
307 static const int tlsCipher[SSL_CIPHER_MAX][2] =
308 {
309     {MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256, 0},
310     {MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, 0},
311     {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
312     {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, 0},
313     {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM, 0},
314     {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 0},
315     {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, 0},
316     {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 0},
317     {MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, 0},
318     {MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 0},
319     {MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256, 0}
320 };
321
322 static int g_cipherSuitesList[SSL_CIPHER_MAX];
323
324 mbedtls_ecp_group_id curve[ADAPTER_CURVE_MAX][2] =
325 {
326     {MBEDTLS_ECP_DP_SECP256R1, MBEDTLS_ECP_DP_NONE}
327 };
328
329 static PkiInfo_t g_pkiInfo = {{NULL, 0}, {NULL, 0}, {NULL, 0}, {NULL, 0}};
330
331 typedef struct  {
332     int code;
333     int alert;
334 } CrtVerifyAlert_t;
335
336 static const CrtVerifyAlert_t crtVerifyAlerts[] = {
337     {MBEDTLS_X509_BADCERT_EXPIRED,       MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED},
338     {MBEDTLS_X509_BADCERT_REVOKED,       MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED},
339     {MBEDTLS_X509_BADCERT_CN_MISMATCH,   MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN},
340     {MBEDTLS_X509_BADCERT_NOT_TRUSTED,   MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA},
341     {MBEDTLS_X509_BADCRL_NOT_TRUSTED,    MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA},
342     {MBEDTLS_X509_BADCRL_EXPIRED,        MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
343     {MBEDTLS_X509_BADCERT_MISSING,       MBEDTLS_SSL_ALERT_MSG_NO_CERT},
344     {MBEDTLS_X509_BADCERT_SKIP_VERIFY,   MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
345     {MBEDTLS_X509_BADCERT_OTHER,         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR},
346     {MBEDTLS_X509_BADCERT_FUTURE,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
347     {MBEDTLS_X509_BADCRL_FUTURE,         MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
348     {MBEDTLS_X509_BADCERT_KEY_USAGE,     MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
349     {MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
350     {MBEDTLS_X509_BADCERT_NS_CERT_TYPE,  MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
351     {MBEDTLS_X509_BADCERT_BAD_MD,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
352     {MBEDTLS_X509_BADCERT_BAD_PK,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
353     {MBEDTLS_X509_BADCERT_BAD_KEY,       MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
354     {MBEDTLS_X509_BADCRL_BAD_MD,         MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
355     {MBEDTLS_X509_BADCRL_BAD_PK,         MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
356     {MBEDTLS_X509_BADCRL_BAD_KEY,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
357     {0, 0}
358 };
359
360 static int GetAlertCode(uint32_t flags)
361 {
362     const CrtVerifyAlert_t *cur;
363
364     for (cur = crtVerifyAlerts; cur->alert != 0 ; cur++)
365     {
366         if (flags & cur->code)
367         {
368             return cur->alert;
369         }
370     }
371     return 0;
372 }
373
374 #if !defined(NDEBUG) || defined(TB_LOG)
375 /**
376  * Pass a message to the OIC logger.
377  *
378  * @param[in] ctx  opaque context for the callback
379  * @param[in] level  debug level
380  * @param[in] file  file name
381  * @param[in] line  line number
382  * @param[in] str  message
383  */
384 static void DebugSsl(void *ctx, int level, const char *file, int line, const char *str)
385 {
386     ((void) level);
387     ((void) file);
388     ((void) line);
389     ((void) ctx);
390
391     char * temp = (char*) str;
392     size_t len = strlen(temp);
393     if (1 <= len && temp[len - 1] == '\n')
394     {
395         temp[len - 1] = '\0';
396     }
397
398     OIC_LOG_V(DEBUG, MBED_TLS_TAG, "%s", str);
399 }
400 #endif
401
402 /**
403  * structure to holds the information of cache message and address info.
404  */
405 typedef ByteArray_t SslCacheMessage_t;
406
407
408 /**
409  * Data structure for holding the send and recv callbacks.
410  */
411 typedef struct TlsCallBacks
412 {
413     CAPacketReceivedCallback recvCallback;  /**< Callback used to send data to upper layer. */
414     CAPacketSendCallback sendCallback;      /**< Callback used to send data to socket layer. */
415 } SslCallbacks_t;
416
417 /**
418  * Data structure for holding the mbedTLS interface related info.
419  */
420 typedef struct SslContext
421 {
422     u_arraylist_t *peerList;         /**< peer list which holds the mapping between
423                                               peer id, it's n/w address and mbedTLS context. */
424     mbedtls_entropy_context entropy;
425     mbedtls_ctr_drbg_context rnd;
426     mbedtls_x509_crt ca;
427     mbedtls_x509_crt crt;
428     mbedtls_pk_context pkey;
429
430     mbedtls_ssl_config clientTlsConf;
431     mbedtls_ssl_config serverTlsConf;
432     mbedtls_ssl_config clientDtlsConf;
433     mbedtls_ssl_config serverDtlsConf;
434
435     SslCipher_t cipher;
436     SslCallbacks_t adapterCallbacks[MAX_SUPPORTED_ADAPTERS];
437     mbedtls_x509_crl crl;
438     bool cipherFlag[2];
439     int selectedCipher;
440
441 #ifdef __WITH_DTLS__
442     int timerId;
443 #endif
444
445 } SslContext_t;
446
447 /**
448  * @var g_caSslContext
449  * @brief global context which holds tls context and cache list information.
450  */
451 static SslContext_t * g_caSslContext = NULL;
452
453 /**
454  * @var g_getCredentialsCallback
455  * @brief callback to get TLS credentials (same as for DTLS)
456  */
457 static CAgetPskCredentialsHandler g_getCredentialsCallback = NULL;
458 /**
459  * @var g_getCerdentilTypesCallback
460  * @brief callback to get different credential types from SRM
461  */
462 static CAgetCredentialTypesHandler g_getCredentialTypesCallback = NULL;
463 /**
464  * @var g_getPkixInfoCallback
465  *
466  * @brief callback to get X.509-based Public Key Infrastructure
467  */
468 static CAgetPkixInfoHandler g_getPkixInfoCallback = NULL;
469
470 /**
471  * @var g_dtlsContextMutex
472  * @brief Mutex to synchronize access to g_caSslContext.
473  */
474 static oc_mutex g_sslContextMutex = NULL;
475
476 /**
477  * @var g_sslCallback
478  * @brief callback to deliver the TLS handshake result
479  */
480 static CAErrorCallback g_sslCallback = NULL;
481
482 /**
483  * Data structure for holding the data to be received.
484  */
485 typedef struct SslRecBuf
486 {
487     uint8_t * buff;
488     size_t len;
489     size_t loaded;
490 } SslRecBuf_t;
491 /**
492  * Data structure for holding the data related to endpoint
493  * and TLS session.
494  */
495 typedef struct SslEndPoint
496 {
497     mbedtls_ssl_context ssl;
498     CASecureEndpoint_t sep;
499     u_arraylist_t * cacheList;
500     SslRecBuf_t recBuf;
501     uint8_t master[MASTER_SECRET_LEN];
502     uint8_t random[2*RANDOM_LEN];
503 #ifdef __WITH_DTLS__
504     mbedtls_ssl_cookie_ctx cookieCtx;
505     mbedtls_timing_delay_context timer;
506 #endif // __WITH_DTLS__
507 } SslEndPoint_t;
508
509 void CAsetPskCredentialsCallback(CAgetPskCredentialsHandler credCallback)
510 {
511     // TODO Does this method needs protection of tlsContextMutex?
512     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
513     g_getCredentialsCallback = credCallback;
514     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
515 }
516
517 void CAsetPkixInfoCallback(CAgetPkixInfoHandler infoCallback)
518 {
519     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
520     g_getPkixInfoCallback = infoCallback;
521     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
522 }
523 void CAsetCredentialTypesCallback(CAgetCredentialTypesHandler credTypesCallback)
524 {
525     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
526     g_getCredentialTypesCallback = credTypesCallback;
527     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
528 }
529
530 static int GetAdapterIndex(CATransportAdapter_t adapter)
531 {
532     switch (adapter)
533     {
534         case CA_ADAPTER_IP:
535             return 0;
536         case CA_ADAPTER_TCP:
537             return 1;
538         case CA_ADAPTER_GATT_BTLE:
539             return 2;
540         default:
541             OIC_LOG(ERROR, NET_SSL_TAG, "Unsupported adapter");
542             return -1;
543     }
544 }
545 /**
546  * Write callback.
547  *
548  * @param[in]  tep    TLS endpoint
549  * @param[in]  data    message
550  * @param[in]  dataLen    message length
551  *
552  * @return  message length or -1 on error.
553  */
554 static int SendCallBack(void * tep, const unsigned char * data, size_t dataLen)
555 {
556     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
557     VERIFY_NON_NULL_RET(tep, NET_SSL_TAG, "secure endpoint is NULL", -1);
558     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "data is NULL", -1);
559     VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", -1);
560     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data len: %zu", dataLen);
561     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Adapter: %u", ((SslEndPoint_t * )tep)->sep.endpoint.adapter);
562     ssize_t sentLen = 0;
563     int adapterIndex = GetAdapterIndex(((SslEndPoint_t * )tep)->sep.endpoint.adapter);
564     if (0 <= adapterIndex && MAX_SUPPORTED_ADAPTERS > adapterIndex)
565     {
566         CAPacketSendCallback sendCallback = g_caSslContext->adapterCallbacks[adapterIndex].sendCallback;
567         sentLen = sendCallback(&(((SslEndPoint_t * )tep)->sep.endpoint), (const void *) data, dataLen);
568         if (sentLen != dataLen)
569         {
570             OIC_LOG_V(DEBUG, NET_SSL_TAG,
571                       "Packet was partially sent - total/sent/remained bytes : %d/%d/%d",
572                       sentLen, dataLen, (dataLen - sentLen));
573         }
574     }
575     else
576     {
577         OIC_LOG(ERROR, NET_SSL_TAG, "Unsupported adapter");
578         return -1;
579     }
580
581     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
582     return sentLen;
583 }
584 /**
585  * Read callback.
586  *
587  * @param[in]  tep    TLS endpoint
588  * @param[in]  data    message
589  * @param[in]  dataLen    message length
590  *
591  * @return  read length
592  */
593 static int RecvCallBack(void * tep, unsigned char * data, size_t dataLen)
594 {
595     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
596     VERIFY_NON_NULL_RET(tep, NET_SSL_TAG, "endpoint is NULL", 0);
597     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "data is NULL", 0);
598
599     SslRecBuf_t *recBuf = &((SslEndPoint_t *)tep)->recBuf;
600     size_t retLen = (recBuf->len > recBuf->loaded ? recBuf->len - recBuf->loaded : 0);
601     retLen = (retLen < dataLen ? retLen : dataLen);
602
603     if (retLen > INT_MAX)
604     {
605         return 0;
606     }
607
608     memcpy(data, recBuf->buff + recBuf->loaded, retLen);
609     recBuf->loaded += retLen;
610
611     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
612     return (int)retLen;
613 }
614
615 /**
616  * Parse chain of X.509 certificates.
617  *
618  * @param[out] crt     container for X.509 certificates
619  * @param[in]  data    buffer with X.509 certificates. Certificates may be in either in PEM
620                        or DER format in a jumble, delimiting symbols does not matter.
621  * @param[in]  bufLen  buffer length
622  * @param[in]  errNum  number certificates that failed to parse
623  *
624  * @return  number of successfully parsed certificates or -1 on error
625  */
626 static int ParseChain(mbedtls_x509_crt * crt, unsigned char * buf, int bufLen, int * errNum)
627 {
628     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
629     VERIFY_NON_NULL_RET(crt, NET_SSL_TAG, "Param crt is NULL" , -1);
630     VERIFY_NON_NULL_RET(buf, NET_SSL_TAG, "Param buf is NULL" , -1);
631
632     char pemCertHeader[] = {
633         0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x43, 0x45, 0x52,
634         0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d
635     };
636     char pemCertFooter[] = {
637         0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49,
638         0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d
639     };
640     size_t pemCertHeaderLen = sizeof(pemCertHeader);
641     size_t pemCertFooterLen = sizeof(pemCertFooter);
642
643     size_t len = 0;
644     unsigned char * tmp = NULL;
645     int count = 0;
646     int ret = 0;
647     int pos = 0;
648
649     *errNum = 0;
650     while (pos < bufLen)
651     {
652         if (buf[pos] == 0x30 && buf[pos + 1] == 0x82)
653         {
654             tmp = (unsigned char *)buf + pos + 1;
655             CHECK_MBEDTLS_RET(mbedtls_asn1_get_len, &tmp, buf + bufLen, &len);
656             if (pos + len < bufLen)
657             {
658                 ret = mbedtls_x509_crt_parse_der(crt, buf + pos, len + 4);
659                 if (0 == ret)
660                 {
661                     count++;
662                 }
663                 else
664                 {
665                     (*errNum)++;
666                     OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse_der returned -0x%04x\n", -(ret));
667                 }
668             }
669             pos += len + 4;
670         }
671         else if ((buf + pos + pemCertHeaderLen < buf + bufLen) &&
672                  (0 == memcmp(buf + pos, pemCertHeader, pemCertHeaderLen)))
673         {
674             void * endPos = NULL;
675             endPos = memmem(&(buf[pos]), bufLen - pos, pemCertFooter, pemCertFooterLen);
676             if (NULL == endPos)
677             {
678                 OIC_LOG(ERROR, NET_SSL_TAG, "Error: end of PEM certificate not found.");
679                 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
680                 return -1;
681             }
682             len = (char*)endPos - ((char*)buf + pos) + pemCertFooterLen;
683             if (pos + len + 1 <= bufLen)
684             {
685                 char con = buf[pos + len];
686                 buf[pos + len] = 0x00;
687                 ret = mbedtls_x509_crt_parse(crt, buf + pos, len + 1);
688                 if (0 == ret)
689                 {
690                     count++;
691                 }
692                 else
693                 {
694                     (*errNum)++;
695                     OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse returned -0x%04x\n", -(ret));
696                 }
697                 buf[pos + len] = con;
698             }
699             else
700             {
701                 unsigned char * lastCert = (unsigned char *)OICMalloc((len + 1) * sizeof(unsigned char));
702                 memcpy(lastCert, buf + pos, len);
703                 lastCert[len] = 0x00;
704                 ret = mbedtls_x509_crt_parse(crt, lastCert, len + 1);
705                 if (0 == ret)
706                 {
707                     count++;
708                 }
709                 else
710                 {
711                     (*errNum)++;
712                     OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse returned -0x%04x\n", -(ret));
713                 }
714                 OICFree(lastCert);
715             }
716             pos += len;
717         }
718         else
719         {
720             pos++;
721         }
722     }
723     OIC_LOG_V(DEBUG, NET_SSL_TAG, "%s successfully parsed %d certificates", __func__, count);
724     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
725     return count;
726
727 exit:
728     return -1;
729 }
730
731 //Loads PKIX related information from SRM
732 static int InitPKIX(CATransportAdapter_t adapter)
733 {
734     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
735     VERIFY_NON_NULL_RET(g_getPkixInfoCallback, NET_SSL_TAG, "PKIX info callback is NULL", -1);
736     // load pk key, cert, trust chain and crl
737     if (g_getPkixInfoCallback)
738     {
739         g_getPkixInfoCallback(&g_pkiInfo);
740     }
741
742     VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", -1);
743
744     mbedtls_x509_crt_free(&g_caSslContext->ca);
745     mbedtls_x509_crt_free(&g_caSslContext->crt);
746     mbedtls_pk_free(&g_caSslContext->pkey);
747     mbedtls_x509_crl_free(&g_caSslContext->crl);
748
749     mbedtls_x509_crt_init(&g_caSslContext->ca);
750     mbedtls_x509_crt_init(&g_caSslContext->crt);
751     mbedtls_pk_init(&g_caSslContext->pkey);
752     mbedtls_x509_crl_init(&g_caSslContext->crl);
753
754     mbedtls_ssl_config * serverConf = (adapter == CA_ADAPTER_IP ||
755                                    adapter == CA_ADAPTER_GATT_BTLE ?
756                                    &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
757     mbedtls_ssl_config * clientConf = (adapter == CA_ADAPTER_IP ||
758                                    adapter == CA_ADAPTER_GATT_BTLE ?
759                                    &g_caSslContext->clientDtlsConf : &g_caSslContext->clientTlsConf);
760     // optional
761     int ret;
762     int errNum;
763     int count = ParseChain(&g_caSslContext->crt, g_pkiInfo.crt.data, g_pkiInfo.crt.len, &errNum);
764     if (0 >= count)
765     {
766         OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate chain parsing error");
767         goto required;
768     }
769     if (0 != errNum)
770     {
771         OIC_LOG_V(WARNING, NET_SSL_TAG, "Own certificate chain parsing error: %d certs failed to parse", errNum);
772         goto required;
773     }
774     ret =  mbedtls_pk_parse_key(&g_caSslContext->pkey, g_pkiInfo.key.data, g_pkiInfo.key.len,
775                                                                                NULL, 0);
776     if (0 != ret)
777     {
778         OIC_LOG(WARNING, NET_SSL_TAG, "Key parsing error");
779         goto required;
780     }
781
782     ret = mbedtls_ssl_conf_own_cert(serverConf, &g_caSslContext->crt, &g_caSslContext->pkey);
783     if (0 != ret)
784     {
785         OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate parsing error");
786         goto required;
787     }
788     ret = mbedtls_ssl_conf_own_cert(clientConf, &g_caSslContext->crt, &g_caSslContext->pkey);
789     if(0 != ret)
790     {
791         OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate configuration error");
792         goto required;
793     }
794
795     required:
796     count = ParseChain(&g_caSslContext->ca, g_pkiInfo.ca.data, g_pkiInfo.ca.len, &errNum);
797     if(0 >= count)
798     {
799         OIC_LOG(ERROR, NET_SSL_TAG, "CA chain parsing error");
800         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
801         return -1;
802     }
803     if(0 != errNum)
804     {
805         OIC_LOG_V(WARNING, NET_SSL_TAG, "CA chain parsing warning: %d certs failed to parse", errNum);
806     }
807
808     ret = mbedtls_x509_crl_parse_der(&g_caSslContext->crl, g_pkiInfo.crl.data, g_pkiInfo.crl.len);
809     if(0 != ret)
810     {
811         OIC_LOG(WARNING, NET_SSL_TAG, "CRL parsing error");
812         CONF_SSL(clientConf, serverConf, mbedtls_ssl_conf_ca_chain, &g_caSslContext->ca, NULL);
813     }
814     else
815     {
816         CONF_SSL(clientConf, serverConf, mbedtls_ssl_conf_ca_chain,
817                  &g_caSslContext->ca, &g_caSslContext->crl);
818     }
819
820     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
821     return 0;
822 }
823
824 /*
825  * PSK callback.
826  *
827  * @param[in]  notUsed     opaque context
828  * @param[in]  ssl    mbedTLS context
829  * @param[in]  desc    identity
830  * @param[in]  descLen    identity length
831  *
832  * @return  0 on success any other return value will result in a denied PSK identity
833  */
834 static int GetPskCredentialsCallback(void * notUsed, mbedtls_ssl_context * ssl,
835                                      const unsigned char * desc, size_t descLen)
836 {
837     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
838     VERIFY_NON_NULL_RET(g_getCredentialsCallback, NET_SSL_TAG, "Credential callback s NULL", -1);
839     VERIFY_NON_NULL_RET(ssl, NET_SSL_TAG, "ssl pointer is NULL", -1);
840     VERIFY_NON_NULL_RET(desc, NET_SSL_TAG, "desc pointer is NULL", -1);
841     if (descLen > CA_MAX_ENDPOINT_IDENTITY_LEN)
842     {
843         OIC_LOG(ERROR, NET_SSL_TAG, "desc too long!");
844         return -1;
845     }
846     (void) notUsed;
847     uint8_t keyBuf[PSK_LENGTH] = {0};
848
849     // Retrieve the credentials blob from security module
850     int ret = g_getCredentialsCallback(CA_DTLS_PSK_KEY, desc, descLen, keyBuf, PSK_LENGTH);
851     if (ret > 0)
852     {
853         memcpy(((SslEndPoint_t *) ssl)->sep.identity.id, desc, descLen);
854         ((SslEndPoint_t *) ssl)->sep.identity.id_length = descLen;
855         OIC_LOG(DEBUG, NET_SSL_TAG, "PSK:");
856         OIC_LOG_BUFFER(DEBUG, NET_SSL_TAG, keyBuf, ret);
857
858         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
859         return(mbedtls_ssl_set_hs_psk(ssl, keyBuf, ret));
860     }
861     OIC_LOG_V(WARNING, NET_SSL_TAG, "Out %s", __func__);
862     return -1;
863 }
864 /**
865  * Gets session corresponding for endpoint.
866  *
867  * @param[in]  peer    remote address
868  *
869  * @return  TLS session or NULL
870  */
871 static SslEndPoint_t *GetSslPeer(const CAEndpoint_t *peer)
872 {
873     uint32_t listIndex = 0;
874     uint32_t listLength = 0;
875     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
876     VERIFY_NON_NULL_RET(peer, NET_SSL_TAG, "TLS peer is NULL", NULL);
877     VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", NULL);
878
879     SslEndPoint_t *tep = NULL;
880     listLength = u_arraylist_length(g_caSslContext->peerList);
881     for (listIndex = 0; listIndex < listLength; listIndex++)
882     {
883         tep = (SslEndPoint_t *) u_arraylist_get(g_caSslContext->peerList, listIndex);
884         if (NULL == tep)
885         {
886             continue;
887         }
888
889         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Compare [%s:%d] and [%s:%d] for %d adapter",
890                   peer->addr, peer->port, tep->sep.endpoint.addr, tep->sep.endpoint.port,
891                   peer->adapter);
892
893         if((peer->adapter == tep->sep.endpoint.adapter)
894                 && (0 == strncmp(peer->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA))
895                 && (peer->port == tep->sep.endpoint.port || CA_ADAPTER_GATT_BTLE == peer->adapter))
896         {
897             OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
898             return tep;
899         }
900     }
901     OIC_LOG(DEBUG, NET_SSL_TAG, "Return NULL");
902     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
903     return NULL;
904 }
905
906 #ifdef MULTIPLE_OWNER
907 /**
908  * Gets CA secure endpoint info corresponding for endpoint.
909  *
910  * @param[in]  peer    remote address
911  *
912  * @return  CASecureEndpoint or NULL
913  */
914 const CASecureEndpoint_t *GetCASecureEndpointData(const CAEndpoint_t* peer)
915 {
916     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
917
918     oc_mutex_lock(g_sslContextMutex);
919     if (NULL == g_caSslContext)
920     {
921         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
922         oc_mutex_unlock(g_sslContextMutex);
923         return NULL;
924     }
925
926     SslEndPoint_t* sslPeer = GetSslPeer(peer);
927     if(sslPeer)
928     {
929         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
930         oc_mutex_unlock(g_sslContextMutex);
931         return &sslPeer->sep;
932     }
933
934     OIC_LOG(DEBUG, NET_SSL_TAG, "Return NULL");
935     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
936     oc_mutex_unlock(g_sslContextMutex);
937     return NULL;
938 }
939 #endif
940
941 /**
942  * Deletes cached message.
943  *
944  * @param[in]  msg    message
945  */
946 static void DeleteCacheMessage(SslCacheMessage_t * msg)
947 {
948     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
949     VERIFY_NON_NULL_VOID(msg, NET_SSL_TAG, "msg");
950
951     OICFree(msg->data);
952     OICFree(msg);
953
954     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
955 }
956 /**
957  * Deletes cached message list.
958  *
959  * @param[in] cacheList  list of cached messages
960  */
961 static void DeleteCacheList(u_arraylist_t * cacheList)
962 {
963     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
964     VERIFY_NON_NULL_VOID(cacheList, NET_SSL_TAG, "cacheList");
965     uint32_t listIndex = 0;
966     uint32_t listLength = 0;
967
968     listLength = u_arraylist_length(cacheList);
969     for (listIndex = 0; listIndex < listLength; listIndex++)
970     {
971         SslCacheMessage_t * msg = (SslCacheMessage_t *) u_arraylist_get(cacheList, listIndex);
972         if (NULL != msg)
973         {
974             DeleteCacheMessage(msg);
975         }
976     }
977     u_arraylist_free(&cacheList);
978
979     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
980 }
981 /**
982  * Deletes endpoint with session.
983  *
984  * @param[in]  tep    endpoint with session info
985  */
986 static void DeleteSslEndPoint(SslEndPoint_t * tep)
987 {
988     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
989     VERIFY_NON_NULL_VOID(tep, NET_SSL_TAG, "tep");
990
991     mbedtls_ssl_free(&tep->ssl);
992 #ifdef __WITH_DTLS__
993     mbedtls_ssl_cookie_free(&tep->cookieCtx);
994 #endif
995     DeleteCacheList(tep->cacheList);
996     OICFree(tep);
997     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
998 }
999 /**
1000  * Removes endpoint session from list.
1001  *
1002  * @param[in]  endpoint    remote address
1003  */
1004 static void RemovePeerFromList(CAEndpoint_t * endpoint)
1005 {
1006     VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL");
1007     VERIFY_NON_NULL_VOID(endpoint, NET_SSL_TAG, "endpoint");
1008     uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
1009     for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
1010     {
1011         SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList,listIndex);
1012         if (NULL == tep)
1013         {
1014             continue;
1015         }
1016         if(0 == strncmp(endpoint->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA)
1017                 && (endpoint->port == tep->sep.endpoint.port))
1018         {
1019             u_arraylist_remove(g_caSslContext->peerList, listIndex);
1020             DeleteSslEndPoint(tep);
1021             return;
1022         }
1023     }
1024 }
1025 /**
1026  * Deletes session list.
1027  */
1028 static void DeletePeerList()
1029 {
1030     VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL");
1031
1032     uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
1033     for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
1034     {
1035         SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList,listIndex);
1036         if (NULL == tep)
1037         {
1038             continue;
1039         }
1040         if (MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
1041         {
1042             int ret = 0;
1043             do
1044             {
1045                 ret = mbedtls_ssl_close_notify(&tep->ssl);
1046             }
1047             while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);
1048         }
1049         DeleteSslEndPoint(tep);
1050     }
1051     u_arraylist_free(&g_caSslContext->peerList);
1052 }
1053
1054 CAResult_t CAcloseSslConnection(const CAEndpoint_t *endpoint)
1055 {
1056     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1057     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
1058
1059     oc_mutex_lock(g_sslContextMutex);
1060     if (NULL == g_caSslContext)
1061     {
1062         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1063         oc_mutex_unlock(g_sslContextMutex);
1064         return CA_STATUS_FAILED;
1065     }
1066     SslEndPoint_t * tep = GetSslPeer(endpoint);
1067     if (NULL == tep)
1068     {
1069         OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
1070         oc_mutex_unlock(g_sslContextMutex);
1071         return CA_STATUS_FAILED;
1072     }
1073     /* No error checking, the connection might be closed already */
1074     int ret = 0;
1075     do
1076     {
1077         ret = mbedtls_ssl_close_notify(&tep->ssl);
1078     }
1079     while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);
1080
1081     RemovePeerFromList(&tep->sep.endpoint);
1082     oc_mutex_unlock(g_sslContextMutex);
1083
1084     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1085     return CA_STATUS_OK;
1086 }
1087
1088 void CAcloseSslConnectionAll(CATransportAdapter_t transportType)
1089 {
1090     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1091     oc_mutex_lock(g_sslContextMutex);
1092     if (NULL == g_caSslContext)
1093     {
1094         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1095         oc_mutex_unlock(g_sslContextMutex);
1096         return;
1097     }
1098
1099     uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
1100     OIC_LOG_V(DEBUG, NET_SSL_TAG,
1101             "Required transport [%d], peer count [%u]", transportType, listLength);
1102     for (uint32_t i = listLength; i > 0; i--)
1103     {
1104         SslEndPoint_t *tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList, i - 1);
1105         if (NULL == tep)
1106         {
1107             continue;
1108         }
1109         OIC_LOG_V(DEBUG, NET_SSL_TAG, "SSL Connection [%s:%d], Transport [%d]",
1110                   tep->sep.endpoint.addr, tep->sep.endpoint.port, tep->sep.endpoint.adapter);
1111
1112         // check transport matching
1113         if (0 == (tep->sep.endpoint.adapter & transportType))
1114         {
1115             OIC_LOG(DEBUG, NET_SSL_TAG, "Skip the un-matched transport session");
1116             continue;
1117         }
1118
1119         // TODO: need to check below code after socket close is ensured.
1120         /*int ret = 0;
1121         do
1122         {
1123             ret = mbedtls_ssl_close_notify(&tep->ssl);
1124         }
1125         while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);*/
1126
1127         // delete from list
1128         u_arraylist_remove(g_caSslContext->peerList, i - 1);
1129         DeleteSslEndPoint(tep);
1130     }
1131     oc_mutex_unlock(g_sslContextMutex);
1132
1133     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1134     return;
1135 }
1136 /**
1137  * Creates session for endpoint.
1138  *
1139  * @param[in]  endpoint    remote address
1140  * @param[in]  config    mbedTLS configuration info
1141  *
1142  * @return  TLS endpoint or NULL
1143  */
1144 static SslEndPoint_t * NewSslEndPoint(const CAEndpoint_t * endpoint, mbedtls_ssl_config * config)
1145 {
1146     SslEndPoint_t * tep = NULL;
1147     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1148     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "endpoint", NULL);
1149     VERIFY_NON_NULL_RET(config, NET_SSL_TAG, "config", NULL);
1150     VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", NULL);
1151
1152     tep = (SslEndPoint_t *) OICCalloc(1, sizeof (SslEndPoint_t));
1153     if (NULL == tep)
1154     {
1155         OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
1156         return NULL;
1157     }
1158
1159     tep->sep.endpoint = *endpoint;
1160     tep->sep.endpoint.flags = (CATransportFlags_t)(tep->sep.endpoint.flags | CA_SECURE);
1161
1162     if(0 != mbedtls_ssl_setup(&tep->ssl, config))
1163     {
1164         OIC_LOG(ERROR, NET_SSL_TAG, "Setup failed");
1165         OICFree(tep);
1166         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1167         return NULL;
1168     }
1169
1170     mbedtls_ssl_set_bio(&tep->ssl, tep, SendCallBack, RecvCallBack, NULL);
1171     if (MBEDTLS_SSL_TRANSPORT_DATAGRAM == config->transport)
1172     {
1173         mbedtls_ssl_set_timer_cb(&tep->ssl, &tep->timer,
1174                                   mbedtls_timing_set_delay, mbedtls_timing_get_delay);
1175         if (MBEDTLS_SSL_IS_SERVER == config->endpoint)
1176         {
1177             if (0 != mbedtls_ssl_cookie_setup(&tep->cookieCtx, mbedtls_ctr_drbg_random,
1178                                               &g_caSslContext->rnd))
1179             {
1180                 OIC_LOG(ERROR, NET_SSL_TAG, "Cookie setup failed!");
1181                 OICFree(tep);
1182                 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1183                 return NULL;
1184             }
1185             mbedtls_ssl_conf_dtls_cookies(config, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check,
1186                                           &tep->cookieCtx);
1187             if (0 != mbedtls_ssl_set_client_transport_id(&tep->ssl,
1188                                     (const unsigned char *) endpoint->addr, sizeof(endpoint->addr)))
1189             {
1190                 OIC_LOG(ERROR, NET_SSL_TAG, "Transport id setup failed!");
1191                 OICFree(tep);
1192                 OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1193                 return NULL;
1194             }
1195         }
1196     }
1197     tep->cacheList = u_arraylist_create();
1198     if (NULL == tep->cacheList)
1199     {
1200         OIC_LOG(ERROR, NET_SSL_TAG, "cacheList initialization failed!");
1201         mbedtls_ssl_free(&tep->ssl);
1202         OICFree(tep);
1203         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1204         return NULL;
1205     }
1206     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1207     return tep;
1208 }
1209 /**
1210  * Initializes PSK identity.
1211  *
1212  * @param[out]  config    client/server config to be updated
1213  *
1214  * @return  0 on success or -1 on error
1215  */
1216 static int InitPskIdentity(mbedtls_ssl_config * config)
1217 {
1218     uint8_t idBuf[UUID_LENGTH] = {0};
1219     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1220     VERIFY_NON_NULL_RET(config, NET_SSL_TAG, "Param config is NULL" , -1);
1221
1222     if (0 > g_getCredentialsCallback(CA_DTLS_PSK_IDENTITY, NULL, 0, idBuf, UUID_LENGTH))
1223     {
1224         OIC_LOG(ERROR, NET_SSL_TAG, "Identity not found");
1225         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1226         return -1;
1227     }
1228     if (0 != mbedtls_ssl_conf_psk(config, idBuf, 0, idBuf, UUID_LENGTH))
1229     {
1230         OIC_LOG(ERROR, NET_SSL_TAG, "Identity initialization failed!");
1231         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1232         return -1;
1233     }
1234     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1235     return 0;
1236 }
1237 static void SetupCipher(mbedtls_ssl_config * config, CATransportAdapter_t adapter)
1238 {
1239     int index = 0;
1240     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1241     VERIFY_NON_NULL_VOID(config, NET_SSL_TAG, "Invaild param");
1242     VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL");
1243     VERIFY_NON_NULL_VOID(g_getCredentialTypesCallback, NET_SSL_TAG, "Param callback is null");
1244
1245     g_getCredentialTypesCallback(g_caSslContext->cipherFlag);
1246     // Retrieve the PSK credential from SRM
1247     if (0 != InitPskIdentity(config))
1248     {
1249         OIC_LOG(ERROR, NET_SSL_TAG, "PSK identity initialization failed!");
1250     }
1251
1252     // Retrieve the Cert credential from SRM
1253     if (true == g_caSslContext->cipherFlag[1])
1254     {
1255         int ret = InitPKIX(adapter);
1256         if (0 != ret)
1257         {
1258             OIC_LOG(ERROR, NET_SSL_TAG, "Failed to init X.509");
1259         }
1260     }
1261
1262     memset(g_cipherSuitesList, 0, sizeof(g_cipherSuitesList));
1263     if (SSL_CIPHER_MAX != g_caSslContext->cipher)
1264     {
1265         g_cipherSuitesList[index] = tlsCipher[g_caSslContext->cipher][0];
1266     }
1267     else
1268     {
1269     if (true == g_caSslContext->cipherFlag[1])
1270     {
1271         for (int i = 2; i < SSL_CIPHER_MAX - 2; i++)
1272             {
1273                 g_cipherSuitesList[index] = tlsCipher[i][0];
1274                 index ++;
1275             }
1276         }
1277         if (true == g_caSslContext->cipherFlag[0])
1278         {
1279            g_cipherSuitesList[index] = MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
1280         }
1281     }
1282
1283     mbedtls_ssl_conf_ciphersuites(config, g_cipherSuitesList);
1284
1285     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1286 }
1287 /**
1288  * Initiate TLS handshake with endpoint.
1289  *
1290  * @param[in]  endpoint    remote address
1291  *
1292  * @return  TLS endpoint or NULL
1293  */
1294 static SslEndPoint_t * InitiateTlsHandshake(const CAEndpoint_t *endpoint)
1295 {
1296     int ret = 0;
1297     SslEndPoint_t * tep = NULL;
1298
1299     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1300     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , NULL);
1301     VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", NULL);
1302
1303     mbedtls_ssl_config * config = (endpoint->adapter == CA_ADAPTER_IP ||
1304                                    endpoint->adapter == CA_ADAPTER_GATT_BTLE ?
1305                                    &g_caSslContext->clientDtlsConf : &g_caSslContext->clientTlsConf);
1306     tep = NewSslEndPoint(endpoint, config);
1307     if (NULL == tep)
1308     {
1309         OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
1310         return NULL;
1311     }
1312
1313     //Load allowed SVR suites from SVR DB
1314     SetupCipher(config, endpoint->adapter);
1315
1316     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Add %s:%d", tep->sep.endpoint.addr, tep->sep.endpoint.port);
1317     ret = u_arraylist_add(g_caSslContext->peerList, (void *) tep);
1318     if (!ret)
1319     {
1320         OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
1321         DeleteSslEndPoint(tep);
1322         return NULL;
1323     }
1324
1325     while (MBEDTLS_SSL_HANDSHAKE_OVER > tep->ssl.state)
1326     {
1327         ret = mbedtls_ssl_handshake_step(&tep->ssl);
1328         if (MBEDTLS_ERR_SSL_CONN_EOF == ret)
1329         {
1330             break;
1331         }
1332         else if (-1 == ret)
1333         {
1334             OIC_LOG(ERROR, NET_SSL_TAG, "Handshake failed due to socket error");
1335             RemovePeerFromList(&tep->sep.endpoint);
1336             return NULL;
1337         }
1338         SSL_CHECK_FAIL(tep, ret, "Handshake error", 0, NULL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1339     }
1340     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1341     return tep;
1342 }
1343 #ifdef __WITH_DTLS__
1344 /**
1345  * Stops DTLS retransmission.
1346  */
1347 static void StopRetransmit()
1348 {
1349     if (g_caSslContext)
1350     {
1351         unregisterTimer(g_caSslContext->timerId);
1352         g_caSslContext->timerId= -1;
1353     }
1354 }
1355 #endif
1356 void CAdeinitSslAdapter()
1357 {
1358     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1359
1360     VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "context is NULL");
1361     VERIFY_NON_NULL_VOID(g_sslContextMutex, NET_SSL_TAG, "context mutex is NULL");
1362
1363     //Lock tlsContext mutex
1364     oc_mutex_lock(g_sslContextMutex);
1365
1366     // Clear all lists
1367     DeletePeerList();
1368
1369     // De-initialize mbedTLS
1370     mbedtls_x509_crt_free(&g_caSslContext->crt);
1371     mbedtls_pk_free(&g_caSslContext->pkey);
1372 #ifdef __WITH_TLS__
1373     mbedtls_ssl_config_free(&g_caSslContext->clientTlsConf);
1374     mbedtls_ssl_config_free(&g_caSslContext->serverTlsConf);
1375 #endif // __WITH_TLS__
1376 #ifdef __WITH_DTLS__
1377     mbedtls_ssl_config_free(&g_caSslContext->clientDtlsConf);
1378     mbedtls_ssl_config_free(&g_caSslContext->serverDtlsConf);
1379 #endif // __WITH_DTLS__
1380     mbedtls_ctr_drbg_free(&g_caSslContext->rnd);
1381     mbedtls_entropy_free(&g_caSslContext->entropy);
1382 #ifdef __WITH_DTLS__
1383     StopRetransmit();
1384 #endif
1385     // De-initialize tls Context
1386     OICFree(g_caSslContext);
1387     g_caSslContext = NULL;
1388
1389     // Unlock tlsContext mutex and de-initialize it
1390     oc_mutex_unlock(g_sslContextMutex);
1391     oc_mutex_free(g_sslContextMutex);
1392     g_sslContextMutex = NULL;
1393
1394     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s ", __func__);
1395 }
1396
1397 static int InitConfig(mbedtls_ssl_config * conf, int transport, int mode)
1398 {
1399     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1400     VERIFY_NON_NULL_RET(conf, NET_SSL_TAG, "Param conf is NULL" , -1);
1401     VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", -1);
1402     mbedtls_ssl_config_init(conf);
1403     if (mbedtls_ssl_config_defaults(conf, mode, transport, MBEDTLS_SSL_PRESET_DEFAULT) != 0)
1404     {
1405         OIC_LOG(ERROR, NET_SSL_TAG, "Config initialization failed!");
1406         return -1;
1407     }
1408
1409     /*
1410      * Configure mbedTLS runtime options. Many options are configured at build
1411      * time, see extlibs/mbedtls/config-iotivity.h
1412      */
1413     mbedtls_ssl_conf_psk_cb(conf, GetPskCredentialsCallback, NULL);
1414     mbedtls_ssl_conf_rng(conf, mbedtls_ctr_drbg_random, &g_caSslContext->rnd);
1415     mbedtls_ssl_conf_curves(conf, curve[ADAPTER_CURVE_SECP256R1]);
1416     mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
1417
1418     /* Set TLS 1.2 as the minimum allowed version. */
1419     mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
1420
1421 #if !defined(NDEBUG) || defined(TB_LOG)
1422     mbedtls_ssl_conf_dbg(conf, DebugSsl, NULL);
1423 #if defined(MBEDTLS_DEBUG_C)
1424     mbedtls_debug_set_threshold(MBED_TLS_DEBUG_LEVEL);
1425 #endif
1426 #endif
1427     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1428     return 0;
1429 }
1430 #ifdef __WITH_DTLS__
1431 /**
1432  * Starts DTLS retransmission.
1433  */
1434 static int StartRetransmit()
1435 {
1436     uint32_t listIndex = 0;
1437     uint32_t listLength = 0;
1438     SslEndPoint_t *tep = NULL;
1439
1440     oc_mutex_lock(g_sslContextMutex);
1441     if (NULL == g_caSslContext)
1442     {
1443         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL. Stop retransmission");
1444         oc_mutex_unlock(g_sslContextMutex);
1445         return -1;
1446     }
1447
1448     if (g_caSslContext->timerId != -1)
1449     {
1450         //clear previous timer
1451         unregisterTimer(g_caSslContext->timerId);
1452
1453         listLength = u_arraylist_length(g_caSslContext->peerList);
1454         for (listIndex = 0; listIndex < listLength; listIndex++)
1455         {
1456             tep = (SslEndPoint_t *) u_arraylist_get(g_caSslContext->peerList, listIndex);
1457             if (NULL == tep
1458                 || (tep->ssl.conf && MBEDTLS_SSL_TRANSPORT_STREAM == tep->ssl.conf->transport)
1459                 || MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
1460             {
1461                 continue;
1462             }
1463             int ret = mbedtls_ssl_handshake_step(&tep->ssl);
1464
1465             if (MBEDTLS_ERR_SSL_CONN_EOF != ret)
1466             {
1467                 //start new timer
1468                 registerTimer(RETRANSMISSION_TIME, &g_caSslContext->timerId, (void *) StartRetransmit);
1469                 //unlock & return
1470                 SSL_CHECK_FAIL(tep, ret, "Retransmission", 1, CA_STATUS_FAILED,
1471                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1472             }
1473         }
1474     }
1475     //start new timer
1476     registerTimer(RETRANSMISSION_TIME, &g_caSslContext->timerId, (void *) StartRetransmit);
1477     oc_mutex_unlock(g_sslContextMutex);
1478     return 0;
1479 }
1480 #endif
1481
1482 CAResult_t CAinitSslAdapter()
1483 {
1484     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1485     // Initialize mutex for tlsContext
1486     if (NULL == g_sslContextMutex)
1487     {
1488         g_sslContextMutex = oc_mutex_new();
1489         VERIFY_NON_NULL_RET(g_sslContextMutex, NET_SSL_TAG, "malloc failed", CA_MEMORY_ALLOC_FAILED);
1490     }
1491     else
1492     {
1493         OIC_LOG(INFO, NET_SSL_TAG, "Done already!");
1494         return CA_STATUS_OK;
1495     }
1496
1497     // Lock tlsContext mutex and create tlsContext
1498     oc_mutex_lock(g_sslContextMutex);
1499     g_caSslContext = (SslContext_t *)OICCalloc(1, sizeof(SslContext_t));
1500
1501     if (NULL == g_caSslContext)
1502     {
1503         OIC_LOG(ERROR, NET_SSL_TAG, "Context malloc failed");
1504         oc_mutex_unlock(g_sslContextMutex);
1505         oc_mutex_free(g_sslContextMutex);
1506         g_sslContextMutex = NULL;
1507         return CA_MEMORY_ALLOC_FAILED;
1508     }
1509
1510     // Create peer list
1511     g_caSslContext->peerList = u_arraylist_create();
1512
1513     if(NULL == g_caSslContext->peerList)
1514     {
1515         OIC_LOG(ERROR, NET_SSL_TAG, "peerList initialization failed!");
1516         OICFree(g_caSslContext);
1517         g_caSslContext = NULL;
1518         oc_mutex_unlock(g_sslContextMutex);
1519         oc_mutex_free(g_sslContextMutex);
1520         g_sslContextMutex = NULL;
1521         return CA_STATUS_FAILED;
1522     }
1523
1524     /* Initialize TLS library
1525      */
1526 #if !defined(NDEBUG) || defined(TB_LOG)
1527 #ifdef MBEDTLS_VERSION_C
1528     char version[MBED_TLS_VERSION_LEN];
1529     mbedtls_version_get_string(version);
1530     OIC_LOG_V(INFO, NET_SSL_TAG, "mbed TLS version: %s", version);
1531 #else
1532     OIC_LOG_V(INFO, NET_SSL_TAG, "mbed TLS version: %s", MBEDTLS_VERSION_STRING);
1533 #endif
1534 #endif
1535
1536     /* Entropy settings
1537      */
1538     mbedtls_entropy_init(&g_caSslContext->entropy);
1539     mbedtls_ctr_drbg_init(&g_caSslContext->rnd);
1540
1541     if(0 != mbedtls_ctr_drbg_seed(&g_caSslContext->rnd, mbedtls_entropy_func,
1542                                   &g_caSslContext->entropy,
1543                                   (const unsigned char*) PERSONALIZATION_STRING, sizeof(PERSONALIZATION_STRING)))
1544     {
1545         OIC_LOG(ERROR, NET_SSL_TAG, "Seed initialization failed!");
1546         oc_mutex_unlock(g_sslContextMutex);
1547         CAdeinitSslAdapter();
1548         return CA_STATUS_FAILED;
1549     }
1550     mbedtls_ctr_drbg_set_prediction_resistance(&g_caSslContext->rnd, MBEDTLS_CTR_DRBG_PR_ON);
1551
1552 #ifdef __WITH_TLS__
1553     if (0 != InitConfig(&g_caSslContext->clientTlsConf,
1554                         MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_CLIENT))
1555     {
1556         OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
1557         oc_mutex_unlock(g_sslContextMutex);
1558         CAdeinitSslAdapter();
1559         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1560         return CA_STATUS_FAILED;
1561     }
1562
1563     if (0 != InitConfig(&g_caSslContext->serverTlsConf,
1564                         MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_SERVER))
1565     {
1566         OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
1567         oc_mutex_unlock(g_sslContextMutex);
1568         CAdeinitSslAdapter();
1569         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1570         return CA_STATUS_FAILED;
1571     }
1572 #endif // __WITH_TLS__
1573 #ifdef __WITH_DTLS__
1574     if (0 != InitConfig(&g_caSslContext->clientDtlsConf,
1575                         MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_CLIENT))
1576     {
1577         OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
1578         oc_mutex_unlock(g_sslContextMutex);
1579         CAdeinitSslAdapter();
1580         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1581         return CA_STATUS_FAILED;
1582     }
1583
1584     if (0 != InitConfig(&g_caSslContext->serverDtlsConf,
1585                         MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_SERVER))
1586     {
1587         OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
1588         oc_mutex_unlock(g_sslContextMutex);
1589         CAdeinitSslAdapter();
1590         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1591         return CA_STATUS_FAILED;
1592     }
1593 #endif // __WITH_DTLS__
1594
1595     // set default cipher
1596     g_caSslContext->cipher = SSL_CIPHER_MAX;
1597
1598     // init X.509
1599     mbedtls_x509_crt_init(&g_caSslContext->ca);
1600     mbedtls_x509_crt_init(&g_caSslContext->crt);
1601     mbedtls_pk_init(&g_caSslContext->pkey);
1602     mbedtls_x509_crl_init(&g_caSslContext->crl);
1603
1604 #ifdef __WITH_DTLS__
1605     g_caSslContext->timerId = -1;
1606 #endif
1607
1608    oc_mutex_unlock(g_sslContextMutex);
1609 #ifdef __WITH_DTLS__
1610     StartRetransmit();
1611 #endif
1612
1613     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1614     return CA_STATUS_OK;
1615 }
1616
1617 SslCacheMessage_t *  NewCacheMessage(uint8_t * data, size_t dataLen)
1618 {
1619     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1620     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , NULL);
1621     if (0 == dataLen)
1622     {
1623         OIC_LOG(ERROR, NET_SSL_TAG, "dataLen is equal to zero");
1624         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1625         return NULL;
1626     }
1627     SslCacheMessage_t * message = (SslCacheMessage_t *) OICCalloc(1, sizeof(SslCacheMessage_t));
1628     if (NULL == message)
1629     {
1630         OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
1631         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1632         return NULL;
1633     }
1634
1635     message->data = (uint8_t *)OICCalloc(dataLen, sizeof(uint8_t));
1636     if (NULL == message->data)
1637     {
1638         OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
1639         OICFree(message);
1640         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1641         return NULL;
1642     }
1643     memcpy(message->data, data, dataLen);
1644     message->len = dataLen;
1645     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1646     return message;
1647 }
1648
1649 /* Send data via TLS connection.
1650  */
1651 CAResult_t CAencryptSsl(const CAEndpoint_t *endpoint,
1652                         void *data, uint32_t dataLen)
1653 {
1654     int ret = 0;
1655
1656     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s ", __func__);
1657
1658     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG,"Remote address is NULL", CA_STATUS_INVALID_PARAM);
1659     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Data is NULL", CA_STATUS_INVALID_PARAM);
1660     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Port %d", endpoint->port);
1661
1662     if (0 == dataLen)
1663     {
1664         OIC_LOG_V(ERROR, NET_SSL_TAG, "dataLen is zero [%d]", dataLen);
1665         return CA_STATUS_FAILED;
1666     }
1667
1668     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data to be encrypted dataLen [%d]", dataLen);
1669
1670     oc_mutex_lock(g_sslContextMutex);
1671     if(NULL == g_caSslContext)
1672     {
1673         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1674         oc_mutex_unlock(g_sslContextMutex);
1675         return CA_STATUS_FAILED;
1676     }
1677
1678     SslEndPoint_t * tep = GetSslPeer(endpoint);
1679     if (NULL == tep)
1680     {
1681         tep = InitiateTlsHandshake(endpoint);
1682     }
1683     if (NULL == tep)
1684     {
1685         OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
1686         oc_mutex_unlock(g_sslContextMutex);
1687         return CA_STATUS_FAILED;
1688     }
1689
1690     if (MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
1691     {
1692         unsigned char *dataBuf = (unsigned char *)data;
1693         size_t written = 0;
1694
1695         do
1696         {
1697             ret = mbedtls_ssl_write(&tep->ssl, dataBuf, dataLen - written);
1698             if (ret < 0)
1699             {
1700                 if (MBEDTLS_ERR_SSL_WANT_WRITE != ret)
1701                 {
1702                     OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedTLS write failed! returned 0x%x", -ret);
1703                     RemovePeerFromList(&tep->sep.endpoint);
1704                     oc_mutex_unlock(g_sslContextMutex);
1705                     return CA_STATUS_FAILED;
1706                 }
1707                 continue;
1708             }
1709             OIC_LOG_V(DEBUG, NET_SSL_TAG, "mbedTLS write returned with sent bytes[%d]", ret);
1710
1711             dataBuf += ret;
1712             written += ret;
1713         } while (dataLen > written);
1714
1715     }
1716     else
1717     {
1718         SslCacheMessage_t * msg = NewCacheMessage((uint8_t*) data, dataLen);
1719         if (NULL == msg || !u_arraylist_add(tep->cacheList, (void *) msg))
1720         {
1721             OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
1722             oc_mutex_unlock(g_sslContextMutex);
1723             return CA_STATUS_FAILED;
1724         }
1725     }
1726
1727     oc_mutex_unlock(g_sslContextMutex);
1728
1729     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1730     return CA_STATUS_OK;
1731 }
1732 /**
1733  * Sends cached messages via TLS connection.
1734  *
1735  * @param[in]  tep    remote address with session info
1736  */
1737 static void SendCacheMessages(SslEndPoint_t * tep)
1738 {
1739     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1740     VERIFY_NON_NULL_VOID(tep, NET_SSL_TAG, "Param tep is NULL");
1741
1742     uint32_t listIndex = 0;
1743     uint32_t listLength = 0;
1744     listLength = u_arraylist_length(tep->cacheList);
1745     for (listIndex = 0; listIndex < listLength;)
1746     {
1747         int ret = 0;
1748         SslCacheMessage_t * msg = (SslCacheMessage_t *) u_arraylist_get(tep->cacheList, listIndex);
1749         if (NULL != msg && NULL != msg->data && 0 != msg->len)
1750         {
1751             unsigned char *dataBuf = (unsigned char *)msg->data;
1752             size_t written = 0;
1753
1754             do
1755             {
1756                 ret = mbedtls_ssl_write(&tep->ssl, dataBuf, msg->len - written);
1757                 if (ret < 0)
1758                 {
1759                     if (MBEDTLS_ERR_SSL_WANT_WRITE != ret)
1760                     {
1761                         OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedTLS write failed! returned -0x%x", -ret);
1762                         break;
1763                     }
1764                     continue;
1765                 }
1766                 OIC_LOG_V(DEBUG, NET_SSL_TAG, "mbedTLS write returned with sent bytes[%d]", ret);
1767
1768                 dataBuf += ret;
1769                 written += ret;
1770             } while (msg->len > written);
1771
1772             if (u_arraylist_remove(tep->cacheList, listIndex))
1773             {
1774                 DeleteCacheMessage(msg);
1775                 // Reduce list length by 1 as we removed one element.
1776                 listLength--;
1777             }
1778             else
1779             {
1780                 OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_remove failed.");
1781                 break;
1782             }
1783         }
1784         else
1785         {
1786             // Move to the next element
1787             ++listIndex;
1788         }
1789     }
1790     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1791 }
1792
1793 void CAsetSslHandshakeCallback(CAErrorCallback tlsHandshakeCallback)
1794 {
1795     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1796     g_sslCallback = tlsHandshakeCallback;
1797     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1798 }
1799
1800 /* Read data from TLS connection
1801  */
1802 CAResult_t CAdecryptSsl(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t dataLen)
1803 {
1804     int ret = 0;
1805     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1806     VERIFY_NON_NULL_RET(sep, NET_SSL_TAG, "endpoint is NULL" , CA_STATUS_INVALID_PARAM);
1807     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , CA_STATUS_INVALID_PARAM);
1808
1809     oc_mutex_lock(g_sslContextMutex);
1810     if (NULL == g_caSslContext)
1811     {
1812         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1813         oc_mutex_unlock(g_sslContextMutex);
1814         return CA_STATUS_FAILED;
1815     }
1816
1817
1818     SslEndPoint_t * peer = GetSslPeer(&sep->endpoint);
1819     if (NULL == peer)
1820     {
1821         mbedtls_ssl_config * config = (sep->endpoint.adapter == CA_ADAPTER_IP ||
1822                                    sep->endpoint.adapter == CA_ADAPTER_GATT_BTLE ?
1823                                    &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
1824         peer = NewSslEndPoint(&sep->endpoint, config);
1825         if (NULL == peer)
1826         {
1827             OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
1828             oc_mutex_unlock(g_sslContextMutex);
1829             return CA_STATUS_FAILED;
1830         }
1831         //Load allowed TLS suites from SVR DB
1832         SetupCipher(config, sep->endpoint.adapter);
1833
1834         ret = u_arraylist_add(g_caSslContext->peerList, (void *) peer);
1835         if (!ret)
1836         {
1837             OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
1838             OICFree(peer);
1839             oc_mutex_unlock(g_sslContextMutex);
1840             return CA_STATUS_FAILED;
1841         }
1842     }
1843
1844     peer->recBuf.buff = data;
1845     peer->recBuf.len = dataLen;
1846     peer->recBuf.loaded = 0;
1847
1848     while (MBEDTLS_SSL_HANDSHAKE_OVER != peer->ssl.state)
1849     {
1850         ret = mbedtls_ssl_handshake_step(&peer->ssl);
1851         if (MBEDTLS_ERR_SSL_CONN_EOF == ret)
1852         {
1853             break;
1854         }
1855
1856         if (MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED == ret)
1857         {
1858             OIC_LOG(DEBUG, NET_SSL_TAG, "Hello verification requested");
1859             mbedtls_ssl_session_reset(&peer->ssl);
1860             mbedtls_ssl_set_client_transport_id(&peer->ssl,
1861                                                 (const unsigned char *) sep->endpoint.addr,
1862                                                  sizeof(sep->endpoint.addr));
1863             ret = mbedtls_ssl_handshake_step(&peer->ssl);
1864         }
1865         uint32_t flags = mbedtls_ssl_get_verify_result(&peer->ssl);
1866         if (0 != flags)
1867         {
1868             OIC_LOG_BUFFER(ERROR, NET_SSL_TAG, (const uint8_t *) &flags, sizeof(flags));
1869             SSL_CHECK_FAIL(peer, flags, "Cert verification failed", 1,
1870                                                      CA_STATUS_FAILED, GetAlertCode(flags));
1871         }
1872         SSL_CHECK_FAIL(peer, ret, "Handshake error", 1, CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1873         if (MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC == peer->ssl.state)
1874         {
1875             memcpy(peer->master, peer->ssl.session_negotiate->master, sizeof(peer->master));
1876             g_caSslContext->selectedCipher = peer->ssl.session_negotiate->ciphersuite;
1877         }
1878         if (MBEDTLS_SSL_CLIENT_KEY_EXCHANGE == peer->ssl.state)
1879         {
1880             memcpy(peer->random, peer->ssl.handshake->randbytes, sizeof(peer->random));
1881         }
1882
1883         if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
1884         {
1885             SSL_RES(peer, CA_STATUS_OK);
1886             if (MBEDTLS_SSL_IS_CLIENT == peer->ssl.conf->endpoint)
1887             {
1888                 SendCacheMessages(peer);
1889             }
1890
1891             int selectedCipher = peer->ssl.session->ciphersuite;
1892             OIC_LOG_V(DEBUG, NET_SSL_TAG, "(D)TLS Session is connected via ciphersuite [0x%x]", selectedCipher);
1893             if (MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 != selectedCipher &&
1894                 MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256 != selectedCipher)
1895             {
1896                 char uuid[UUID_LENGTH * 2 + 5] = {0};
1897                 void * uuidPos = NULL;
1898                 void * userIdPos = NULL;
1899                 const mbedtls_x509_crt * peerCert = mbedtls_ssl_get_peer_cert(&peer->ssl);
1900                 ret = (NULL == peerCert ? -1 : 0);
1901                 SSL_CHECK_FAIL(peer, ret, "Failed to retrieve cert", 1,
1902                                             CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_NO_CERT);
1903                 uuidPos = memmem(peerCert->subject_raw.p, peerCert->subject_raw.len,
1904                                                  UUID_PREFIX, sizeof(UUID_PREFIX) - 1);
1905
1906                 if (NULL != uuidPos)
1907                 {
1908                     memcpy(uuid, (char*) uuidPos + sizeof(UUID_PREFIX) - 1, UUID_LENGTH * 2 + 4);
1909                     OIC_LOG_V(DEBUG, NET_SSL_TAG, "certificate uuid string: %s" , uuid);
1910                     ret = (OCConvertStringToUuid(uuid, peer->sep.identity.id)) ? 0 : -1;
1911                     SSL_CHECK_FAIL(peer, ret, "Failed to convert subject", 1,
1912                                           CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
1913                 }
1914                 else
1915                 {
1916                     OIC_LOG(WARNING, NET_SSL_TAG, "uuid not found");
1917                 }
1918
1919                 userIdPos = memmem(peerCert->subject_raw.p, peerCert->subject_raw.len,
1920                                              USERID_PREFIX, sizeof(USERID_PREFIX) - 1);
1921                 if (NULL != userIdPos)
1922                 {
1923                     memcpy(uuid, (char*) userIdPos + sizeof(USERID_PREFIX) - 1, UUID_LENGTH * 2 + 4);
1924                     ret = (OCConvertStringToUuid(uuid, peer->sep.userId.id)) ? 0 : -1;
1925                     SSL_CHECK_FAIL(peer, ret, "Failed to convert subject alt name", 1,
1926                                       CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
1927                 }
1928                 else
1929                 {
1930                     OIC_LOG(WARNING, NET_SSL_TAG, "Subject alternative name not found");
1931                 }
1932             }
1933
1934             oc_mutex_unlock(g_sslContextMutex);
1935             OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1936             return CA_STATUS_OK;
1937         }
1938     }
1939
1940     if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
1941     {
1942         uint8_t decryptBuffer[TLS_MSG_BUF_LEN] = {0};
1943         do
1944         {
1945             ret = mbedtls_ssl_read(&peer->ssl, decryptBuffer, TLS_MSG_BUF_LEN);
1946         } while (MBEDTLS_ERR_SSL_WANT_READ == ret);
1947
1948         if (MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY == ret ||
1949             // TinyDTLS sends fatal close_notify alert
1950             (MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE == ret &&
1951              MBEDTLS_SSL_ALERT_LEVEL_FATAL == peer->ssl.in_msg[0] &&
1952              MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY == peer->ssl.in_msg[1]))
1953         {
1954             OIC_LOG(INFO, NET_SSL_TAG, "Connection was closed gracefully");
1955             RemovePeerFromList(&peer->sep.endpoint);
1956             oc_mutex_unlock(g_sslContextMutex);
1957             return CA_STATUS_OK;
1958         }
1959
1960         if (0 > ret)
1961         {
1962             OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_ssl_read returned -0x%x", -ret);
1963             //SSL_RES(peer, CA_STATUS_FAILED);
1964             RemovePeerFromList(&peer->sep.endpoint);
1965             oc_mutex_unlock(g_sslContextMutex);
1966             return CA_STATUS_FAILED;
1967         }
1968         else if (0 < ret)
1969         {
1970             int adapterIndex = GetAdapterIndex(peer->sep.endpoint.adapter);
1971             if (0 <= adapterIndex && MAX_SUPPORTED_ADAPTERS > adapterIndex)
1972             {
1973                 g_caSslContext->adapterCallbacks[adapterIndex].recvCallback(&peer->sep, decryptBuffer, ret);
1974             }
1975             else
1976             {
1977                 OIC_LOG(ERROR, NET_SSL_TAG, "Unsuported adapter");
1978                 RemovePeerFromList(&peer->sep.endpoint);
1979                 oc_mutex_unlock(g_sslContextMutex);
1980                 return CA_STATUS_FAILED;
1981             }
1982         }
1983     }
1984
1985     oc_mutex_unlock(g_sslContextMutex);
1986     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1987     return CA_STATUS_OK;
1988 }
1989
1990 void CAsetSslAdapterCallbacks(CAPacketReceivedCallback recvCallback,
1991                               CAPacketSendCallback sendCallback,
1992                               CATransportAdapter_t type)
1993 {
1994     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1995     VERIFY_NON_NULL_VOID(sendCallback, NET_SSL_TAG, "sendCallback is NULL");
1996     VERIFY_NON_NULL_VOID(recvCallback, NET_SSL_TAG, "recvCallback is NULL");
1997     oc_mutex_lock(g_sslContextMutex);
1998     if (NULL == g_caSslContext)
1999     {
2000         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
2001         oc_mutex_unlock(g_sslContextMutex);
2002         return;
2003     }
2004
2005     switch (type)
2006     {
2007         case CA_ADAPTER_IP:
2008             g_caSslContext->adapterCallbacks[0].recvCallback = recvCallback;
2009             g_caSslContext->adapterCallbacks[0].sendCallback = sendCallback;
2010             break;
2011         case CA_ADAPTER_TCP:
2012             g_caSslContext->adapterCallbacks[1].recvCallback = recvCallback;
2013             g_caSslContext->adapterCallbacks[1].sendCallback = sendCallback;
2014             break;
2015         case CA_ADAPTER_GATT_BTLE:
2016             g_caSslContext->adapterCallbacks[2].recvCallback = recvCallback;
2017             g_caSslContext->adapterCallbacks[2].sendCallback = sendCallback;
2018             break;
2019         default:
2020             OIC_LOG_V(ERROR, NET_SSL_TAG, "Unsupported adapter: %d", type);
2021     }
2022
2023     oc_mutex_unlock(g_sslContextMutex);
2024     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2025 }
2026 /**
2027  * Gets index of the TLS ciphersuite in the SslCipher_t enum.
2028  *
2029  * @param[in]  cipher    TLS chiphersuite code
2030  *
2031  * @return   corresponding enum
2032  */
2033
2034 static SslCipher_t GetCipherIndex(const uint32_t cipher)
2035 {
2036     switch(cipher)
2037     {
2038         case MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256:
2039         {
2040             return SSL_RSA_WITH_AES_256_CBC_SHA256;
2041         }
2042         case MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256:
2043         {
2044             return SSL_RSA_WITH_AES_128_GCM_SHA256;
2045         }
2046         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
2047         {
2048             return SSL_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256;
2049         }
2050         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
2051         {
2052             return SSL_ECDHE_ECDSA_WITH_AES_128_CCM_8;
2053         }
2054         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
2055         {
2056             return SSL_ECDHE_ECDSA_WITH_AES_128_CCM;
2057         }
2058         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
2059         {
2060             return SSL_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256;
2061         }
2062         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
2063         {
2064             return SSL_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384;
2065         }
2066         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
2067         {
2068             return SSL_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384;
2069         }
2070         case MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
2071         {
2072             return SSL_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
2073         }
2074         case MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
2075         {
2076             return SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA256;
2077         }
2078         case MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256:
2079         {
2080             return SSL_ECDH_ANON_WITH_AES_128_CBC_SHA256;
2081         }
2082         default:
2083         {
2084             return SSL_CIPHER_MAX;
2085         }
2086     }
2087 }
2088
2089 CAResult_t CAsetTlsCipherSuite(const uint32_t cipher)
2090 {
2091     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2092     VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL context is not initialized." , CA_STATUS_NOT_INITIALIZED);
2093
2094     CAResult_t res = CA_STATUS_FAILED;
2095     SslCipher_t index = GetCipherIndex(cipher);
2096     if (SSL_CIPHER_MAX == index)
2097     {
2098         OIC_LOG(WARNING, NET_SSL_TAG, "Unknown cipher");
2099     }
2100     else
2101     {
2102 #ifdef __WITH_TLS__
2103         CONF_SSL(&g_caSslContext->clientTlsConf, &g_caSslContext->serverTlsConf,
2104         mbedtls_ssl_conf_ciphersuites, tlsCipher[index]);
2105 #endif
2106 #ifdef __WITH_DTLS__
2107         CONF_SSL(&g_caSslContext->clientDtlsConf, &g_caSslContext->serverDtlsConf,
2108         mbedtls_ssl_conf_ciphersuites, tlsCipher[index]);
2109 #endif
2110         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Selected cipher: 0x%x", cipher);
2111     }
2112     g_caSslContext->cipher = index;
2113
2114     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2115     return CA_STATUS_OK;
2116 }
2117
2118 CAResult_t CAinitiateSslHandshake(const CAEndpoint_t *endpoint)
2119 {
2120     CAResult_t res = CA_STATUS_OK;
2121     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2122     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
2123     oc_mutex_lock(g_sslContextMutex);
2124     if (NULL == InitiateTlsHandshake(endpoint))
2125     {
2126         OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
2127         res = CA_STATUS_FAILED;
2128     }
2129     oc_mutex_unlock(g_sslContextMutex);
2130     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2131     return res;
2132 }
2133 /**
2134  * Expands the secret into blocks of data according
2135  * to the algorithm specified in section 5 of RFC 4346
2136  *
2137  * This function writes upto @p bufLen bytes into the given output buffer @p buf
2138  *
2139  * @param  key    secret key.
2140  * @param  keyLen    secret key length.
2141  * @param  label    A PRF label.
2142  * @param  labelLen     Actual length of @p label.
2143  * @param  random1    Random seed.
2144  * @param  random1Len     Actual length of @p random1 (may be zero).
2145  * @param  random2     Random seed.
2146  * @param  random2Len    Actual length of @p random2 (may be zero).
2147  * @param  buf    Output buffer for generated random data.
2148  * @param  bufLen    Maximum size of @p buf.
2149  *
2150  * @return The actual number of bytes written to @p buf or @c -1 on error.
2151  */
2152
2153 static int pHash (const unsigned char *key, size_t keyLen,
2154      const unsigned char *label, size_t labelLen,
2155      const unsigned char *random1, size_t random1Len,
2156      const unsigned char *random2, size_t random2Len,
2157      unsigned char *buf, size_t bufLen)
2158 {
2159     unsigned char A[RANDOM_LEN] = {0};
2160     unsigned char tmp[RANDOM_LEN] = {0};
2161     size_t dLen;   /* digest length */
2162     size_t len = 0;   /* result length */
2163
2164     VERIFY_NON_NULL_RET(key, NET_SSL_TAG, "key is NULL", -1);
2165     VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", -1);
2166     VERIFY_NON_NULL_RET(random1, NET_SSL_TAG, "random1 is NULL", -1);
2167     VERIFY_NON_NULL_RET(random2, NET_SSL_TAG, "random2 is NULL", -1);
2168     VERIFY_NON_NULL_RET(buf, NET_SSL_TAG, "buf is NULL", -1);
2169
2170     mbedtls_md_context_t hmacA;
2171     mbedtls_md_context_t hmacP;
2172
2173     mbedtls_md_init(&hmacA);
2174     mbedtls_md_init(&hmacP);
2175
2176     CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacA, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
2177     CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacP, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
2178
2179     CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen );
2180     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, label, labelLen);
2181     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random1, random1Len);
2182     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random2, random2Len);
2183     CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);
2184
2185     dLen = RANDOM_LEN;
2186
2187     CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2188
2189     while (len + dLen < bufLen)
2190     {
2191         CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
2192         CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2193         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);
2194         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
2195         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
2196         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);
2197
2198         CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);
2199
2200         len += RANDOM_LEN;
2201
2202         memcpy(buf, tmp, dLen);
2203         buf += dLen;
2204
2205         CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacA);
2206         CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen);
2207         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, A, dLen);
2208         CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);
2209     }
2210
2211     CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
2212     CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2213     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);
2214
2215     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
2216     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
2217     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);
2218     CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);
2219
2220     memcpy(buf, tmp, bufLen - len);
2221
2222     mbedtls_md_free(&hmacA);
2223     mbedtls_md_free(&hmacP);
2224     return bufLen;
2225     // exit label required for CHECK_MBEDTLS_RET macro
2226 exit:
2227     mbedtls_md_free(&hmacA);
2228     mbedtls_md_free(&hmacP);
2229     return -1;
2230 }
2231
2232 CAResult_t CAsslGenerateOwnerPsk(const CAEndpoint_t *endpoint,
2233                             const uint8_t* label, const size_t labelLen,
2234                             const uint8_t* rsrcServerDeviceId, const size_t rsrcServerDeviceIdLen,
2235                             const uint8_t* provServerDeviceId, const size_t provServerDeviceIdLen,
2236                             uint8_t* ownerPsk, const size_t ownerPskSize)
2237 {
2238     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2239     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "endpoint is NULL", CA_STATUS_INVALID_PARAM);
2240     VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", CA_STATUS_INVALID_PARAM);
2241     VERIFY_NON_NULL_RET(rsrcServerDeviceId, NET_SSL_TAG, "rsrcId is NULL", CA_STATUS_INVALID_PARAM);
2242     VERIFY_NON_NULL_RET(provServerDeviceId, NET_SSL_TAG, "provId is NULL", CA_STATUS_INVALID_PARAM);
2243     VERIFY_NON_NULL_RET(ownerPsk, NET_SSL_TAG, "ownerPSK is NULL", CA_STATUS_INVALID_PARAM);
2244
2245     oc_mutex_lock(g_sslContextMutex);
2246     if (NULL == g_caSslContext)
2247     {
2248         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
2249         oc_mutex_unlock(g_sslContextMutex);
2250         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2251         return CA_STATUS_FAILED;
2252     }
2253     SslEndPoint_t * tep = GetSslPeer(endpoint);
2254     if (NULL == tep)
2255     {
2256         OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
2257         oc_mutex_unlock(g_sslContextMutex);
2258         return CA_STATUS_FAILED;
2259     }
2260
2261     // keyBlockLen set up according to OIC 1.1 Security Specification Section 7.3.2
2262     int macKeyLen = 0;
2263     int ivSize = 0;
2264     int keySize = 0;
2265     int keyBlockLen = 0;
2266     if (MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher ||
2267         MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher ||
2268         MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher ||
2269         MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 == g_caSslContext->selectedCipher)
2270     {
2271         // 2 * ( 32 + 0 + 16 ) = 96
2272         macKeyLen = SHA256_MAC_KEY_LENGTH;
2273         ivSize = CBC_IV_LENGTH;
2274         keySize = AES128_KEY_LENGTH;
2275     }
2276     else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM == g_caSslContext->selectedCipher ||
2277              MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 == g_caSslContext->selectedCipher)
2278     {
2279         // 2 * ( 0 + 4 + 16 ) = 40
2280         macKeyLen = CCM_MAC_KEY_LENGTH;
2281         ivSize = CCM_IV_LENGTH;
2282         keySize = AES128_KEY_LENGTH;
2283     }
2284     else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 == g_caSslContext->selectedCipher)
2285     {
2286         // 2 * ( 32 + 12 + 16 ) = 120
2287         macKeyLen = SHA256_MAC_KEY_LENGTH;
2288         ivSize = GCM_IV_LENGTH;
2289         keySize = AES128_KEY_LENGTH;
2290     }
2291     else if (MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 == g_caSslContext->selectedCipher)
2292     {
2293         // 2 * ( 32 + 0 + 32 ) = 128
2294         macKeyLen = SHA256_MAC_KEY_LENGTH;
2295         ivSize = CBC_IV_LENGTH;
2296         keySize = AES256_KEY_LENGTH;
2297     }
2298     else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 == g_caSslContext->selectedCipher)
2299     {
2300         // 2 * ( 48 + 0 + 32 ) = 160
2301         macKeyLen = SHA384_MAC_KEY_LENGTH;
2302         ivSize = CBC_IV_LENGTH;
2303         keySize = AES256_KEY_LENGTH;
2304     }
2305     else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 == g_caSslContext->selectedCipher)
2306     {
2307         // 2 * ( 48 + 12 + 32 ) = 184
2308         macKeyLen = SHA384_MAC_KEY_LENGTH;
2309         ivSize = GCM_IV_LENGTH;
2310         keySize = AES256_KEY_LENGTH;
2311     }
2312     else if (MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 == g_caSslContext->selectedCipher)
2313     {
2314         // 2 * ( 48 + 12 + 32 ) = 184
2315         macKeyLen = SHA256_MAC_KEY_LENGTH;
2316         ivSize = GCM_IV_LENGTH;
2317         keySize = AES128_KEY_LENGTH;
2318     }
2319     keyBlockLen = 2 * (macKeyLen + keySize + ivSize);
2320
2321     uint8_t * keyblock = (uint8_t *)OICMalloc(keyBlockLen);
2322     if (NULL == keyblock)
2323     {
2324         OIC_LOG(ERROR, NET_SSL_TAG, "Failed to OICMalloc for keyblock");
2325         oc_mutex_unlock(g_sslContextMutex);
2326         return CA_STATUS_FAILED;
2327     }
2328
2329     // "key expansion"
2330     uint8_t lab[] = {0x6b, 0x65, 0x79, 0x20, 0x65, 0x78, 0x70, 0x61, 0x6e, 0x73, 0x69, 0x6f, 0x6e};
2331     int ret = pHash(tep->master, sizeof(tep->master), lab, sizeof(lab),
2332                     (tep->random) + RANDOM_LEN, RANDOM_LEN, tep->random, RANDOM_LEN,
2333                     keyblock, keyBlockLen);
2334     if (-1 == ret)
2335     {
2336         OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
2337         OICFree(keyblock);
2338         oc_mutex_unlock(g_sslContextMutex);
2339         return CA_STATUS_FAILED;
2340     }
2341
2342     ret = pHash(keyblock, keyBlockLen, label, labelLen,
2343                 rsrcServerDeviceId, rsrcServerDeviceIdLen,
2344                 provServerDeviceId, provServerDeviceIdLen,
2345                 ownerPsk, ownerPskSize);
2346     if (-1 == ret)
2347     {
2348         OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
2349         OICFree(keyblock);
2350         oc_mutex_unlock(g_sslContextMutex);
2351         return CA_STATUS_FAILED;
2352     }
2353
2354     OICFree(keyblock);
2355     oc_mutex_unlock(g_sslContextMutex);
2356
2357     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2358     return CA_STATUS_OK;
2359 }