credresource.c 42.9 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 473 474 475 476 477 478
}

/**
 * This function generates the bin credential data.
 *
 * @param subject pointer to subject of this credential.
 * @param credType credential type.
 * @param publicData public data such as public key.
 * @param privateData private data such as private key.
479
 *        The privateData is expected in base64 encoded format.
Sachin Agrawal's avatar
Sachin Agrawal committed
480 481 482 483 484 485 486 487
 * @param ownersLen length of owners array
 * @param owners array of owners.
 *
 * @retval
 *      pointer to instance of OicSecCred_t  - success
 *      NULL                                 - error
 */
OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t credType,
488 489
                                  const uint8_t * publicData, const uint8_t* privateData,
                                  size_t ownersLen, const OicUuid_t * owners)
Sachin Agrawal's avatar
Sachin Agrawal committed
490
{
Jon A. Cruz's avatar
Jon A. Cruz committed
491
    (void)publicData;
Sachin Agrawal's avatar
Sachin Agrawal committed
492 493
    OCStackResult ret = OC_STACK_ERROR;

494
    OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
Sachin Agrawal's avatar
Sachin Agrawal committed
495 496
    VERIFY_NON_NULL(TAG, cred, ERROR);

497 498 499
    //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
500 501 502 503

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

504 505
    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
506 507
    cred->credType = credType;

Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
508
#ifdef __WITH_X509__
Sachin Agrawal's avatar
Sachin Agrawal committed
509 510
    if(publicData)
    {
511
        cred->publicData.data = (uint8_t *)OICCalloc(1, PUBLIC_KEY_SIZE);
Sachin Agrawal's avatar
Sachin Agrawal committed
512
        VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
513
        memcpy(cred->publicData.data, publicData, PUBLIC_KEY_SIZE);
Sachin Agrawal's avatar
Sachin Agrawal committed
514
    }
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
515
#endif // __WITH_X509__
Sachin Agrawal's avatar
Sachin Agrawal committed
516 517 518

    if(privateData)
    {
519 520
#ifdef __WITH_X509__
        cred->privateData.data = (uint8_t *)OICCalloc(1, PRIVATE_KEY_SIZE);
Sachin Agrawal's avatar
Sachin Agrawal committed
521
        VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
522 523
        memcpy(cred->privateData.data, privateData, PRIVATE_KEY_SIZE);
#endif // __WITH_X509__
Sachin Agrawal's avatar
Sachin Agrawal committed
524 525 526 527 528
    }

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

529
    cred->owners = (OicUuid_t *)OICCalloc(cred->ownersLen, sizeof(*cred->owners));
Sachin Agrawal's avatar
Sachin Agrawal committed
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
    VERIFY_NON_NULL(TAG, cred->owners, ERROR);
    for(size_t i = 0; i < cred->ownersLen; i++)
    {
        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;
}

546 547 548 549 550
static bool UpdatePersistentStorage(const OicSecCred_t *cred)
{
    bool ret = false;

    // Convert Cred data into JSON for update to persistent storage
551 552 553 554
    uint8_t *payload = NULL;
    size_t size = 0;
    OCStackResult res = CredToCBORPayload(cred, &payload, &size);
    if ((OC_STACK_OK == res) && payload)
555
    {
556
        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, payload, size))
557 558 559
        {
            ret = true;
        }
560
        OICFree(payload);
561 562 563
    }
    else //Empty cred list
    {
564
        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, NULL, size))
565 566 567 568 569 570 571 572
        {
            ret = true;
        }
    }
    return ret;
}

/**
573 574 575 576 577 578 579 580 581 582 583 584
 * Compare function used LL_SORT for sorting credentials
 *
 * @param first   pointer to OicSecCred_t struct
 * @param second  pointer to OicSecCred_t struct
 *
 *@retval
 *  -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
 */
static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
{
585
    if (first->credId < second->credId)
586 587 588
    {
        return -1;
    }
589
    else if (first->credId > second->credId)
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
    {
        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.
 *
 * @retval
 *      next available credId  - success
 *      0                      - error
 */

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)
    {
        if(currentCred->credId == nextCredId)
        {
            nextCredId += 1;
        }
        else
        {
            break;
        }
    }

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

exit:
    return 0;
}
635

636 637 638 639 640 641 642 643
/**
 * Get the default value
 * @retval  NULL for now. Update it when we finalize the default info.
 */
static OicSecCred_t* GetCredDefault()
{
    return NULL;
}
644

Sachin Agrawal's avatar
Sachin Agrawal committed
645 646 647 648 649 650 651 652 653 654 655 656
/**
 * This function adds the new cred to the credential list.
 *
 * @param cred pointer to new credential.
 *
 * @retval
 *      OC_STACK_OK     - cred not NULL and persistent storage gets updated
 *      OC_STACK_ERROR  - cred is NULL or fails to update persistent storage
 */
