credresource.c 132 KB
Newer Older
Sachin Agrawal's avatar
Sachin Agrawal committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
//******************************************************************
//
// Copyright 2015 Intel Mobile Communications GmbH 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

21
#define __STDC_LIMIT_MACROS
Sahil Bansal's avatar
Sahil Bansal committed
22

23
#include "iotivity_config.h"
Sahil Bansal's avatar
Sahil Bansal committed
24
#include <stdlib.h>
25
#ifdef HAVE_STRING_H
Sahil Bansal's avatar
Sahil Bansal committed
26
#include <string.h>
27 28
#endif
#ifdef HAVE_STRINGS_H
Sahil Bansal's avatar
Sahil Bansal committed
29 30 31
#include <strings.h>
#endif
#include <stdint.h>
Andrii Shtompel's avatar
Andrii Shtompel committed
32
#include <stdbool.h>
George Nash's avatar
George Nash committed
33
#include <inttypes.h>
Sahil Bansal's avatar
Sahil Bansal committed
34 35 36

#include "cainterface.h"
#include "payload_logging.h"
Sachin Agrawal's avatar
Sachin Agrawal committed
37
#include "ocstack.h"
Sahil Bansal's avatar
Sahil Bansal committed
38 39 40
#include "ocrandom.h"
#include "base64.h"
#include "ocserverrequest.h"
Sachin Agrawal's avatar
Sachin Agrawal committed
41
#include "oic_malloc.h"
42
#include "oic_string.h"
Sahil Bansal's avatar
Sahil Bansal committed
43
#include "ocpayload.h"
44
#include "ocpayloadcbor.h"
Sachin Agrawal's avatar
Sachin Agrawal committed
45 46 47
#include "utlist.h"
#include "credresource.h"
#include "doxmresource.h"
Sahil Bansal's avatar
Sahil Bansal committed
48
#include "pstatresource.h"
leechul's avatar
leechul committed
49
#include "iotvticalendar.h"
Sahil Bansal's avatar
Sahil Bansal committed
50 51 52 53 54 55
#include "pbkdf2.h"
#include "resourcemanager.h"
#include "srmresourcestrings.h"
#include "srmutility.h"
#include "psinterface.h"
#include "pinoxmcommon.h"
Kevin Kane's avatar
Kevin Kane committed
56 57
#include "certhelpers.h"
#include "cacommon.h"
58
#include "secureresourcemanager.h"
59
#include "deviceonboardingstate.h"
60

Andrii Shtompel's avatar
Andrii Shtompel committed
61 62 63 64 65 66 67
#ifdef __unix__
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#endif

68 69
#if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
#include <mbedtls/ssl_ciphersuites.h>
70 71 72
#include <mbedtls/pk.h>
#include <mbedtls/base64.h>
#include <mbedtls/pem.h>
Sahil Bansal's avatar
Sahil Bansal committed
73
#endif
leechul's avatar
leechul committed
74

75
#define TAG  "OIC_SRM_CREDL"
Sahil Bansal's avatar
Sahil Bansal committed
76

77 78
#ifdef HAVE_WINDOWS_H
#include <wincrypt.h>
79
#include <intsafe.h>
80 81
#endif

Andrii Shtompel's avatar
Andrii Shtompel committed
82 83
/** Max credential types number used for TLS */
#define MAX_TYPE 2
Sahil Bansal's avatar
Sahil Bansal committed
84 85
/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
 * The value of payload size is increased until reaching belox max cbor size. */
leechul's avatar
leechul committed
86
static const uint16_t CBOR_SIZE = 2048;
87

leechul's avatar
leechul committed
88
/** CRED size - Number of mandatory items. */
Randeep's avatar
Randeep committed
89
static const uint8_t CRED_ROOT_MAP_SIZE = 4;
90
static const uint8_t CRED_EMPTY_ROOT_MAP_SIZE = 2;
leechul's avatar
leechul committed
91
static const uint8_t CRED_MAP_SIZE = 3;
92
static const uint8_t ROLEID_MAP_SIZE = 1;
leechul's avatar
leechul committed
93

Shilpa Sodani's avatar
Shilpa Sodani committed
94

Sachin Agrawal's avatar
Sachin Agrawal committed
95 96 97
static OicSecCred_t        *gCred = NULL;
static OCResourceHandle    gCredHandle = NULL;

98 99 100 101 102 103
typedef enum CredCompareResult{
    CRED_CMP_EQUAL = 0,
    CRED_CMP_NOT_EQUAL = 1,
    CRED_CMP_ERROR = 2
}CredCompareResult_t;

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
typedef struct CredIdList CredIdList_t;

struct CredIdList
{
    uint16_t credId;
    CredIdList_t *next;
};

static void DeleteCredIdList(CredIdList_t** list)
{
    if (list)
    {
        CredIdList_t *head = *list;

        while (head)
        {
            CredIdList_t *tmp = head->next;
            OICFree(head);
            head = tmp;
        }
    }
}

127 128 129 130
static bool ValueWithinBounds(uint64_t value, uint64_t maxValue)
{
    if (value > maxValue)
    {
131
        OIC_LOG_V(ERROR, TAG, "The value (%" PRId64 ") is greater than allowed maximum of %" PRId64 ".", value, maxValue);
132 133 134 135 136 137
        return false;
    }

    return true;
}

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
/**
 * Internal function to check a subject of SIGNED_ASYMMETRIC_KEY(Certificate).
 * If that subject is NULL or wildcard, set it to own deviceID.
 * @param cred credential on SVR DB file
 * @param deviceID own deviceuuid of doxm resource
 *
 * @return
 *     true successfully done
 *     false Invalid cred
 */

