ca_adapter_net_ssl.c 95.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/******************************************************************
 *
 * 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.
 *
 ******************************************************************/

Oleksii Beketov's avatar
Oleksii Beketov committed
21

Dave Thaler's avatar
Dave Thaler committed
22
#include "iotivity_config.h"
Oleksii Beketov's avatar
Oleksii Beketov committed
23

Jaewook Jung's avatar
Jaewook Jung committed
24
#ifndef _GNU_SOURCE
25
#define _GNU_SOURCE
Jaewook Jung's avatar
Jaewook Jung committed
26
#endif
27 28 29

#include <stddef.h>
#include <stdbool.h>
30
#include <assert.h>
31
#include <inttypes.h>
32 33 34
#include "ca_adapter_net_ssl.h"
#include "cacommon.h"
#include "caipinterface.h"
35
#include "cacertprofile.h"
36
#include "oic_malloc.h"
37
#include "experimental/ocrandom.h"
38
#include "experimental/byte_array.h"
39
#include "octhread.h"
40
#include "octimer.h"
41 42 43 44 45 46 47 48

// 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"
49
#include "mbedtls/net_sockets.h"
Kevin Kane's avatar
Kevin Kane committed
50
#include "mbedtls/oid.h"
Oleksandr Dmytrenko's avatar
Oleksandr Dmytrenko committed
51 52
#include "mbedtls/x509.h"
#include "mbedtls/error.h"
53 54 55 56 57
#ifdef __WITH_DTLS__
#include "mbedtls/timing.h"
#include "mbedtls/ssl_cookie.h"
#endif

58
#if !defined(NDEBUG) || defined(TB_LOG)
59 60 61 62
#include "mbedtls/debug.h"
#include "mbedtls/version.h"
#endif

Dave Thaler's avatar
Dave Thaler committed
63
#ifdef HAVE_SYS_TYPES_H
64
#include <sys/types.h>
Dave Thaler's avatar
Dave Thaler committed
65 66
#endif
#ifdef HAVE_SYS_STAT_H
67
#include <sys/stat.h>
Dave Thaler's avatar
Dave Thaler committed
68 69
#endif
#ifdef HAVE_FCNTL_H
70
#include <fcntl.h>
Dave Thaler's avatar
Dave Thaler committed
71 72
#endif
#ifdef HAVE_UNISTD_H
73 74 75 76 77 78 79 80
#include <unistd.h>
#endif

/**
 * @def MBED_TLS_VERSION_LEN
 * @brief mbedTLS version string length
 */
#define MBED_TLS_VERSION_LEN (16)
81 82 83
 /**
 * @def PERSONALIZATION_STRING
 * @brief Personalization string for the mbedtls RNG
84
 */
85
#define PERSONALIZATION_STRING "IOTIVITY_RND"
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
/**
 * @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
105
 * Level 1 logs errors only, level 4 is verbose logging.
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
 */
#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)
/**
Oleksii Beketov's avatar
Oleksii Beketov committed
136 137
 * @def SHA384_MAC_KEY_LENGTH
 * @brief MAC key length for SHA384 cipher suites
138
 */
Oleksii Beketov's avatar
Oleksii Beketov committed
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
#define SHA384_MAC_KEY_LENGTH (48)
/**
 * @def SHA256_MAC_KEY_LENGTH
 * @brief MAC key length for SHA256 cipher suites
 */
#define SHA256_MAC_KEY_LENGTH (32)
/**
 * @def CCM_MAC_KEY_LENGTH
 * @brief MAC key length for CCM cipher suites
 */
#define CCM_MAC_KEY_LENGTH (0)
/**
 * @def AES256_KEY_LENGTH
 * @brief key material length for AES256 cipher suites
 */
#define AES256_KEY_LENGTH (32)
/**
 * @def AES128_KEY_LENGTH
 * @brief key material length for AES128 cipher suites
 */
#define AES128_KEY_LENGTH (16)
/**
 * @def GCM_IV_LENGTH
 * @brief length of nonce for GCM cipher suites
163
 */
Oleksii Beketov's avatar
Oleksii Beketov committed
164 165 166 167 168 169 170 171 172 173 174
#define GCM_IV_LENGTH (12)
/**
 * @def CCM_IV_LENGTH
 * @brief length of nonce for CCM cipher suites
 */
#define CCM_IV_LENGTH (4)
/**
 * @def CBC_IV_LENGTH
 * @brief length of nonce for CBC cipher suites
 */
