credresource.c 27.5 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
Sachin Agrawal's avatar
Sachin Agrawal committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include "ocstack.h"
#include "logger.h"
#include "oic_malloc.h"
#include "cJSON.h"
#include "resourcemanager.h"
#include "psinterface.h"
#include "utlist.h"
#include "srmresourcestrings.h"
#include "credresource.h"
#include "ocrandom.h"
#include "doxmresource.h"
#include "base64.h"
#include "srmutility.h"
#include "cainterface.h"
36
#include "pbkdf2.h"
Sachin Agrawal's avatar
Sachin Agrawal committed
37
#include <stdlib.h>
38
#ifdef WITH_ARDUINO
Sachin Agrawal's avatar
Sachin Agrawal committed
39
#include <string.h>
40 41 42
#else
#include <strings.h>
#endif
43 44
#include <stdint.h>

Sachin Agrawal's avatar
Sachin Agrawal committed
45 46
#define TAG  PCF("SRM-CREDL")

Shilpa Sodani's avatar
Shilpa Sodani committed
47

Sachin Agrawal's avatar
Sachin Agrawal committed
48 49 50
static OicSecCred_t        *gCred = NULL;
static OCResourceHandle    gCredHandle = NULL;

51 52 53 54
/**
 * This function frees OicSecCred_t object's fields and object itself.
 */
static void FreeCred(OicSecCred_t *cred)
Sachin Agrawal's avatar
Sachin Agrawal committed
55
{
56
    if(NULL == cred)
Sachin Agrawal's avatar
Sachin Agrawal committed
57
    {
58 59 60 61
        OC_LOG (INFO, TAG, PCF("Invalid Parameter"));
        return;
    }
    //Note: Need further clarification on roleID data type
Sachin Agrawal's avatar
Sachin Agrawal committed
62
#if 0
63 64
    //Clean roleIds
    OICFree(cred->roleIds);
Sachin Agrawal's avatar
Sachin Agrawal committed
65 66
#endif

67 68
    //Clean PublicData
    OICFree(cred->publicData.data);
Sachin Agrawal's avatar
Sachin Agrawal committed
69

70 71
    //Clean PrivateData
    OICFree(cred->privateData.data);
Sachin Agrawal's avatar
Sachin Agrawal committed
72

73 74
    //Clean Period
    OICFree(cred->period);
Sachin Agrawal's avatar
Sachin Agrawal committed
75

76 77 78 79 80 81
    //Clean Owners
    OICFree(cred->owners);

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

83 84 85 86 87 88 89 90 91
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
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
        }
    }
}

/**
 * This function converts credential data into JSON format.
 * Caller needs to invoke 'free' when done using
 * returned string.
 * @param cred  pointer to instance of OicSecCred_t structure.
 *
 * @retval
 *      pointer to JSON credential representation - if credential for subjectId found
 *      NULL                                      - if credential for subjectId not found
 */