static bool CheckSubjectOfCertificate(OicSecCred_t* cred, OicUuid_t deviceID)
{
    OIC_LOG(DEBUG, TAG, "IN CheckSubjectOfCertificate");
    VERIFY_NOT_NULL(TAG, cred, ERROR);

#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
155 156
    const OicUuid_t emptyUuid = { .id = { 0 } };

157 158 159 160 161 162 163 164
    if ( SIGNED_ASYMMETRIC_KEY == cred->credType)
    {
        if((0 == memcmp(cred->subject.id, emptyUuid.id, sizeof(cred->subject.id))) ||
            (0 == memcmp(cred->subject.id, &WILDCARD_SUBJECT_ID, sizeof(cred->subject.id))))
        {
            memcpy(cred->subject.id, deviceID.id, sizeof(deviceID.id));
        }
    }
165 166
#else
    OC_UNUSED(deviceID);
167 168 169 170 171 172 173 174 175
#endif

    OIC_LOG(DEBUG, TAG, "OUT CheckSubjectOfCertificate");
    return true;
exit:
    OIC_LOG(ERROR, TAG, "OUT CheckSubjectOfCertificate");
    return false;
}

176 177 178
/**
 * Internal function to check credential
 */
179
static bool IsValidCredential(const OicSecCred_t* cred)
180 181 182 183
{
    OicUuid_t emptyUuid = {.id={0}};


184
    OIC_LOG(DEBUG, TAG, "IN IsValidCredential");
185

186
    VERIFY_NOT_NULL(TAG, cred, ERROR);
187 188 189 190 191 192 193 194 195 196 197 198
    VERIFY_SUCCESS(TAG, 0 != cred->credId, ERROR);
    OIC_LOG_V(DEBUG, TAG, "Cred ID = %d", cred->credId);

#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
    OIC_LOG_V(DEBUG, TAG, "Cred Type = %d", cred->credType);

    switch(cred->credType)
    {
        case SYMMETRIC_PAIR_WISE_KEY:
        case SYMMETRIC_GROUP_KEY:
        case PIN_PASSWORD:
        {
199
            VERIFY_NOT_NULL(TAG, cred->privateData.data, ERROR);
200 201 202 203 204 205 206 207 208
            VERIFY_SUCCESS(TAG, 0 != cred->privateData.len, ERROR);
            VERIFY_SUCCESS(TAG, \
                           (OIC_ENCODING_RAW == cred->privateData.encoding || \
                           OIC_ENCODING_BASE64 == cred->privateData.encoding), \
                           ERROR);
            break;
        }
        case ASYMMETRIC_KEY:
        {
209
            VERIFY_NOT_NULL(TAG, cred->publicData.data, ERROR);
210
            VERIFY_SUCCESS(TAG, 0 != cred->publicData.len, ERROR);
211 212 213 214
            VERIFY_SUCCESS(TAG, \
                           (OIC_ENCODING_UNKNOW < cred->publicData.encoding && \
                            OIC_ENCODING_DER >= cred->publicData.encoding),
                           ERROR);
215 216 217 218 219 220 221 222 223 224
            break;
        }
        case SIGNED_ASYMMETRIC_KEY:
        {
            VERIFY_SUCCESS(TAG, (NULL != cred->publicData.data ||NULL != cred->optionalData.data) , ERROR);
            VERIFY_SUCCESS(TAG, (0 != cred->publicData.len || 0 != cred->optionalData.len), ERROR);

            if(NULL != cred->optionalData.data)
            {
                VERIFY_SUCCESS(TAG, \
225 226
                               (OIC_ENCODING_UNKNOW < cred->optionalData.encoding && \
                                OIC_ENCODING_DER >= cred->optionalData.encoding),
227 228 229 230 231 232
                               ERROR);
            }
            break;
        }
        case ASYMMETRIC_ENCRYPTION_KEY:
        {
233
            VERIFY_NOT_NULL(TAG, cred->privateData.data, ERROR);
234 235
            VERIFY_SUCCESS(TAG, 0 != cred->privateData.len, ERROR);
            VERIFY_SUCCESS(TAG, \
236 237
                           (OIC_ENCODING_UNKNOW < cred->privateData.encoding && \
                            OIC_ENCODING_DER >= cred->privateData.encoding),
238 239 240 241 242 243 244 245 246 247 248 249 250
                           ERROR);
            break;
        }
        default:
        {
            OIC_LOG(WARNING, TAG, "Unknown credential type");
            return false;
        }
    }
#endif

    VERIFY_SUCCESS(TAG, 0 != memcmp(emptyUuid.id, cred->subject.id, sizeof(cred->subject.id)), ERROR);

251
    OIC_LOG(DEBUG, TAG, "OUT IsValidCredential");
252 253
    return true;
exit:
254
    OIC_LOG(WARNING, TAG, "OUT IsValidCredential : Invalid Credential detected.");
255 256 257
    return false;
}

258 259 260 261 262
static bool IsEmptyCred(const OicSecCred_t* cred)
{
    OicUuid_t emptyUuid = {.id={0}};

    VERIFY_SUCCESS(TAG, (0 == memcmp(cred->subject.id, emptyUuid.id, sizeof(emptyUuid))), ERROR);
263
    VERIFY_SUCCESS(TAG, !IsNonEmptyRole(&cred->roleId), ERROR);
264 265 266 267 268 269 270 271 272 273 274 275 276
    VERIFY_SUCCESS(TAG, (0 == cred->credId), ERROR);
    VERIFY_SUCCESS(TAG, (0 == cred->credType), ERROR);
#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
    VERIFY_SUCCESS(TAG, (NULL == cred->privateData.data), ERROR);
    VERIFY_SUCCESS(TAG, (NULL == cred->publicData.data), ERROR);
    VERIFY_SUCCESS(TAG, (NULL == cred->optionalData.data), ERROR);
    VERIFY_SUCCESS(TAG, (NULL == cred->credUsage), ERROR);
#endif
    return true;
exit:
    return false;
}

277 278 279 280
/**
 * This function frees OicSecCred_t object's fields and object itself.
 */