#define CBC_IV_LENGTH (0)
Chul Lee's avatar
Chul Lee committed
175 176 177 178 179 180 181

/**
 * @var RETRANSMISSION_TIME
 * @brief Maximum timeout value (in seconds) to start DTLS retransmission.
 */
#define RETRANSMISSION_TIME 1

Oleksii Beketov's avatar
Oleksii Beketov committed
182 183 184 185 186 187 188
/**@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
 */
189 190 191 192 193 194
#define SSL_CLOSE_NOTIFY(peer, ret)                                                                \
do                                                                                                 \
{                                                                                                  \
    (ret) = mbedtls_ssl_close_notify(&(peer)->ssl);                                                \
} while (MBEDTLS_ERR_SSL_WANT_WRITE == (ret))

195 196 197 198 199 200
/* OCF-defined EKU value indicating an identity certificate, that can be used for
 * TLS client and server authentication.  This is the DER encoding of the OID
 * 1.3.6.1.4.1.44924.1.6.
 */
static const unsigned char EKU_IDENTITY[] = { 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xDE, 0x7C, 0x01, 0x06 };

Oleksii Beketov's avatar
Oleksii Beketov committed
201 202 203 204 205 206 207 208 209 210
/**@def CONF_SSL(clientConf, serverConf, fn, ...)
 *
 * Calls \a fn for \a clientConf and \a serverConf.
 *
 */
#define CONF_SSL(clientConf, serverConf, fn, ...) do {                                             \
fn((clientConf), __VA_ARGS__);                                                                     \
fn((serverConf), __VA_ARGS__);                                                                     \
} while (0)

211 212 213 214 215
/** @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
216 217 218
 * **IMPORTANT:** Any time CHECK_MBEDTLS_RET is used an `exit:` goto label must
 *                be present to handle error processing.
 *
219 220 221 222 223 224 225
 * @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;                                                                                     \
Oleksii Beketov's avatar
Oleksii Beketov committed
226
} } while (0)
227 228 229

typedef enum
{
Oleksii Beketov's avatar
Oleksii Beketov committed
230 231 232 233 234 235 236 237 238 239 240 241 242
    SSL_RSA_WITH_AES_256_CBC_SHA256,
    SSL_RSA_WITH_AES_128_GCM_SHA256,
    SSL_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
    SSL_ECDHE_ECDSA_WITH_AES_128_CCM_8,
    SSL_ECDHE_ECDSA_WITH_AES_128_CCM,
    SSL_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
    SSL_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
    SSL_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
    SSL_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
    SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
    SSL_ECDH_ANON_WITH_AES_128_CBC_SHA256,
    SSL_CIPHER_MAX
} SslCipher_t;
243 244 245 246 247 248 249

typedef enum
{
    ADAPTER_CURVE_SECP256R1,
    ADAPTER_CURVE_MAX
} AdapterCurve_t;

Oleksii Beketov's avatar
Oleksii Beketov committed
250
static const int tlsCipher[SSL_CIPHER_MAX][2] =
251
{
Oleksii Beketov's avatar
Oleksii Beketov committed
252 253 254
    {MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256, 0},
    {MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, 0},
    {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
255
    {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, 0},
Chul Lee's avatar
Chul Lee committed
256
    {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM, 0},
Oleksii Beketov's avatar
Oleksii Beketov committed
257 258 259 260 261 262
    {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 0},
    {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, 0},
    {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 0},
    {MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, 0},
    {MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 0},
    {MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256, 0}
263 264
};

Oleksii Beketov's avatar
Oleksii Beketov committed
265
static int g_cipherSuitesList[SSL_CIPHER_MAX];
266 267 268 269 270 271 272 273

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

typedef struct  {
    int code;
274
    unsigned char alert;
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
} 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}
};

301
static unsigned char GetAlertCode(uint32_t flags)
302 303 304 305 306 307 308 309 310 311 312 313 314
{
    const CrtVerifyAlert_t *cur;

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

315
#if !defined(NDEBUG) || defined(TB_LOG)
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
/**
 * 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);

Dmitriy Zhuravlev's avatar
Dmitriy Zhuravlev committed
332 333 334 335 336 337 338
    char * temp = (char*) str;
    size_t len = strlen(temp);
    if (1 <= len && temp[len - 1] == '\n')
    {
        temp[len - 1] = '\0';
    }

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
    OIC_LOG_V(DEBUG, MBED_TLS_TAG, "%s", str);
}
#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. */
356
    CAErrorHandleCallback errorCallback;    /**< Callback used to pass error to upper layer. */
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
} 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;
Chul Lee's avatar
Chul Lee committed
376

