ca_adapter_net_ssl.c 70.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
/******************************************************************
 *
 * Copyright 2016 Samsung Electronics All Rights Reserved.
 *
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ******************************************************************/

#define _GNU_SOURCE

#include <stddef.h>
#include <stdbool.h>
#include "ca_adapter_net_ssl.h"
#include "cacommon.h"
#include "caipinterface.h"
#include "oic_malloc.h"
#include "byte_array.h"
#include "octhread.h"

// headers required for mbed TLS
#include "mbedtls/platform.h"
#include "mbedtls/ssl.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/pkcs12.h"
#include "mbedtls/ssl_internal.h"
#ifdef __WITH_DTLS__
#include "mbedtls/timing.h"
#include "mbedtls/ssl_cookie.h"
#endif

#ifndef NDEBUG
#include "mbedtls/debug.h"
#include "mbedtls/version.h"
#endif

#ifdef __unix__
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#endif


/**
 * @def MBED_TLS_VERSION_LEN
 * @brief mbedTLS version string length
 */
#define MBED_TLS_VERSION_LEN (16)
/**
 * @def SEED
 * @brief Seed for initialization RNG
 */
#define SEED "IOTIVITY_RND"
/**
 * @def UUID_PREFIX
 * @brief uuid prefix in certificate subject field
 */
#define UUID_PREFIX "uuid:"
/**
 * @def USERID_PREFIX
 * @brief userid prefix in certificate alternative subject name field
 */
#define USERID_PREFIX "userid:"

/**
 * @def NET_SSL_TAG
 * @brief Logging tag for module name
 */
#define NET_SSL_TAG "OIC_CA_NET_SSL"
/**
 * @def MBED_TLS_TAG
 * @brief Logging tag for mbedTLS library
 */
#define MBED_TLS_TAG "MBED_TLS"
/**
 * @def MMBED_TLS_DEBUG_LEVEL
 * @brief Logging level for mbedTLS library
 */
#define MBED_TLS_DEBUG_LEVEL (4)

/**
 * @def TLS_MSG_BUF_LEN
 * @brief Buffer size for TLS record. A single TLS record may be up to 16384 octets in length
 */

#define TLS_MSG_BUF_LEN (16384)
/**
 * @def PSK_LENGTH
 * @brief PSK keys max length
 */
#define PSK_LENGTH (256/8)
/**
 * @def UUID_LENGTHPSK_LENGTH
 * @brief Identity max length
 */
#define UUID_LENGTH (128/8)
/**
 * @def MASTER_SECRET_LEN
 * @brief TLS master secret length
 */
#define MASTER_SECRET_LEN (48)
/**
 * @def RANDOM_LEN
 * @brief TLS client and server random bytes length
 */
#define RANDOM_LEN (32)
/**
 * @def RANDOM_LEN
 * @brief PSK generated keyblock length
 */
#define KEY_BLOCK_LEN (96)

/**@def SSL_CLOSE_NOTIFY(peer, ret)
 *
 * Notifies of existing \a peer about closing TLS connection.
 *
 * @param[in] peer remote peer
 * @param[in] ret used internaly
 */
#define SSL_CLOSE_NOTIFY(peer, ret)                                                                \
do                                                                                                 \
{                                                                                                  \
    (ret) = mbedtls_ssl_close_notify(&(peer)->ssl);                                                \
} while (MBEDTLS_ERR_SSL_WANT_WRITE == (ret))

/**@def SSL_RES(peer, status)
 *
 * Sets SSL result for callback.
 *
 * @param[in] peer remote peer
 */
#define SSL_RES(peer, status)                                                                      \
if (g_sslCallback)                                                                                 \
{                                                                                                  \
    CAErrorInfo_t errorInfo;                                                                       \
    errorInfo.result = (status);                                                                   \
    g_sslCallback(&(peer)->sep.endpoint, &errorInfo);                                              \
}
/**@def SSL_CHECK_FAIL(peer, ret, str, mutex, error, msg)
 *
 * Checks handshake result and send alert if needed.
 *
 * @param[in] peer remote peer
 * @param[in] ret error code
 * @param[in] str debug string
 * @param[in] mutex ca mutex
 * @param[in] return error code
 * @param[in] msg allert message
 */
#define SSL_CHECK_FAIL(peer, ret, str, mutex, error, msg)                                          \
if (0 != (ret) && MBEDTLS_ERR_SSL_WANT_READ != (int) (ret) &&                                      \
    MBEDTLS_ERR_SSL_WANT_WRITE != (int) (ret) &&                                                   \
    MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED != (int) (ret) &&                                        \
    MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY != (int) (ret))                                              \
{                                                                                                  \
    OIC_LOG_V(ERROR, NET_SSL_TAG, "%s: -0x%x", (str), -(ret));                                     \
    if ((int) MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE != (int) (ret) &&                                \
       (int) MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO != (int) (ret))                                   \
    {                                                                                              \
        mbedtls_ssl_send_alert_message(&(peer)->ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, (msg));        \
    }                                                                                              \
Dmitriy Zhuravlev's avatar
Dmitriy Zhuravlev committed
175 176 177 178 179 180 181 182
    if ((int) MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE == (int) (ret) &&                                \
        ((int) MBEDTLS_SSL_ALERT_MSG_DECRYPTION_FAILED == (peer)->ssl.in_msg[1] ||                 \
         (int) MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR == (peer)->ssl.in_msg[1] ||                     \
         (int) MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE == (peer)->ssl.in_msg[1] ||                 \
         (int) MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC == (peer)->ssl.in_msg[1]))                     \
    {                                                                                              \
        SSL_RES((peer), CA_DTLS_AUTHENTICATION_FAILURE);                                           \
    }                                                                                              \
183 184 185 186 187 188 189 190 191 192 193 194 195
    RemovePeerFromList(&(peer)->sep.endpoint);                                                     \
    if (mutex)                                                                                     \
    {                                                                                              \
        oc_mutex_unlock(g_sslContextMutex);                                                        \
    }                                                                                              \
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);                                             \
    return (error);                                                                                \
}
/** @def CHECK_MBEDTLS_RET(f, ...)
 * A macro that checks \a f function return code
 *
 * If function returns error code it goes to error processing.
 *
George Nash's avatar
George Nash committed
196 197 198
 * **IMPORTANT:** Any time CHECK_MBEDTLS_RET is used an `exit:` goto label must
 *                be present to handle error processing.
 *
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
 * @param[in] f  Function to call
 */
#define CHECK_MBEDTLS_RET(f, ...) do {                                                             \
int ret = (f)(__VA_ARGS__);                                                                        \
if (0 != ret) {                                                                                    \
    OIC_LOG_V(ERROR, NET_SSL_TAG, "%s returned -0x%04x\n", __func__, -(ret));                      \
    goto exit;                                                                                     \
} } while(0)

typedef enum
{
    ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA,
    ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
    ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256,
    ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
    ADAPTER_CIPHER_MAX
} AdapterCipher_t;

typedef enum
{
    ADAPTER_CURVE_SECP256R1,
    ADAPTER_CURVE_MAX
} AdapterCurve_t;

int tlsCipher[ADAPTER_CIPHER_MAX][2] =
{
    {MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA, 0},
    {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, 0},
    {MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256, 0},
    {MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, 0}
};

static int g_cipherSuitesList[ADAPTER_CIPHER_MAX];

mbedtls_ecp_group_id curve[ADAPTER_CURVE_MAX][2] =
{
    {MBEDTLS_ECP_DP_SECP256R1, MBEDTLS_ECP_DP_NONE}
};

static PkiInfo_t g_pkiInfo = {{NULL, 0}, {NULL, 0}, {NULL, 0}, {NULL, 0}};

typedef struct  {
    int code;
    int alert;
} CrtVerifyAlert_t;

