credresource.c 42.2 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
22 23 24 25 26 27 28 29 30 31 32

#include <stdlib.h>
#ifdef WITH_ARDUINO
#include <string.h>
#else
#include <strings.h>
#endif
#include <stdint.h>

#include "cainterface.h"
#include "payload_logging.h"
Sachin Agrawal's avatar
Sachin Agrawal committed
33
#include "ocstack.h"
34 35
#include "ocrandom.h"
#include "ocserverrequest.h"
Sachin Agrawal's avatar
Sachin Agrawal committed
36
#include "oic_malloc.h"
37
#include "ocpayload.h"
Sachin Agrawal's avatar
Sachin Agrawal committed
38 39 40
#include "utlist.h"
#include "credresource.h"
#include "doxmresource.h"
41
#include "pstatresource.h"
42
#include "iotvticalendar.h"
43 44 45 46 47 48
#include "pbkdf2.h"
#include "resourcemanager.h"
#include "srmresourcestrings.h"
#include "srmutility.h"
#include "psinterface.h"
#include "pinoxmcommon.h"
49

50 51
#ifdef __WITH_DTLS__
#include "global.h"
52
#endif
53

54
#define TAG  "SRM-CREDL"
Sachin Agrawal's avatar
Sachin Agrawal committed
55

56 57 58 59 60 61 62 63 64
/** 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. */
static const uint8_t CBOR_SIZE = 255;

/** Max cbor size payload. */
static const uint16_t CBOR_MAX_SIZE = 4400;

/** CRED Map size - Number of mandatory items. */
static const uint8_t CRED_MAP_SIZE = 4;
Shilpa Sodani's avatar
Shilpa Sodani committed
65

Sachin Agrawal's avatar
Sachin Agrawal committed
66 67 68
static OicSecCred_t        *gCred = NULL;
static OCResourceHandle    gCredHandle = NULL;

69 70 71 72
/**
 * This function frees OicSecCred_t object's fields and object itself.
 */
static void FreeCred(OicSecCred_t *cred)
Sachin Agrawal's avatar
Sachin Agrawal committed
73
{
74
    if(NULL == cred)
Sachin Agrawal's avatar
Sachin Agrawal committed
75
    {
76
        OIC_LOG(ERROR, TAG, "Invalid Parameter");
77 78 79
        return;
    }
    //Note: Need further clarification on roleID data type
Sachin Agrawal's avatar
Sachin Agrawal committed
80
#if 0
81 82
    //Clean roleIds
    OICFree(cred->roleIds);
Sachin Agrawal's avatar
Sachin Agrawal committed
83 84
#endif

85 86
    //Clean PublicData
    OICFree(cred->publicData.data);
Sachin Agrawal's avatar
Sachin Agrawal committed
87

88 89
    //Clean PrivateData
    OICFree(cred->privateData.data);
Sachin Agrawal's avatar
Sachin Agrawal committed
90

91 92
    //Clean Period
    OICFree(cred->period);
Sachin Agrawal's avatar
Sachin Agrawal committed
93

94 95 96 97 98 99
    //Clean Owners
    OICFree(cred->owners);

    //Clean Cred node itself
    OICFree(cred);
}
Sachin Agrawal's avatar
Sachin Agrawal committed
100

101 102 103 104 105 106 107 108 109
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
110 111 112 113
        }
    }
}

114
static size_t OicSecCredCount(const OicSecCred_t *secCred)
Sachin Agrawal's avatar
Sachin Agrawal committed
115
{
116 117 118 119 120 121 122
    size_t size = 0;
    for (const OicSecCred_t *cred = secCred; cred; cred = cred->next)
    {
        size++;
    }
    return size;
}
Sachin Agrawal's avatar
Sachin Agrawal committed
123