Oleksii Beketov's avatar
Oleksii Beketov committed
377
    SslCipher_t cipher;
378 379 380 381 382
    SslCallbacks_t adapterCallbacks[MAX_SUPPORTED_ADAPTERS];
    mbedtls_x509_crl crl;
    bool cipherFlag[2];
    int selectedCipher;

383
#ifdef __WITH_DTLS__
384
    mbedtls_ssl_cookie_ctx cookieCtx;
385 386 387
    int timerId;
#endif

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
} 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
415
 * @brief Mutex to synchronize access to g_caSslContext and g_sslCallback.
416 417 418 419 420 421 422
 */
static oc_mutex g_sslContextMutex = NULL;

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

425 426 427 428 429 430 431
/**
 * @var g_peerCNVerifyCallback
 *
 * @brief callback to utilize peer certificate information
 */
static PeerCNVerifyCallback g_peerCNVerifyCallback = NULL;

432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
/**
 * 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__
Chul Lee's avatar
Chul Lee committed
454 455
    mbedtls_timing_delay_context timer;
#endif // __WITH_DTLS__
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
} 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__);
}
472

473 474 475 476 477 478 479
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__);
}

480 481 482 483 484 485 486 487 488 489 490
void CAsetPeerCNVerifyCallback(PeerCNVerifyCallback cb)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "IN %s", __func__);
    if (NULL == cb)
    {
        OIC_LOG(DEBUG, NET_SSL_TAG, "UNSET peerCNVerifyCallback");
    }
    g_peerCNVerifyCallback = cb;
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "OUT %s", __func__);
}

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
/**
 * Sets SSL result for callback.
 *
 * @param[in] peer remote peer
 */
static CAResult_t notifySubscriber(SslEndPoint_t* peer, CAResult_t status)
{
    CAResult_t result = CA_STATUS_OK;
    oc_mutex_assert_owner(g_sslContextMutex, true);
    if (g_sslCallback)
    {
        CAErrorInfo_t errorInfo;
        errorInfo.result = status;
        result = g_sslCallback(&peer->sep.endpoint, &errorInfo);
    }
    return result;
}

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 542 543 544 545
static CAResult_t PeerCertExtractCN(const mbedtls_x509_crt *peerCert)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "IN %s", __func__);

    CAResult_t res = CA_STATUS_OK;

    mbedtls_asn1_named_data *subject = (mbedtls_asn1_named_data *)&(peerCert->subject);
    while (NULL != subject)
    {
        if (0 == MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &(subject->oid)))
        {
            break;
        }
        subject = subject->next;
    }

    if (NULL != g_peerCNVerifyCallback)
    {
        if (NULL != subject)
        {
            res = g_peerCNVerifyCallback(subject->val.p, subject->val.len);
        }
        else
        {
            OIC_LOG(DEBUG, NET_SSL_TAG, "Common Name not found");
            res = g_peerCNVerifyCallback(NULL, 0);
        }
    }
    else
    {
        OIC_LOG(DEBUG, NET_SSL_TAG, "g_peerCNVerifyCallback is not set");
    }

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "OUT %s", __func__);
    return res;
}

546 547 548 549 550 551 552 553
static int GetAdapterIndex(CATransportAdapter_t adapter)
{
    switch (adapter)
    {
        case CA_ADAPTER_IP:
            return 0;
        case CA_ADAPTER_TCP:
            return 1;
554 555
        case CA_ADAPTER_GATT_BTLE:
            return 2;
556 557 558 559 560
        default:
            OIC_LOG(ERROR, NET_SSL_TAG, "Unsupported adapter");
            return -1;
    }
}
561 562 563

static void SendCacheMessages(SslEndPoint_t * tep, CAResult_t errorCode);

564 565 566 567 568 569 570
/**
 * Write callback.
 *
 * @param[in]  tep    TLS endpoint
 * @param[in]  data    message
 * @param[in]  dataLen    message length
 *
571
 * @return  message length or -1 on error.
572 573 574 575
 */
static int SendCallBack(void * tep, const unsigned char * data, size_t dataLen)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
576 577
    VERIFY_NON_NULL_RET(tep, NET_SSL_TAG, "secure endpoint is NULL", -1);
    VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "data is NULL", -1);
578
    VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", -1);