static const CrtVerifyAlert_t crtVerifyAlerts[] = {
    {MBEDTLS_X509_BADCERT_EXPIRED,       MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED},
    {MBEDTLS_X509_BADCERT_REVOKED,       MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED},
    {MBEDTLS_X509_BADCERT_CN_MISMATCH,   MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN},
    {MBEDTLS_X509_BADCERT_NOT_TRUSTED,   MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA},
    {MBEDTLS_X509_BADCRL_NOT_TRUSTED,    MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA},
    {MBEDTLS_X509_BADCRL_EXPIRED,        MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
    {MBEDTLS_X509_BADCERT_MISSING,       MBEDTLS_SSL_ALERT_MSG_NO_CERT},
    {MBEDTLS_X509_BADCERT_SKIP_VERIFY,   MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
    {MBEDTLS_X509_BADCERT_OTHER,         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR},
    {MBEDTLS_X509_BADCERT_FUTURE,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
    {MBEDTLS_X509_BADCRL_FUTURE,         MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
    {MBEDTLS_X509_BADCERT_KEY_USAGE,     MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
    {MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
    {MBEDTLS_X509_BADCERT_NS_CERT_TYPE,  MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
    {MBEDTLS_X509_BADCERT_BAD_MD,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
    {MBEDTLS_X509_BADCERT_BAD_PK,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
    {MBEDTLS_X509_BADCERT_BAD_KEY,       MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
    {MBEDTLS_X509_BADCRL_BAD_MD,         MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
    {MBEDTLS_X509_BADCRL_BAD_PK,         MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
    {MBEDTLS_X509_BADCRL_BAD_KEY,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
    {0, 0}
};

static int GetAlertCode(uint32_t flags)
{
    const CrtVerifyAlert_t *cur;

    for (cur = crtVerifyAlerts; cur->alert != 0 ; cur++)
    {
        if (flags & cur->code)
        {
            return cur->alert;
        }
    }
    return 0;
}

#ifndef NDEBUG
/**
 * Pass a message to the OIC logger.
 *
 * @param[in] ctx  opaque context for the callback
 * @param[in] level  debug level
 * @param[in] file  file name
 * @param[in] line  line number
 * @param[in] str  message
 */
static void DebugSsl(void *ctx, int level, const char *file, int line, const char *str)
{
    ((void) level);
    ((void) file);
    ((void) line);
    ((void) ctx);

    OIC_LOG_V(DEBUG, MBED_TLS_TAG, "%s", str);
}
#endif

#if defined(_WIN32)
/*
 * Finds the first occurrence of the byte string s in byte string l.
 */

static void * memmem(const void *l, size_t lLen, const void *s, size_t sLen)
{
    char *cur;
    char *last;
    const char *cl = (const char *)l;
    const char *cs = (const char *)s;

    if (lLen == 0 || sLen == 0)
    {
        return NULL;
    }
    if (lLen < sLen)
    {
        return NULL;
    }
    if (sLen == 1)
    {
326
        return (void *)memchr(l, (int)*cs, lLen);
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
    }

    last = (char *)cl + lLen - sLen;

    for (cur = (char *)cl; cur <= last; cur++)
    {
        if (cur[0] == cs[0] && memcmp(cur, cs, sLen) == 0)
        {
            return cur;
        }
    }
    return NULL;
}
#endif
/**
 * structure to holds the information of cache message and address info.
 */
typedef ByteArray_t SslCacheMessage_t;


/**
 * Data structure for holding the send and recv callbacks.
 */
typedef struct TlsCallBacks
{
    CAPacketReceivedCallback recvCallback;  /**< Callback used to send data to upper layer. */
    CAPacketSendCallback sendCallback;      /**< Callback used to send data to socket layer. */
} SslCallbacks_t;

/**
 * Data structure for holding the mbedTLS interface related info.
 */
typedef struct SslContext
{
    u_arraylist_t *peerList;         /**< peer list which holds the mapping between
                                              peer id, it's n/w address and mbedTLS context. */
    mbedtls_entropy_context entropy;
    mbedtls_ctr_drbg_context rnd;
    mbedtls_x509_crt ca;
    mbedtls_x509_crt crt;
    mbedtls_pk_context pkey;

    mbedtls_ssl_config clientTlsConf;
    mbedtls_ssl_config serverTlsConf;
    mbedtls_ssl_config clientDtlsConf;
    mbedtls_ssl_config serverDtlsConf;
#ifdef __WITH_DTLS__
    mbedtls_ssl_cookie_ctx cookie_ctx;
    mbedtls_timing_delay_context timer;
#endif // __WITH_DTLS__
    AdapterCipher_t cipher;
    SslCallbacks_t adapterCallbacks[MAX_SUPPORTED_ADAPTERS];
    mbedtls_x509_crl crl;
    bool cipherFlag[2];
    int selectedCipher;

} SslContext_t;

/**
 * @var g_caSslContext
 * @brief global context which holds tls context and cache list information.
 */
static SslContext_t * g_caSslContext = NULL;

/**
 * @var g_getCredentialsCallback
 * @brief callback to get TLS credentials (same as for DTLS)
 */
static CAgetPskCredentialsHandler g_getCredentialsCallback = NULL;
/**
 * @var g_getCerdentilTypesCallback
 * @brief callback to get different credential types from SRM
 */
static CAgetCredentialTypesHandler g_getCredentialTypesCallback = NULL;
/**
 * @var g_getPkixInfoCallback
 *
 * @brief callback to get X.509-based Public Key Infrastructure
 */
static CAgetPkixInfoHandler g_getPkixInfoCallback = NULL;

/**
 * @var g_dtlsContextMutex
 * @brief Mutex to synchronize access to g_caSslContext.
 */
static oc_mutex g_sslContextMutex = NULL;

/**
 * @var g_sslCallback
 * @brief callback to deliver the TLS handshake result
 */
static CAErrorCallback g_sslCallback = NULL;

/**
 * Data structure for holding the data to be received.
 */
typedef struct SslRecBuf
{
    uint8_t * buff;
    size_t len;
    size_t loaded;
} SslRecBuf_t;
/**
 * Data structure for holding the data related to endpoint
 * and TLS session.
 */
typedef struct SslEndPoint
{
    mbedtls_ssl_context ssl;
    CASecureEndpoint_t sep;
    u_arraylist_t * cacheList;
    SslRecBuf_t recBuf;
    uint8_t master[MASTER_SECRET_LEN];
    uint8_t random[2*RANDOM_LEN];
#ifdef __WITH_DTLS__
    mbedtls_ssl_cookie_ctx cookieCtx;
#endif

} SslEndPoint_t;

void CAsetPskCredentialsCallback(CAgetPskCredentialsHandler credCallback)
{
    // TODO Does this method needs protection of tlsContextMutex?
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    g_getCredentialsCallback = credCallback;
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
}

void CAsetPkixInfoCallback(CAgetPkixInfoHandler infoCallback)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    g_getPkixInfoCallback = infoCallback;
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
}
void CAsetCredentialTypesCallback(CAgetCredentialTypesHandler credTypesCallback)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    g_getCredentialTypesCallback = credTypesCallback;
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
}

static int GetAdapterIndex(CATransportAdapter_t adapter)
{
    switch (adapter)
    {
        case CA_ADAPTER_IP:
            return 0;
        case CA_ADAPTER_TCP:
            return 1;
        default:
            OIC_LOG(ERROR, NET_SSL_TAG, "Unsupported adapter");
            return -1;
    }
}
/**
 * Write callback.
 *
 * @param[in]  tep    TLS endpoint
 * @param[in]  data    message
 * @param[in]  dataLen    message length
 *
 * @return  message length
 */
static int SendCallBack(void * tep, const unsigned char * data, size_t dataLen)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(tep, NET_SSL_TAG, "secure endpoint is NULL", 0);
    VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "data is NULL", 0);
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data len: %zu", dataLen);
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Adapter: %u", ((SslEndPoint_t * )tep)->sep.endpoint.adapter);
    int adapterIndex = GetAdapterIndex(((SslEndPoint_t * )tep)->sep.endpoint.adapter);
    if (0 == adapterIndex || 1 == adapterIndex)
    {
        CAPacketSendCallback sendCallback = g_caSslContext->adapterCallbacks[adapterIndex].sendCallback;
        sendCallback(&(((SslEndPoint_t * )tep)->sep.endpoint), (const void *) data, (uint32_t) dataLen);
    }
    else
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Unsupported adapter");
        dataLen = 0;
    }

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return dataLen;
}
/**
 * Read callback.
 *
 * @param[in]  tep    TLS endpoint
 * @param[in]  data    message
 * @param[in]  dataLen    message length
 *
 * @return  read length
 */
static int RecvCallBack(void * tep, unsigned char * data, size_t dataLen)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(tep, NET_SSL_TAG, "endpoint is NULL", 0);
    VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "data is NULL", 0);

    SslRecBuf_t *recBuf = &((SslEndPoint_t *)tep)->recBuf;
    size_t retLen = (recBuf->len > recBuf->loaded ? recBuf->len - recBuf->loaded : 0);
    retLen = (retLen < dataLen ? retLen : dataLen);

    memcpy(data, recBuf->buff + recBuf->loaded, retLen);
    recBuf->loaded += retLen;

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return (int)retLen;
}

/**
 * Parse chain of X.509 certificates.
 *
 * @param[out] crt     container for X.509 certificates
George Nash's avatar
George Nash committed
542
 * @param[in]  buf     buffer with X.509 certificates. Certificates may be in either in PEM
543 544 545 546 547
                       or DER format in a jumble. Each PEM certificate must be NULL-terminated.
 * @param[in]  bufLen  buffer length
 *
 * @return  0 on success, -1 on error
 */
George Nash's avatar
George Nash committed
548
static int ParseChain(mbedtls_x509_crt * crt, const unsigned char * buf, size_t bufLen)
549 550 551 552 553
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(crt, NET_SSL_TAG, "Param crt is NULL" , -1);
    VERIFY_NON_NULL_RET(buf, NET_SSL_TAG, "Param buf is NULL" , -1);

George Nash's avatar
George Nash committed
554
    size_t pos = 0;
555 556
    size_t len = 0;
    unsigned char * tmp = NULL;
George Nash's avatar
George Nash committed
557
    /* byte encoded ASCII string '-----BEGIN CERTIFICATE-----' */
558 559 560 561
    char pemCertHeader[] = {
        0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x43, 0x45, 0x52,
        0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d
    };
George Nash's avatar
George Nash committed
562
    // byte encoded ASCII string '-----END CERTIFICATE-----' */
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
    char pemCertFooter[] = {
        0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49,
        0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d
    };
    size_t pemCertHeaderLen = sizeof(pemCertHeader);
    size_t pemCertFooterLen = sizeof(pemCertFooter);

    while (pos < bufLen)
    {
        if (buf[pos] == 0x30 && buf[pos + 1] == 0x82)
        {
            tmp = (unsigned char *)buf + pos + 1;
            CHECK_MBEDTLS_RET(mbedtls_asn1_get_len, &tmp, buf + bufLen, &len);
            if (pos + len < bufLen)
            {
                CHECK_MBEDTLS_RET(mbedtls_x509_crt_parse_der, crt, buf + pos, len + 4);
            }
            pos += len + 4;
        }
        else if (0 == memcmp(buf + pos, pemCertHeader, pemCertHeaderLen))
        {
            void * endPos = NULL;
            endPos = memmem(&(buf[pos]), bufLen - pos, pemCertFooter, pemCertFooterLen);
            if (NULL == endPos)
            {
                OIC_LOG(ERROR, NET_SSL_TAG, "Error: end of PEM certificate not found.");
                OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
                return -1;
            }
            if ((*((char*)endPos + pemCertFooterLen + 0) == 0x0d) &&
                (*((char*)endPos + pemCertFooterLen + 1) == 0x0a) &&
                (*((char*)endPos + pemCertFooterLen + 2) == 0x00))
            {
                len = (char*)endPos - ((char*)buf + pos) + pemCertFooterLen + 3;
            }
            else if ((*((char*)endPos + pemCertFooterLen + 0) == 0x0a) &&
                     (*((char*)endPos + pemCertFooterLen + 1) == 0x00))
            {
                len = (char*)endPos - ((char*)buf + pos) + pemCertFooterLen + 2;
            }
            else
            {
                OIC_LOG_V(ERROR, NET_SSL_TAG, "Incorrect PEM certificate ending");
                OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
                return -1;
            }
            CHECK_MBEDTLS_RET(mbedtls_x509_crt_parse, crt, buf + pos, len);
            pos += len;
        }
        else
        {
             OIC_LOG_BUFFER(DEBUG, NET_SSL_TAG, buf, bufLen);
             OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
             return -1;
        }
    }
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return 0;
George Nash's avatar
George Nash committed
621
    // exit label required for CHECK_MBEDTLS_RET macro
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
exit:
    return -1;
}

//Loads PKIX related information from SRM
static int InitPKIX(CATransportAdapter_t adapter)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(g_getPkixInfoCallback, NET_SSL_TAG, "PKIX info callback is NULL", -1);
    g_getPkixInfoCallback(&g_pkiInfo);

    mbedtls_x509_crt_free(&g_caSslContext->ca);
    mbedtls_x509_crt_free(&g_caSslContext->crt);
    mbedtls_pk_free(&g_caSslContext->pkey);
    mbedtls_x509_crl_free(&g_caSslContext->crl);

    mbedtls_x509_crt_init(&g_caSslContext->ca);
    mbedtls_x509_crt_init(&g_caSslContext->crt);
    mbedtls_pk_init(&g_caSslContext->pkey);
    mbedtls_x509_crl_init(&g_caSslContext->crl);

    mbedtls_ssl_config * serverConf = (adapter == CA_ADAPTER_IP ?
                                   &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
    mbedtls_ssl_config * clientConf = (adapter == CA_ADAPTER_IP ?
                                   &g_caSslContext->clientDtlsConf : &g_caSslContext->clientTlsConf);
    // optional
    int ret = ParseChain(&g_caSslContext->crt, g_pkiInfo.crt.data, g_pkiInfo.crt.len);
    if (0 != ret)
    {
        OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate chain parsing error");
        goto required;
    }
    ret =  mbedtls_pk_parse_key(&g_caSslContext->pkey, g_pkiInfo.key.data, g_pkiInfo.key.len,
                                                                               NULL, 0);
    if (0 != ret)
    {
        OIC_LOG(WARNING, NET_SSL_TAG, "Key parsing error");
        goto required;
    }

    ret = mbedtls_ssl_conf_own_cert(serverConf, &g_caSslContext->crt, &g_caSslContext->pkey);
    if (0 != ret)
    {
        OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate parsing error");
        goto required;
    }
    ret = mbedtls_ssl_conf_own_cert(clientConf, &g_caSslContext->crt, &g_caSslContext->pkey);
    if(0 != ret)
    {
        OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate configuration error");
        goto required;
    }

    required:
    ret = ParseChain(&g_caSslContext->ca, g_pkiInfo.ca.data, g_pkiInfo.ca.len);
    if(0 != ret)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "CA chain parsing error");
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        return -1;
    }

    ret = mbedtls_x509_crl_parse_der(&g_caSslContext->crl, g_pkiInfo.crl.data, g_pkiInfo.crl.len);
    if(0 != ret)
    {
        OIC_LOG(WARNING, NET_SSL_TAG, "CRL parsing error");
        mbedtls_ssl_conf_ca_chain(clientConf, &g_caSslContext->ca, NULL);
        mbedtls_ssl_conf_ca_chain(serverConf, &g_caSslContext->ca, NULL);
    }
    else
    {
        mbedtls_ssl_conf_ca_chain(clientConf, &g_caSslContext->ca, &g_caSslContext->crl);
        mbedtls_ssl_conf_ca_chain(serverConf, &g_caSslContext->ca, &g_caSslContext->crl);
    }

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return 0;
}

/*
 * PSK callback.
 *
 * @param[in]  notUsed     opaque context
 * @param[in]  ssl    mbedTLS context
 * @param[in]  desc    identity
 * @param[in]  descLen    identity length
 *
 * @return  0 on success any other return value will result in a denied PSK identity
 */
static int GetPskCredentialsCallback(void * notUsed, mbedtls_ssl_context * ssl,
                                     const unsigned char * desc, size_t descLen)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(g_getCredentialsCallback, NET_SSL_TAG, "Credential callback s NULL", -1);
    VERIFY_NON_NULL_RET(ssl, NET_SSL_TAG, "ssl pointer is NULL", -1);
    VERIFY_NON_NULL_RET(desc, NET_SSL_TAG, "desc pointer is NULL", -1);
    if (descLen > CA_MAX_ENDPOINT_IDENTITY_LEN)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "desc too long!");
        return -1;
    }
    (void) notUsed;
    uint8_t keyBuf[PSK_LENGTH] = {0};

    // Retrieve the credentials blob from security module
    int ret = g_getCredentialsCallback(CA_DTLS_PSK_KEY, desc, descLen, keyBuf, PSK_LENGTH);
    if (ret > 0)
    {
        memcpy(((SslEndPoint_t *) ssl)->sep.identity.id, desc, descLen);
        ((SslEndPoint_t *) ssl)->sep.identity.id_length = descLen;
        OIC_LOG(DEBUG, NET_SSL_TAG, "PSK:");
        OIC_LOG_BUFFER(DEBUG, NET_SSL_TAG, keyBuf, ret);

        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        return(mbedtls_ssl_set_hs_psk(ssl, keyBuf, ret));
    }
    OIC_LOG_V(WARNING, NET_SSL_TAG, "Out %s", __func__);
    return -1;
}
/**
 * Gets session corresponding for endpoint.
 *
 * @param[in]  peer    remote address
 *
 * @return  TLS session or NULL
 */