char * BinToCredJSON(const OicSecCred_t * cred)
{
    cJSON *jsonRoot = NULL;
    char *jsonStr = NULL;

    if (cred)
    {
        char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
        uint32_t outLen = 0;
        B64Result b64Ret = B64_OK;

        jsonRoot = cJSON_CreateObject();
        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);

        cJSON *jsonCredArray = NULL;
        cJSON_AddItemToObject(jsonRoot, OIC_JSON_CRED_NAME,
                jsonCredArray = cJSON_CreateArray());
        VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);

        while(cred)
        {
            cJSON *jsonCred = cJSON_CreateObject();
            VERIFY_NON_NULL(TAG, jsonCred, ERROR);

            //CredID -- Mandatory
            cJSON_AddNumberToObject(jsonCred, OIC_JSON_CREDID_NAME, (int)cred->credId);

            //Subject -- Mandatory
            outLen = 0;
            memset(base64Buff, 0, sizeof(base64Buff));
            b64Ret = b64Encode(cred->subject.id, sizeof(cred->subject.id), base64Buff,
                   sizeof(base64Buff), &outLen);
            VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
            cJSON_AddStringToObject(jsonCred, OIC_JSON_SUBJECT_NAME, base64Buff);

            //Note: Need further clarification on roleID data type
#if 0
            //RoleId -- Not Mandatory
            if(cred->roleIdsLen > 0)
            {
                cJSON *jsonRoleIdsArray = NULL;
                cJSON_AddItemToObject (jsonCred, OIC_JSON_ROLEIDS_NAME,
                                         jsonRoleIdsArray = cJSON_CreateArray());
                VERIFY_NON_NULL(TAG, jsonRoleIdsArray, ERROR);
                for (size_t i = 0; i < cred->roleIdsLen; i++)
                {
                    cJSON_AddItemToArray (jsonRoleIdsArray,
                            cJSON_CreateString((char *)cred->roleIds[i].id));
                }
            }
#endif

            //CredType -- Mandatory
            cJSON_AddNumberToObject(jsonCred, OIC_JSON_CREDTYPE_NAME,(int)cred->credType);

#if 0
            //PublicData -- Not Mandatory
            if(cred->publicData.data)
            {
                cJSON_AddStringToObject(jsonCred, OIC_JSON_PUBLICDATA_NAME, cred->publicData.data);
            }
#endif
            //PrivateData -- Not Mandatory
            if(cred->privateData.data)
            {
                cJSON_AddStringToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME, cred->privateData.data);
            }

            //Period -- Not Mandatory
            if(cred->period)
            {
                cJSON_AddStringToObject(jsonCred, OIC_JSON_PERIOD_NAME,
                                        cred->period);
            }

            //Owners -- Mandatory
            cJSON *jsonOwnrArray = NULL;
            cJSON_AddItemToObject (jsonCred, OIC_JSON_OWNERS_NAME,
                                             jsonOwnrArray = cJSON_CreateArray());
            VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
            for (size_t i = 0; i < cred->ownersLen; i++)
            {
                outLen = 0;
                memset(base64Buff, 0, sizeof(base64Buff));
                b64Ret = b64Encode(cred->owners[i].id, sizeof(cred->owners[i].id),
                        base64Buff, sizeof(base64Buff), &outLen);
                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
                cJSON_AddItemToArray (jsonOwnrArray,
                                       cJSON_CreateString((char *)(base64Buff)));
            }

            /* Attach current cred node to cred Array */
            cJSON_AddItemToArray(jsonCredArray, jsonCred);
            cred = cred->next;
        }

        jsonStr = cJSON_PrintUnformatted(jsonRoot);
    }

exit:
    if (jsonRoot)
    {
        cJSON_Delete(jsonRoot);
    }
    return jsonStr;
}

/*
 * This internal method converts JSON cred into binary cred.
 */
OicSecCred_t * JSONToCredBin(const char * jsonStr)
{
    OCStackResult ret = OC_STACK_ERROR;
    OicSecCred_t * headCred = NULL;
    OicSecCred_t * prevCred = NULL;
    cJSON *jsonCredArray = NULL;

    cJSON *jsonRoot = cJSON_Parse(jsonStr);
    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);

    jsonCredArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
    VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
    if (cJSON_Array == jsonCredArray->type)
    {
        int numCred = cJSON_GetArraySize(jsonCredArray);
        int idx = 0;

        unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
        uint32_t outLen = 0;
        B64Result b64Ret = B64_OK;

        VERIFY_SUCCESS(TAG, numCred > 0, ERROR);
        do
        {
            cJSON *jsonCred = cJSON_GetArrayItem(jsonCredArray, idx);
            VERIFY_NON_NULL(TAG, jsonCred, ERROR);

            OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
            VERIFY_NON_NULL(TAG, cred, ERROR);

            headCred = (headCred) ? headCred : cred;
            if (prevCred)
            {
                prevCred->next = cred;
            }
            size_t jsonObjLen = 0;
            cJSON *jsonObj = NULL;

            //CredId -- Mandatory
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDID_NAME);
256 257 258 259 260
            if(jsonObj)
            {
                VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
                cred->credId = jsonObj->valueint;
            }
Sachin Agrawal's avatar
Sachin Agrawal committed
261 262 263 264

            //subject -- Mandatory
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_SUBJECT_NAME);
            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
265
            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