static void FreeCred(OicSecCred_t *cred)
Sachin Agrawal's avatar
Sachin Agrawal committed
281
{
282
    if(NULL == cred)
Sachin Agrawal's avatar
Sachin Agrawal committed
283
    {
Sahil Bansal's avatar
Sahil Bansal committed
284
        OIC_LOG(ERROR, TAG, "Invalid Parameter");
285 286 287
        return;
    }
    //Note: Need further clarification on roleID data type
Sachin Agrawal's avatar
Sachin Agrawal committed
288
#if 0
289 290
    //Clean roleIds
    OICFree(cred->roleIds);
Sachin Agrawal's avatar
Sachin Agrawal committed
291 292
#endif

293
    //Clean PublicData/OptionalData/Credusage
294
#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
295
     // TODO: Need to check credUsage.
296
    OICFree(cred->publicData.data);
297 298 299
    OICFree(cred->optionalData.data);
    OICFree(cred->credUsage);

300
#endif /* __WITH_DTLS__ ||  __WITH_TLS__*/
Sachin Agrawal's avatar
Sachin Agrawal committed
301

302
    //Clean PrivateData
303
    OICClearMemory(cred->privateData.data, cred->privateData.len);
304
    OICFree(cred->privateData.data);
Sachin Agrawal's avatar
Sachin Agrawal committed
305

306 307
    //Clean Period
    OICFree(cred->period);
Sachin Agrawal's avatar
Sachin Agrawal committed
308

saurabh.s9's avatar
saurabh.s9 committed
309
#ifdef MULTIPLE_OWNER
310 311 312 313
    //Clean eowner
    OICFree(cred->eownerID);
#endif

314 315 316
    //Clean Cred node itself
    OICFree(cred);
}
Sachin Agrawal's avatar
Sachin Agrawal committed
317

318 319 320 321 322 323 324 325 326
void DeleteCredList(OicSecCred_t* cred)
{
    if (cred)
    {
        OicSecCred_t *credTmp1 = NULL, *credTmp2 = NULL;
        LL_FOREACH_SAFE(cred, credTmp1, credTmp2)
        {
            LL_DELETE(cred, credTmp1);
            FreeCred(credTmp1);
Sachin Agrawal's avatar
Sachin Agrawal committed
327 328 329 330
        }
    }
}

Andrii Shtompel's avatar
Andrii Shtompel committed
331 332 333 334 335 336 337 338 339 340 341 342
size_t GetCredKeyDataSize(const OicSecCred_t* cred)
{
    size_t size = 0;
    if (cred)
    {
        OicSecCred_t *credPtr = NULL, *credTmp = NULL;
        LL_FOREACH_SAFE((OicSecCred_t*)cred, credPtr, credTmp)
        {
            if (credPtr->privateData.data && 0 < credPtr->privateData.len)
            {
                size += credPtr->privateData.len;
            }
343
#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
Andrii Shtompel's avatar
Andrii Shtompel committed
344 345 346 347 348 349 350 351 352 353 354
            if (credPtr->publicData.data && 0 < credPtr->publicData.len)
            {
                size += credPtr->publicData.len;
            }
            if (credPtr->optionalData.data && 0 < credPtr->optionalData.len)
            {
                size += credPtr->optionalData.len;
            }
#endif
        }
    }
355
    OIC_LOG_V(DEBUG, TAG, "Cred Key Data Size : %u", (unsigned int) size);
Andrii Shtompel's avatar
Andrii Shtompel committed
356 357 358
    return size;
}

Sahil Bansal's avatar
Sahil Bansal committed
359
static size_t OicSecCredCount(const OicSecCred_t *secCred)
Sachin Agrawal's avatar
Sachin Agrawal committed
360
{
Sahil Bansal's avatar
Sahil Bansal committed
361 362
    size_t size = 0;
    for (const OicSecCred_t *cred = secCred; cred; cred = cred->next)
Sachin Agrawal's avatar
Sachin Agrawal committed
363
    {
Sahil Bansal's avatar
Sahil Bansal committed
364 365 366 367
        size++;
    }
    return size;
}
368

369
static const char* EncodingValueToString(OicEncodingType_t encoding)
370 371 372
{
    switch (encoding)
    {
373 374 375 376 377
        case OIC_ENCODING_RAW:    return OIC_SEC_ENCODING_RAW;
        case OIC_ENCODING_BASE64: return OIC_SEC_ENCODING_BASE64;
        case OIC_ENCODING_DER:    return OIC_SEC_ENCODING_DER;
        case OIC_ENCODING_PEM:    return OIC_SEC_ENCODING_PEM;
        default:                  return NULL;
378 379 380 381 382 383
    }
}

