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