124 125 126 127
OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload,
                                size_t *cborSize)
{
    if (NULL == credS || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
Sachin Agrawal's avatar
Sachin Agrawal committed
128
    {
129 130
        return OC_STACK_INVALID_PARAM;
    }
131

132 133 134 135 136 137
    OCStackResult ret = OC_STACK_ERROR;
    size_t cborLen = *cborSize;
    if (0 == cborLen)
    {
        cborLen = CBOR_SIZE;
    }
138

139 140
    *cborSize = 0;
    *cborPayload = NULL;
Sachin Agrawal's avatar
Sachin Agrawal committed
141

142 143 144
    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
    CborEncoder credArray = { {.ptr = NULL }, .end = 0 };
    CborError cborEncoderResult = CborNoError;
Sachin Agrawal's avatar
Sachin Agrawal committed
145

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
    const OicSecCred_t *cred = credS;
    size_t mapSize = CRED_MAP_SIZE;
    if (cred->period)
    {
        mapSize++;
    }
    if (cred->publicData.data)
    {
        mapSize++;
    }
    if (cred->privateData.data)
    {
        mapSize++;
    }
    if (cred->period)
    {
        mapSize++;
    }
    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
    VERIFY_NON_NULL(TAG, outPayload, ERROR);
    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
Sachin Agrawal's avatar
Sachin Agrawal committed
167

168 169 170
    // Create CRED Array
    cborEncoderResult = cbor_encoder_create_array(&encoder, &credArray, OicSecCredCount(cred));
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding0 Cred Array.");
Sachin Agrawal's avatar
Sachin Agrawal committed
171

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
    while (cred)
    {
        CborEncoder credMap = { {.ptr = NULL }, .end = 0 };
        cborEncoderResult = cbor_encoder_create_map(&credArray, &credMap, mapSize);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Map");

        //CredID -- Mandatory
        cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_CREDID_NAME,
            strlen(OIC_JSON_CREDID_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Id Tag. ");
        cborEncoderResult = cbor_encode_int(&credMap, cred->credId);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Id Value.");

        //Subject -- Mandatory
        cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_SUBJECT_NAME,
            strlen(OIC_JSON_SUBJECT_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Tag.");
        cborEncoderResult = cbor_encode_byte_string(&credMap, cred->subject.id,
            sizeof(cred->subject.id));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Value.");

        //CredType -- Mandatory
        cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_CREDTYPE_NAME,
            strlen(OIC_JSON_CREDTYPE_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag.");
        cborEncoderResult = cbor_encode_int(&credMap, cred->credType);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
Sachin Agrawal's avatar
Sachin Agrawal committed
199

Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
200
#ifdef __WITH_X509__
201 202 203 204 205 206 207 208 209 210
        //PublicData -- Not Mandatory
        if (cred->publicData.data)
        {
            cborEncoderResult = cbor_encode_text_string(&credMap,
                OIC_JSON_PUBLICDATA_NAME, strlen(OIC_JSON_PUBLICDATA_NAME));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Public Data Tag.");
            cborEncoderResult = cbor_encode_byte_string(&credMap, cred->publicData.data,
                    sizeof(cred->publicData.data));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Public Tag Value.");
        }
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
211
#endif /*__WITH_X509__*/
212 213 214 215 216 217 218 219 220 221
        //PrivateData -- Not Mandatory
        if(cred->privateData.data)
        {
            cborEncoderResult = cbor_encode_text_string(&credMap,
                OIC_JSON_PRIVATEDATA_NAME, strlen(OIC_JSON_PRIVATEDATA_NAME));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Data Tag");
            cborEncoderResult = cbor_encode_byte_string(&credMap, cred->privateData.data,
                sizeof(cred->privateData.data));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Data Value.");
        }
Sachin Agrawal's avatar
Sachin Agrawal committed
222

223 224 225 226 227 228 229 230 231 232
        //Period -- Not Mandatory
        if(cred->period)
        {
            cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_PERIOD_NAME,
                strlen(OIC_JSON_PERIOD_NAME));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Name Tag.");
            cborEncoderResult = cbor_encode_text_string(&credMap, cred->period,
                strlen(cred->period));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Name Value.");
        }
Sachin Agrawal's avatar
Sachin Agrawal committed
233

234 235 236 237 238 239 240 241
        //Owners -- Mandatory
        {
            cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_OWNERS_NAME,
                strlen(OIC_JSON_OWNERS_NAME));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owners Name Tag.");
            CborEncoder owners = { {.ptr = NULL }, .end = 0 };
            cborEncoderResult = cbor_encoder_create_array(&credMap, &owners, cred->ownersLen);
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owners Name Array.");
Sachin Agrawal's avatar
Sachin Agrawal committed
242 243
            for (size_t i = 0; i < cred->ownersLen; i++)
            {
244 245 246 247
                cborEncoderResult = cbor_encode_byte_string(&owners,
                    (uint8_t *)cred->owners[i].id,
                    sizeof(cred->owners[i].id));
                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owners Array Value.");
Sachin Agrawal's avatar
Sachin Agrawal committed
248
            }
249 250
            cborEncoderResult = cbor_encoder_close_container(&credMap, &owners);
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Owners Name Array.");
Sachin Agrawal's avatar
Sachin Agrawal committed
251
        }
252 253
        cborEncoderResult = cbor_encoder_close_container(&credArray, &credMap);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Map.");
Sachin Agrawal's avatar
Sachin Agrawal committed
254

255 256 257 258 259 260 261 262 263 264
        cred = cred->next;
   }
   cborEncoderResult = cbor_encoder_close_container(&encoder, &credArray);
   VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Array.");

   if (CborNoError == cborEncoderResult)
   {
       *cborPayload = outPayload;
       *cborSize = encoder.ptr - outPayload;
        ret = OC_STACK_OK;
Sachin Agrawal's avatar
Sachin Agrawal committed
265 266 267
    }

exit:
268
    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
Sachin Agrawal's avatar
Sachin Agrawal committed
269
    {
270 271 272 273 274 275 276 277 278 279 280 281
       // reallocate and try again!
       OICFree(outPayload);
       outPayload = NULL;
       // Since the allocated initial memory failed, double the memory.
       cborLen += encoder.ptr - encoder.end;
       cborEncoderResult = CborNoError;
       ret = CredToCBORPayload(credS, cborPayload, &cborLen);
       if (CborNoError == cborEncoderResult)
       {
           *cborSize = cborLen;
            ret = OC_STACK_OK;
        }
Sachin Agrawal's avatar
Sachin Agrawal committed
282
    }
283 284 285 286 287 288 289 290 291 292 293

    if (CborNoError != cborEncoderResult)
    {
       OICFree(outPayload);
       outPayload = NULL;
       *cborSize = 0;
       *cborPayload = NULL;
       ret = OC_STACK_ERROR;
    }

    return ret;
Sachin Agrawal's avatar
Sachin Agrawal committed
294 295
}

296 297
OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                                OicSecCred_t **secCred)
Sachin Agrawal's avatar
Sachin Agrawal committed
298
{
299 300 301 302 303 304 305
    if (NULL == cborPayload || NULL == secCred || NULL != *secCred)
    {
        return OC_STACK_INVALID_PARAM;
    }

    *secCred = NULL;

Sachin Agrawal's avatar
Sachin Agrawal committed
306 307
    OCStackResult ret = OC_STACK_ERROR;

308 309 310 311 312
    CborValue credCbor = { .parser = NULL };
    CborParser parser = { .end = NULL };
    CborError cborFindResult = CborNoError;
    OicSecCred_t *cred = NULL;
    char *name = NULL;
Sachin Agrawal's avatar
Sachin Agrawal committed
313

314 315
    int cborLen = size;
    if (0 == size)
Sachin Agrawal's avatar
Sachin Agrawal committed
316
    {
317 318 319
        cborLen = CBOR_SIZE;
    }
    cbor_parser_init(cborPayload, cborLen, 0, &parser, &credCbor);
Sachin Agrawal's avatar
Sachin Agrawal committed
320

321
    OicSecCred_t *headCred = NULL;
Sachin Agrawal's avatar
Sachin Agrawal committed
322

323 324 325
    CborValue credArray = { .parser = NULL };
    cborFindResult = cbor_value_enter_container(&credCbor, &credArray);
    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Array.");
Sachin Agrawal's avatar
Sachin Agrawal committed
326

327 328 329 330 331
    while (cbor_value_is_valid(&credArray))
    {
        CborValue credMap = { .parser = NULL };
        cborFindResult = cbor_value_enter_container(&credArray, &credMap);
        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Map.");
Sachin Agrawal's avatar
Sachin Agrawal committed
332

333 334 335 336 337 338 339 340 341 342 343 344
        cred = (OicSecCred_t *) OICCalloc(1, sizeof(*cred));
        VERIFY_NON_NULL(TAG, cred, ERROR);

        while (cbor_value_is_valid(&credMap))
        {
            size_t len = 0;
            cborFindResult = cbor_value_dup_text_string(&credMap, &name, &len, NULL);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Name.");
            cborFindResult = cbor_value_advance(&credMap);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Cred Name. ");

            CborType type = cbor_value_get_type(&credMap);
Sachin Agrawal's avatar
Sachin Agrawal committed
345 346

            //CredId -- Mandatory
347
            if (0 == strcmp(OIC_JSON_CREDID_NAME, name))
348
            {
349 350
                cborFindResult = cbor_value_get_int(&credMap, (int *) &cred->credId);
                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Id Value.");
351
            }
Sachin Agrawal's avatar
Sachin Agrawal committed
352
            //subject -- Mandatory
353
            if (0 == strcmp(OIC_JSON_SUBJECT_NAME, name))
Sachin Agrawal's avatar
Sachin Agrawal committed
354
            {
355 356 357 358 359
                uint8_t *id = NULL;
                cborFindResult = cbor_value_dup_byte_string(&credMap, &id, &len, NULL);
                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Subject Name Value.");
                memcpy(cred->subject.id, id, len);
                OICFree(id);
Sachin Agrawal's avatar
Sachin Agrawal committed
360
            }
361 362
            //CredType -- Mandatory
            if (0 == strcmp(OIC_JSON_CREDTYPE_NAME, name))
Sachin Agrawal's avatar
Sachin Agrawal committed
363
            {
364 365
                cborFindResult = cbor_value_get_int(&credMap, (int *) &cred->credType);
                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Type Value.");
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
366
            }
367 368
            //Owners -- Mandatory
            if (0 == strcmp(OIC_JSON_OWNERS_NAME, name))
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
369
            {
370 371 372 373 374 375 376 377 378
                CborValue owners = { .parser = NULL };
                cborFindResult = cbor_value_get_array_length(&credMap, &cred->ownersLen);
                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owners Name Array Len.");
                cborFindResult = cbor_value_enter_container(&credMap, &owners);
                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owners Name.");
                int i = 0;
                cred->owners = (OicUuid_t *)OICCalloc(cred->ownersLen, sizeof(*cred->owners));
                VERIFY_NON_NULL(TAG, cred->owners, ERROR);
                while (cbor_value_is_valid(&owners))
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
379
                {
380 381 382 383 384 385 386
                    uint8_t *owner = NULL;
                    cborFindResult = cbor_value_dup_byte_string(&owners, &owner, &len, NULL);
                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
                    memcpy(cred->owners[i].id, owner, len);
                    OICFree(owner);
                    cborFindResult = cbor_value_advance(&owners);
                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Owner Value.");
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
387
                }
388 389 390 391 392 393 394
            }
            //PrivateData is mandatory for some of the credential types listed below.
            if (0 == strcmp(OIC_JSON_PRIVATEDATA_NAME, name))
            {
                if ((cred->credType & SYMMETRIC_PAIR_WISE_KEY) ||
                    (cred->credType & SYMMETRIC_GROUP_KEY) ||
                    (cred->credType & PIN_PASSWORD))
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
395
                {
396 397 398
                    cborFindResult = cbor_value_dup_byte_string(&credMap,
                        &cred->privateData.data, &len, NULL);
                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Private Data Value.");
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
399 400
                }
            }
401 402 403 404
            else
            {
                cred->privateData.data = NULL;
            }
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
405 406

            //PublicData is mandatory only for SIGNED_ASYMMETRIC_KEY credentials type.
407
            if (0 == strcmp(OIC_JSON_PUBLICDATA_NAME, name))
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
408
            {
409
                if (cred->credType & SIGNED_ASYMMETRIC_KEY)
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
410
                {
411 412 413
                    cborFindResult = cbor_value_dup_byte_string(&credMap,
                        &cred->publicData.data, &len, NULL);
                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ");
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
414
                }
Sachin Agrawal's avatar
Sachin Agrawal committed
415 416
            }
            //Period -- Not Mandatory
417
            if (0 == strcmp(OIC_JSON_PERIOD_NAME, name))
Sachin Agrawal's avatar
Sachin Agrawal committed
418
            {
419 420 421
                cborFindResult = cbor_value_dup_text_string(&credMap,
                    &cred->period, &len, NULL);
                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Period Name Value.");
Sachin Agrawal's avatar
Sachin Agrawal committed
422
            }
423 424 425 426 427 428 429 430
            if (CborMapType != type && cbor_value_is_valid(&credMap))
            {
                cborFindResult = cbor_value_advance(&credMap);
                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Cred Map.");
            }
            OICFree(name);
            name = NULL;
        }
Sachin Agrawal's avatar
Sachin Agrawal committed
431

432 433 434 435 436 437 438 439 440
        cred->next = NULL;
        if (NULL == headCred)
        {
            headCred = cred;
        }
        else
        {
            OicSecCred_t *temp = headCred;
            while (temp->next)
Sachin Agrawal's avatar
Sachin Agrawal committed
441
            {
442
                temp = temp->next;
Sachin Agrawal's avatar
Sachin Agrawal committed
443
            }
444 445 446 447 448 449 450
            temp->next = cred;
        }
        if (cbor_value_is_valid(&credArray))
        {
            cborFindResult = cbor_value_advance(&credArray);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Cred Array. ");
        }
Sachin Agrawal's avatar
Sachin Agrawal committed
451
    }
452
    *secCred = headCred;
Sachin Agrawal's avatar
Sachin Agrawal committed
453 454
    ret = OC_STACK_OK;
exit:
455
    if (CborNoError != cborFindResult)
Sachin Agrawal's avatar
Sachin Agrawal committed
456 457 458
    {
        DeleteCredList(headCred);
        headCred = NULL;
459
        ret = OC_STACK_ERROR;
Sachin Agrawal's avatar
Sachin Agrawal committed
460
    }
461 462 463 464 465 466 467 468 469
    if (cred)
    {
        DeleteCredList(cred);
    }
    if (name)
    {
        OICFree(name);
    }
    return ret;
Sachin Agrawal's avatar
Sachin Agrawal committed
470 471 472
}

OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t credType,
473 474
                                  const uint8_t * publicData, const uint8_t* privateData,
                                  size_t ownersLen, const OicUuid_t * owners)