Sachin Agrawal's avatar
Sachin Agrawal committed
266 267 268 269 270 271 272 273 274 275 276
            outLen = 0;
            memset(base64Buff, 0, sizeof(base64Buff));
            b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring),
                    base64Buff, sizeof(base64Buff), &outLen);
            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(cred->subject.id)),
                           ERROR);
            memcpy(cred->subject.id, base64Buff, outLen);

            //CredType -- Mandatory
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDTYPE_NAME);
            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
277
            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
Sachin Agrawal's avatar
Sachin Agrawal committed
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
            cred->credType = jsonObj->valueint;

            //PrivateData is mandatory for some of the credential types listed below.
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PRIVATEDATA_NAME);
            if ((cred->credType & SYMMETRIC_PAIR_WISE_KEY) ||
                (cred->credType & SYMMETRIC_GROUP_KEY) ||
                (cred->credType & PIN_PASSWORD))
            {
                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
                VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
            }
            if(jsonObj && cJSON_String == jsonObj->type)
            {
                jsonObjLen = strlen(jsonObj->valuestring) + 1;
                cred->privateData.data = (char *)OICMalloc(jsonObjLen);
                VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
                strncpy((char *)cred->privateData.data, (char *)jsonObj->valuestring, jsonObjLen);
            }

            //Period -- Not Mandatory
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PERIOD_NAME);
            if(jsonObj && cJSON_String == jsonObj->type)
            {
                jsonObjLen = strlen(jsonObj->valuestring) + 1;
                cred->period = (char *)OICMalloc(jsonObjLen);
                VERIFY_NON_NULL(TAG, cred->period, ERROR);
                strncpy(cred->period, jsonObj->valuestring, jsonObjLen);
            }

            //Owners -- Mandatory
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_OWNERS_NAME);
            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
310
            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
Sachin Agrawal's avatar
Sachin Agrawal committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
            cred->ownersLen = cJSON_GetArraySize(jsonObj);
            VERIFY_SUCCESS(TAG, cred->ownersLen > 0, ERROR);
            cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
            VERIFY_NON_NULL(TAG, (cred->owners), ERROR);
            for(size_t i = 0; i < cred->ownersLen; i++)
            {
                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, i);
                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
                outLen = 0;
                memset(base64Buff, 0, sizeof(base64Buff));
                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring),
                         base64Buff, sizeof(base64Buff), &outLen);
                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK &&
                               outLen <= sizeof(cred->owners[i].id)), ERROR);
                memcpy(cred->owners[i].id, base64Buff, outLen);
            }
            prevCred = cred;
        } while( ++idx < numCred);
    }

    ret = OC_STACK_OK;

exit:
    cJSON_Delete(jsonRoot);
    if (OC_STACK_OK != ret)
    {
        DeleteCredList(headCred);
        headCred = NULL;
    }
    return headCred;
}

