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