Sachin Agrawal's avatar
Sachin Agrawal committed
475
{
Jon A. Cruz's avatar
Jon A. Cruz committed
476
    (void)publicData;
Sachin Agrawal's avatar
Sachin Agrawal committed
477 478
    OCStackResult ret = OC_STACK_ERROR;

479
    OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
Sachin Agrawal's avatar
Sachin Agrawal committed
480 481
    VERIFY_NON_NULL(TAG, cred, ERROR);

482 483 484
    //CredId is assigned before appending new cred to the existing
    //credential list and updating svr database in AddCredential().
    cred->credId = 0;
Sachin Agrawal's avatar
Sachin Agrawal committed
485 486 487 488

    VERIFY_NON_NULL(TAG, subject, ERROR);
    memcpy(cred->subject.id, subject->id , sizeof(cred->subject.id));

489 490
    VERIFY_SUCCESS(TAG, credType < (NO_SECURITY_MODE | SYMMETRIC_PAIR_WISE_KEY |
            SYMMETRIC_GROUP_KEY | ASYMMETRIC_KEY | SIGNED_ASYMMETRIC_KEY | PIN_PASSWORD), ERROR);
Sachin Agrawal's avatar
Sachin Agrawal committed
491 492
    cred->credType = credType;

Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
493
#ifdef __WITH_X509__
494
    if (publicData)
Sachin Agrawal's avatar
Sachin Agrawal committed
495
    {
496
        cred->publicData.data = (uint8_t *)OICCalloc(1, PUBLIC_KEY_SIZE);
Sachin Agrawal's avatar
Sachin Agrawal committed
497
        VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
498
        memcpy(cred->publicData.data, publicData, PUBLIC_KEY_SIZE);
Sachin Agrawal's avatar
Sachin Agrawal committed
499
    }
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
500
#endif // __WITH_X509__
Sachin Agrawal's avatar
Sachin Agrawal committed
501

502
    if (privateData)
Sachin Agrawal's avatar
Sachin Agrawal committed
503
    {
504 505
#ifdef __WITH_X509__
        cred->privateData.data = (uint8_t *)OICCalloc(1, PRIVATE_KEY_SIZE);
Sachin Agrawal's avatar
Sachin Agrawal committed
506
        VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
507 508
        memcpy(cred->privateData.data, privateData, PRIVATE_KEY_SIZE);
#endif // __WITH_X509__
Sachin Agrawal's avatar
Sachin Agrawal committed
509 510 511 512 513
    }

    VERIFY_SUCCESS(TAG, ownersLen > 0, ERROR);
    cred->ownersLen = ownersLen;

514
    cred->owners = (OicUuid_t *)OICCalloc(cred->ownersLen, sizeof(*cred->owners));
Sachin Agrawal's avatar
Sachin Agrawal committed
515
    VERIFY_NON_NULL(TAG, cred->owners, ERROR);
516
    for (size_t i = 0; i < cred->ownersLen; i++)
Sachin Agrawal's avatar
Sachin Agrawal committed
517 518 519 520 521 522 523 524 525 526 527 528 529 530
    {
        memcpy(cred->owners[i].id, owners[i].id, sizeof(cred->owners[i].id));
    }

    ret = OC_STACK_OK;
exit:
    if (OC_STACK_OK != ret)
    {
        DeleteCredList(cred);
        cred = NULL;
    }
    return cred;
}