static SslEndPoint_t *GetSslPeer(const CAEndpoint_t *peer)
{
    uint32_t listIndex = 0;
    uint32_t listLength = 0;
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(peer, NET_SSL_TAG, "TLS peer is NULL", NULL);

    SslEndPoint_t *tep = NULL;
    listLength = u_arraylist_length(g_caSslContext->peerList);
    for (listIndex = 0; listIndex < listLength; listIndex++)
    {
        tep = (SslEndPoint_t *) u_arraylist_get(g_caSslContext->peerList, listIndex);
        if (NULL == tep)
        {
            continue;
        }
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Compare [%s:%d] and [%s:%d]",
                  peer->addr, peer->port, tep->sep.endpoint.addr, tep->sep.endpoint.port);
        if((0 == strncmp(peer->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA))
                && (peer->port == tep->sep.endpoint.port))
        {
            OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
            return tep;
        }
    }
    OIC_LOG(DEBUG, NET_SSL_TAG, "Return NULL");
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return NULL;
}
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815

#ifdef _ENABLE_MULTIPLE_OWNER_
/**
 * Gets CA secure endpoint info corresponding for endpoint.
 *
 * @param[in]  peer    remote address
 *
 * @return  CASecureEndpoint or NULL
 */
const CASecureEndpoint_t *GetCASecureEndpointData(const CAEndpoint_t* peer)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);

    // TODO: Added as workaround, need to debug
    oc_mutex_unlock(g_sslContextMutex);

    oc_mutex_lock(g_sslContextMutex);
    if (NULL == g_caSslContext)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
        oc_mutex_unlock(g_sslContextMutex);
        return NULL;
    }

    SslEndPoint_t* sslPeer = GetSslPeer(peer);
    if(sslPeer)
    {
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        oc_mutex_unlock(g_sslContextMutex);
        return &sslPeer->sep;
    }

    OIC_LOG(DEBUG, NET_SSL_TAG, "Return NULL");
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    oc_mutex_unlock(g_sslContextMutex);
    return NULL;
}
#endif

