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