579
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data len: %" PRIuPTR, dataLen);
580
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Adapter: %u", ((SslEndPoint_t * )tep)->sep.endpoint.adapter);
581
    ssize_t sentLen = 0;
582
    int adapterIndex = GetAdapterIndex(((SslEndPoint_t * )tep)->sep.endpoint.adapter);
583
    if (0 <= adapterIndex && MAX_SUPPORTED_ADAPTERS > adapterIndex)
584
    {
585
        size_t dataToSend = (dataLen > INT_MAX) ? INT_MAX : dataLen;
586
        CAPacketSendCallback sendCallback = g_caSslContext->adapterCallbacks[adapterIndex].sendCallback;
587
        sentLen = sendCallback(&(((SslEndPoint_t * )tep)->sep.endpoint), (const void *) data, dataToSend);
588 589 590 591 592
        if (0 > sentLen)
        {
            OIC_LOG(ERROR, NET_SSL_TAG, "Error sending packet. The error will be reported in the adapter.");
        }
        else if ((size_t)sentLen != dataLen)
593 594
        {
            OIC_LOG_V(DEBUG, NET_SSL_TAG,
595
                      "Packet was partially sent - sent/total/remained bytes : %" PRIdPTR "/%" PRIuPTR "/%" PRIuPTR,
596 597
                      sentLen, dataLen, (dataLen - sentLen));
        }
598 599 600 601
    }
    else
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Unsupported adapter");
602
        return -1;
603 604 605
    }

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
606
    return (int)sentLen;
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
}
/**
 * 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;
624 625
    size_t retLen = ((recBuf->len > recBuf->loaded) ? (recBuf->len - recBuf->loaded) : 0);
    retLen = (retLen < dataLen) ? retLen : dataLen;
626

627 628 629 630 631
    if (retLen > INT_MAX)
    {
        return 0;
    }

632 633 634 635 636 637 638 639 640 641 642
    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
643 644
 * @param[in]  buf     buffer with X.509 certificates. Certificates must be in a single null-terminated
 *                     string, with each certificate in PEM encoding with headers.
645
 * @param[in]  bufLen  buffer length
Oleksii Beketov's avatar
Oleksii Beketov committed
646
 * @param[in]  errNum  number certificates that failed to parse
647
 *
Oleksii Beketov's avatar
Oleksii Beketov committed
648
 * @return  number of successfully parsed certificates or -1 on error
649
 */
650
static int ParseChain(mbedtls_x509_crt * crt, unsigned char * buf, size_t bufLen, int * errNum)
651
{
652
    int ret;
653
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
654 655
    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);
656

657
    if (NULL != errNum)
658
    {
659
        *errNum = 0;
660
    }
Oleksii Beketov's avatar
Oleksii Beketov committed
661

662
    if ((bufLen >= 2) && (buf[0] == 0x30) && (buf[1] == 0x82))
663
    {
664 665
        OIC_LOG_V(ERROR, NET_SSL_TAG, "DER-encoded certificate passed to ParseChain");
        return -1;
666
    }
Oleksii Beketov's avatar
Oleksii Beketov committed
667

668 669 670 671 672 673 674 675 676 677 678
    ret = mbedtls_x509_crt_parse(crt, buf, bufLen);
    if (0 > ret)
    {
        OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_x509_crt_parse failed: -0x%04x", -(ret));
        return -1;
    }

    if (NULL != errNum)
    {
        *errNum = ret;
    }
679

680 681 682 683 684
    ret = 0;
    for (const mbedtls_x509_crt *cur = crt; cur != NULL; cur = cur->next)
    {
        ret++;
    }
685

686 687
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return ret;
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
/**
 * Deinit Pki Info
 *
 * @param[out] inf structure with certificate, private key and crl to be free.
 *
 */
static void DeInitPkixInfo(PkiInfo_t * inf)
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    if (NULL == inf)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "NULL passed");
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
        return;
    }

    DEINIT_BYTE_ARRAY(inf->crt);
    DEINIT_BYTE_ARRAY(inf->key);
    DEINIT_BYTE_ARRAY(inf->ca);
    DEINIT_BYTE_ARRAY(inf->crl);

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

714 715 716 717 718
//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);
719
    // load pk key, cert, trust chain and crl
720 721 722 723 724 725 726
    PkiInfo_t pkiInfo = {
        BYTE_ARRAY_INITIALIZER,
        BYTE_ARRAY_INITIALIZER,
        BYTE_ARRAY_INITIALIZER,
        BYTE_ARRAY_INITIALIZER
    };

