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