816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
/**
 * Deletes cached message.
 *
 * @param[in]  msg    message
 */
static void DeleteCacheMessage(SslCacheMessage_t * msg)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_VOID(msg, NET_SSL_TAG, "msg");

    OICFree(msg->data);
    OICFree(msg);

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
}
/**
 * Deletes cached message list.
 *
 * @param[in] cacheList  list of cached messages
 */
static void DeleteCacheList(u_arraylist_t * cacheList)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_VOID(cacheList, NET_SSL_TAG, "cacheList");
    uint32_t listIndex = 0;
    uint32_t listLength = 0;

    listLength = u_arraylist_length(cacheList);
    for (listIndex = 0; listIndex < listLength; listIndex++)
    {
        SslCacheMessage_t * msg = (SslCacheMessage_t *) u_arraylist_get(cacheList, listIndex);
        if (NULL != msg)
        {
            DeleteCacheMessage(msg);
        }
    }
    u_arraylist_free(&cacheList);

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
}
/**
 * Deletes endpoint with session.
 *
 * @param[in]  tep    endpoint with session info
 */
static void DeleteSslEndPoint(SslEndPoint_t * tep)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_VOID(tep, NET_SSL_TAG, "tep");

    mbedtls_ssl_free(&tep->ssl);
#ifdef __WITH_DTLS__
    mbedtls_ssl_cookie_free(&tep->cookieCtx);
#endif
    DeleteCacheList(tep->cacheList);
    OICFree(tep);
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
}
/**
 * Removes endpoint session from list.
 *
 * @param[in]  endpoint    remote address
 */
static void RemovePeerFromList(CAEndpoint_t * endpoint)
{
    uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
    VERIFY_NON_NULL_VOID(endpoint, NET_SSL_TAG, "endpoint");
    for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
    {
        SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList,listIndex);
        if (NULL == tep)
        {
            continue;
        }
        if(0 == strncmp(endpoint->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA)
                && (endpoint->port == tep->sep.endpoint.port))
        {
            u_arraylist_remove(g_caSslContext->peerList, listIndex);
            DeleteSslEndPoint(tep);
            return;
        }
    }
}
/**
 * Deletes session list.
 */
static void DeletePeerList()
{
    uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
    for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
    {
        SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList,listIndex);
        if (NULL == tep)
        {
            continue;
        }
        DeleteSslEndPoint(tep);
    }
    u_arraylist_free(&g_caSslContext->peerList);
}

CAResult_t CAcloseSslConnection(const CAEndpoint_t *endpoint)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);

    oc_mutex_lock(g_sslContextMutex);
    if (NULL == g_caSslContext)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
        oc_mutex_unlock(g_sslContextMutex);
        return CA_STATUS_FAILED;
    }
    SslEndPoint_t * tep = GetSslPeer(endpoint);
    if (NULL == tep)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
        oc_mutex_unlock(g_sslContextMutex);
        return CA_STATUS_FAILED;
    }
    /* No error checking, the connection might be closed already */
    int ret = 0;
    do
    {
        ret = mbedtls_ssl_close_notify(&tep->ssl);
    }
    while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);

    RemovePeerFromList(&tep->sep.endpoint);
    oc_mutex_unlock(g_sslContextMutex);

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return CA_STATUS_OK;
}
/**
 * Creates session for endpoint.
 *
 * @param[in]  endpoint    remote address
 * @param[in]  config    mbedTLS configuration info
 *
 * @return  TLS endpoint or NULL
 */
static SslEndPoint_t * NewSslEndPoint(const CAEndpoint_t * endpoint, mbedtls_ssl_config * config)
{
    SslEndPoint_t * tep = NULL;
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "endpoint", NULL);
    VERIFY_NON_NULL_RET(config, NET_SSL_TAG, "config", NULL);

    tep = (SslEndPoint_t *) OICCalloc(1, sizeof (SslEndPoint_t));
    if (NULL == tep)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
        return NULL;
    }

    tep->sep.endpoint = *endpoint;
    tep->sep.endpoint.flags = (CATransportFlags_t)(tep->sep.endpoint.flags | CA_SECURE);

    if(0 != mbedtls_ssl_setup(&tep->ssl, config))
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Setup failed");
        OICFree(tep);
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        return NULL;
    }

    mbedtls_ssl_set_bio(&tep->ssl, tep, SendCallBack, RecvCallBack, NULL);
    if (MBEDTLS_SSL_TRANSPORT_DATAGRAM == config->transport)
    {
        mbedtls_ssl_set_timer_cb(&tep->ssl, &g_caSslContext->timer,
                                  mbedtls_timing_set_delay, mbedtls_timing_get_delay);
        if (MBEDTLS_SSL_IS_SERVER == config->endpoint)
        {
            if (0 != mbedtls_ssl_cookie_setup(&tep->cookieCtx, mbedtls_ctr_drbg_random,
                                              &g_caSslContext->rnd))
            {
                OIC_LOG(ERROR, NET_SSL_TAG, "Cookie setup failed!");
                OICFree(tep);
                OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
                return NULL;
            }
            mbedtls_ssl_conf_dtls_cookies(config, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check,
                                          &tep->cookieCtx);
            if (0 != mbedtls_ssl_set_client_transport_id(&tep->ssl,
                                    (const unsigned char *) endpoint->addr, sizeof(endpoint->addr)))
            {
                OIC_LOG(ERROR, NET_SSL_TAG, "Transport id setup failed!");
                OICFree(tep);
                OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
                return NULL;
            }
        }
    }
    tep->cacheList = u_arraylist_create();
    if (NULL == tep->cacheList)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "cacheList initialization failed!");
        mbedtls_ssl_free(&tep->ssl);
        OICFree(tep);
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        return NULL;
    }
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return tep;
}
/**
 * Initializes PSK identity.
 *
 * @param[out]  config    client/server config to be updated
 *
 * @return  0 on success or -1 on error
 */