727 728
    if (g_getPkixInfoCallback)
    {
729
        g_getPkixInfoCallback(&pkiInfo);
730 731 732
    }

    VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", -1);
733 734 735 736 737 738 739 740 741 742 743

    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);

744 745
    mbedtls_ssl_config * serverConf = (adapter == CA_ADAPTER_IP ||
                                   adapter == CA_ADAPTER_GATT_BTLE ?
746
                                   &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
747 748
    mbedtls_ssl_config * clientConf = (adapter == CA_ADAPTER_IP ||
                                   adapter == CA_ADAPTER_GATT_BTLE ?
749 750
                                   &g_caSslContext->clientDtlsConf : &g_caSslContext->clientTlsConf);
    // optional
Oleksii Beketov's avatar
Oleksii Beketov committed
751 752
    int ret;
    int errNum;
753
    int count = ParseChain(&g_caSslContext->crt, pkiInfo.crt.data, pkiInfo.crt.len, &errNum);
Oleksii Beketov's avatar
Oleksii Beketov committed
754
    if (0 >= count)
755 756 757 758
    {
        OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate chain parsing error");
        goto required;
    }
Oleksii Beketov's avatar
Oleksii Beketov committed
759 760 761 762 763
    if (0 != errNum)
    {
        OIC_LOG_V(WARNING, NET_SSL_TAG, "Own certificate chain parsing error: %d certs failed to parse", errNum);
        goto required;
    }
764 765 766 767 768 769 770 771 772 773 774 775 776

    ret = ValidateAuthCertChainProfiles(&g_caSslContext->crt);
    if (CP_INVALID_CERT_CHAIN == ret)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Invalid own cert chain");
        goto required;
    }
    else if (0 != ret)
    {
        OIC_LOG_V(ERROR, NET_SSL_TAG, "%d certificate(s) in own cert chain do not satisfy OCF profile requirements", ret);
        goto required;
    }

777
    ret =  mbedtls_pk_parse_key(&g_caSslContext->pkey, pkiInfo.key.data, pkiInfo.key.len,
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
                                                                               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;
    }

798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
    /* If we get here, certificates could be used, so configure OCF EKUs. */
    ret = mbedtls_ssl_conf_ekus(serverConf, (const char*)EKU_IDENTITY, sizeof(EKU_IDENTITY),
        (const char*)EKU_IDENTITY, sizeof(EKU_IDENTITY));
    if (0 == ret)
    {
        ret = mbedtls_ssl_conf_ekus(clientConf, (const char*)EKU_IDENTITY, sizeof(EKU_IDENTITY),
            (const char*)EKU_IDENTITY, sizeof(EKU_IDENTITY));
    }
    if (0 != ret)
    {
        /* Cert-based ciphersuites will fail, but if PSK ciphersuites are in
         * the list they might work, so don't return error.
         */
        OIC_LOG(WARNING, NET_SSL_TAG, "EKU configuration error");
    }

814
    required:
815
    count = ParseChain(&g_caSslContext->ca, pkiInfo.ca.data, pkiInfo.ca.len, &errNum);
Oleksii Beketov's avatar
Oleksii Beketov committed
816
    if(0 >= count)
817 818 819
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "CA chain parsing error");
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
820
        DeInitPkixInfo(&pkiInfo);
821 822
        return -1;
    }
Oleksii Beketov's avatar
Oleksii Beketov committed
823 824 825 826
    if(0 != errNum)
    {
        OIC_LOG_V(WARNING, NET_SSL_TAG, "CA chain parsing warning: %d certs failed to parse", errNum);
    }
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
    else
    {
        ret = ValidateRootCACertListProfiles(&g_caSslContext->ca);
        if (CP_INVALID_CERT_LIST == ret)
        {
            OIC_LOG(ERROR, NET_SSL_TAG, "Invalid own CA cert chain");
            OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
            DeInitPkixInfo(&pkiInfo);
            return -1;
        }
        else if (0 < ret )
        {
            OIC_LOG_V(ERROR, NET_SSL_TAG, "%d certificate(s) in own CA cert chain violate OCF Root CA cert profile requirements", ret);
            OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
            DeInitPkixInfo(&pkiInfo);
            return -1;
        }
    }
845

846
    ret = mbedtls_x509_crl_parse_der(&g_caSslContext->crl, pkiInfo.crl.data, pkiInfo.crl.len);
