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