static CborError SerializeEncodingToCborInternal(CborEncoder *map, const OicSecKey_t *value)
{
    CborError cborEncoderResult = CborNoError;
384
    const char *encoding = EncodingValueToString(value->encoding);
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
    if (encoding)
    {
        cborEncoderResult = cbor_encode_text_string(map, OIC_JSON_ENCODING_NAME,
            strlen(OIC_JSON_ENCODING_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Encoding Tag.");
        cborEncoderResult = cbor_encode_text_string(map, encoding,
            strlen(encoding));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Encoding Value.");

        cborEncoderResult = cbor_encode_text_string(map, OIC_JSON_DATA_NAME,
            strlen(OIC_JSON_DATA_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Name Tag.");
        if (OIC_ENCODING_DER == value->encoding ||
            OIC_ENCODING_RAW == value->encoding)
        {
            cborEncoderResult = cbor_encode_byte_string(map,
                    value->data, value->len);
        }
        else
        {
            cborEncoderResult = cbor_encode_text_string(map,
                    (char*)value->data, value->len);
        }
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Name Value.");
    }
    else
    {
412
        OIC_LOG_V(ERROR, TAG, "%s: Unknown encoding type: %u.", __func__, value->encoding);
413
        return CborErrorUnknownType;
414 415 416 417 418
    }
    exit:
    return cborEncoderResult;
}

419
CborError SerializeEncodingToCbor(CborEncoder *rootMap, const char* tag, const OicSecKey_t *value)
420 421 422 423 424 425 426 427 428 429 430
{
    CborError cborEncoderResult = CborNoError;
    CborEncoder map;
    const size_t mapSize = 2;

    cborEncoderResult = cbor_encode_text_string(rootMap, tag, strlen(tag));
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PrivateData Tag.");

    cborEncoderResult = cbor_encoder_create_map(rootMap, &map, mapSize);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Map");

431 432
    cborEncoderResult = SerializeEncodingToCborInternal(&map, value);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed adding OicSecKey_t structure");
433 434 435 436 437 438 439 440

    cborEncoderResult = cbor_encoder_close_container(rootMap, &map);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Map.");

    exit:
    return cborEncoderResult;
}

441
CborError SerializeSecOptToCbor(CborEncoder *rootMap, const char* tag, const OicSecOpt_t *value)
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
{
    CborError cborEncoderResult = CborNoError;
    CborEncoder map;
    const size_t mapSize = 3;

    cborEncoderResult = cbor_encode_text_string(rootMap, tag, strlen(tag));
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PrivateData Tag.");

    cborEncoderResult = cbor_encoder_create_map(rootMap, &map, mapSize);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Map");

    OicSecKey_t in;
    in.data = value->data;
    in.encoding = value->encoding;
    in.len = value->len;

458 459
    cborEncoderResult = SerializeEncodingToCborInternal(&map, &in);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed adding OicSecKey_t structure");
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

    cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_REVOCATION_STATUS_NAME,
        strlen(OIC_JSON_REVOCATION_STATUS_NAME));
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding optional revstat Tag.");
    cborEncoderResult = cbor_encode_boolean(&map, value->revstat);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding optional revstat Value.");

    cborEncoderResult = cbor_encoder_close_container(rootMap, &map);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Map.");

    exit:
    return cborEncoderResult;
}

static CborError DeserializeEncodingFromCborInternal(CborValue *map, char *name, OicSecKey_t *value)
{
    size_t len = 0;
    CborError cborFindResult = CborNoError;

    // data -- Mandatory
    if (strcmp(name, OIC_JSON_DATA_NAME) == 0)
    {
        if(cbor_value_is_byte_string(map))
        {
            cborFindResult = cbor_value_dup_byte_string(map, &value->data,
                &value->len, NULL);
        }
        else if(cbor_value_is_text_string(map))
        {
            cborFindResult = cbor_value_dup_text_string(map, (char**)(&value->data),
                &value->len, NULL);
        }
        else
        {
            cborFindResult = CborErrorUnknownType;
            OIC_LOG(ERROR, TAG, "Unknown type for private data.");
        }
        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PrivateData.");
    }

    // encoding -- Mandatory
    if (strcmp(name, OIC_JSON_ENCODING_NAME) == 0)
    {
        char* strEncoding = NULL;
        cborFindResult = cbor_value_dup_text_string(map, &strEncoding, &len, NULL);
        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding EncodingType");

        if(strcmp(strEncoding, OIC_SEC_ENCODING_RAW) == 0)
        {
            value->encoding = OIC_ENCODING_RAW;
        }
        else if(strcmp(strEncoding, OIC_SEC_ENCODING_BASE64) == 0)
        {
            value->encoding = OIC_ENCODING_BASE64;
        }
        else if(strcmp(strEncoding, OIC_SEC_ENCODING_DER) == 0)
        {
            value->encoding = OIC_ENCODING_DER;
        }
        else if(strcmp(strEncoding, OIC_SEC_ENCODING_PEM) == 0)
        {
            value->encoding = OIC_ENCODING_PEM;
        }
        else
        {
            //For unit test
            value->encoding = OIC_ENCODING_RAW;
527
            OIC_LOG_V(WARNING, TAG, "%s: Unknown encoding type detected.", __func__);
528
        }
529 530
        //Because cbor using malloc directly, it is required to use free() instead of OICFree
        free(strEncoding);
531 532 533 534 535
    }
    exit:
    return cborFindResult;
}

536
CborError DeserializeEncodingFromCbor(CborValue *rootMap, OicSecKey_t *value)
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
{
    CborValue map = { .parser = NULL };
    CborError cborFindResult = cbor_value_enter_container(rootMap, &map);
    size_t len = 0;

    while (cbor_value_is_valid(&map))
    {
        char* name = NULL;
        CborType type = cbor_value_get_type(&map);
        if (type == CborTextStringType && cbor_value_is_text_string(&map))
        {
            cborFindResult = cbor_value_dup_text_string(&map, &name, &len, NULL);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get text");
            cborFindResult = cbor_value_advance(&map);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance value");
        }
        if (name)
        {
555 556
            cborFindResult = DeserializeEncodingFromCborInternal(&map, name, value);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to read OicSecKey_t value");
557 558 559 560 561 562
        }
        if (cbor_value_is_valid(&map))
        {
            cborFindResult = cbor_value_advance(&map);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Map.");
        }
563 564
        //Because cbor using malloc directly, it is required to use free() instead of OICFree
        free(name);
565 566 567 568 569
    }
    exit:
    return cborFindResult;
}

570
CborError DeserializeSecOptFromCbor(CborValue *rootMap, OicSecOpt_t *value)
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
{
    CborValue map = { .parser = NULL };
    CborError cborFindResult = cbor_value_enter_container(rootMap, &map);
    size_t len = 0;
    value->revstat = false;

    while (cbor_value_is_valid(&map))
    {
        char* name = NULL;
        CborType type = cbor_value_get_type(&map);
        if (type == CborTextStringType && cbor_value_is_text_string(&map))
        {
            cborFindResult = cbor_value_dup_text_string(&map, &name, &len, NULL);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get text");
            cborFindResult = cbor_value_advance(&map);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance value");
        }
        if (name)
        {
            // OptionalData::revstat -- Mandatory
            if (strcmp(name, OIC_JSON_REVOCATION_STATUS_NAME) == 0)
            {
                cborFindResult = cbor_value_get_boolean(&map, &value->revstat);
                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding revstat Value.")
            }
            OicSecKey_t out;
597 598
            cborFindResult = DeserializeEncodingFromCborInternal(&map, name, &out);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to read OicSecKey_t value");
599 600 601 602 603 604 605 606 607 608

            value->data = out.data;
            value->encoding = out.encoding;
            value->len = out.len;
        }
        if (cbor_value_is_valid(&map))
        {
            cborFindResult = cbor_value_advance(&map);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Map.");
        }
609 610
        //Because cbor using malloc directly, it is required to use free() instead of OICFree
        free(name);
611 612 613 614 615
    }
    exit:
    return cborFindResult;
}

616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
/* Produce debugging output for all credentials, output metadata. */
static void logCredMetadata()
{
#if defined(TB_LOG)
    OicSecCred_t * temp = NULL;
    size_t count = 0;
    char uuidString[UUID_STRING_SIZE];
    OicUuid_t ownUuid;

    OIC_LOG_V(DEBUG, TAG, "IN %s:", __func__);

    if (GetDoxmDeviceID(&ownUuid) == OC_STACK_OK && OCConvertUuidToString(ownUuid.id, uuidString))
    {
        OIC_LOG_V(DEBUG, TAG, "Own UUID: %s", uuidString);
    }

    LL_FOREACH(gCred, temp)
    {
        count++;
        OIC_LOG(DEBUG, TAG, " ");
        OIC_LOG_V(DEBUG, TAG, "Cred ID: %d", temp->credId);
        if (OCConvertUuidToString(temp->subject.id, uuidString))
        {
            OIC_LOG_V(DEBUG, TAG, "Subject UUID: %s", uuidString);
        }
641 642 643 644 645
        if (IsNonEmptyRole(&temp->roleId))
        {
            OIC_LOG_V(DEBUG, TAG, "Role ID: %s", temp->roleId.id);
            OIC_LOG_V(DEBUG, TAG, "Role authority: %s", temp->roleId.authority);
        }
646
        OIC_LOG_V(DEBUG, TAG, "Cred Type: %d", temp->credType);
647
        OIC_LOG_V(DEBUG, TAG, "privateData length: %" PRIuPTR ", encoding: %d", temp->privateData.len, temp->privateData.encoding);
648 649

#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
650
        OIC_LOG_V(DEBUG, TAG, "publicData length: %" PRIuPTR ", encoding: %d", temp->publicData.len, temp->publicData.encoding);
651 652 653 654 655
        if (temp->credUsage)
        {
            OIC_LOG_V(DEBUG, TAG, "credUsage: %s", temp->credUsage);
        }

656
        OIC_LOG_V(DEBUG, TAG, "optionalData length: %" PRIuPTR", encoding: %d" PRIuPTR, temp->optionalData.len, temp->optionalData.encoding);
657 658 659 660
#endif

    }

661
    OIC_LOG_V(DEBUG, TAG, "Found %" PRIuPTR " credentials.", count);
662 663 664 665 666

    OIC_LOG_V(DEBUG, TAG, "OUT %s:", __func__);
#endif
}

Sahil Bansal's avatar
Sahil Bansal committed
667
OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload,
668
                                size_t *cborSize, int secureFlag)
Sahil Bansal's avatar
Sahil Bansal committed
669
{
670
    OIC_LOG_V(DEBUG, TAG, "IN %s:", __func__);
671
    if (NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
Sahil Bansal's avatar
Sahil Bansal committed
672 673 674
    {
        return OC_STACK_INVALID_PARAM;
    }
675

Sahil Bansal's avatar
Sahil Bansal committed
676
    OCStackResult ret = OC_STACK_ERROR;
Sachin Agrawal's avatar
Sachin Agrawal committed
677

leechul's avatar
leechul committed
678 679 680
    CborError cborEncoderResult = CborNoError;
    uint8_t *outPayload = NULL;
    size_t cborLen = *cborSize;
Sahil Bansal's avatar
Sahil Bansal committed
681 682
    *cborSize = 0;
    *cborPayload = NULL;
leechul's avatar
leechul committed
683
    const OicSecCred_t *cred = credS;
684 685 686
    CborEncoder encoder;
    CborEncoder credArray;
    CborEncoder credRootMap;
687
    CborEncoder roleIdMap;
Sachin Agrawal's avatar
Sachin Agrawal committed
688

leechul's avatar
leechul committed
689 690 691 692 693 694
    if (0 == cborLen)
    {
        cborLen = CBOR_SIZE;
    }

    outPayload = (uint8_t *)OICCalloc(1, cborLen);
695 696
    VERIFY_NOT_NULL_RETURN(TAG, outPayload, ERROR, OC_STACK_ERROR);

Sahil Bansal's avatar
Sahil Bansal committed
697
    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
Sachin Agrawal's avatar
Sachin Agrawal committed
698

699 700
    size_t credRootMapSize = (NULL == cred)? CRED_EMPTY_ROOT_MAP_SIZE : CRED_ROOT_MAP_SIZE;

leechul's avatar
leechul committed
701
    // Create CRED Root Map (creds, rownerid)
702
    cborEncoderResult = cbor_encoder_create_map(&encoder, &credRootMap, credRootMapSize);
leechul's avatar
leechul committed
703 704 705 706 707 708 709 710 711 712
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Root Map");

    // creds
    cborEncoderResult = cbor_encode_text_string(&credRootMap, OIC_JSON_CREDS_NAME,
        strlen(OIC_JSON_CREDS_NAME));
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding creds Name Tag.");

    // creds array
    cborEncoderResult = cbor_encoder_create_array(&credRootMap, &credArray, OicSecCredCount(cred));
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Array.");
leechul's avatar
leechul committed
713

Sahil Bansal's avatar
Sahil Bansal committed
714 715
    while (cred)
    {
716
        CborEncoder credMap;
Sahil Bansal's avatar
Sahil Bansal committed
717
        size_t mapSize = CRED_MAP_SIZE;
718
        size_t inLen = 0;
Sahil Bansal's avatar
Sahil Bansal committed
719 720 721 722
        if (cred->period)
        {
            mapSize++;
        }
723

724
#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
saurabh.s9's avatar
saurabh.s9 committed
725
#ifdef MULTIPLE_OWNER
726 727 728 729
        if(cred->eownerID)
        {
            mapSize++;
        }
saurabh.s9's avatar
saurabh.s9 committed
730
#endif //MULTIPLE_OWNER
731

732
        if ((SIGNED_ASYMMETRIC_KEY == cred->credType || ASYMMETRIC_KEY == cred->credType)
Kevin Kane's avatar
Kevin Kane committed
733
            && cred->publicData.data)
Sahil Bansal's avatar
Sahil Bansal committed
734 735 736
        {
            mapSize++;
        }
737 738 739 740 741 742 743 744
        if (SIGNED_ASYMMETRIC_KEY == cred->credType && cred->optionalData.data)
        {
            mapSize++;
        }
        if (cred->credUsage)
        {
            mapSize++;
        }
745 746 747 748
        if (IsNonEmptyRole(&cred->roleId))
        {
            mapSize++;
        }
749
#endif /* __WITH_DTLS__ ||  __WITH_TLS__*/
750
        if (!secureFlag && cred->privateData.data)
Sahil Bansal's avatar
Sahil Bansal committed
751 752 753
        {
            mapSize++;
        }
leechul's avatar
leechul committed
754
        cborEncoderResult = cbor_encoder_create_map(&credArray, &credMap, mapSize);
Sahil Bansal's avatar
Sahil Bansal committed
755 756 757
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Map");

        //CredID -- Mandatory
leechul's avatar
leechul committed
758
        cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_CREDID_NAME,
Sahil Bansal's avatar
Sahil Bansal committed
759 760
            strlen(OIC_JSON_CREDID_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Id Tag. ");
leechul's avatar
leechul committed
761
        cborEncoderResult = cbor_encode_int(&credMap, cred->credId);
Sahil Bansal's avatar
Sahil Bansal committed
762 763 764
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Id Value.");

        //Subject -- Mandatory
leechul's avatar
leechul committed
765 766
        cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_SUBJECTID_NAME,
            strlen(OIC_JSON_SUBJECTID_NAME));
Sahil Bansal's avatar
Sahil Bansal committed
767
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Tag.");
768
        inLen = (memcmp(&(cred->subject), &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0) ?
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
            WILDCARD_SUBJECT_ID_LEN : sizeof(OicUuid_t);
        if(inLen == WILDCARD_SUBJECT_ID_LEN)
        {
            cborEncoderResult = cbor_encode_text_string(&credMap, WILDCARD_RESOURCE_URI,
                strlen(WILDCARD_RESOURCE_URI));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Subject Id wildcard Value.");
        }
        else
        {
            char *subject = NULL;
            ret = ConvertUuidToStr(&cred->subject, &subject);
            VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
            cborEncoderResult = cbor_encode_text_string(&credMap, subject, strlen(subject));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Subject Id Value.");
            OICFree(subject);
        }
Sahil Bansal's avatar
Sahil Bansal committed
785

786 787 788 789 790 791 792 793 794
        //Role ID -- optional
        if (IsNonEmptyRole(&cred->roleId))
        {
            cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_ROLEID_NAME,
                strlen(OIC_JSON_ROLEID_NAME));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed adding role ID map tag");

            bool includeAuthority = (0 != memcmp(&cred->roleId.authority, &EMPTY_ROLE.authority, sizeof(EMPTY_ROLE.authority)));

795
            cborEncoderResult = cbor_encoder_create_map(&credMap, &roleIdMap, ROLEID_MAP_SIZE + (includeAuthority ? 1 : 0));
796 797 798 799
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed adding role ID map");

            cborEncoderResult = cbor_encode_text_string(&roleIdMap, OIC_JSON_ROLE_NAME, strlen(OIC_JSON_ROLE_NAME));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed adding role tag");
800

801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
            cborEncoderResult = cbor_encode_text_string(&roleIdMap, cred->roleId.id, strlen(cred->roleId.id));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed adding role value");

            if (includeAuthority)
            {
                cborEncoderResult = cbor_encode_text_string(&roleIdMap, OIC_JSON_AUTHORITY_NAME, strlen(OIC_JSON_AUTHORITY_NAME));
                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed adding authority tag");

                cborEncoderResult = cbor_encode_text_string(&roleIdMap, cred->roleId.authority, strlen(cred->roleId.authority));
                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed adding authority value");
            }

            cborEncoderResult = cbor_encoder_close_container(&credMap, &roleIdMap);
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed closing role ID map");
        }

Sahil Bansal's avatar
Sahil Bansal committed
817
        //CredType -- Mandatory
leechul's avatar
leechul committed
818
        cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_CREDTYPE_NAME,
Sahil Bansal's avatar
Sahil Bansal committed
819 820
            strlen(OIC_JSON_CREDTYPE_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag.");
leechul's avatar
leechul committed
821
        cborEncoderResult = cbor_encode_int(&credMap, cred->credType);
Sahil Bansal's avatar
Sahil Bansal committed
822
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
Sachin Agrawal's avatar
Sachin Agrawal committed
823

824
#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
Sahil Bansal's avatar
Sahil Bansal committed
825
        //PublicData -- Not Mandatory
826
        if ((SIGNED_ASYMMETRIC_KEY == cred->credType || ASYMMETRIC_KEY == cred->credType)
Kevin Kane's avatar
Kevin Kane committed
827
            && cred->publicData.data)
Sahil Bansal's avatar
Sahil Bansal committed
828
        {
829 830
            cborEncoderResult = SerializeEncodingToCbor(&credMap,
                                         OIC_JSON_PUBLICDATA_NAME, &cred->publicData);
leechul's avatar
leechul committed
831
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PublicData Tag.");
Sahil Bansal's avatar
Sahil Bansal committed
832
        }
833 834 835
        //OptionalData -- Not Mandatory
        if (SIGNED_ASYMMETRIC_KEY == cred->credType && cred->optionalData.data)
        {
836 837
            cborEncoderResult = SerializeSecOptToCbor(&credMap,
                                         OIC_JSON_OPTDATA_NAME, &cred->optionalData);
838 839 840 841 842 843 844 845 846 847 848 849
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding OptionalData Tag.");
        }
        //CredUsage -- Not Mandatory
        if(cred->credUsage)
        {
            cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_CREDUSAGE_NAME,
                strlen(OIC_JSON_CREDUSAGE_NAME));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Credusage Name Tag.");
            cborEncoderResult = cbor_encode_text_string(&credMap, cred->credUsage,
                strlen(cred->credUsage));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Credusage Name Value.");
        }
850
#endif /* __WITH_DTLS__ ||  __WITH_TLS__*/
Sahil Bansal's avatar
Sahil Bansal committed
851
        //PrivateData -- Not Mandatory
852
        if(!secureFlag && cred->privateData.data)
Sahil Bansal's avatar
Sahil Bansal committed
853
        {
854 855
            cborEncoderResult = SerializeEncodingToCbor(&credMap,
                                         OIC_JSON_PRIVATEDATA_NAME, &cred->privateData);
leechul's avatar
leechul committed
856
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PrivateData Tag.");
Sahil Bansal's avatar
Sahil Bansal committed
857
        }
Sachin Agrawal's avatar
Sachin Agrawal committed
858

Sahil Bansal's avatar
Sahil Bansal committed
859 860 861
        //Period -- Not Mandatory
        if(cred->period)
        {
leechul's avatar
leechul committed
862
            cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_PERIOD_NAME,
Sahil Bansal's avatar
Sahil Bansal committed
863 864
                strlen(OIC_JSON_PERIOD_NAME));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Name Tag.");
leechul's avatar
leechul committed
865
            cborEncoderResult = cbor_encode_text_string(&credMap, cred->period,
Sahil Bansal's avatar
Sahil Bansal committed
866 867 868
                strlen(cred->period));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Name Value.");
        }
Sachin Agrawal's avatar
Sachin Agrawal committed
869

saurabh.s9's avatar
saurabh.s9 committed
870
#ifdef MULTIPLE_OWNER
871 872 873 874 875 876 877 878 879 880 881 882 883
        // Eownerid -- Not Mandatory
        if(cred->eownerID)
        {
            char *eowner = NULL;
            cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_EOWNERID_NAME,
                strlen(OIC_JSON_EOWNERID_NAME));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding eownerId Name Tag.");
            ret = ConvertUuidToStr(cred->eownerID, &eowner);
            VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
            cborEncoderResult = cbor_encode_text_string(&credMap, eowner, strlen(eowner));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding eownerId Value.");
            OICFree(eowner);
        }
saurabh.s9's avatar
saurabh.s9 committed
884
#endif //MULTIPLE_OWNER
leechul's avatar
leechul committed
885 886

        cborEncoderResult = cbor_encoder_close_container(&credArray, &credMap);
Sahil Bansal's avatar
Sahil Bansal committed
887
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Map.");
888

Sahil Bansal's avatar
Sahil Bansal committed
889
        cred = cred->next;
leechul's avatar
leechul committed
890 891 892 893 894
    }
    cborEncoderResult = cbor_encoder_close_container(&credRootMap, &credArray);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Array.");

    cred = credS;
895

leechul's avatar
leechul committed
896 897 898 899 900 901
    // Rownerid
    {
        char *rowner = NULL;
        cborEncoderResult = cbor_encode_text_string(&credRootMap, OIC_JSON_ROWNERID_NAME,
            strlen(OIC_JSON_ROWNERID_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding rownerid Name.");
902 903 904
        OicUuid_t emptyUuid = { .id = { 0 } };
        const OicUuid_t* rownerID = (NULL == cred)? &emptyUuid : &cred->rownerID;
        ret = ConvertUuidToStr(rownerID, &rowner);
leechul's avatar
leechul committed
905 906 907 908 909 910
        VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
        cborEncoderResult = cbor_encode_text_string(&credRootMap, rowner, strlen(rowner));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding rownerid Value.");
        OICFree(rowner);
    }

911
    if (cred != NULL)
Randeep's avatar
Randeep committed
912
    {
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
        //RT -- Mandatory
        CborEncoder rtArray;
        cborEncoderResult = cbor_encode_text_string(&credRootMap, OIC_JSON_RT_NAME,
                strlen(OIC_JSON_RT_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
        cborEncoderResult = cbor_encoder_create_array(&credRootMap, &rtArray, 1);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
        for (size_t i = 0; i < 1; i++)
        {
            cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_CRED,
                    strlen(OIC_RSRC_TYPE_SEC_CRED));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
        }
        cborEncoderResult = cbor_encoder_close_container(&credRootMap, &rtArray);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
Randeep's avatar
Randeep committed
928

929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
        //IF-- Mandatory
        CborEncoder ifArray;
        cborEncoderResult = cbor_encode_text_string(&credRootMap, OIC_JSON_IF_NAME,
                 strlen(OIC_JSON_IF_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
        cborEncoderResult = cbor_encoder_create_array(&credRootMap, &ifArray, 1);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
        for (size_t i = 0; i < 1; i++)
        {
            cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
                    strlen(OC_RSRVD_INTERFACE_DEFAULT));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
        }
        cborEncoderResult = cbor_encoder_close_container(&credRootMap, &ifArray);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
Randeep's avatar
Randeep committed
944 945
    }

leechul's avatar
leechul committed
946 947 948 949 950 951 952 953
    // Close CRED Root Map
    cborEncoderResult = cbor_encoder_close_container(&encoder, &credRootMap);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing CRED Root Map.");

    if (CborNoError == cborEncoderResult)
    {
        OIC_LOG(DEBUG, TAG, "CredToCBORPayload Successed");
        *cborPayload = outPayload;
954
        *cborSize = cbor_encoder_get_buffer_size(&encoder, outPayload);
Sahil Bansal's avatar
Sahil Bansal committed
955 956 957
        ret = OC_STACK_OK;
    }
    OIC_LOG(DEBUG, TAG, "CredToCBORPayload OUT");
Sachin Agrawal's avatar
Sachin Agrawal committed
958
exit:
leechul's avatar
leechul committed
959
    if (CborErrorOutOfMemory == cborEncoderResult)
960
    {
leechul's avatar
leechul committed
961 962 963 964
        OIC_LOG(DEBUG, TAG, "CredToCBORPayload:CborErrorOutOfMemory : retry with more memory");
        // reallocate and try again!
        OICFree(outPayload);
        // Since the allocated initial memory failed, double the memory.
965
        cborLen += cbor_encoder_get_buffer_size(&encoder, encoder.end);
leechul's avatar
leechul committed
966
        cborEncoderResult = CborNoError;
967
        ret = CredToCBORPayload(credS, cborPayload, &cborLen, secureFlag);
leechul's avatar
leechul committed
968
        *cborSize = cborLen;
969
    }
Sahil Bansal's avatar
Sahil Bansal committed
970 971 972

    if (CborNoError != cborEncoderResult)
    {
leechul's avatar
leechul committed
973 974 975 976 977 978
        OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
        OICFree(outPayload);
        outPayload = NULL;
        *cborSize = 0;
        *cborPayload = NULL;
        ret = OC_STACK_ERROR;
Sahil Bansal's avatar
Sahil Bansal committed
979 980
    }

981 982
    OIC_LOG_V(DEBUG, TAG, "OUT %s:", __func__);

Sahil Bansal's avatar
Sahil Bansal committed
983
    return ret;
Sachin Agrawal's avatar
Sachin Agrawal committed
984 985
}

Sahil Bansal's avatar
Sahil Bansal committed
986 987
OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                                OicSecCred_t **secCred)
Sachin Agrawal's avatar
Sachin Agrawal committed
988
{
Ashwini Kumar's avatar
Ashwini Kumar committed
989
    if (NULL == cborPayload || NULL == secCred || NULL != *secCred || 0 == size)
Sahil Bansal's avatar
Sahil Bansal committed
990 991 992
    {
        return OC_STACK_INVALID_PARAM;
    }
Sachin Agrawal's avatar
Sachin Agrawal committed
993

994 995 996
    char* tagName = NULL;
    char* roleIdTagName = NULL;
    char* name = NULL;
Sahil Bansal's avatar
Sahil Bansal committed
997
    OCStackResult ret = OC_STACK_ERROR;
leechul's avatar
leechul committed
998 999
    CborValue credCbor = { .parser = NULL };
    CborParser parser = { .end = NULL };
Sahil Bansal's avatar
Sahil Bansal committed
1000
    CborError cborFindResult = CborNoError;
leechul's avatar
leechul committed
1001
    cbor_parser_init(cborPayload, size, 0, &parser, &credCbor);
leechul's avatar
leechul committed
1002

1003 1004 1005 1006 1007
    if (!cbor_value_is_container(&credCbor))
    {
        return OC_STACK_ERROR;
    }

1008
    OicSecCred_t *headCred = NULL;
1009

leechul's avatar
leechul committed
1010 1011 1012 1013
    // Enter CRED Root Map
    CborValue CredRootMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
    cborFindResult = cbor_value_enter_container(&credCbor, &CredRootMap);
    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering CRED Root Map.");
Sachin Agrawal's avatar
Sachin Agrawal committed
1014

1015 1016 1017
    headCred = (OicSecCred_t *) OICCalloc(1, sizeof(OicSecCred_t));
    VERIFY_NOT_NULL(TAG, headCred, ERROR);

leechul's avatar
leechul committed
1018
    while (cbor_value_is_valid(&CredRootMap))
Sahil Bansal's avatar
Sahil Bansal committed
1019
    {
leechul's avatar
leechul committed
1020 1021
        size_t len = 0;
        CborType type = cbor_value_get_type(&CredRootMap);
1022
        if (type == CborTextStringType && cbor_value_is_text_string(&CredRootMap))
Sahil Bansal's avatar
Sahil Bansal committed
1023
        {
leechul's avatar
leechul committed
1024 1025 1026 1027
            cborFindResult = cbor_value_dup_text_string(&CredRootMap, &tagName, &len, NULL);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in CRED Root Map.");
            cborFindResult = cbor_value_advance(&CredRootMap);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in CRED Root Map.");
Sahil Bansal's avatar
Sahil Bansal committed
1028
        }
leechul's avatar
leechul committed
1029
        if(tagName)
Sahil Bansal's avatar
Sahil Bansal committed
1030
        {
leechul's avatar
leechul committed
1031
            if (strcmp(tagName, OIC_JSON_CREDS_NAME)  == 0)
1032
            {
leechul's avatar
leechul committed
1033
                // Enter CREDS Array
1034
                size_t tempLen = 0;
leechul's avatar
leechul committed
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
                int credCount = 0;
                CborValue credArray = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
                cborFindResult = cbor_value_enter_container(&CredRootMap, &credArray);
                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Array.");

                while (cbor_value_is_valid(&credArray))
                {
                    credCount++;
                    //CredId -- Mandatory
                    CborValue credMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
                    cborFindResult = cbor_value_enter_container(&credArray, &credMap);
                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Map.");
                    OicSecCred_t *cred = NULL;

                    if(1 == credCount)
                    {
                        cred = headCred;
                    }
                    else
                    {
                        cred = (OicSecCred_t *) OICCalloc(1, sizeof(OicSecCred_t));
1056
                        VERIFY_NOT_NULL(TAG, cred, ERROR);
leechul's avatar
leechul committed
1057 1058 1059 1060 1061 1062 1063 1064
                        OicSecCred_t *temp = headCred;
                        while (temp->next)
                        {
                            temp = temp->next;
                        }
                        temp->next = cred;
                    }

1065
                    while(cbor_value_is_valid(&credMap) && cbor_value_is_text_string(&credMap))
leechul's avatar
leechul committed
1066
                    {
1067 1068
                        CborType cmType = cbor_value_get_type(&credMap);
                        if (cmType == CborTextStringType)
leechul's avatar
leechul committed
1069
                        {
1070
                            cborFindResult = cbor_value_dup_text_string(&credMap, &name, &tempLen, NULL);
leechul's avatar
leechul committed
1071 1072 1073 1074 1075 1076 1077 1078 1079
                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in CRED Map.");
                            cborFindResult = cbor_value_advance(&credMap);
                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in CRED Map.");
                        }
                        if(name)
                        {
                            //credid
                            if (strcmp(name, OIC_JSON_CREDID_NAME)  == 0)
                            {
1080 1081
                                uint64_t credId = 0;
                                cborFindResult = cbor_value_get_uint64(&credMap, &credId);
leechul's avatar
leechul committed
1082
                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CredId.");
1083
                                cred->credId = (uint16_t)credId;
leechul's avatar
leechul committed
1084 1085 1086 1087 1088
                            }
                            // subjectid
                            if (strcmp(name, OIC_JSON_SUBJECTID_NAME)  == 0)
                            {
                                char *subjectid = NULL;
1089
                                cborFindResult = cbor_value_dup_text_string(&credMap, &subjectid, &tempLen, NULL);
leechul's avatar
leechul committed
1090
                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding subjectid Value.");
1091 1092 1093 1094 1095 1096 1097 1098 1099
                                if(strcmp(subjectid, WILDCARD_RESOURCE_URI) == 0)
                                {
                                    cred->subject.id[0] = '*';
                                }
                                else
                                {
                                    ret = ConvertStrToUuid(subjectid, &cred->subject);
                                    VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
                                }
1100 1101 1102
                                //Because cbor using malloc directly
                                //It is required to use free() instead of OICFree
                                free(subjectid);
leechul's avatar
leechul committed
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