static int InitPskIdentity(mbedtls_ssl_config * config)
{
    uint8_t idBuf[UUID_LENGTH] = {0};
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(config, NET_SSL_TAG, "Param config is NULL" , -1);

    if (0 > g_getCredentialsCallback(CA_DTLS_PSK_IDENTITY, NULL, 0, idBuf, UUID_LENGTH))
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Identity not found");
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        return -1;
    }
    if (0 != mbedtls_ssl_conf_psk(config, idBuf, 0, idBuf, UUID_LENGTH))
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Identity initialization failed!");
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        return -1;
    }
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return 0;
}
static void SetupCipher(mbedtls_ssl_config * config, CATransportAdapter_t adapter)
{
    int index = 0;
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    if (NULL == g_getCredentialTypesCallback)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Param callback is null");
        return;
    }

    g_getCredentialTypesCallback(g_caSslContext->cipherFlag);
    // Retrieve the PSK credential from SRM
    // PIN OTM if (true == g_caSslContext->cipherFlag[0] && 0 != InitPskIdentity(config))
    if (0 != InitPskIdentity(config))
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "PSK identity initialization failed!");
    }

    // Retrieve the ECC credential from SRM
    if (true == g_caSslContext->cipherFlag[1] || ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA == g_caSslContext->cipher)
    {
        int ret = InitPKIX(adapter);
        if (0 != ret)
        {
            OIC_LOG(ERROR, NET_SSL_TAG, "Failed to init X.509");
        }
    }

    memset(g_cipherSuitesList, 0, sizeof(g_cipherSuitesList));
    if (ADAPTER_CIPHER_MAX != g_caSslContext->cipher)
    {
        g_cipherSuitesList[index] = tlsCipher[g_caSslContext->cipher][0];
        index ++;
    }
    if (true == g_caSslContext->cipherFlag[1])
    {
        g_cipherSuitesList[index] = MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
        index ++;
    }
    if (true == g_caSslContext->cipherFlag[0])
    {
       g_cipherSuitesList[index] = MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
    }

    mbedtls_ssl_conf_ciphersuites(config, g_cipherSuitesList);

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
}
/**
 * Initiate TLS handshake with endpoint.
 *
 * @param[in]  endpoint    remote address
 *
 * @return  TLS endpoint or NULL
 */
static SslEndPoint_t * InitiateTlsHandshake(const CAEndpoint_t *endpoint)
{
    int ret = 0;
    SslEndPoint_t * tep = NULL;

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , NULL);


    mbedtls_ssl_config * config = (endpoint->adapter == CA_ADAPTER_IP ?
                                   &g_caSslContext->clientDtlsConf : &g_caSslContext->clientTlsConf);
    tep = NewSslEndPoint(endpoint, config);
    if (NULL == tep)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
        return NULL;
    }

    //Load allowed SVR suites from SVR DB
    SetupCipher(config, endpoint->adapter);

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Add %s:%d", tep->sep.endpoint.addr, tep->sep.endpoint.port);
    ret = u_arraylist_add(g_caSslContext->peerList, (void *) tep);
    if (!ret)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
        DeleteSslEndPoint(tep);
        return NULL;
    }

    while (MBEDTLS_SSL_HANDSHAKE_OVER > tep->ssl.state)
    {
        ret = mbedtls_ssl_handshake_step(&tep->ssl);
        if (MBEDTLS_ERR_SSL_CONN_EOF == ret)
        {
            break;
        }
        SSL_CHECK_FAIL(tep, ret, "Handshake error", 0, NULL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
    }
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return tep;
}

void CAdeinitSslAdapter()
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);

    VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "context is NULL");
    VERIFY_NON_NULL_VOID(g_sslContextMutex, NET_SSL_TAG, "context mutex is NULL");

    //Lock tlsContext mutex
    oc_mutex_lock(g_sslContextMutex);

    // Clear all lists
    DeletePeerList();

    // De-initialize mbedTLS
    mbedtls_x509_crt_free(&g_caSslContext->crt);
    mbedtls_pk_free(&g_caSslContext->pkey);
#ifdef __WITH_TLS__
    mbedtls_ssl_config_free(&g_caSslContext->clientTlsConf);
    mbedtls_ssl_config_free(&g_caSslContext->serverTlsConf);
#endif // __WITH_TLS__
#ifdef __WITH_DTLS__
    mbedtls_ssl_config_free(&g_caSslContext->clientDtlsConf);
    mbedtls_ssl_config_free(&g_caSslContext->serverDtlsConf);
#endif // __WITH_DTLS__
    mbedtls_ctr_drbg_free(&g_caSslContext->rnd);
    mbedtls_entropy_free(&g_caSslContext->entropy);

    // De-initialize tls Context
    OICFree(g_caSslContext);
    g_caSslContext = NULL;

    // Unlock tlsContext mutex and de-initialize it
    oc_mutex_unlock(g_sslContextMutex);
    oc_mutex_free(g_sslContextMutex);
    g_sslContextMutex = NULL;

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s ", __func__);
}

static int InitConfig(mbedtls_ssl_config * conf, int transport, int mode)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(conf, NET_SSL_TAG, "Param conf is NULL" , -1);
    mbedtls_ssl_config_init(conf);
    if (mbedtls_ssl_config_defaults(conf, mode, transport, MBEDTLS_SSL_PRESET_DEFAULT) != 0)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Config initialization failed!");
        return -1;
    }

    mbedtls_ssl_conf_psk_cb(conf, GetPskCredentialsCallback, NULL);
    mbedtls_ssl_conf_rng(conf, mbedtls_ctr_drbg_random, &g_caSslContext->rnd);
    mbedtls_ssl_conf_curves(conf, curve[ADAPTER_CURVE_SECP256R1]);
    mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
    mbedtls_ssl_conf_renegotiation(conf, MBEDTLS_SSL_RENEGOTIATION_DISABLED);
    mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);

#ifndef NDEBUG
    mbedtls_ssl_conf_dbg(conf, DebugSsl, NULL);
    mbedtls_debug_set_threshold(MBED_TLS_DEBUG_LEVEL);
#endif
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return 0;
}

CAResult_t CAinitSslAdapter()
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    // Initialize mutex for tlsContext
    if (NULL == g_sslContextMutex)
    {
        g_sslContextMutex = oc_mutex_new();
        VERIFY_NON_NULL_RET(g_sslContextMutex, NET_SSL_TAG, "malloc failed", CA_MEMORY_ALLOC_FAILED);
    }
    else
    {
        OIC_LOG(INFO, NET_SSL_TAG, "Done already!");
        return CA_STATUS_OK;
    }

    // Lock tlsContext mutex and create tlsContext
    oc_mutex_lock(g_sslContextMutex);
    g_caSslContext = (SslContext_t *)OICCalloc(1, sizeof(SslContext_t));

    if (NULL == g_caSslContext)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Context malloc failed");
        oc_mutex_unlock(g_sslContextMutex);
        oc_mutex_free(g_sslContextMutex);
        g_sslContextMutex = NULL;
        return CA_MEMORY_ALLOC_FAILED;
    }

    // Create peer list
    g_caSslContext->peerList = u_arraylist_create();

    if(NULL == g_caSslContext->peerList)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "peerList initialization failed!");
        OICFree(g_caSslContext);
        g_caSslContext = NULL;
        oc_mutex_unlock(g_sslContextMutex);
        oc_mutex_free(g_sslContextMutex);
        g_sslContextMutex = NULL;
        return CA_STATUS_FAILED;
    }

    /* Initialize TLS library
     */
#ifndef NDEBUG
    char version[MBED_TLS_VERSION_LEN];
    mbedtls_version_get_string(version);
    OIC_LOG_V(INFO, NET_SSL_TAG, "mbed TLS version: %s", version);
#endif

    /* Entropy settings
     */
    mbedtls_entropy_init(&g_caSslContext->entropy);
    mbedtls_ctr_drbg_init(&g_caSslContext->rnd);

#ifdef __unix__
    unsigned char seed[sizeof(SEED)] = {0};
    int urandomFd = -2;
    urandomFd = open("/dev/urandom", O_RDONLY);
    if(urandomFd == -1)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Fails open /dev/urandom!");
        oc_mutex_unlock(g_sslContextMutex);
        CAdeinitSslAdapter();
        return CA_STATUS_FAILED;
    }
    if(0 > read(urandomFd, seed, sizeof(seed)))
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Fails read from /dev/urandom!");
        close(urandomFd);
        oc_mutex_unlock(g_sslContextMutex);
        CAdeinitSslAdapter();
        return CA_STATUS_FAILED;
    }
    close(urandomFd);