531 532 533 534 535
static bool UpdatePersistentStorage(const OicSecCred_t *cred)
{
    bool ret = false;

    // Convert Cred data into JSON for update to persistent storage
536 537 538 539
    uint8_t *payload = NULL;
    size_t size = 0;
    OCStackResult res = CredToCBORPayload(cred, &payload, &size);
    if ((OC_STACK_OK == res) && payload)
540
    {
541
        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, payload, size))
542 543 544
        {
            ret = true;
        }
545
        OICFree(payload);
546 547 548
    }
    else //Empty cred list
    {
549
        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, NULL, size))
550 551 552 553 554 555 556 557
        {
            ret = true;
        }
    }
    return ret;
}

/**
558
 * Compare function used LL_SORT for sorting credentials.
559
 *
560 561
 * @param first pointer to OicSecCred_t struct.
 * @param second  pointer to OicSecCred_t struct.
562
 *
563 564 565
 *@return -1, if credId of first is less than credId of second.
 * 0, if credId of first is equal to credId of second.
 * 1, if credId of first is greater than credId of second.
566 567 568
 */
static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
{
569
    if (first->credId < second->credId)
570 571 572
    {
        return -1;
    }
573
    else if (first->credId > second->credId)
574 575 576 577 578 579 580 581 582 583 584 585 586
    {
        return 1;
    }
    else
        return 0;
}