/**
 * 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.
351
 *        The privateData is expected in base64 encoded format.
Sachin Agrawal's avatar
Sachin Agrawal committed
352 353 354 355 356 357 358 359 360 361 362
 * @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,
                                 const char * publicData, const char * privateData,
                                 size_t ownersLen, const OicUuid_t * owners)
{
Jon A. Cruz's avatar
Jon A. Cruz committed
363
    (void)publicData;
Sachin Agrawal's avatar
Sachin Agrawal committed
364 365 366 367 368
    OCStackResult ret = OC_STACK_ERROR;

    OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
    VERIFY_NON_NULL(TAG, cred, ERROR);

369 370 371
    //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
372 373 374 375

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

376 377
    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
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
    cred->credType = credType;

#if 0
    if(publicData)
    {
        cred->publicData.data = (char *)OICMalloc(strlen(publicData)+1);
        VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
        strncpy((char *)cred->publicData.data, publicData, strlen(publicData)+1);
    }
#endif

    if(privateData)
    {
        cred->privateData.data = (char *)OICMalloc(strlen(privateData)+1);
        VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
        strncpy((char *)cred->privateData.data, privateData, strlen(privateData)+1);
    }

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

    cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
    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;
}

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
static bool UpdatePersistentStorage(const OicSecCred_t *cred)
{
    bool ret = false;

    // Convert Cred data into JSON for update to persistent storage
    char *jsonStr = BinToCredJSON(cred);
    if (jsonStr)
    {
        cJSON *jsonCred = cJSON_Parse(jsonStr);
        OICFree(jsonStr);

        if ((jsonCred) &&
          (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, jsonCred)))
        {
            ret = true;
        }
        cJSON_Delete(jsonCred );
    }
    else //Empty cred list
    {
        if (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, NULL))
        {
            ret = true;
        }
    }
    return ret;
}

/**
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
 * 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)
{
    if(first->credId < second->credId)
    {
        return -1;
    }
    else if(first->credId > second->credId)
    {
        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;
}
507 508


Sachin Agrawal's avatar
Sachin Agrawal committed
509 510 511 512 513 514 515 516 517 518 519 520 521
/**
 * 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;

522 523 524 525 526 527
    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
528 529 530 531

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

532
    if(UpdatePersistentStorage(gCred))
Sachin Agrawal's avatar
Sachin Agrawal committed
533
    {
534 535 536 537 538 539 540 541 542 543 544 545 546
        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
547

548 549 550
    LL_FOREACH_SAFE(gCred, cred, tempCred)
    {
        if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
Sachin Agrawal's avatar
Sachin Agrawal committed
551
        {
552 553 554
            LL_DELETE(gCred, cred);
            FreeCred(cred);
            deleteFlag = 1;
Sachin Agrawal's avatar
Sachin Agrawal committed
555 556 557
        }
    }

558 559 560 561 562 563 564
    if(deleteFlag)
    {
        if(UpdatePersistentStorage(gCred))
        {
            ret = OC_STACK_RESOURCE_DELETED;
        }
    }
Sachin Agrawal's avatar
Sachin Agrawal committed
565
    return ret;
566

Sachin Agrawal's avatar
Sachin Agrawal committed
567 568 569 570 571 572 573
}

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

    //Get binary representation of json
574
    OicSecCred_t * cred  = JSONToCredBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
Sachin Agrawal's avatar
Sachin Agrawal committed
575 576 577

    if(cred)
    {
578 579 580 581
        //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.
Sachin Agrawal's avatar
Sachin Agrawal committed
582 583 584 585 586 587
        ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
    }

    return ret;
}

588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *ehRequest)
{
    OC_LOG_V (INFO, TAG, PCF("Processing CredDeleteRequest"));

    OCEntityHandlerResult ehRet = OC_EH_ERROR;

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

   OicParseQueryIter_t parseIter = {.attrPos=NULL};
   OicUuid_t subject = {.id={0}};

   //Parsing REST query to get the subject
   ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
   while(GetNextQuery(&parseIter))
   {
       if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME,
               parseIter.attrLen) == 0)
       {
           unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
           uint32_t outLen = 0;
           B64Result b64Ret = B64_OK;

           b64Ret = b64Decode((char *)parseIter.valPos, parseIter.valLen,
                   base64Buff, sizeof(base64Buff), &outLen);

           VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(subject.id)), ERROR);
           memcpy(subject.id, base64Buff, outLen);
       }
   }

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

exit:
    return ehRet;
}


Sachin Agrawal's avatar
Sachin Agrawal committed
631 632 633 634 635
/*
 * This internal method is the entity handler for Cred resources
 * to handle REST request (PUT/POST/DEL)
 */
OCEntityHandlerResult CredEntityHandler (OCEntityHandlerFlag flag,
636 637
                                        OCEntityHandlerRequest * ehRequest,
                                        void* callbackParameter)