847 848 849
    if(0 != ret)
    {
        OIC_LOG(WARNING, NET_SSL_TAG, "CRL parsing error");
Oleksii Beketov's avatar
Oleksii Beketov committed
850
        CONF_SSL(clientConf, serverConf, mbedtls_ssl_conf_ca_chain, &g_caSslContext->ca, NULL);
851 852 853
    }
    else
    {
Oleksii Beketov's avatar
Oleksii Beketov committed
854 855
        CONF_SSL(clientConf, serverConf, mbedtls_ssl_conf_ca_chain,
                 &g_caSslContext->ca, &g_caSslContext->crl);
856 857
    }

858 859
    DeInitPkixInfo(&pkiInfo);

860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
    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);
881 882 883
    VERIFY_TRUE_RET((descLen <= CA_MAX_ENDPOINT_IDENTITY_LEN), NET_SSL_TAG,
                    "desc too long!", -1);

884 885 886 887 888 889 890 891
    (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);
892
        ((SslEndPoint_t *) ssl)->sep.identity.id_length = (uint16_t)descLen;
893 894 895
        OIC_LOG(DEBUG, NET_SSL_TAG, "PSK:");
        OIC_LOG_BUFFER(DEBUG, NET_SSL_TAG, keyBuf, ret);

896 897 898
        OIC_LOG(DEBUG, NET_SSL_TAG, "Identity:");
        OIC_LOG_BUFFER(DEBUG, NET_SSL_TAG, desc, descLen);

899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
        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)
{
914 915
    size_t listIndex = 0;
    size_t listLength = 0;
916
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
917 918 919

    oc_mutex_assert_owner(g_sslContextMutex, true);

920
    VERIFY_NON_NULL_RET(peer, NET_SSL_TAG, "TLS peer is NULL", NULL);
921
    VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", NULL);
922 923 924 925 926 927 928 929 930 931

    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;
        }
932 933 934 935 936 937 938 939

        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Compare [%s:%d] and [%s:%d] for %d adapter",
                  peer->addr, peer->port, tep->sep.endpoint.addr, tep->sep.endpoint.port,
                  peer->adapter);

        if((peer->adapter == tep->sep.endpoint.adapter)
                && (0 == strncmp(peer->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA))
                && (peer->port == tep->sep.endpoint.port || CA_ADAPTER_GATT_BTLE == peer->adapter))
940 941 942 943 944 945 946 947 948
        {
            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;
}
949 950

/**
951
 * Gets a copy of CA secure endpoint info corresponding for endpoint.
952 953
 *
 * @param[in]  peer    remote address
954
 * @param[out] sep     copy of secure endpoint data
955
 *
956
 * @return  CA_STATUS_OK on success; other error code on failure
957
 */
958
CAResult_t GetCASecureEndpointData(const CAEndpoint_t* peer, CASecureEndpoint_t* sep)
959 960 961 962
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);

    oc_mutex_lock(g_sslContextMutex);
963

964 965 966 967
    if (NULL == g_caSslContext)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
        oc_mutex_unlock(g_sslContextMutex);
968
        return CA_STATUS_NOT_INITIALIZED;
969 970 971
    }

    SslEndPoint_t* sslPeer = GetSslPeer(peer);
972
    if (sslPeer)
973
    {
974 975
        // sslPeer could be destroyed after releasing the lock, so make a copy
        // of the endpoint information before releasing the lock.
976
        memcpy(sep, &sslPeer->sep, sizeof(sslPeer->sep));
977
        oc_mutex_unlock(g_sslContextMutex);
978 979

        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
980
        return CA_STATUS_OK;
981 982 983
    }

    oc_mutex_unlock(g_sslContextMutex);
984 985 986

    OIC_LOG(DEBUG, NET_SSL_TAG, "GetSslPeer returned NULL");
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
987
    return CA_STATUS_INVALID_PARAM;
988 989
}

990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
/**
 * Adds a bit to the attributes field of a secure endpoint.
 *
 * @param[in]  peer         remote address
 * @param[in]  newAttribute bit to be added to the attributes field
 *
 * @return  true if the secure endpoint has been found, false otherwise.
 */