/**
 * GetCredId goes through the cred list and returns the next
 * available credId. The next credId could be the credId that is
 * available due deletion of OicSecCred_t object or one more than
 * credId of last credential in the list.
 *
587
 * @return next available credId if successful, else 0 for error.
588 589 590 591 592 593 594 595 596 597 598
 */
static uint16_t GetCredId()
{
    //Sorts credential list in incremental order of credId
    LL_SORT(gCred, CmpCredId);

    OicSecCred_t *currentCred = NULL, *credTmp = NULL;
    uint16_t nextCredId = 1;

    LL_FOREACH_SAFE(gCred, currentCred, credTmp)
    {
599
        if (currentCred->credId == nextCredId)
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
        {
            nextCredId += 1;
        }
        else
        {
            break;
        }
    }

    VERIFY_SUCCESS(TAG, nextCredId < UINT16_MAX, ERROR);
    return nextCredId;

exit:
    return 0;
}
615

616
/**
617 618 619
 * Get the default value.
 *
 * @return  NULL for now.
620 621 622
 */
static OicSecCred_t* GetCredDefault()
{
623
    // TODO:Update it when we finalize the default info.
624 625
    return NULL;
}
626

Sachin Agrawal's avatar
Sachin Agrawal committed
627 628 629
OCStackResult AddCredential(OicSecCred_t * newCred)
{
    OCStackResult ret = OC_STACK_ERROR;
630 631 632 633 634
    VERIFY_SUCCESS(TAG, NULL != newCred, ERROR);

    //Assigning credId to the newCred
    newCred->credId = GetCredId();
    VERIFY_SUCCESS(TAG, newCred->credId != 0, ERROR);
Sachin Agrawal's avatar
Sachin Agrawal committed
635 636 637

    //Append the new Cred to existing list
    LL_APPEND(gCred, newCred);
638

639
    if (UpdatePersistentStorage(gCred))
Sachin Agrawal's avatar
Sachin Agrawal committed
640
    {
641 642 643 644 645 646 647 648 649 650 651 652 653
        ret = OC_STACK_OK;
    }

exit:
    return ret;
}