Sachin Agrawal's avatar
Sachin Agrawal committed
638
{
Jon A. Cruz's avatar
Jon A. Cruz committed
639
    (void)callbackParameter;
Sachin Agrawal's avatar
Sachin Agrawal committed
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
    OCEntityHandlerResult ret = OC_EH_ERROR;

    if(!ehRequest)
    {
        return OC_EH_ERROR;
    }
    if (flag & OC_REQUEST_FLAG)
    {
        OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
        //TODO :  Handle PUT/DEL methods
        switch(ehRequest->method)
        {
            case OC_REST_GET:
                ret = OC_EH_FORBIDDEN;
                break;
            case OC_REST_POST:
                ret = HandlePostRequest(ehRequest);
                break;
658 659 660
            case OC_REST_DELETE:
                ret = HandleDeleteRequest(ehRequest);
                break;
Sachin Agrawal's avatar
Sachin Agrawal committed
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
            default:
                ret = OC_EH_ERROR;
                break;
        }
    }

    //Send payload to request originator
    ret = (SendSRMResponse(ehRequest, ret, NULL) == OC_STACK_OK ?
                       ret : OC_EH_ERROR);

    return ret;
}

/*
 * This internal method is used to create '/oic/sec/Cred' resource.
 */
OCStackResult CreateCredResource()
{
    OCStackResult ret;

    ret = OCCreateResource(&gCredHandle,
                           OIC_RSRC_TYPE_SEC_CRED,
                           OIC_MI_DEF,
                           OIC_RSRC_CRED_URI,
                           CredEntityHandler,
686
                           NULL,
Sachin Agrawal's avatar
Sachin Agrawal committed
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
                           OC_RES_PROP_NONE);

    if (OC_STACK_OK != ret)
    {
        OC_LOG (FATAL, TAG, PCF("Unable to instantiate Cred resource"));
        DeInitCredResource();
    }
    return ret;
}

/**
 * Get the default value
 * @retval  NULL for now. Update it when we finalize the default info.
 */
static OicSecCred_t* GetCredDefault()
{
    return NULL;
}

/**
 * Initialize Cred resource by loading data from persistent storage.
 *
 * @retval
 *     OC_STACK_OK    - no errors
 *     OC_STACK_ERROR - stack process error
 */
OCStackResult InitCredResource()
{
    OCStackResult ret = OC_STACK_ERROR;

    //Read Cred resource from PS
    char* jsonSVRDatabase = GetSVRDatabase();

    if (jsonSVRDatabase)
    {
        //Convert JSON Cred into binary format
        gCred = JSONToCredBin(jsonSVRDatabase);
    }
    /*
     * 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.
     */
    if (!jsonSVRDatabase || !gCred)
    {
        gCred = GetCredDefault();
    }
    //Instantiate 'oic.sec.cred'
    ret = CreateCredResource();
    OICFree(jsonSVRDatabase);
    return ret;
}

/**
 * Perform cleanup for Cred resources.
 *
 * @return
 *     OC_STACK_OK              - no errors
 *     OC_STACK_ERROR           - stack process error
 *     OC_STACK_NO_RESOURCE     - resource not found
 *     OC_STACK_INVALID_PARAM   - invalid param
 */
OCStackResult DeInitCredResource()
{
    OCStackResult result = OCDeleteResource(gCredHandle);
    DeleteCredList(gCred);
    gCred = NULL;
    return result;
}

/**
 * This method is used by tinydtls/SRM to retrieve credential for given Subject.
 *
 * @param subject - subject for which credential is required.
 *
 * @retval
 *     reference to OicSecCred_t - if credential is found
 *     NULL                      - if credential not found
 */
const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject)
{
    OicSecCred_t *cred = NULL;

770
   if ( NULL == subject)
Sachin Agrawal's avatar
Sachin Agrawal committed
771
    {
772
       return NULL;
Sachin Agrawal's avatar
Sachin Agrawal committed
773 774 775 776 777 778
    }

    LL_FOREACH(gCred, cred)
    {
        if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
        {
779
            return cred;
Sachin Agrawal's avatar
Sachin Agrawal committed
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
        }
    }
    return NULL;
}


#if defined(__WITH_DTLS__)
/**
 * This internal callback is used by lower stack (i.e. CA layer) to
 * retrieve PSK credentials from RI security layer.
 *
 * Note: When finished, caller should initialize memory to zeros and
 * invoke OICFree to delete @p credInfo.
 *
 * @param credInfo
 *     binary blob containing PSK credentials
 *
 * @retval none
 */
void GetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
{
    CADtlsPskCredsBlob_t * caBlob = NULL;
    if(credInfo)
    {
        caBlob = (CADtlsPskCredsBlob_t *)OICCalloc(sizeof(CADtlsPskCredsBlob_t), 1);
        if (caBlob)
        {
Shilpa Sodani's avatar
Shilpa Sodani committed
807
            OicUuid_t deviceID = {.id={}};
Sachin Agrawal's avatar
Sachin Agrawal committed
808 809 810 811 812 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 851 852 853 854 855 856 857 858 859 860 861 862 863 864

            // Retrieve Device ID from doxm resource and copy in PSK creds blob
            VERIFY_SUCCESS(TAG, GetDoxmDeviceID(&deviceID) == OC_STACK_OK, ERROR);
            memcpy(caBlob->identity, deviceID.id, sizeof(caBlob->identity));

            OicSecCred_t *cred = NULL;
            size_t count = 0;
            LL_FOREACH(gCred, cred)
            {
                // Currently, Iotivity supports only symmetric pair wise key credentials
                if (cred->credType == SYMMETRIC_PAIR_WISE_KEY)
                {
                    ++count;
                }
            }
            caBlob->num = count;
            if (caBlob->num)
            {
                caBlob->creds =
                    (OCDtlsPskCreds*) OICMalloc(caBlob->num * sizeof(OCDtlsPskCreds));
                VERIFY_NON_NULL(TAG, caBlob->creds, ERROR);

                unsigned int i = 0;
                LL_FOREACH(gCred, cred)
                {
                    if ((cred->credType == SYMMETRIC_PAIR_WISE_KEY) &&
                            (i < count))

                    {
                        // Copy subject ID
                        memcpy(caBlob->creds[i].id, cred->subject.id,
                                sizeof(caBlob->creds[i].id));

                        // Convert PSK from JSON to binary before copying
                        uint32_t outLen = 0;
                        B64Result b64Ret = b64Decode(cred->privateData.data,
                                strlen(cred->privateData.data), caBlob->creds[i].psk,
                                sizeof(caBlob->creds[i].psk), &outLen);
                        VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
                        i++;
                    }
                }
            }
        }
        *credInfo = caBlob;
        // Return from here after making the credential list
        return;
    }

exit:
    if (caBlob)
    {
        memset(caBlob->creds, 0, caBlob->num * sizeof(OCDtlsPskCreds));
        OICFree(caBlob->creds);
    }
    OICFree(caBlob);
}
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921

/**
 * 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(tmpSubject == NULL || pin == NULL || pinSize == 0 || tmpCredSubject == NULL)
    {
        return OC_STACK_INVALID_PARAM;
    }

    uint8_t privData[OWNER_PSK_LENGTH_128] = {0,};
    int dtlsRes = DeriveCryptoKeyFromPassword((const unsigned char *)pin, pinSize, owners->id,
                                              UUID_LENGTH, PBKDF_ITERATIONS,
                                              OWNER_PSK_LENGTH_128, privData);
    VERIFY_SUCCESS(TAG, (dtlsRes == 0) , ERROR);

    uint32_t outLen = 0;
    char base64Buff[B64ENCODE_OUT_SAFESIZE(OWNER_PSK_LENGTH_128) + 1] = {};
    B64Result b64Ret = b64Encode(privData, OWNER_PSK_LENGTH_128, base64Buff,
                                sizeof(base64Buff), &outLen);
    VERIFY_SUCCESS(TAG, (B64_OK == b64Ret), ERROR);

    OicSecCred_t* cred = GenerateCredential(tmpSubject, credType, NULL,
                                            base64Buff, ownersLen, owners);
    if(NULL == cred)
    {
        OC_LOG(ERROR, TAG, "GeneratePskWithPIN() : Failed to generate credential");
        return OC_STACK_ERROR;
    }

    memcpy(tmpCredSubject->id, cred->subject.id, UUID_LENGTH);

    ret = AddCredential(cred);
    if( OC_STACK_OK != ret)
    {
        OC_LOG(ERROR, TAG, "GeneratePskWithPIN() : Failed to add credential");
    }

exit:
    return ret;
}

Sachin Agrawal's avatar
Sachin Agrawal committed
922
#endif /* __WITH_DTLS__ */