bool SetCASecureEndpointAttribute(const CAEndpoint_t* peer, uint32_t newAttribute)
{
    bool result = false;

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s(peer = %s:%u, attribute = %#x)", __func__,
        peer->addr, (uint32_t)peer->port, newAttribute);

1005
    // In the current implementation, the caller already owns g_sslContextMutex.
1006
    oc_mutex_assert_owner(g_sslContextMutex, true);
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

    if (NULL == g_caSslContext)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
    }
    else
    {
        SslEndPoint_t* sslPeer = GetSslPeer(peer);

        if (!sslPeer)
        {
            OIC_LOG(ERROR, NET_SSL_TAG, "SSL peer not found");
        }
        else
        {
            sslPeer->sep.attributes |= newAttribute;
            result = true;
        }
    }

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s -> %s", __func__, result ? "success" : "failed");
    return result;
}

/**
 * Gets the attributes field of a secure endpoint.
 *
 * @param[in]  peer          remote address
 * @param[out] allAttributes all the attributes bits for that remote address
 *
 * @return  true if the secure endpoint has been found, false otherwise.
 */
bool GetCASecureEndpointAttributes(const CAEndpoint_t* peer, uint32_t* allAttributes)
{
    bool result = false;

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s(peer = %s:%u)", __func__,
        peer->addr, (uint32_t)peer->port);

1046 1047
    // In the current implementation, the caller doesn't own g_sslContextMutex.
    oc_mutex_assert_owner(g_sslContextMutex, false);
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
    oc_mutex_lock(g_sslContextMutex);

    if (NULL == g_caSslContext)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
    }
    else
    {
        SslEndPoint_t* sslPeer = GetSslPeer(peer);

        if (!sslPeer)
        {
            OIC_LOG(ERROR, NET_SSL_TAG, "SSL peer not found");
        }
        else
        {
            *allAttributes = sslPeer->sep.attributes;
            result = true;
        }
    }

    oc_mutex_unlock(g_sslContextMutex);

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s -> %s, attributes = %#x", __func__,
        result ? "success" : "failed", result ? *allAttributes : 0);
    return result;
}

1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
/**
 * 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");
1100 1101
    size_t listIndex = 0;
    size_t listLength = 0;
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115

    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__);
}
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126

static CAResult_t ConvertMbedtlsCodesToCAResult(int code)
{
    //TODO:properly implement
    switch (code)
    {
        case 0:  return CA_STATUS_OK;
        default: return CA_DTLS_AUTHENTICATION_FAILURE;
    }
}

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
/**
 * 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);
    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)
{
1149 1150
    oc_mutex_assert_owner(g_sslContextMutex, true);

1151
    VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL");
1152
    VERIFY_NON_NULL_VOID(endpoint, NET_SSL_TAG, "endpoint");
1153

1154 1155
    size_t listLength = u_arraylist_length(g_caSslContext->peerList);
    for (size_t listIndex = 0; listIndex < listLength; listIndex++)
1156
    {
1157
        SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList, listIndex);
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
        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;
        }
    }
}
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188

 /**
  * Checks handshake result. Removes peer from list and sends alert
  * if handshake failed.
  *
  * @param[in] peer Remote peer's endpoint.
  * @param[in] ret  Error code.
  * @param[in] str  Debug string.
  * @param[in] msg  Alert message.
  *
  * @return - "true" if the SSL handshake was successful.
  *         - "false" otherwise.
  */
