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