OCStackResult AddCredential(OicSecCred_t * newCred)
{
    OCStackResult ret = OC_STACK_ERROR;
657 658 659 660 661
    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
662 663 664

    //Append the new Cred to existing list
    LL_APPEND(gCred, newCred);
665
    if (UpdatePersistentStorage(gCred))
Sachin Agrawal's avatar
Sachin Agrawal committed
666
    {
667 668 669 670 671 672 673 674 675 676 677 678 679
        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
680

681 682 683
    LL_FOREACH_SAFE(gCred, cred, tempCred)
    {
        if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
Sachin Agrawal's avatar
Sachin Agrawal committed
684
        {
685 686 687
            LL_DELETE(gCred, cred);
            FreeCred(cred);
            deleteFlag = 1;
Sachin Agrawal's avatar
Sachin Agrawal committed
688 689 690
        }
    }

691 692 693 694 695 696 697
    if(deleteFlag)
    {
        if(UpdatePersistentStorage(gCred))
        {
            ret = OC_STACK_RESOURCE_DELETED;
        }
    }
Sachin Agrawal's avatar
Sachin Agrawal committed
698
    return ret;
699

Sachin Agrawal's avatar
Sachin Agrawal committed
700 701
}

702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
/**
 * 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();

    if(!UpdatePersistentStorage(gCred))
    {
        return OC_STACK_ERROR;
    }
    return OC_STACK_OK;
}

721 722
#ifdef __WITH_DTLS__
/**
723
 * Internal function to fill private data of owner PSK.
724
 *
725
 * @param receviedCred recevied owner credential from OBT(PT)
726 727 728 729
 * @param ownerAdd address of OBT(PT)
 * @param doxm current device's doxm resource
 *
 * @retval
730 731
 *     true successfully done and valid ower psk information
 *     false Invalid owner psk information or failed to owner psk generation
732
 */
733
static bool FillPrivateDataOfOwnerPSK(OicSecCred_t* receviedCred, const CAEndpoint_t* ownerAddr,
734 735 736 737 738 739 740 741 742 743 744 745 746 747
                           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);

748 749 750 751
    OIC_LOG(DEBUG, TAG, "OwnerPSK dump :");
    OIC_LOG_BUFFER(DEBUG, TAG, ownerPSK, OWNER_PSK_LENGTH_128);

    //Generate owner credential based on recevied credential information
752
    receviedCred->privateData.data = (uint8_t *)OICCalloc(1, OWNER_PSK_LENGTH_128);
753
    VERIFY_NON_NULL(TAG, receviedCred->privateData.data, ERROR);
754
    memcpy(receviedCred->privateData.data, ownerPSK, OWNER_PSK_LENGTH_128);
755 756 757 758 759
    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);
760
exit:
761
    //receviedCred->privateData.data will be deallocated when deleting credential.
762 763 764 765 766 767 768 769 770 771
    return false;
}

#endif //__WITH_DTLS__

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

    //Get binary representation of json
772 773 774 775 776
    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)
777 778 779 780 781 782 783 784 785 786 787 788
    {
#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;
789
                    if(FillPrivateDataOfOwnerPSK(cred, (CAEndpoint_t *)&request->devAddr, doxm))
790
                    {
791 792 793 794 795 796
                        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.");
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
                        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;
                    }

813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
                    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;
                        }
                    }

851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
                    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;
                }
            }
870 871 872 873 874 875 876 877 878 879

            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();
            }
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
        }
        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__
    }

902 903 904 905 906 907 908 909 910
    if(OC_EH_RESOURCE_CREATED != ret)
    {
        if(OC_STACK_OK != RemoveCredential(&cred->subject))
        {
            OIC_LOG(WARNING, TAG, "Failed to remove the invalid credential");
        }
        FreeCred(cred);
    }

911 912 913
    return ret;
}

Sachin Agrawal's avatar
Sachin Agrawal committed
914 915 916 917
static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
{
    OCEntityHandlerResult ret = OC_EH_ERROR;

918 919 920 921 922
    //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
923
    {
924 925 926 927
        //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.
928
        ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
Sachin Agrawal's avatar
Sachin Agrawal committed
929
    }
930

Sachin Agrawal's avatar
Sachin Agrawal committed
931 932 933
    return ret;
}

934 935
static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *ehRequest)
{
936
    OIC_LOG(DEBUG, TAG, "Processing CredDeleteRequest");
937 938 939 940 941 942 943 944

    OCEntityHandlerResult ehRet = OC_EH_ERROR;

    if(NULL == ehRequest->query)
   {
       return ehRet;
   }

945
   OicParseQueryIter_t parseIter = { .attrPos=NULL };
946 947 948 949 950 951
   OicUuid_t subject = {.id={0}};

   //Parsing REST query to get the subject
   ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
   while(GetNextQuery(&parseIter))
   {
952
       if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME,
953 954
               parseIter.attrLen) == 0)
       {
955
           memcpy(subject.id, parseIter.valPos, parseIter.valLen);
956 957 958 959 960 961 962 963 964 965 966
       }
   }

   if(OC_STACK_RESOURCE_DELETED == RemoveCredential(&subject))
   {
       ehRet = OC_EH_RESOURCE_DELETED;
   }

    return ehRet;
}