static bool checkSslOperation(SslEndPoint_t*  peer,
                              int ret,
                              const char* str,
                              unsigned char msg)
{
1189
    OC_UNUSED(str);
1190
    OC_UNUSED(msg);
1191

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
    if ((0 != ret) &&
        (MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY != ret) &&
        (MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED != ret) &&
        (MBEDTLS_ERR_SSL_WANT_READ != ret) &&
        (MBEDTLS_ERR_SSL_WANT_WRITE != ret) &&
        (MBEDTLS_ERR_SSL_NON_FATAL != ret) &&
        (MBEDTLS_SSL_ALERT_MSG_USER_CANCELED != ret) &&
        (MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION != ret) &&
        (MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT != ret) &&
        (MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY != ret) &&
        (MBEDTLS_SSL_ALERT_MSG_NO_CERT != ret) &&
        (MBEDTLS_SSL_ALERT_MSG_BAD_CERT != ret) &&
        (MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT != ret) &&
        (MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED != ret) &&
        (MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED != ret) &&
        (MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN != ret) &&
        (MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK != ret) &&
        (MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME != ret) &&
        (MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY != ret) &&
        (MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL != ret))
    {
Oleksandr Dmytrenko's avatar
Oleksandr Dmytrenko committed
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
        size_t bufSize = 1024;
        char *bufMsg = (char*)OICCalloc(1, bufSize);
        if (bufMsg)
        {
            mbedtls_strerror(ret, bufMsg, bufSize);
            OIC_LOG_V(ERROR, NET_SSL_TAG, "%s: 0x%X: %s", __func__, -ret, bufMsg);
            OICFree(bufMsg);
        }
        else
        {
            OIC_LOG_V(ERROR, NET_SSL_TAG, "%s: -0x%x", (str), -ret);
        }
1225 1226

        // Make a copy of the endpoint, because the callback might
1227
        // free the peer object, during notifySubscriber() below.
1228 1229
        CAEndpoint_t removedEndpoint = (peer)->sep.endpoint;

1230
        oc_mutex_lock(g_sslContextMutex);
1231 1232 1233

        if (MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO != ret)
        {
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
            CAResult_t result = notifySubscriber(peer, CA_DTLS_AUTHENTICATION_FAILURE);

            //return an error to app layer
            if (MBEDTLS_SSL_IS_CLIENT == peer->ssl.conf->endpoint)
            {
                if (CA_STATUS_OK == result)
                {
                    result = ConvertMbedtlsCodesToCAResult(ret);
                }

                SendCacheMessages(peer, result);
            }
1246 1247
        }

1248
        RemovePeerFromList(&removedEndpoint);
1249 1250

        oc_mutex_unlock(g_sslContextMutex);
1251 1252 1253 1254 1255 1256
        return false;
    }

    return true;
}

1257 1258 1259 1260 1261
/**
 * Deletes session list.
 */
static void DeletePeerList()
{
1262 1263
    oc_mutex_assert_owner(g_sslContextMutex, true);

1264 1265
    VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL");

1266 1267
    size_t listLength = u_arraylist_length(g_caSslContext->peerList);
    for (size_t listIndex = 0; listIndex < listLength; listIndex++)
1268
    {
1269
        SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList, listIndex);
1270 1271 1272 1273
        if (NULL == tep)
        {
            continue;
        }
Dmitriy Zhuravlev's avatar
Dmitriy Zhuravlev committed
1274 1275 1276 1277 1278 1279 1280 1281 1282
        if (MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
        {
            int ret = 0;
            do
            {
                ret = mbedtls_ssl_close_notify(&tep->ssl);
            }
            while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);
        }
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
        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;
}
1321

1322
void CAcloseSslConnectionAll(CATransportAdapter_t transportType)
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
{
    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
    oc_mutex_lock(g_sslContextMutex);
    if (NULL == g_caSslContext)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
        oc_mutex_unlock(g_sslContextMutex);
        return;
    }

1333
    size_t listLength = u_arraylist_length(g_caSslContext->peerList);
1334
    OIC_LOG_V(DEBUG, NET_SSL_TAG,
1335 1336
            "Required transport [%d], peer count [%" PRIuPTR "]", transportType, listLength);
    for (size_t i = listLength; i > 0; i--)
1337
    {
1338
        SslEndPoint_t *tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList, i - 1);
1339 1340 1341 1342
        if (NULL == tep)
        {
            continue;
        }
1343 1344 1345 1346 1347 1348 1349 1350 1351
        OIC_LOG_V(DEBUG, NET_SSL_TAG, "SSL Connection [%s:%d], Transport [%d]",
                  tep->sep.endpoint.addr, tep->sep.endpoint.port, tep->sep.endpoint.adapter);

        // check transport matching
        if (0 == (tep->sep.endpoint.adapter & transportType))
        {
            OIC_LOG(DEBUG, NET_SSL_TAG, "Skip the un-matched transport session");
            continue;
        }
1352 1353 1354 1355 1356 1357 1358 1359 1360

        // TODO: need to check below code after socket close is ensured.
        /*int ret = 0;
        do
        {
            ret = mbedtls_ssl_close_notify(&tep->ssl);
        }
        while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);*/

1361 1362
        // delete from list
        u_arraylist_remove(g_caSslContext->peerList, i - 1);
1363 1364 1365 1366 1367 1368 1369
        DeleteSslEndPoint(tep);
    }
    oc_mutex_unlock(g_sslContextMutex);

    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
    return;
}
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
/**
 * 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);
1384
    VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", NULL);
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406

    tep = (SslEndPoint_t *) OICCalloc(1, sizeof (SslEndPoint_t));
    if (NULL == tep)
    {
        OIC_LOG(ERROR, NET_SSL_TAG, "Malloc fail