#else
    unsigned char * seed = (unsigned char*) SEED;
#endif
    if(0 != mbedtls_ctr_drbg_seed(&g_caSslContext->rnd, mbedtls_entropy_func,
                                  &g_caSslContext->entropy, seed, sizeof(SEED)))
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Seed initialization failed!");
        oc_mutex_unlock(g_sslContextMutex);
        CAdeinitSslAdapter();
        return CA_STATUS_FAILED;
    }
    mbedtls_ctr_drbg_set_prediction_resistance(&g_caSslContext->rnd, MBEDTLS_CTR_DRBG_PR_OFF);

#ifdef __WITH_TLS__
    if (0 != InitConfig(&g_caSslContext->clientTlsConf,
                        MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_CLIENT))
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
        oc_mutex_unlock(g_sslContextMutex);
        CAdeinitSslAdapter();
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        return CA_STATUS_FAILED;
    }

    if (0 != InitConfig(&g_caSslContext->serverTlsConf,
                        MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_SERVER))
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
        oc_mutex_unlock(g_sslContextMutex);
        CAdeinitSslAdapter();
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        return CA_STATUS_FAILED;
    }
#endif // __WITH_TLS__
#ifdef __WITH_DTLS__
    if (0 != InitConfig(&g_caSslContext->clientDtlsConf,
                        MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_CLIENT))
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
        oc_mutex_unlock(g_sslContextMutex);
        CAdeinitSslAdapter();
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        return CA_STATUS_FAILED;
    }

    if (0 != InitConfig(&g_caSslContext->serverDtlsConf,
                        MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_SERVER))
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
        oc_mutex_unlock(g_sslContextMutex);
        CAdeinitSslAdapter();
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        return CA_STATUS_FAILED;
    }
#endif // __WITH_DTLS__

    // set default cipher
    g_caSslContext->cipher = ADAPTER_CIPHER_MAX;

    // init X.509
    mbedtls_x509_crt_init(&g_caSslContext->ca);
    mbedtls_x509_crt_init(&g_caSslContext->crt);
    mbedtls_pk_init(&g_caSslContext->pkey);
    mbedtls_x509_crl_init(&g_caSslContext->crl);

    oc_mutex_unlock(g_sslContextMutex);

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return CA_STATUS_OK;
}

SslCacheMessage_t *  NewCacheMessage(uint8_t * data, size_t dataLen)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , NULL);
    if (0 == dataLen)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "dataLen is equal to zero");
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        return NULL;
    }
    SslCacheMessage_t * message = (SslCacheMessage_t *) OICCalloc(1, sizeof(SslCacheMessage_t));
    if (NULL == message)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        return NULL;
    }

    message->data = (uint8_t *)OICCalloc(dataLen, sizeof(uint8_t));
    if (NULL == message->data)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
        OICFree(message);
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        return NULL;
    }
    memcpy(message->data, data, dataLen);
    message->len = dataLen;
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return message;
}

/* Send data via TLS connection.
 */
CAResult_t CAencryptSsl(const CAEndpoint_t *endpoint,
                        void *data, uint32_t dataLen)
{
    int ret = 0;

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s ", __func__);

    VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG,"Remote address is NULL", CA_STATUS_INVALID_PARAM);
    VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Data is NULL", CA_STATUS_INVALID_PARAM);
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Port %d", endpoint->port);

    if (0 == dataLen)
    {
        OIC_LOG_V(ERROR, NET_SSL_TAG, "dataLen is zero [%d]", dataLen);
        return CA_STATUS_FAILED;
    }

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data to be encrypted dataLen [%d]", dataLen);

    oc_mutex_lock(g_sslContextMutex);
    if(NULL == g_caSslContext)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
        oc_mutex_unlock(g_sslContextMutex);
        return CA_STATUS_FAILED;
    }

    SslEndPoint_t * tep = GetSslPeer(endpoint);
    if (NULL == tep)
    {
        tep = InitiateTlsHandshake(endpoint);
    }
    if (NULL == tep)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
        oc_mutex_unlock(g_sslContextMutex);
        return CA_STATUS_FAILED;
    }

    if (MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
    {
        ret = mbedtls_ssl_write(&tep->ssl, (unsigned char *) data, dataLen);

        if(ret < 0)
        {
            OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedTLS write returned %d", ret);
            RemovePeerFromList(&tep->sep.endpoint);
            oc_mutex_unlock(g_sslContextMutex);
            return CA_STATUS_FAILED;
        }
    }
    else
    {
        SslCacheMessage_t * msg = NewCacheMessage((uint8_t*) data, dataLen);
        if (NULL == msg || !u_arraylist_add(tep->cacheList, (void *) msg))
        {
            OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
            oc_mutex_unlock(g_sslContextMutex);
            return CA_STATUS_FAILED;
        }
    }

    oc_mutex_unlock(g_sslContextMutex);

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return CA_STATUS_OK;
}
/**
 * Sends cached messages via TLS connection.
 *
 * @param[in]  tep    remote address with session info
 */
static void SendCacheMessages(SslEndPoint_t * tep)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_VOID(tep, NET_SSL_TAG, "Param tep is NULL");

    uint32_t listIndex = 0;
    uint32_t listLength = 0;
    listLength = u_arraylist_length(tep->cacheList);
    for (listIndex = 0; listIndex < listLength;)
    {
        int ret = 0;
        SslCacheMessage_t * msg = (SslCacheMessage_t *) u_arraylist_get(tep->cacheList, listIndex);
        if (NULL != msg && NULL != msg->data && 0 != msg->len)
        {
            do
            {
                ret = mbedtls_ssl_write(&tep->ssl, (unsigned char *) msg->data, msg->len);
            }
            while(MBEDTLS_ERR_SSL_WANT_WRITE == ret);

            if(ret < 0)
            {
                OIC_LOG_V(ERROR, NET_SSL_TAG,"mbedTLS write returned %d", ret );
            }
            if (u_arraylist_remove(tep->cacheList, listIndex))
            {
                DeleteCacheMessage(msg);
                // Reduce list length by 1 as we removed one element.
                listLength--;
            }
            else
            {
                OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_remove failed.");
                break;
            }
        }
        else
        {
            // Move to the next element
            ++listIndex;
        }
    }
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
}

void CAsetSslHandshakeCallback(CAErrorCallback tlsHandshakeCallback)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    g_sslCallback = tlsHandshakeCallback;
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
}
// TODO move ConvertStrToUuid function to common module
/*
 * Converts string UUID to CARemoteId_t
 *
 * @param strUuid Device UUID in string format
 * @param uuid converted UUID in CARemoteId_t format
 *
 * @return 0 for success.
 * */
static int ConvertStrToUuid(const char* strUuid, CARemoteId_t* uuid)
{
    if(NULL == strUuid || NULL == uuid)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "ConvertStrToUuid : Invalid param");
        return -1;
    }

    size_t urnIdx = 0;
    size_t uuidIdx = 0;
    size_t strUuidLen = 0;
    char convertedUuid[UUID_LENGTH * 2] = {0};

    strUuidLen = strlen(strUuid);
    if(0 == strUuidLen)
    {
        OIC_LOG(INFO, NET_SSL_TAG, "The empty string detected, The UUID will be converted to "\
                           "\"00000000-0000-0000-0000-000000000000\"");
    }
    else if(UUID_LENGTH * 2 + 4 == strUuidLen)
    {
        for(uuidIdx=0, urnIdx=0; uuidIdx < UUID_LENGTH ; uuidIdx++, urnIdx+=2)
        {
            if(*(strUuid + urnIdx) == '-')
            {
                urnIdx++;
            }
            sscanf(strUuid + urnIdx, "%2hhx", &convertedUuid[uuidIdx]);
        }
    }
    else
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Invalid string uuid format");
        return -1;
    }

    memcpy(uuid->id, convertedUuid, UUID_LENGTH);
    uuid->id_length = UUID_LENGTH;
    return 0;
}

/* Read data from TLS connection
 */
