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