OCStackResult RemoveCredential(const OicUuid_t *subject)
{
    OCStackResult ret = OC_STACK_ERROR;
    OicSecCred_t *cred = NULL;
    OicSecCred_t *tempCred = NULL;
    bool deleteFlag = false;
Sachin Agrawal's avatar
Sachin Agrawal committed
654

655 656
    LL_FOREACH_SAFE(gCred, cred, tempCred)
    {
657
        if (memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
Sachin Agrawal's avatar
Sachin Agrawal committed
658
        {
659 660 661
            LL_DELETE(gCred, cred);
            FreeCred(cred);
            deleteFlag = 1;
Sachin Agrawal's avatar
Sachin Agrawal committed
662 663 664
        }
    }

665
    if (deleteFlag)
666
    {
667
        if (UpdatePersistentStorage(gCred))
668 669 670 671
        {
            ret = OC_STACK_RESOURCE_DELETED;
        }
    }
Sachin Agrawal's avatar
Sachin Agrawal committed
672
    return ret;
673

Sachin Agrawal's avatar
Sachin Agrawal committed
674 675
}

676 677 678 679 680 681 682 683 684 685 686 687
/**
 * Remove all credential data on credential resource and persistent storage
 *
 * @retval
 *     OC_STACK_OK              - no errors
 *     OC_STACK_ERROR           - stack process error
 */
OCStackResult RemoveAllCredentials(void)
{
    DeleteCredList(gCred);
    gCred = GetCredDefault();

688
    if (!UpdatePersistentStorage(gCred))
689 690 691 692 693 694
    {
        return OC_STACK_ERROR;
    }
    return OC_STACK_OK;
}

695 696
#ifdef __WITH_DTLS__
/**
697
 * Internal function to fill private data of owner PSK.
698
 *
699
 * @param receviedCred recevied owner credential from OBT(PT)
700 701 702
 * @param ownerAdd address of OBT(PT)
 * @param doxm current device's doxm resource
 *
703
 * @return
704 705
 *     true successfully done and valid ower psk information
 *     false Invalid owner psk information or failed to owner psk generation
706
 */
707
static bool FillPrivateDataOfOwnerPSK(OicSecCred_t* receviedCred, const CAEndpoint_t* ownerAddr,
708 709 710 711 712 713 714 715 716 717 718 719 720 721
                           const OicSecDoxm_t* doxm)
{
    //Derive OwnerPSK locally
    const char* oxmLabel = GetOxmString(doxm->oxmSel);
    VERIFY_NON_NULL(TAG, oxmLabel, ERROR);

    uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
    CAResult_t pskRet = CAGenerateOwnerPSK(ownerAddr,
        (uint8_t*)oxmLabel, strlen(oxmLabel),
        doxm->owner.id, sizeof(doxm->owner.id),
        doxm->deviceID.id, sizeof(doxm->deviceID.id),
        ownerPSK, OWNER_PSK_LENGTH_128);
    VERIFY_SUCCESS(TAG, pskRet == CA_STATUS_OK, ERROR);

722 723 724 725
    OIC_LOG(DEBUG, TAG, "OwnerPSK dump :");
    OIC_LOG_BUFFER(DEBUG, TAG, ownerPSK, OWNER_PSK_LENGTH_128);

    //Generate owner credential based on recevied credential information
726
    receviedCred->privateData.data = (uint8_t *)OICCalloc(1, OWNER_PSK_LENGTH_128);
727
    VERIFY_NON_NULL(TAG, receviedCred->privateData.data, ERROR);
728
    memcpy(receviedCred->privateData.data, ownerPSK, OWNER_PSK_LENGTH_128);
729

730 731 732 733 734
    OIC_LOG(INFO, TAG, "PrivateData of OwnerPSK was calculated successfully");

    //Verify OwnerPSK information
    return (memcmp(&(receviedCred->subject), &(doxm->owner), sizeof(OicUuid_t)) == 0 &&
            receviedCred->credType == SYMMETRIC_PAIR_WISE_KEY);
735
exit:
736
    //receviedCred->privateData.data will be deallocated when deleting credential.
737 738 739 740 741 742 743 744 745 746
    return false;
}

#endif //__WITH_DTLS__

static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehRequest)
{
    OCEntityHandlerResult ret = OC_EH_ERROR;

    //Get binary representation of json
747 748 749 750 751
    OicSecCred_t * cred  = NULL;
    uint8_t *payload = (((OCSecurityPayload*)ehRequest->payload)->securityData1);
    //size_t size = (((OCSecurityPayload*)ehRequest->payload)->payloadSize);
    OCStackResult res = CBORPayloadToCred(payload, 0, &cred);
    if (res == OC_STACK_OK)
752 753 754 755 756 757 758 759 760 761 762 763
    {
#ifdef __WITH_DTLS__
        OicUuid_t emptyUuid = {.id={0}};
        const OicSecDoxm_t* doxm = GetDoxmResourceData();
        if(false == doxm->owned && memcmp(&(doxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0)
        {
            //in case of owner PSK
            switch(cred->credType)
            {
                case SYMMETRIC_PAIR_WISE_KEY:
                {
                    OCServerRequest *request = (OCServerRequest *)ehRequest->requestHandle;
764
                    if(FillPrivateDataOfOwnerPSK(cred, (CAEndpoint_t *)&request->devAddr, doxm))
765
                    {
766 767 768 769 770 771
                        if(OC_STACK_RESOURCE_DELETED == RemoveCredential(&cred->subject))
                        {
                            OIC_LOG(WARNING, TAG, "The credential with the same subject ID was detected!");
                        }

                        OIC_LOG(ERROR, TAG, "OwnerPSK was generated successfully.");
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
                        if(OC_STACK_OK == AddCredential(cred))
                        {
                            ret = OC_EH_RESOURCE_CREATED;
                        }
                        else
                        {
                            OIC_LOG(ERROR, TAG, "Failed to save the OwnerPSK as cred resource");
                            ret = OC_EH_ERROR;
                        }
                    }
                    else
                    {
                        OIC_LOG(ERROR, TAG, "Failed to verify receviced OwnerPKS.");
                        ret = OC_EH_ERROR;
                    }

788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
                    if(OC_EH_RESOURCE_CREATED == ret)
                    {
                        /**
                         * in case of random PIN based OxM,
                         * revert get_psk_info callback of tinyDTLS to use owner credential.
                         */
                        if(OIC_RANDOM_DEVICE_PIN == doxm->oxmSel)
                        {
                            OicUuid_t emptyUuid = { .id={0}};
                            SetUuidForRandomPinOxm(&emptyUuid);

                            if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
                            {
                                OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
                                ret = OC_EH_ERROR;
                                break;
                            }
                        }

                        //Select cipher suite to use owner PSK
                        if(CA_STATUS_OK != CAEnableAnonECDHCipherSuite(false))
                        {
                            OIC_LOG(ERROR, TAG, "Failed to disable anonymous cipher suite");
                            ret = OC_EH_ERROR;
                        }
                        else
                        {
                            OIC_LOG(INFO, TAG, "Anonymous cipher suite is DISABLED");
                        }

                        if(CA_STATUS_OK !=
                           CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256))
                        {
                            OIC_LOG(ERROR, TAG, "Failed to select cipher suite");
                            ret = OC_EH_ERROR;
                        }
                    }

826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
                    break;
                }
                case SYMMETRIC_GROUP_KEY:
                case ASYMMETRIC_KEY:
                case SIGNED_ASYMMETRIC_KEY:
                case PIN_PASSWORD:
                case ASYMMETRIC_ENCRYPTION_KEY:
                {
                    OIC_LOG(WARNING, TAG, "Unsupported credential type for owner credential.");
                    ret = OC_EH_ERROR;
                    break;
                }
                default:
                {
                    OIC_LOG(WARNING, TAG, "Unknow credential type for owner credential.");
                    ret = OC_EH_ERROR;
                    break;
                }
            }
845 846 847 848 849 850 851 852 853 854

            if(OC_EH_RESOURCE_CREATED != ret)
            {
                /*
                  * If some error is occured while ownership transfer,
                  * ownership transfer related resource should be revert back to initial status.
                  */
                RestoreDoxmToInitState();
                RestorePstatToInitState();
            }
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
        }
        else
        {
            /*
             * If the post request credential has credId, it will be
             * discarded and the next available credId will be assigned
             * to it before getting appended to the existing credential
             * list and updating svr database.
             */
            ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
        }
#else //not __WITH_DTLS__
        /*
         * If the post request credential has credId, it will be
         * discarded and the next available credId will be assigned
         * to it before getting appended to the existing credential
         * list and updating svr database.
         */
        ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
#endif//__WITH_DTLS__
    }

877
    if (OC_EH_RESOURCE_CREATED != ret)
878 879 880 881 882 883 884 885
    {
        if(OC_STACK_OK != RemoveCredential(&cred->subject))
        {
            OIC_LOG(WARNING, TAG, "Failed to remove the invalid credential");
        }
        FreeCred(cred);
    }

886 887 888
    return ret;
}

Sachin Agrawal's avatar
Sachin Agrawal committed
889 890 891 892
static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
{
    OCEntityHandlerResult ret = OC_EH_ERROR;

893 894 895 896 897
    //Get binary representation of CBOR
    OicSecCred_t *cred  = NULL;
    uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData1;
    OCStackResult res = CBORPayloadToCred(payload, 0, &cred);
    if ((OC_STACK_OK == res) && cred)
Sachin Agrawal's avatar
Sachin Agrawal committed
898
    {
899 900 901 902
        //If the Post request credential has credId, it will be
        //discarded and the next available credId will be assigned
        //to it before getting appended to the existing credential
        //list and updating svr database.
903
        ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
Sachin Agrawal's avatar
Sachin Agrawal committed
904
    }
905

Sachin Agrawal's avatar
Sachin Agrawal committed
906 907 908
    return ret;
}

909 910
static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *ehRequest)
{
911
    OIC_LOG(DEBUG, TAG, "Processing CredDeleteRequest");
912 913 914

    OCEntityHandlerResult ehRet = OC_EH_ERROR;

915
    if (NULL == ehRequest->query)
916 917 918 919
   {
       return ehRet;
   }

920
   OicParseQueryIter_t parseIter = { .attrPos=NULL };
921 922 923 924
   OicUuid_t subject = {.id={0}};

   //Parsing REST query to get the subject
   ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
925
   while (GetNextQuery(&parseIter))
926
   {
927
       if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME,
928 929
               parseIter.attrLen) == 0)
       {
930
           memcpy(subject.id, parseIter.valPos, parseIter.valLen);
931 932 933
       }
   }