CAResult_t CAdecryptSsl(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t dataLen)
{
    int ret = 0;
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(sep, NET_SSL_TAG, "endpoint is NULL" , CA_STATUS_INVALID_PARAM);
    VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , CA_STATUS_INVALID_PARAM);

    oc_mutex_lock(g_sslContextMutex);
    if (NULL == g_caSslContext)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
        oc_mutex_unlock(g_sslContextMutex);
        return CA_STATUS_FAILED;
    }


    SslEndPoint_t * peer = GetSslPeer(&sep->endpoint);
    if (NULL == peer)
    {
        mbedtls_ssl_config * config = (sep->endpoint.adapter == CA_ADAPTER_IP ?
                                   &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
        peer = NewSslEndPoint(&sep->endpoint, config);
        if (NULL == peer)
        {
            OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
            oc_mutex_unlock(g_sslContextMutex);
            return CA_STATUS_FAILED;
        }
        //Load allowed TLS suites from SVR DB
        SetupCipher(config, sep->endpoint.adapter);

        ret = u_arraylist_add(g_caSslContext->peerList, (void *) peer);
        if (!ret)
        {
            OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
            OICFree(peer);
            oc_mutex_unlock(g_sslContextMutex);
            return CA_STATUS_FAILED;
        }
    }

    peer->recBuf.buff = data;
    peer->recBuf.len = dataLen;
    peer->recBuf.loaded = 0;

    while (MBEDTLS_SSL_HANDSHAKE_OVER != peer->ssl.state)
    {
        ret = mbedtls_ssl_handshake_step(&peer->ssl);
        if (MBEDTLS_ERR_SSL_CONN_EOF == ret)
        {
            break;
        }

        if (MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED == ret)
        {
            OIC_LOG(DEBUG, NET_SSL_TAG, "Hello verification requested");
            mbedtls_ssl_session_reset(&peer->ssl);
            mbedtls_ssl_set_client_transport_id(&peer->ssl,
                                                (const unsigned char *) sep->endpoint.addr,
                                                 sizeof(sep->endpoint.addr));
            ret = mbedtls_ssl_handshake_step(&peer->ssl);
        }
        uint32_t flags = mbedtls_ssl_get_verify_result(&peer->ssl);
        if (0 != flags)
        {
            OIC_LOG_BUFFER(ERROR, NET_SSL_TAG, (const uint8_t *) &flags, sizeof(flags));
            SSL_CHECK_FAIL(peer, flags, "Cert verification failed", 1,
                                                     CA_STATUS_FAILED, GetAlertCode(flags));
        }
        SSL_CHECK_FAIL(peer, ret, "Handshake error", 1, CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
        if (MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC == peer->ssl.state)
        {
            memcpy(peer->master, peer->ssl.session_negotiate->master, sizeof(peer->master));
            g_caSslContext->selectedCipher = peer->ssl.session_negotiate->ciphersuite;
        }
        if (MBEDTLS_SSL_CLIENT_KEY_EXCHANGE == peer->ssl.state)
        {
            memcpy(peer->random, peer->ssl.handshake->randbytes, sizeof(peer->random));
        }

        if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
        {
            SSL_RES(peer, CA_STATUS_OK);
            if (MBEDTLS_SSL_IS_CLIENT == peer->ssl.conf->endpoint)
            {
                SendCacheMessages(peer);
            }

            if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 == g_caSslContext->selectedCipher ||
                MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA == g_caSslContext->selectedCipher)
            {
                char uuid[UUID_LENGTH * 2 + 5] = {0};
                void * uuidPos = NULL;
                void * userIdPos = NULL;
                const mbedtls_x509_crt * peerCert = mbedtls_ssl_get_peer_cert(&peer->ssl);
                ret = (NULL == peerCert ? -1 : 0);
                SSL_CHECK_FAIL(peer, ret, "Failed to retrieve cert", 1,
                                            CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_NO_CERT);
                uuidPos = memmem(peerCert->subject_raw.p, peerCert->subject_raw.len,
                                                 UUID_PREFIX, sizeof(UUID_PREFIX) - 1);

                if (NULL != uuidPos)
                {
                    memcpy(uuid, (char*) uuidPos + sizeof(UUID_PREFIX) - 1, UUID_LENGTH * 2 + 4);
                    ret = ConvertStrToUuid(uuid, &peer->sep.identity);
                    SSL_CHECK_FAIL(peer, ret, "Failed to convert subject", 1,
                                          CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
                }
                else
                {
                    OIC_LOG(WARNING, NET_SSL_TAG, "uuid not found");
                }

                userIdPos = memmem(peerCert->subject_raw.p, peerCert->subject_raw.len,
                                             USERID_PREFIX, sizeof(USERID_PREFIX) - 1);
                if (NULL != userIdPos)
                {
                    memcpy(uuid, (char*) userIdPos + sizeof(USERID_PREFIX) - 1, UUID_LENGTH * 2 + 4);
                    ret = ConvertStrToUuid(uuid, &peer->sep.userId);
                    SSL_CHECK_FAIL(peer, ret, "Failed to convert subject alt name", 1,
                                      CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
                }
                else
                {
                    OIC_LOG(WARNING, NET_SSL_TAG, "Subject alternative name not found");
                }
            }

            oc_mutex_unlock(g_sslContextMutex);
            OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
            return CA_STATUS_OK;
        }
    }

    if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
    {
        uint8_t decryptBuffer[TLS_MSG_BUF_LEN] = {0};
        do
        {
            ret = mbedtls_ssl_read(&peer->ssl, decryptBuffer, TLS_MSG_BUF_LEN);
        } while (MBEDTLS_ERR_SSL_WANT_READ == ret);

        if (MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY == ret)
        {
            OIC_LOG(INFO, NET_SSL_TAG, "Connection was closed gracefully");
            SSL_CLOSE_NOTIFY(peer, ret);
            RemovePeerFromList(&peer->sep.endpoint);
            oc_mutex_unlock(g_sslContextMutex);
            return CA_STATUS_OK;
        }

        if (0 > ret)
        {
            OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_ssl_read returned -0x%x", -ret);
            //SSL_RES(peer, CA_STATUS_FAILED);
            RemovePeerFromList(&peer->sep.endpoint);
            oc_mutex_unlock(g_sslContextMutex);
            return CA_STATUS_FAILED;
        }
        int adapterIndex = GetAdapterIndex(peer->sep.endpoint.adapter);
        if (0 == adapterIndex || adapterIndex == 1)
        {
            g_caSslContext->adapterCallbacks[adapterIndex].recvCallback(&peer->sep, decryptBuffer, ret);
        }
        else
        {
            OIC_LOG(ERROR, NET_SSL_TAG, "Unsuported adapter");
            RemovePeerFromList(&peer->sep.endpoint);
            oc_mutex_unlock(g_sslContextMutex);
            return CA_STATUS_FAILED;
        }
    }

    oc_mutex_unlock(g_sslContextMutex);
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return CA_STATUS_OK;
}

void CAsetSslAdapterCallbacks(CAPacketReceivedCallback recvCallback,
                              CAPacketSendCallback sendCallback,
                              CATransportAdapter_t type)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_VOID(sendCallback, NET_SSL_TAG, "sendCallback is NULL");
    VERIFY_NON_NULL_VOID(recvCallback, NET_SSL_TAG, "recvCallback is NULL");
    oc_mutex_lock(g_sslContextMutex);
    if (NULL == g_caSslContext)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
        oc_mutex_unlock(g_sslContextMutex);
        return;
    }

//    if (MAX_SUPPORTED_ADAPTERS > type)
    {
        switch (type)
        {
            case CA_ADAPTER_IP:
                g_caSslContext->adapterCallbacks[0].recvCallback = recvCallback;
                g_caSslContext->adapterCallbacks[0].sendCallback = sendCallback;
                break;
            case CA_ADAPTER_TCP:
                g_caSslContext->adapterCallbacks[1].recvCallback = recvCallback;
                g_caSslContext->adapterCallbacks[1].sendCallback = sendCallback;
                break;
            default:
                OIC_LOG_V(ERROR, NET_SSL_TAG, "Unsupported adapter: %d", type);
        }
    }

    oc_mutex_unlock(g_sslContextMutex);
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
}

CAResult_t CAsetTlsCipherSuite(const uint32_t cipher)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(g_getCredentialTypesCallback, NET_SSL_TAG, "Param callback is null", CA_STATUS_FAILED);
    g_getCredentialTypesCallback(g_caSslContext->cipherFlag);
    switch(cipher)
    {
        case MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA:
        {
#ifdef __WITH_TLS__
            //todo check that Cred with RSA cert exists
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientTlsConf,
                                         tlsCipher[ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA]);
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverTlsConf,
                                         tlsCipher[ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA]);
