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