934
   if (OC_STACK_RESOURCE_DELETED == RemoveCredential(&subject))
935 936 937 938 939 940 941
   {
       ehRet = OC_EH_RESOURCE_DELETED;
   }

    return ehRet;
}

942
OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
943 944
                                        OCEntityHandlerRequest * ehRequest,
                                        void* callbackParameter)
Sachin Agrawal's avatar
Sachin Agrawal committed
945
{
Jon A. Cruz's avatar
Jon A. Cruz committed
946
    (void)callbackParameter;
Sachin Agrawal's avatar
Sachin Agrawal committed
947 948
    OCEntityHandlerResult ret = OC_EH_ERROR;

949
    if (!ehRequest)
Sachin Agrawal's avatar
Sachin Agrawal committed
950 951 952 953 954
    {
        return OC_EH_ERROR;
    }
    if (flag & OC_REQUEST_FLAG)
    {
955
        OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
Sachin Agrawal's avatar
Sachin Agrawal committed
956
        //TODO :  Handle PUT/DEL methods
957
        switch (ehRequest->method)
Sachin Agrawal's avatar
Sachin Agrawal committed
958 959 960 961
        {
            case OC_REST_GET:
                ret = OC_EH_FORBIDDEN;
                break;
962 963 964
            case OC_REST_PUT:
                ret = HandlePutRequest(ehRequest);
                break;
Sachin Agrawal's avatar
Sachin Agrawal committed
965 966 967
            case OC_REST_POST:
                ret = HandlePostRequest(ehRequest);
                break;
968 969 970
            case OC_REST_DELETE:
                ret = HandleDeleteRequest(ehRequest);
                break;
Sachin Agrawal's avatar
Sachin Agrawal committed
971 972 973 974 975 976 977
            default:
                ret = OC_EH_ERROR;
                break;
        }
    }

    //Send payload to request originator
978 979
    ret = (SendSRMCBORResponse(ehRequest, ret, NULL) == OC_STACK_OK) ?
                       ret : OC_EH_ERROR;
Sachin Agrawal's avatar
Sachin Agrawal committed
980 981 982 983 984 985

    return ret;
}

OCStackResult CreateCredResource()
{
986 987 988 989 990 991 992
    OCStackResult ret = OCCreateResource(&gCredHandle,
                                         OIC_RSRC_TYPE_SEC_CRED,
                                         OIC_MI_DEF,
                                         OIC_RSRC_CRED_URI,
                                         CredEntityHandler,
                                         NULL,
                                         OC_RES_PROP_NONE);
Sachin Agrawal's avatar
Sachin Agrawal committed
993 994 995

    if (OC_STACK_OK != ret)
    {
996
        OIC_LOG (FATAL, TAG, "Unable to instantiate Cred resource");
Sachin Agrawal's avatar
Sachin Agrawal committed
997 998 999 1000 1001 1002 1003 1004 1005 1006
        DeInitCredResource();
    }
    return ret;
}