#endif
#ifdef __WITH_DTLS__
            //todo check that Cred with RSA cert exists
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientDtlsConf,
                                         tlsCipher[ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA]);
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverDtlsConf,
                                         tlsCipher[ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA]);
#endif
            g_caSslContext->cipher = ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA;
            break;
        }
        case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
        {
            if (false == g_caSslContext->cipherFlag[1])
            {
                OIC_LOG(ERROR, NET_SSL_TAG, "No Credential for ECC");
                return CA_STATUS_FAILED;
            }
#ifdef __WITH_TLS__
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientTlsConf,
                                         tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8]);
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverTlsConf,
                                         tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8]);
#endif
#ifdef __WITH_DTLS__
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientDtlsConf,
                                         tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8]);
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverDtlsConf,
                                         tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8]);
#endif
            g_caSslContext->cipher = ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
            break;
        }
        case MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256:
        {
#ifdef __WITH_TLS__
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientTlsConf,
                                         tlsCipher[ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256]);
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverTlsConf,
                                         tlsCipher[ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256]);
#endif
#ifdef __WITH_DTLS__
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientDtlsConf,
                                         tlsCipher[ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256]);
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverDtlsConf,
                                         tlsCipher[ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256]);
#endif
            g_caSslContext->cipher = ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256;
            break;
        }
        case MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
        {
#if 0 // PIN OTM
            if (false == g_caSslContext->cipherFlag[0])
            {
                OIC_LOG(ERROR, NET_SSL_TAG, "No Credential for PSK");
                return CA_STATUS_FAILED;
            }
#endif
#ifdef __WITH_TLS__
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientTlsConf,
                                          tlsCipher[ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256]);
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverTlsConf,
                                          tlsCipher[ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256]);
#endif
#ifdef __WITH_DTLS__
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientDtlsConf,
                                          tlsCipher[ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256]);
            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverDtlsConf,
                                          tlsCipher[ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256]);
#endif
            g_caSslContext->cipher = ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
            break;
        }
        default:
        {
            OIC_LOG(ERROR, NET_SSL_TAG, "Unknown cipher");
            return CA_STATUS_FAILED;
        }
    }
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Selected cipher: 0x%x", cipher);
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return CA_STATUS_OK;
}

CAResult_t CAinitiateSslHandshake(const CAEndpoint_t *endpoint)
{
    CAResult_t res = CA_STATUS_OK;
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
    oc_mutex_lock(g_sslContextMutex);
    if (NULL == InitiateTlsHandshake(endpoint))
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
        res = CA_STATUS_FAILED;
    }
    oc_mutex_unlock(g_sslContextMutex);
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return res;
}
/**
 * Expands the secret into blocks of data according
 * to the algorithm specified in section 5 of RFC 4346
 *
 * This function writes upto @p bufLen bytes into the given output buffer @p buf
 *
 * @param  key    secret key.
 * @param  keyLen    secret key length.
 * @param  label    A PRF label.
 * @param  labelLen     Actual length of @p label.
 * @param  random1    Random seed.
 * @param  random1Len     Actual length of @p random1 (may be zero).
 * @param  random2     Random seed.
 * @param  random2Len    Actual length of @p random2 (may be zero).
 * @param  buf    Output buffer for generated random data.
 * @param  bufLen    Maximum size of @p buf.
 *
 * @return The actual number of bytes written to @p buf or @c -1 on error.
 */

static int pHash (const unsigned char *key, size_t keyLen,
     const unsigned char *label, size_t labelLen,
     const unsigned char *random1, size_t random1Len,
     const unsigned char *random2, size_t random2Len,
     unsigned char *buf, size_t bufLen)
{
    unsigned char A[RANDOM_LEN] = {0};
    unsigned char tmp[RANDOM_LEN] = {0};
    size_t dLen;   /* digest length */
    size_t len = 0;   /* result length */

    VERIFY_NON_NULL_RET(key, NET_SSL_TAG, "key is NULL", -1);
    VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", -1);
    VERIFY_NON_NULL_RET(random1, NET_SSL_TAG, "random1 is NULL", -1);
    VERIFY_NON_NULL_RET(random2, NET_SSL_TAG, "random2 is NULL", -1);
    VERIFY_NON_NULL_RET(buf, NET_SSL_TAG, "buf is NULL", -1);

    mbedtls_md_context_t hmacA;
    mbedtls_md_context_t hmacP;

    mbedtls_md_init(&hmacA);
    mbedtls_md_init(&hmacP);

    CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacA, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
    CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacP, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);

    CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen );
    CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, label, labelLen);
    CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random1, random1Len);
    CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random2, random2Len);
    CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);

    dLen = RANDOM_LEN;

    CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);

    while (len + dLen < bufLen)
    {
        CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
        CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
        CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);
        CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
        CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
        CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);

        CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);

        len += RANDOM_LEN;

        memcpy(buf, tmp, dLen);
        buf += dLen;

        CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacA);
        CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen);
        CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, A, dLen);
        CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);
    }

    CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
    CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
    CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);

    CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
    CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
    CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);
    CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);

    memcpy(buf, tmp, bufLen - len);

    mbedtls_md_free(&hmacA);
    mbedtls_md_free(&hmacP);
    return bufLen;
George Nash's avatar
George Nash committed
1990
    // exit label required for CHECK_MBEDTLS_RET macro
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
exit:
    mbedtls_md_free(&hmacA);
    mbedtls_md_free(&hmacP);
    return -1;
}

CAResult_t CAsslGenerateOwnerPsk(const CAEndpoint_t *endpoint,
                            const uint8_t* label, const size_t labelLen,
                            const uint8_t* rsrcServerDeviceId, const size_t rsrcServerDeviceIdLen,
                            const uint8_t* provServerDeviceId, const size_t provServerDeviceIdLen,
                            uint8_t* ownerPsk, const size_t ownerPskSize)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "endpoint is NULL", CA_STATUS_INVALID_PARAM);
    VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", CA_STATUS_INVALID_PARAM);
    VERIFY_NON_NULL_RET(rsrcServerDeviceId, NET_SSL_TAG, "rsrcId is NULL", CA_STATUS_INVALID_PARAM);
    VERIFY_NON_NULL_RET(provServerDeviceId, NET_SSL_TAG, "provId is NULL", CA_STATUS_INVALID_PARAM);
    VERIFY_NON_NULL_RET(ownerPsk, NET_SSL_TAG, "ownerPSK is NULL", CA_STATUS_INVALID_PARAM);

2010 2011 2012
    // TODO: Added as workaround, need to debug
    oc_mutex_unlock(g_sslContextMutex);

2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
    oc_mutex_lock(g_sslContextMutex);
    if (NULL == g_caSslContext)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
        oc_mutex_unlock(g_sslContextMutex);
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        return CA_STATUS_FAILED;
    }
    SslEndPoint_t * tep = GetSslPeer(endpoint);
    if (NULL == tep)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
        oc_mutex_unlock(g_sslContextMutex);
        return CA_STATUS_FAILED;
    }

    uint8_t keyblock[KEY_BLOCK_LEN] = {0};
    // "key expansion"
    uint8_t lab[] = {0x6b, 0x65, 0x79, 0x20, 0x65, 0x78, 0x70, 0x61, 0x6e, 0x73, 0x69, 0x6f, 0x6e};
    int ret = pHash(tep->master, sizeof(tep->master), lab, sizeof(lab),
                    (tep->random) + RANDOM_LEN, RANDOM_LEN, tep->random, RANDOM_LEN,
                    keyblock, KEY_BLOCK_LEN);
    if (-1 == ret)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
        oc_mutex_unlock(g_sslContextMutex);
        return CA_STATUS_FAILED;
    }
    ret = pHash(keyblock, sizeof(keyblock), label, labelLen,
                rsrcServerDeviceId, rsrcServerDeviceIdLen,
                provServerDeviceId, provServerDeviceIdLen,
                ownerPsk, ownerPskSize);
    if (-1 == ret)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
        oc_mutex_unlock(g_sslContextMutex);
        return CA_STATUS_FAILED;
    }

    oc_mutex_unlock(g_sslContextMutex);

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return CA_STATUS_OK;
}