[IOT-1548] Fix to transfer a large size of data on CoAPs over TCP
[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     }
1218 }
1219 #endif
1220 void CAdeinitSslAdapter()
1221 {
1222     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1223
1224     VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "context is NULL");
1225     VERIFY_NON_NULL_VOID(g_sslContextMutex, NET_SSL_TAG, "context mutex is NULL");
1226
1227     //Lock tlsContext mutex
1228     ca_mutex_lock(g_sslContextMutex);
1229
1230     // Clear all lists
1231     DeletePeerList();
1232
1233     // De-initialize mbedTLS
1234     mbedtls_x509_crt_free(&g_caSslContext->crt);
1235     mbedtls_pk_free(&g_caSslContext->pkey);
1236 #ifdef __WITH_TLS__
1237     mbedtls_ssl_config_free(&g_caSslContext->clientTlsConf);
1238     mbedtls_ssl_config_free(&g_caSslContext->serverTlsConf);
1239 #endif // __WITH_TLS__
1240 #ifdef __WITH_DTLS__
1241     mbedtls_ssl_config_free(&g_caSslContext->clientDtlsConf);
1242     mbedtls_ssl_config_free(&g_caSslContext->serverDtlsConf);
1243 #endif // __WITH_DTLS__
1244     mbedtls_ctr_drbg_free(&g_caSslContext->rnd);
1245     mbedtls_entropy_free(&g_caSslContext->entropy);
1246 #ifdef __WITH_DTLS__
1247     StopRetransmit();
1248 #endif
1249     // De-initialize tls Context
1250     OICFree(g_caSslContext);
1251     g_caSslContext = NULL;
1252
1253     // Unlock tlsContext mutex and de-initialize it
1254     ca_mutex_unlock(g_sslContextMutex);
1255     ca_mutex_free(g_sslContextMutex);
1256     g_sslContextMutex = NULL;
1257
1258     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s ", __func__);
1259 }
1260
1261 static int InitConfig(mbedtls_ssl_config * conf, int transport, int mode)
1262 {
1263     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1264     VERIFY_NON_NULL_RET(conf, NET_SSL_TAG, "Param conf is NULL" , -1);
1265     mbedtls_ssl_config_init(conf);
1266     if (mbedtls_ssl_config_defaults(conf, mode, transport, MBEDTLS_SSL_PRESET_DEFAULT) != 0)
1267     {
1268         OIC_LOG(ERROR, NET_SSL_TAG, "Config initialization failed!");
1269         return -1;
1270     }
1271
1272     mbedtls_ssl_conf_psk_cb(conf, GetPskCredentialsCallback, NULL);
1273     mbedtls_ssl_conf_rng(conf, mbedtls_ctr_drbg_random, &g_caSslContext->rnd);
1274     mbedtls_ssl_conf_curves(conf, curve[ADAPTER_CURVE_SECP256R1]);
1275     mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
1276     mbedtls_ssl_conf_renegotiation(conf, MBEDTLS_SSL_RENEGOTIATION_DISABLED);
1277     mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
1278
1279 #if !defined(NDEBUG) || defined(TB_LOG)
1280     mbedtls_ssl_conf_dbg(conf, DebugSsl, NULL);
1281     mbedtls_debug_set_threshold(MBED_TLS_DEBUG_LEVEL);
1282 #endif
1283     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1284     return 0;
1285 }
1286 #ifdef __WITH_DTLS__
1287 /**
1288  * Starts DTLS retransmission.
1289  */
1290 static int StartRetransmit()
1291 {
1292     uint32_t listIndex = 0;
1293     uint32_t listLength = 0;
1294     SslEndPoint_t *tep = NULL;
1295     if (NULL == g_caSslContext)
1296     {
1297         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL. Stop retransmission");
1298         return -1;
1299     }
1300     ca_mutex_lock(g_sslContextMutex);
1301     if (g_caSslContext->timerId != -1)
1302     {
1303         //clear previous timer
1304         unregisterTimer(g_caSslContext->timerId);
1305
1306         listLength = u_arraylist_length(g_caSslContext->peerList);
1307         for (listIndex = 0; listIndex < listLength; listIndex++)
1308         {
1309             tep = (SslEndPoint_t *) u_arraylist_get(g_caSslContext->peerList, listIndex);
1310             if (NULL == tep
1311                 || MBEDTLS_SSL_TRANSPORT_STREAM == tep->ssl.conf->transport
1312                 || MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
1313             {
1314                 continue;
1315             }
1316             int ret = mbedtls_ssl_handshake_step(&tep->ssl);
1317
1318             if (MBEDTLS_ERR_SSL_CONN_EOF != ret)
1319             {
1320                 SSL_CHECK_FAIL(tep, ret, "Retransmission", NULL, -1,
1321                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1322             }
1323         }
1324     }
1325     //start new timer
1326     registerTimer(RETRANSMISSION_TIME, &g_caSslContext->timerId, (void *) StartRetransmit);
1327     ca_mutex_unlock(g_sslContextMutex);
1328     return 0;
1329 }
1330 #endif
1331
1332 CAResult_t CAinitSslAdapter()
1333 {
1334     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1335     // Initialize mutex for tlsContext
1336     if (NULL == g_sslContextMutex)
1337     {
1338         g_sslContextMutex = ca_mutex_new();
1339         VERIFY_NON_NULL_RET(g_sslContextMutex, NET_SSL_TAG, "malloc failed", CA_MEMORY_ALLOC_FAILED);
1340     }
1341     else
1342     {
1343         OIC_LOG(INFO, NET_SSL_TAG, "Done already!");
1344         return CA_STATUS_OK;
1345     }
1346
1347     // Lock tlsContext mutex and create tlsContext
1348     ca_mutex_lock(g_sslContextMutex);
1349     g_caSslContext = (SslContext_t *)OICCalloc(1, sizeof(SslContext_t));
1350
1351     if (NULL == g_caSslContext)
1352     {
1353         OIC_LOG(ERROR, NET_SSL_TAG, "Context malloc failed");
1354         ca_mutex_unlock(g_sslContextMutex);
1355         ca_mutex_free(g_sslContextMutex);
1356         g_sslContextMutex = NULL;
1357         return CA_MEMORY_ALLOC_FAILED;
1358     }
1359
1360     // Create peer list
1361     g_caSslContext->peerList = u_arraylist_create();
1362
1363     if(NULL == g_caSslContext->peerList)
1364     {
1365         OIC_LOG(ERROR, NET_SSL_TAG, "peerList initialization failed!");
1366         OICFree(g_caSslContext);
1367         g_caSslContext = NULL;
1368         ca_mutex_unlock(g_sslContextMutex);
1369         ca_mutex_free(g_sslContextMutex);
1370         g_sslContextMutex = NULL;
1371         return CA_STATUS_FAILED;
1372     }
1373
1374     /* Initialize TLS library
1375      */
1376 #if !defined(NDEBUG) || defined(TB_LOG)
1377     char version[MBED_TLS_VERSION_LEN];
1378     mbedtls_version_get_string(version);
1379     OIC_LOG_V(INFO, NET_SSL_TAG, "mbed TLS version: %s", version);
1380 #endif
1381
1382     /* Entropy settings
1383      */
1384     mbedtls_entropy_init(&g_caSslContext->entropy);
1385     mbedtls_ctr_drbg_init(&g_caSslContext->rnd);
1386
1387 #ifdef __unix__
1388     unsigned char seed[sizeof(SEED)] = {0};
1389     int urandomFd = -2;
1390     urandomFd = open("/dev/urandom", O_RDONLY);
1391     if(urandomFd == -1)
1392     {
1393         OIC_LOG(ERROR, NET_SSL_TAG, "Fails open /dev/urandom!");
1394         ca_mutex_unlock(g_sslContextMutex);
1395         CAdeinitSslAdapter();
1396         return CA_STATUS_FAILED;
1397     }
1398     if(0 > read(urandomFd, seed, sizeof(seed)))
1399     {
1400         OIC_LOG(ERROR, NET_SSL_TAG, "Fails read from /dev/urandom!");
1401         close(urandomFd);
1402         ca_mutex_unlock(g_sslContextMutex);
1403         CAdeinitSslAdapter();
1404         return CA_STATUS_FAILED;
1405     }
1406     close(urandomFd);
1407
1408 #else
1409     unsigned char * seed = (unsigned char*) SEED;
1410 #endif
1411     if(0 != mbedtls_ctr_drbg_seed(&g_caSslContext->rnd, mbedtls_entropy_func,
1412                                   &g_caSslContext->entropy, seed, sizeof(SEED)))
1413     {
1414         OIC_LOG(ERROR, NET_SSL_TAG, "Seed initialization failed!");
1415         ca_mutex_unlock(g_sslContextMutex);
1416         CAdeinitSslAdapter();
1417         return CA_STATUS_FAILED;
1418     }
1419     mbedtls_ctr_drbg_set_prediction_resistance(&g_caSslContext->rnd, MBEDTLS_CTR_DRBG_PR_OFF);
1420
1421 #ifdef __WITH_TLS__
1422     if (0 != InitConfig(&g_caSslContext->clientTlsConf,
1423                         MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_CLIENT))
1424     {
1425         OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
1426         ca_mutex_unlock(g_sslContextMutex);
1427         CAdeinitSslAdapter();
1428         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1429         return CA_STATUS_FAILED;
1430     }
1431
1432     if (0 != InitConfig(&g_caSslContext->serverTlsConf,
1433                         MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_SERVER))
1434     {
1435         OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
1436         ca_mutex_unlock(g_sslContextMutex);
1437         CAdeinitSslAdapter();
1438         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1439         return CA_STATUS_FAILED;
1440     }
1441 #endif // __WITH_TLS__
1442 #ifdef __WITH_DTLS__
1443     if (0 != InitConfig(&g_caSslContext->clientDtlsConf,
1444                         MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_CLIENT))
1445     {
1446         OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
1447         ca_mutex_unlock(g_sslContextMutex);
1448         CAdeinitSslAdapter();
1449         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1450         return CA_STATUS_FAILED;
1451     }
1452
1453     if (0 != InitConfig(&g_caSslContext->serverDtlsConf,
1454                         MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_SERVER))
1455     {
1456         OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
1457         ca_mutex_unlock(g_sslContextMutex);
1458         CAdeinitSslAdapter();
1459         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1460         return CA_STATUS_FAILED;
1461     }
1462 #endif // __WITH_DTLS__
1463
1464     // set default cipher
1465     g_caSslContext->cipher = ADAPTER_CIPHER_MAX;
1466
1467     // init X.509
1468     mbedtls_x509_crt_init(&g_caSslContext->ca);
1469     mbedtls_x509_crt_init(&g_caSslContext->crt);
1470     mbedtls_pk_init(&g_caSslContext->pkey);
1471     mbedtls_x509_crl_init(&g_caSslContext->crl);
1472
1473 #ifdef __WITH_DTLS__
1474     g_caSslContext->timerId = -1;
1475 #endif
1476
1477    ca_mutex_unlock(g_sslContextMutex);
1478 #ifdef __WITH_DTLS__
1479     StartRetransmit();
1480 #endif
1481
1482     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1483     return CA_STATUS_OK;
1484 }
1485
1486 SslCacheMessage_t *  NewCacheMessage(uint8_t * data, size_t dataLen)
1487 {
1488     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1489     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , NULL);
1490     if (0 == dataLen)
1491     {
1492         OIC_LOG(ERROR, NET_SSL_TAG, "dataLen is equal to zero");
1493         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1494         return NULL;
1495     }
1496     SslCacheMessage_t * message = (SslCacheMessage_t *) OICCalloc(1, sizeof(SslCacheMessage_t));
1497     if (NULL == message)
1498     {
1499         OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
1500         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1501         return NULL;
1502     }
1503
1504     message->data = (uint8_t *)OICCalloc(dataLen, sizeof(uint8_t));
1505     if (NULL == message->data)
1506     {
1507         OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
1508         OICFree(message);
1509         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1510         return NULL;
1511     }
1512     memcpy(message->data, data, dataLen);
1513     message->len = dataLen;
1514     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1515     return message;
1516 }
1517
1518 /* Send data via TLS connection.
1519  */
1520 CAResult_t CAencryptSsl(const CAEndpoint_t *endpoint,
1521                         void *data, uint32_t dataLen)
1522 {
1523     int ret = 0;
1524
1525     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s ", __func__);
1526
1527     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG,"Remote address is NULL", CA_STATUS_INVALID_PARAM);
1528     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Data is NULL", CA_STATUS_INVALID_PARAM);
1529     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Port %d", endpoint->port);
1530
1531     if (0 == dataLen)
1532     {
1533         OIC_LOG_V(ERROR, NET_SSL_TAG, "dataLen is zero [%d]", dataLen);
1534         return CA_STATUS_FAILED;
1535     }
1536
1537     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data to be encrypted dataLen [%d]", dataLen);
1538
1539     ca_mutex_lock(g_sslContextMutex);
1540     if(NULL == g_caSslContext)
1541     {
1542         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1543         ca_mutex_unlock(g_sslContextMutex);
1544         return CA_STATUS_FAILED;
1545     }
1546
1547     SslEndPoint_t * tep = GetSslPeer(endpoint);
1548     if (NULL == tep)
1549     {
1550         tep = InitiateTlsHandshake(endpoint);
1551     }
1552     if (NULL == tep)
1553     {
1554         OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
1555         ca_mutex_unlock(g_sslContextMutex);
1556         return CA_STATUS_FAILED;
1557     }
1558
1559     if (MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
1560     {
1561         unsigned char *dataBuf = (unsigned char *)data;
1562         size_t written = 0;
1563
1564         do
1565         {
1566             ret = mbedtls_ssl_write(&tep->ssl, dataBuf, dataLen - written);
1567             if (ret < 0)
1568             {
1569                 if (MBEDTLS_ERR_SSL_WANT_WRITE != ret)
1570                 {
1571                     OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedTLS write failed! returned 0x%x", -ret);
1572                     RemovePeerFromList(&tep->sep.endpoint);
1573                     ca_mutex_unlock(g_sslContextMutex);
1574                     return CA_STATUS_FAILED;
1575                 }
1576                 continue;
1577             }
1578             OIC_LOG_V(DEBUG, NET_SSL_TAG, "mbedTLS write returned with sent bytes[%d]", ret);
1579
1580             dataBuf += ret;
1581             written += ret;
1582         } while (dataLen > written);
1583
1584     }
1585     else
1586     {
1587         SslCacheMessage_t * msg = NewCacheMessage((uint8_t*) data, dataLen);
1588         if (NULL == msg || !u_arraylist_add(tep->cacheList, (void *) msg))
1589         {
1590             OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
1591             ca_mutex_unlock(g_sslContextMutex);
1592             return CA_STATUS_FAILED;
1593         }
1594     }
1595
1596     ca_mutex_unlock(g_sslContextMutex);
1597
1598     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1599     return CA_STATUS_OK;
1600 }
1601 /**
1602  * Sends cached messages via TLS connection.
1603  *
1604  * @param[in]  tep    remote address with session info
1605  */
1606 static void SendCacheMessages(SslEndPoint_t * tep)
1607 {
1608     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1609     VERIFY_NON_NULL_VOID(tep, NET_SSL_TAG, "Param tep is NULL");
1610
1611     uint32_t listIndex = 0;
1612     uint32_t listLength = 0;
1613     listLength = u_arraylist_length(tep->cacheList);
1614     for (listIndex = 0; listIndex < listLength;)
1615     {
1616         int ret = 0;
1617         SslCacheMessage_t * msg = (SslCacheMessage_t *) u_arraylist_get(tep->cacheList, listIndex);
1618         if (NULL != msg && NULL != msg->data && 0 != msg->len)
1619         {
1620             unsigned char *dataBuf = (unsigned char *)msg->data;
1621             size_t written = 0;
1622
1623             do
1624             {
1625                 ret = mbedtls_ssl_write(&tep->ssl, dataBuf, msg->len - written);
1626                 if (ret < 0)
1627                 {
1628                     if (MBEDTLS_ERR_SSL_WANT_WRITE != ret)
1629                     {
1630                         OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedTLS write failed! returned -0x%x", -ret);
1631                         break;
1632                     }
1633                     continue;
1634                 }
1635                 OIC_LOG_V(DEBUG, NET_SSL_TAG, "mbedTLS write returned with sent bytes[%d]", ret);
1636
1637                 dataBuf += ret;
1638                 written += ret;
1639             } while (msg->len > written);
1640
1641             if (u_arraylist_remove(tep->cacheList, listIndex))
1642             {
1643                 DeleteCacheMessage(msg);
1644                 // Reduce list length by 1 as we removed one element.
1645                 listLength--;
1646             }
1647             else
1648             {
1649                 OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_remove failed.");
1650                 break;
1651             }
1652         }
1653         else
1654         {
1655             // Move to the next element
1656             ++listIndex;
1657         }
1658     }
1659     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1660 }
1661
1662 void CAsetSslHandshakeCallback(CAErrorCallback tlsHandshakeCallback)
1663 {
1664     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1665     g_sslCallback = tlsHandshakeCallback;
1666     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1667 }
1668
1669 /* Read data from TLS connection
1670  */
1671 CAResult_t CAdecryptSsl(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t dataLen)
1672 {
1673     int ret = 0;
1674     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1675     VERIFY_NON_NULL_RET(sep, NET_SSL_TAG, "endpoint is NULL" , CA_STATUS_INVALID_PARAM);
1676     VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , CA_STATUS_INVALID_PARAM);
1677
1678     ca_mutex_lock(g_sslContextMutex);
1679     if (NULL == g_caSslContext)
1680     {
1681         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1682         ca_mutex_unlock(g_sslContextMutex);
1683         return CA_STATUS_FAILED;
1684     }
1685
1686
1687     SslEndPoint_t * peer = GetSslPeer(&sep->endpoint);
1688     if (NULL == peer)
1689     {
1690         mbedtls_ssl_config * config = (sep->endpoint.adapter == CA_ADAPTER_IP ?
1691                                    &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
1692         peer = NewSslEndPoint(&sep->endpoint, config);
1693         if (NULL == peer)
1694         {
1695             OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
1696             ca_mutex_unlock(g_sslContextMutex);
1697             return CA_STATUS_FAILED;
1698         }
1699         //Load allowed TLS suites from SVR DB
1700         SetupCipher(config, sep->endpoint.adapter);
1701
1702         ret = u_arraylist_add(g_caSslContext->peerList, (void *) peer);
1703         if (!ret)
1704         {
1705             OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
1706             OICFree(peer);
1707             ca_mutex_unlock(g_sslContextMutex);
1708             return CA_STATUS_FAILED;
1709         }
1710     }
1711
1712     peer->recBuf.buff = data;
1713     peer->recBuf.len = dataLen;
1714     peer->recBuf.loaded = 0;
1715
1716     while (MBEDTLS_SSL_HANDSHAKE_OVER != peer->ssl.state)
1717     {
1718         ret = mbedtls_ssl_handshake_step(&peer->ssl);
1719         if (MBEDTLS_ERR_SSL_CONN_EOF == ret)
1720         {
1721             break;
1722         }
1723
1724         if (MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED == ret)
1725         {
1726             OIC_LOG(DEBUG, NET_SSL_TAG, "Hello verification requested");
1727             mbedtls_ssl_session_reset(&peer->ssl);
1728             mbedtls_ssl_set_client_transport_id(&peer->ssl,
1729                                                 (const unsigned char *) sep->endpoint.addr,
1730                                                  sizeof(sep->endpoint.addr));
1731             ret = mbedtls_ssl_handshake_step(&peer->ssl);
1732         }
1733         uint32_t flags = mbedtls_ssl_get_verify_result(&peer->ssl);
1734         if (0 != flags)
1735         {
1736             OIC_LOG_BUFFER(ERROR, NET_SSL_TAG, (const uint8_t *) &flags, sizeof(flags));
1737             SSL_CHECK_FAIL(peer, flags, "Cert verification failed", 1,
1738                                                      CA_STATUS_FAILED, GetAlertCode(flags));
1739         }
1740         SSL_CHECK_FAIL(peer, ret, "Handshake error", 1, CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1741         if (MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC == peer->ssl.state)
1742         {
1743             memcpy(peer->master, peer->ssl.session_negotiate->master, sizeof(peer->master));
1744             g_caSslContext->selectedCipher = peer->ssl.session_negotiate->ciphersuite;
1745         }
1746         if (MBEDTLS_SSL_CLIENT_KEY_EXCHANGE == peer->ssl.state)
1747         {
1748             memcpy(peer->random, peer->ssl.handshake->randbytes, sizeof(peer->random));
1749         }
1750
1751         if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
1752         {
1753             SSL_RES(peer, CA_STATUS_OK);
1754             if (MBEDTLS_SSL_IS_CLIENT == peer->ssl.conf->endpoint)
1755             {
1756                 SendCacheMessages(peer);
1757             }
1758
1759             if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 == g_caSslContext->selectedCipher ||
1760                 MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA == g_caSslContext->selectedCipher)
1761             {
1762                 char uuid[UUID_LENGTH * 2 + 5] = {0};
1763                 void * uuidPos = NULL;
1764                 void * userIdPos = NULL;
1765                 const mbedtls_x509_crt * peerCert = mbedtls_ssl_get_peer_cert(&peer->ssl);
1766                 ret = (NULL == peerCert ? -1 : 0);
1767                 SSL_CHECK_FAIL(peer, ret, "Failed to retrieve cert", 1,
1768                                             CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_NO_CERT);
1769                 uuidPos = memmem(peerCert->subject_raw.p, peerCert->subject_raw.len,
1770                                                  UUID_PREFIX, sizeof(UUID_PREFIX) - 1);
1771
1772                 if (NULL != uuidPos)
1773                 {
1774                     memcpy(uuid, (char*) uuidPos + sizeof(UUID_PREFIX) - 1, UUID_LENGTH * 2 + 4);
1775                     OIC_LOG_V(DEBUG, NET_SSL_TAG, "certificate uuid string: %s" , uuid);
1776                     ret = OCConvertStringToUuid(uuid, peer->sep.identity.id);
1777                     SSL_CHECK_FAIL(peer, ret, "Failed to convert subject", 1,
1778                                           CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
1779                 }
1780                 else
1781                 {
1782                     OIC_LOG(WARNING, NET_SSL_TAG, "uuid not found");
1783                 }
1784
1785                 userIdPos = memmem(peerCert->subject_raw.p, peerCert->subject_raw.len,
1786                                              USERID_PREFIX, sizeof(USERID_PREFIX) - 1);
1787                 if (NULL != userIdPos)
1788                 {
1789                     memcpy(uuid, (char*) userIdPos + sizeof(USERID_PREFIX) - 1, UUID_LENGTH * 2 + 4);
1790                     ret = OCConvertStringToUuid(uuid, peer->sep.userId.id);
1791                     SSL_CHECK_FAIL(peer, ret, "Failed to convert subject alt name", 1,
1792                                       CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
1793                 }
1794                 else
1795                 {
1796                     OIC_LOG(WARNING, NET_SSL_TAG, "Subject alternative name not found");
1797                 }
1798             }
1799
1800             ca_mutex_unlock(g_sslContextMutex);
1801             OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1802             return CA_STATUS_OK;
1803         }
1804     }
1805
1806     if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
1807     {
1808         uint8_t decryptBuffer[TLS_MSG_BUF_LEN] = {0};
1809         do
1810         {
1811             ret = mbedtls_ssl_read(&peer->ssl, decryptBuffer, TLS_MSG_BUF_LEN);
1812         } while (MBEDTLS_ERR_SSL_WANT_READ == ret);
1813
1814         if (MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY == ret ||
1815             // TinyDTLS sends fatal close_notify alert
1816             (MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE == ret &&
1817              MBEDTLS_SSL_ALERT_LEVEL_FATAL == peer->ssl.in_msg[0] &&
1818              MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY == peer->ssl.in_msg[1]))
1819         {
1820             OIC_LOG(INFO, NET_SSL_TAG, "Connection was closed gracefully");
1821             SSL_CLOSE_NOTIFY(peer, ret);
1822             RemovePeerFromList(&peer->sep.endpoint);
1823             ca_mutex_unlock(g_sslContextMutex);
1824             return CA_STATUS_OK;
1825         }
1826
1827         if (0 > ret)
1828         {
1829             OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_ssl_read returned -0x%x", -ret);
1830             //SSL_RES(peer, CA_STATUS_FAILED);
1831             RemovePeerFromList(&peer->sep.endpoint);
1832             ca_mutex_unlock(g_sslContextMutex);
1833             return CA_STATUS_FAILED;
1834         }
1835         int adapterIndex = GetAdapterIndex(peer->sep.endpoint.adapter);
1836         if (0 == adapterIndex || adapterIndex == 1)
1837         {
1838             g_caSslContext->adapterCallbacks[adapterIndex].recvCallback(&peer->sep, decryptBuffer, ret);
1839         }
1840         else
1841         {
1842             OIC_LOG(ERROR, NET_SSL_TAG, "Unsuported adapter");
1843             RemovePeerFromList(&peer->sep.endpoint);
1844             ca_mutex_unlock(g_sslContextMutex);
1845             return CA_STATUS_FAILED;
1846         }
1847     }
1848
1849     ca_mutex_unlock(g_sslContextMutex);
1850     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1851     return CA_STATUS_OK;
1852 }
1853
1854 void CAsetSslAdapterCallbacks(CAPacketReceivedCallback recvCallback,
1855                               CAPacketSendCallback sendCallback,
1856                               CATransportAdapter_t type)
1857 {
1858     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1859     VERIFY_NON_NULL_VOID(sendCallback, NET_SSL_TAG, "sendCallback is NULL");
1860     VERIFY_NON_NULL_VOID(recvCallback, NET_SSL_TAG, "recvCallback is NULL");
1861     ca_mutex_lock(g_sslContextMutex);
1862     if (NULL == g_caSslContext)
1863     {
1864         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
1865         ca_mutex_unlock(g_sslContextMutex);
1866         return;
1867     }
1868
1869 //    if (MAX_SUPPORTED_ADAPTERS > type)
1870     {
1871         switch (type)
1872         {
1873             case CA_ADAPTER_IP:
1874                 g_caSslContext->adapterCallbacks[0].recvCallback = recvCallback;
1875                 g_caSslContext->adapterCallbacks[0].sendCallback = sendCallback;
1876                 break;
1877             case CA_ADAPTER_TCP:
1878                 g_caSslContext->adapterCallbacks[1].recvCallback = recvCallback;
1879                 g_caSslContext->adapterCallbacks[1].sendCallback = sendCallback;
1880                 break;
1881             default:
1882                 OIC_LOG_V(ERROR, NET_SSL_TAG, "Unsupported adapter: %d", type);
1883         }
1884     }
1885
1886     ca_mutex_unlock(g_sslContextMutex);
1887     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
1888 }
1889
1890 CAResult_t CAsetTlsCipherSuite(const uint32_t cipher)
1891 {
1892     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
1893     VERIFY_NON_NULL_RET(g_getCredentialTypesCallback, NET_SSL_TAG, "Param callback is null", CA_STATUS_FAILED);
1894     g_getCredentialTypesCallback(g_caSslContext->cipherFlag);
1895     switch(cipher)
1896     {
1897         case MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA:
1898         {
1899 #ifdef __WITH_TLS__
1900             //todo check that Cred with RSA cert exists
1901             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientTlsConf,
1902                                          tlsCipher[ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA]);
1903             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverTlsConf,
1904                                          tlsCipher[ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA]);
1905 #endif
1906 #ifdef __WITH_DTLS__
1907             //todo check that Cred with RSA cert exists
1908             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientDtlsConf,
1909                                          tlsCipher[ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA]);
1910             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverDtlsConf,
1911                                          tlsCipher[ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA]);
1912 #endif
1913             g_caSslContext->cipher = ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA;
1914             break;
1915         }
1916         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
1917         {
1918             if (false == g_caSslContext->cipherFlag[1])
1919             {
1920                 OIC_LOG(ERROR, NET_SSL_TAG, "No Credential for ECC");
1921                 return CA_STATUS_FAILED;
1922             }
1923 #ifdef __WITH_TLS__
1924             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientTlsConf,
1925                                          tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8]);
1926             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverTlsConf,
1927                                          tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8]);
1928 #endif
1929 #ifdef __WITH_DTLS__
1930             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientDtlsConf,
1931                                          tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8]);
1932             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverDtlsConf,
1933                                          tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8]);
1934 #endif
1935             g_caSslContext->cipher = ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
1936             break;
1937         }
1938         case MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256:
1939         {
1940 #ifdef __WITH_TLS__
1941             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientTlsConf,
1942                                          tlsCipher[ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256]);
1943             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverTlsConf,
1944                                          tlsCipher[ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256]);
1945 #endif
1946 #ifdef __WITH_DTLS__
1947             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientDtlsConf,
1948                                          tlsCipher[ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256]);
1949             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverDtlsConf,
1950                                          tlsCipher[ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256]);
1951 #endif
1952             g_caSslContext->cipher = ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256;
1953             break;
1954         }
1955         case MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
1956         {
1957 #if 0 // PIN OTM
1958             if (false == g_caSslContext->cipherFlag[0])
1959             {
1960                 OIC_LOG(ERROR, NET_SSL_TAG, "No Credential for PSK");
1961                 return CA_STATUS_FAILED;
1962             }
1963 #endif
1964 #ifdef __WITH_TLS__
1965             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientTlsConf,
1966                                           tlsCipher[ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256]);
1967             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverTlsConf,
1968                                           tlsCipher[ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256]);
1969 #endif
1970 #ifdef __WITH_DTLS__
1971             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientDtlsConf,
1972                                           tlsCipher[ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256]);
1973             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverDtlsConf,
1974                                           tlsCipher[ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256]);
1975 #endif
1976             g_caSslContext->cipher = ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
1977             break;
1978         }
1979         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
1980         {
1981             if (false == g_caSslContext->cipherFlag[1])
1982             {
1983                 OIC_LOG(ERROR, NET_SSL_TAG, "No Credential for ECC");
1984                 return CA_STATUS_FAILED;
1985             }
1986 #ifdef __WITH_TLS__
1987             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientTlsConf,
1988                                          tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM]);
1989             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverTlsConf,
1990                                          tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM]);
1991 #endif
1992 #ifdef __WITH_DTLS__
1993             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientDtlsConf,
1994                                          tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM]);
1995             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverDtlsConf,
1996                                          tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM]);
1997 #endif
1998             g_caSslContext->cipher = ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM;
1999             break;
2000         }
2001         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
2002         {
2003             if (false == g_caSslContext->cipherFlag[1])
2004             {
2005                 OIC_LOG(ERROR, NET_SSL_TAG, "No Credential for ECC");
2006                 return CA_STATUS_FAILED;
2007             }
2008 #ifdef __WITH_TLS__
2009             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientTlsConf,
2010                                          tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256]);
2011             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverTlsConf,
2012                                          tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256]);
2013 #endif
2014 #ifdef __WITH_DTLS__
2015             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientDtlsConf,
2016                                          tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256]);
2017             mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverDtlsConf,
2018                                          tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256]);
2019 #endif
2020             g_caSslContext->cipher = ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256;
2021             break;
2022         }
2023         default:
2024         {
2025             OIC_LOG(ERROR, NET_SSL_TAG, "Unknown cipher");
2026             return CA_STATUS_FAILED;
2027         }
2028     }
2029     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Selected cipher: 0x%x", cipher);
2030     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2031     return CA_STATUS_OK;
2032 }
2033
2034 CAResult_t CAinitiateSslHandshake(const CAEndpoint_t *endpoint)
2035 {
2036     CAResult_t res = CA_STATUS_OK;
2037     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2038     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
2039     ca_mutex_lock(g_sslContextMutex);
2040     if (NULL == InitiateTlsHandshake(endpoint))
2041     {
2042         OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
2043         res = CA_STATUS_FAILED;
2044     }
2045     ca_mutex_unlock(g_sslContextMutex);
2046     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2047     return res;
2048 }
2049 /**
2050  * Expands the secret into blocks of data according
2051  * to the algorithm specified in section 5 of RFC 4346
2052  *
2053  * This function writes upto @p bufLen bytes into the given output buffer @p buf
2054  *
2055  * @param  key    secret key.
2056  * @param  keyLen    secret key length.
2057  * @param  label    A PRF label.
2058  * @param  labelLen     Actual length of @p label.
2059  * @param  random1    Random seed.
2060  * @param  random1Len     Actual length of @p random1 (may be zero).
2061  * @param  random2     Random seed.
2062  * @param  random2Len    Actual length of @p random2 (may be zero).
2063  * @param  buf    Output buffer for generated random data.
2064  * @param  bufLen    Maximum size of @p buf.
2065  *
2066  * @return The actual number of bytes written to @p buf or @c -1 on error.
2067  */
2068
2069 static int pHash (const unsigned char *key, size_t keyLen,
2070      const unsigned char *label, size_t labelLen,
2071      const unsigned char *random1, size_t random1Len,
2072      const unsigned char *random2, size_t random2Len,
2073      unsigned char *buf, size_t bufLen)
2074 {
2075     unsigned char A[RANDOM_LEN] = {0};
2076     unsigned char tmp[RANDOM_LEN] = {0};
2077     size_t dLen;   /* digest length */
2078     size_t len = 0;   /* result length */
2079
2080     VERIFY_NON_NULL_RET(key, NET_SSL_TAG, "key is NULL", -1);
2081     VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", -1);
2082     VERIFY_NON_NULL_RET(random1, NET_SSL_TAG, "random1 is NULL", -1);
2083     VERIFY_NON_NULL_RET(random2, NET_SSL_TAG, "random2 is NULL", -1);
2084     VERIFY_NON_NULL_RET(buf, NET_SSL_TAG, "buf is NULL", -1);
2085
2086     mbedtls_md_context_t hmacA;
2087     mbedtls_md_context_t hmacP;
2088
2089     mbedtls_md_init(&hmacA);
2090     mbedtls_md_init(&hmacP);
2091
2092     CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacA, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
2093     CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacP, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
2094
2095     CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen );
2096     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, label, labelLen);
2097     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random1, random1Len);
2098     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random2, random2Len);
2099     CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);
2100
2101     dLen = RANDOM_LEN;
2102
2103     CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2104
2105     while (len + dLen < bufLen)
2106     {
2107         CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
2108         CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2109         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);
2110         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
2111         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
2112         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);
2113
2114         CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);
2115
2116         len += RANDOM_LEN;
2117
2118         memcpy(buf, tmp, dLen);
2119         buf += dLen;
2120
2121         CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacA);
2122         CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen);
2123         CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, A, dLen);
2124         CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);
2125     }
2126
2127     CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
2128     CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
2129     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);
2130
2131     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
2132     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
2133     CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);
2134     CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);
2135
2136     memcpy(buf, tmp, bufLen - len);
2137
2138     mbedtls_md_free(&hmacA);
2139     mbedtls_md_free(&hmacP);
2140     return bufLen;
2141
2142 exit:
2143     mbedtls_md_free(&hmacA);
2144     mbedtls_md_free(&hmacP);
2145     return -1;
2146 }
2147
2148 CAResult_t CAsslGenerateOwnerPsk(const CAEndpoint_t *endpoint,
2149                             const uint8_t* label, const size_t labelLen,
2150                             const uint8_t* rsrcServerDeviceId, const size_t rsrcServerDeviceIdLen,
2151                             const uint8_t* provServerDeviceId, const size_t provServerDeviceIdLen,
2152                             uint8_t* ownerPsk, const size_t ownerPskSize)
2153 {
2154     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
2155     VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "endpoint is NULL", CA_STATUS_INVALID_PARAM);
2156     VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", CA_STATUS_INVALID_PARAM);
2157     VERIFY_NON_NULL_RET(rsrcServerDeviceId, NET_SSL_TAG, "rsrcId is NULL", CA_STATUS_INVALID_PARAM);
2158     VERIFY_NON_NULL_RET(provServerDeviceId, NET_SSL_TAG, "provId is NULL", CA_STATUS_INVALID_PARAM);
2159     VERIFY_NON_NULL_RET(ownerPsk, NET_SSL_TAG, "ownerPSK is NULL", CA_STATUS_INVALID_PARAM);
2160
2161     // TODO: Added as workaround, need to debug
2162     ca_mutex_unlock(g_sslContextMutex);
2163
2164     ca_mutex_lock(g_sslContextMutex);
2165     if (NULL == g_caSslContext)
2166     {
2167         OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
2168         ca_mutex_unlock(g_sslContextMutex);
2169         OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2170         return CA_STATUS_FAILED;
2171     }
2172     SslEndPoint_t * tep = GetSslPeer(endpoint);
2173     if (NULL == tep)
2174     {
2175         OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
2176         ca_mutex_unlock(g_sslContextMutex);
2177         return CA_STATUS_FAILED;
2178     }
2179
2180     uint8_t keyblock[KEY_BLOCK_LEN] = {0};
2181     // "key expansion"
2182     uint8_t lab[] = {0x6b, 0x65, 0x79, 0x20, 0x65, 0x78, 0x70, 0x61, 0x6e, 0x73, 0x69, 0x6f, 0x6e};
2183     int ret = pHash(tep->master, sizeof(tep->master), lab, sizeof(lab),
2184                     (tep->random) + RANDOM_LEN, RANDOM_LEN, tep->random, RANDOM_LEN,
2185                     keyblock, KEY_BLOCK_LEN);
2186     if (-1 == ret)
2187     {
2188         OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
2189         ca_mutex_unlock(g_sslContextMutex);
2190         return CA_STATUS_FAILED;
2191     }
2192     ret = pHash(keyblock, sizeof(keyblock), label, labelLen,
2193                 rsrcServerDeviceId, rsrcServerDeviceIdLen,
2194                 provServerDeviceId, provServerDeviceIdLen,
2195                 ownerPsk, ownerPskSize);
2196     if (-1 == ret)
2197     {
2198         OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
2199         ca_mutex_unlock(g_sslContextMutex);
2200         return CA_STATUS_FAILED;
2201     }
2202
2203     ca_mutex_unlock(g_sslContextMutex);
2204
2205     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
2206     return CA_STATUS_OK;
2207 }