967
OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
968 969
                                        OCEntityHandlerRequest * ehRequest,
                                        void* callbackParameter)
Sachin Agrawal's avatar
Sachin Agrawal committed
970
{
Jon A. Cruz's avatar
Jon A. Cruz committed
971
    (void)callbackParameter;
Sachin Agrawal's avatar
Sachin Agrawal committed
972 973 974 975 976 977 978 979
    OCEntityHandlerResult ret = OC_EH_ERROR;

    if(!ehRequest)
    {
        return OC_EH_ERROR;
    }
    if (flag & OC_REQUEST_FLAG)
    {
980
        OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
Sachin Agrawal's avatar
Sachin Agrawal committed
981 982 983 984 985 986
        //TODO :  Handle PUT/DEL methods
        switch(ehRequest->method)
        {
            case OC_REST_GET:
                ret = OC_EH_FORBIDDEN;
                break;
987 988 989
            case OC_REST_PUT:
                ret = HandlePutRequest(ehRequest);
                break;
Sachin Agrawal's avatar
Sachin Agrawal committed
990 991 992
            case OC_REST_POST:
                ret = HandlePostRequest(ehRequest);
                break;
993 994 995
            case OC_REST_DELETE:
                ret = HandleDeleteRequest(ehRequest);
                break;
Sachin Agrawal's avatar
Sachin Agrawal committed
996 997 998 999 1000 1001 1002
            default:
                ret = OC_EH_ERROR;
                break;
        }
    }

    //Send payload to request originator
1003 1004
    ret = (SendSRMCBORResponse(ehRequest, ret, NULL) == OC_STACK_OK) ?
                       ret : OC_EH_ERROR;
Sachin Agrawal's avatar
Sachin Agrawal committed
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017

    return ret;
}

OCStackResult CreateCredResource()
{
    OCStackResult ret;

    ret = OCCreateResource(&gCredHandle,
                           OIC_RSRC_TYPE_SEC_CRED,
                           OIC_MI_DEF,
                           OIC_RSRC_CRED_URI,
                           CredEntityHandler,
1018
                           NULL,
Sachin Agrawal's avatar
Sachin Agrawal committed
1019 1020 1021 1022
                           OC_RES_PROP_NONE);

    if (OC_STACK_OK != ret)
    {
1023
        OIC_LOG (FATAL, TAG, "Unable to instantiate Cred resource");
Sachin Agrawal's avatar
Sachin Agrawal committed
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
        DeInitCredResource();
    }
    return ret;
}

OCStackResult InitCredResource()
{
    OCStackResult ret = OC_STACK_ERROR;

    //Read Cred resource from PS
1034 1035 1036 1037 1038 1039 1040 1041 1042
    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
1043
    {
1044 1045
        // Read ACL resource from PS
        ret = CBORPayloadToCred(data, size, &gCred);
Sachin Agrawal's avatar
Sachin Agrawal committed
1046
    }
1047

Sachin Agrawal's avatar
Sachin Agrawal committed
1048 1049 1050 1051 1052
    /*
     * 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.
     */
1053
    if (ret != OC_STACK_OK || !data || !gCred)
Sachin Agrawal's avatar
Sachin Agrawal committed
1054 1055 1056 1057 1058
    {
        gCred = GetCredDefault();
    }
    //Instantiate 'oic.sec.cred'
    ret = CreateCredResource();
1059
    OICFree(data);
Sachin Agrawal's avatar
Sachin Agrawal committed
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
    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;

1075
   if ( NULL == subject)
Sachin Agrawal's avatar
Sachin Agrawal committed
1076
    {
1077
       return NULL;
Sachin Agrawal's avatar
Sachin Agrawal committed
1078 1079 1080 1081 1082 1083
    }

    LL_FOREACH(gCred, cred)
    {
        if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
        {
1084
            return cred;
Sachin Agrawal's avatar
Sachin Agrawal committed
1085 1086 1087 1088 1089 1090 1091
        }
    }
    return NULL;
}


