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