OCStackResult InitCredResource()
{
    OCStackResult ret = OC_STACK_ERROR;

    //Read Cred resource from PS
1007 1008 1009 1010 1011 1012 1013 1014 1015
    uint8_t *data = NULL;
    size_t size = 0;
    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_CRED_NAME, &data, &size);
    // If database read failed
    if (ret != OC_STACK_OK)
    {
        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
    }
    if (data)
Sachin Agrawal's avatar
Sachin Agrawal committed
1016
    {
1017 1018
        // Read ACL resource from PS
        ret = CBORPayloadToCred(data, size, &gCred);
Sachin Agrawal's avatar
Sachin Agrawal committed
1019
    }
1020

Sachin Agrawal's avatar
Sachin Agrawal committed
1021 1022 1023 1024 1025
    /*
     * If SVR database in persistent storage got corrupted or
     * is not available for some reason, a default Cred is created
     * which allows user to initiate Cred provisioning again.
     */
1026
    if (ret != OC_STACK_OK || !data || !gCred)
Sachin Agrawal's avatar
Sachin Agrawal committed
1027 1028 1029 1030 1031
    {
        gCred = GetCredDefault();
    }
    //Instantiate 'oic.sec.cred'
    ret = CreateCredResource();
1032
    OICFree(data);
Sachin Agrawal's avatar
Sachin Agrawal committed
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
    return ret;
}

OCStackResult DeInitCredResource()
{
    OCStackResult result = OCDeleteResource(gCredHandle);
    DeleteCredList(gCred);
    gCred = NULL;
    return result;
}

const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject)
{
    OicSecCred_t *cred = NULL;

1048
   if ( NULL == subject)
Sachin Agrawal's avatar
Sachin Agrawal committed
1049
    {
1050
       return NULL;
Sachin Agrawal's avatar
Sachin Agrawal committed
1051 1052 1053 1054 1055 1056
    }

    LL_FOREACH(gCred, cred)
    {
        if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
        {
1057
            return cred;
Sachin Agrawal's avatar
Sachin Agrawal committed
1058 1059 1060 1061 1062 1063 1064
        }
    }
    return NULL;
}


#if defined(__WITH_DTLS__)
1065 1066 1067
int32_t GetDtlsPskCredentials(CADtlsPskCredType_t type,
              const uint8_t *desc, size_t desc_len,
              uint8_t *result, size_t result_length)
Sachin Agrawal's avatar
Sachin Agrawal committed
1068
{
1069
    int32_t ret = -1;
Sachin Agrawal's avatar
Sachin Agrawal committed
1070

1071 1072 1073 1074
    if (NULL == result)
    {
        return ret;
    }
Sachin Agrawal's avatar
Sachin Agrawal committed
1075

1076 1077 1078 1079
    switch (type)
    {
        case CA_DTLS_PSK_HINT:
        case CA_DTLS_PSK_IDENTITY:
Sachin Agrawal's avatar
Sachin Agrawal committed
1080
            {
1081 1082 1083
                OicUuid_t deviceID = {.id={}};
                // Retrieve Device ID from doxm resource
                if ( OC_STACK_OK != GetDoxmDeviceID(&deviceID) )
Sachin Agrawal's avatar
Sachin Agrawal committed
1084
                {
1085
                    OIC_LOG (ERROR, TAG, "Unable to retrieve doxm Device ID");
1086
                    return ret;
Sachin Agrawal's avatar
Sachin Agrawal committed
1087
                }
1088 1089 1090

                if (result_length < sizeof(deviceID.id))
                {
1091
                    OIC_LOG (ERROR, TAG, "Wrong value for result_length");
1092 1093 1094 1095
                    return ret;
                }
                memcpy(result, deviceID.id, sizeof(deviceID.id));
                return (sizeof(deviceID.id));
Sachin Agrawal's avatar
Sachin Agrawal committed
1096
            }
1097
            break;
Sachin Agrawal's avatar
Sachin Agrawal committed
1098

1099 1100 1101
        case CA_DTLS_PSK_KEY:
            {
                OicSecCred_t *cred = NULL;
Sachin Agrawal's avatar
Sachin Agrawal committed
1102 1103
                LL_FOREACH(gCred, cred)
                {
1104
                    if (cred->credType != SYMMETRIC_PAIR_WISE_KEY)
Sachin Agrawal's avatar
Sachin Agrawal committed
1105
                    {
1106 1107
                        continue;
                    }
Sachin Agrawal's avatar
Sachin Agrawal committed
1108

1109 1110 1111
                    if ((desc_len == sizeof(cred->subject.id)) &&
                        (memcmp(desc, cred->subject.id, sizeof(cred->subject.id)) == 0))
                    {
1112 1113 1114 1115 1116 1117 1118 1119
                        /*
                         * If the credentials are valid for limited time,
                         * check their expiry.
                         */
                        if (cred->period)
                        {
                            if(IOTVTICAL_VALID_ACCESS != IsRequestWithinValidTime(cred->period, NULL))
                            {
1120
                                OIC_LOG (INFO, TAG, "Credentials are expired.");
1121 1122 1123 1124 1125
                                ret = -1;
                                return ret;
                            }
                        }

1126 1127 1128 1129
                        // Copy PSK.
                        result_length = sizeof(cred->privateData.data);
                        memcpy(result, cred->privateData.data, result_length);
                        return result_length;
Sachin Agrawal's avatar
Sachin Agrawal committed