#if defined(__WITH_DTLS__)
1092 1093 1094
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
1095
{
1096
    int32_t ret = -1;
Sachin Agrawal's avatar
Sachin Agrawal committed
1097

1098 1099 1100 1101
    if (NULL == result)
    {
        return ret;
    }
Sachin Agrawal's avatar
Sachin Agrawal committed
1102

1103 1104 1105 1106
    switch (type)
    {
        case CA_DTLS_PSK_HINT:
        case CA_DTLS_PSK_IDENTITY:
Sachin Agrawal's avatar
Sachin Agrawal committed
1107
            {
1108 1109 1110
                OicUuid_t deviceID = {.id={}};
                // Retrieve Device ID from doxm resource
                if ( OC_STACK_OK != GetDoxmDeviceID(&deviceID) )
Sachin Agrawal's avatar
Sachin Agrawal committed
1111
                {
1112
                    OIC_LOG (ERROR, TAG, "Unable to retrieve doxm Device ID");
1113
                    return ret;
Sachin Agrawal's avatar
Sachin Agrawal committed
1114
                }
1115 1116 1117

                if (result_length < sizeof(deviceID.id))
                {
1118
                    OIC_LOG (ERROR, TAG, "Wrong value for result_length");
1119 1120 1121 1122
                    return ret;
                }
                memcpy(result, deviceID.id, sizeof(deviceID.id));
                return (sizeof(deviceID.id));
Sachin Agrawal's avatar
Sachin Agrawal committed
1123
            }
1124
            break;
Sachin Agrawal's avatar
Sachin Agrawal committed
1125

1126 1127 1128
        case CA_DTLS_PSK_KEY:
            {
                OicSecCred_t *cred = NULL;
Sachin Agrawal's avatar
Sachin Agrawal committed
1129 1130
                LL_FOREACH(gCred, cred)
                {
1131
                    if (cred->credType != SYMMETRIC_PAIR_WISE_KEY)
Sachin Agrawal's avatar
Sachin Agrawal committed
1132
                    {
1133 1134
                        continue;
                    }
Sachin Agrawal's avatar
Sachin Agrawal committed
1135

1136 1137 1138
                    if ((desc_len == sizeof(cred->subject.id)) &&
                        (memcmp(desc, cred->subject.id, sizeof(cred->subject.id)) == 0))
                    {
1139 1140 1141 1142 1143 1144 1145 1146
                        /*
                         * If the credentials are valid for limited time,
                         * check their expiry.
                         */
                        if (cred->period)
                        {
                            if(IOTVTICAL_VALID_ACCESS != IsRequestWithinValidTime(cred->period, NULL))
                            {
1147
                                OIC_LOG (INFO, TAG, "Credentials are expired.");
1148 1149 1150 1151 1152
                                ret = -1;
                                return ret;
                            }
                        }

1153 1154 1155 1156
                        // 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
1157 1158 1159
                    }
                }
            }
1160
            break;
Sachin Agrawal's avatar
Sachin Agrawal committed
1161

1162 1163
        default:
            {
1164
                OIC_LOG (ERROR, TAG, "Wrong value passed for CADtlsPskCredType_t.");
1165 1166 1167
                ret = -1;
            }
            break;
Sachin Agrawal's avatar
Sachin Agrawal committed
1168
    }
1169 1170

    return ret;
Sachin Agrawal's avatar
Sachin Agrawal committed
1171
}
1172

Joonghwan Lee's avatar
Joonghwan Lee committed
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
/**
 * Add temporal PSK to PIN based OxM
 *
 * @param[in] tmpSubject UUID of target device
 * @param[in] credType Type of credential to be added
 * @param[in] pin numeric characters
 * @param[in] pinSize length of 'pin'
 * @param[in] ownersLen Number of owners
 * @param[in] owners Array of owners
 * @param[out] tmpCredSubject Generated credential's subject.
 *
 * @return OC_STACK_OK for success and errorcode otherwise.
 */
OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t credType,
                            const char * pin, size_t pinSize,
                            size_t ownersLen, const OicUuid_t * owners, OicUuid_t* tmpCredSubject)
{
    OCStackResult ret = OC_STACK_ERROR;

    if(NULL == tmpSubject || NULL == pin || 0 == pinSize || NULL == tmpCredSubject)
    {
        return OC_STACK_INVALID_PARAM;
    }

    uint8_t privData[OWNER_PSK_LENGTH_128] = {0,};
1198
    OicSecCred_t* cred = NULL;
Joonghwan Lee's avatar
Joonghwan Lee committed
1199 1200 1201 1202 1203
    int dtlsRes = DeriveCryptoKeyFromPassword((const unsigned char *)pin, pinSize, owners->id,
                                              UUID_LENGTH, PBKDF_ITERATIONS,
                                              OWNER_PSK_LENGTH_128, privData);
    VERIFY_SUCCESS(TAG, (0 == dtlsRes) , ERROR);

1204 1205
    cred = GenerateCredential(tmpSubject, credType, NULL,
                              privData, ownersLen, owners);
Joonghwan Lee's avatar
Joonghwan Lee committed
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
    if(NULL == cred)
    {
        OIC_LOG(ERROR,<