credresource.c 39.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
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
#include "iotvticalendar.h"
39 40
#include "ocserverrequest.h"

41
#ifdef WITH_ARDUINO
Sachin Agrawal's avatar
Sachin Agrawal committed
42
#include <string.h>
43 44 45
#else
#include <strings.h>
#endif
46 47
#include <stdint.h>

48
#define TAG  "SRM-CREDL"
Sachin Agrawal's avatar
Sachin Agrawal committed
49

Shilpa Sodani's avatar
Shilpa Sodani committed
50

Sachin Agrawal's avatar
Sachin Agrawal committed
51 52 53
static OicSecCred_t        *gCred = NULL;
static OCResourceHandle    gCredHandle = NULL;

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

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

73 74
    //Clean PrivateData
    OICFree(cred->privateData.data);
Sachin Agrawal's avatar
Sachin Agrawal committed
75

76 77
    //Clean Period
    OICFree(cred->period);
Sachin Agrawal's avatar
Sachin Agrawal committed
78

79 80 81 82 83 84
    //Clean Owners
    OICFree(cred->owners);

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

86 87 88 89 90 91 92 93 94
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
95 96 97 98 99 100 101 102 103 104 105 106 107 108
        }
    }
}

/**
 * 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
 */
109
char * BinToCredJSON(const OicSecCred_t * cred)
Sachin Agrawal's avatar
Sachin Agrawal committed
110 111 112 113 114 115 116 117 118
{
    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;
119

120 121 122 123 124 125
        jsonRoot = cJSON_CreateObject();
        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);

        cJSON *jsonCredArray = NULL;
        cJSON_AddItemToObject(jsonRoot, OIC_JSON_CRED_NAME,
                jsonCredArray = cJSON_CreateArray());
Sachin Agrawal's avatar
Sachin Agrawal committed
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
        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);
142
            cJSON_AddStringToObject(jsonCred, OIC_JSON_SUBJECT_NAME, base64Buff);
Sachin Agrawal's avatar
Sachin Agrawal committed
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163

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

Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
164
#ifdef __WITH_X509__
Sachin Agrawal's avatar
Sachin Agrawal committed
165 166 167
            //PublicData -- Not Mandatory
            if(cred->publicData.data)
            {
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
168 169 170 171 172 173 174
                if (SIGNED_ASYMMETRIC_KEY == cred->credType)
                {
                    cJSON_AddItemToObject(jsonCred, OIC_JSON_PUBLICDATA_NAME,
                                          cJSON_Parse(cred->publicData.data));
                }
                else
                {
Sachin Agrawal's avatar
Sachin Agrawal committed
175
                cJSON_AddStringToObject(jsonCred, OIC_JSON_PUBLICDATA_NAME, cred->publicData.data);
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
176
                }
Sachin Agrawal's avatar
Sachin Agrawal committed
177
            }
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
178
#endif /*__WITH_X509__*/
Sachin Agrawal's avatar
Sachin Agrawal committed
179 180 181
            //PrivateData -- Not Mandatory
            if(cred->privateData.data)
            {
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
182 183 184 185 186 187 188 189 190 191 192
#ifdef __WITH_X509__
                if (SIGNED_ASYMMETRIC_KEY == cred->credType)
                {
                    cJSON_AddItemToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME,
                                          cJSON_Parse(cred->privateData.data));
                }
                else
                {
                    cJSON_AddStringToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME, cred->privateData.data);
                }
#else
Sachin Agrawal's avatar
Sachin Agrawal committed
193
                cJSON_AddStringToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME, cred->privateData.data);
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
194
#endif
Sachin Agrawal's avatar
Sachin Agrawal committed
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
            }

            //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.
 */
239
OicSecCred_t * JSONToCredBin(const char * jsonStr)
Sachin Agrawal's avatar
Sachin Agrawal committed
240 241 242 243 244 245 246 247 248
{
    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);

249
    jsonCredArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
Sachin Agrawal's avatar
Sachin Agrawal committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
    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);
279 280 281 282 283
            if(jsonObj)
            {
                VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
                cred->credId = jsonObj->valueint;
            }
Sachin Agrawal's avatar
Sachin Agrawal committed
284 285

            //subject -- Mandatory
286
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_SUBJECT_NAME);
Sachin Agrawal's avatar
Sachin Agrawal committed
287
            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
288
            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
Sachin Agrawal's avatar
Sachin Agrawal committed
289 290 291 292 293 294 295 296 297 298 299
            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);
300
            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
301
            cred->credType = (OicSecCredType_t)jsonObj->valueint;
Sachin Agrawal's avatar
Sachin Agrawal committed
302 303 304 305 306 307 308 309 310 311

            //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);
            }
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
312 313
#ifdef __WITH_X509__
            else if (cred->credType & SIGNED_ASYMMETRIC_KEY)
Sachin Agrawal's avatar
Sachin Agrawal committed
314
            {
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
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 351 352 353 354 355 356 357 358 359 360 361
                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
                VERIFY_SUCCESS(TAG, cJSON_Object == jsonObj->type, ERROR);
            }
#endif //  __WITH_X509__
            if (NULL != jsonObj)
            {
                if (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);
                }
#ifdef __WITH_X509__
                else if (SIGNED_ASYMMETRIC_KEY == cred->credType && cJSON_Object == jsonObj->type)
                {
                    cred->privateData.data = cJSON_PrintUnformatted(jsonObj);
                    VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
                }
#endif // __WITH_X509__
            }

            //PublicData is mandatory only for SIGNED_ASYMMETRIC_KEY credentials type.
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PUBLICDATA_NAME);
#ifdef __WITH_X509__
            if (cred->credType & SIGNED_ASYMMETRIC_KEY)
            {
                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
                VERIFY_SUCCESS(TAG, cJSON_Object == jsonObj->type, ERROR);
            }
#endif //  __WITH_X509__
            if (NULL != jsonObj)
            {
                if (cJSON_String == jsonObj->type)
                {
                    jsonObjLen = strlen(jsonObj->valuestring) + 1;
                    cred->publicData.data = (char *)OICMalloc(jsonObjLen);
                    VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
                    strncpy((char *)cred->publicData.data, (char *)jsonObj->valuestring, jsonObjLen);
                }
#ifdef __WITH_X509__
                else if (SIGNED_ASYMMETRIC_KEY == cred->credType && cJSON_Object == jsonObj->type)
                {
                    cred->publicData.data = cJSON_PrintUnformatted(jsonObj);
                    VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
                }
#endif //  __WITH_X509__
Sachin Agrawal's avatar
Sachin Agrawal committed
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
            }

            //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);
377
            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
378
            cred->ownersLen = (size_t)cJSON_GetArraySize(jsonObj);
Sachin Agrawal's avatar
Sachin Agrawal committed
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 416 417
            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.
418
 *        The privateData is expected in base64 encoded format.
Sachin Agrawal's avatar
Sachin Agrawal committed
419 420 421 422 423 424 425 426 427 428 429
 * @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
430
    (void)publicData;
Sachin Agrawal's avatar
Sachin Agrawal committed
431 432 433 434 435
    OCStackResult ret = OC_STACK_ERROR;

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

436 437 438
    //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
439 440 441 442

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

443 444
    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
445 446
    cred->credType = credType;

Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
447
#ifdef __WITH_X509__
Sachin Agrawal's avatar
Sachin Agrawal committed
448 449 450 451 452 453
    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);
    }
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
454
#endif // __WITH_X509__
Sachin Agrawal's avatar
Sachin Agrawal committed
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

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

483 484 485 486 487
static bool UpdatePersistentStorage(const OicSecCred_t *cred)
{
    bool ret = false;

    // Convert Cred data into JSON for update to persistent storage
488
    char *jsonStr = BinToCredJSON(cred);
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
    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;
}

/**
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
 * 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;
}
574

575 576 577 578 579 580 581 582
/**
 * Get the default value
 * @retval  NULL for now. Update it when we finalize the default info.
 */
static OicSecCred_t* GetCredDefault()
{
    return NULL;
}
583

Sachin Agrawal's avatar
Sachin Agrawal committed
584 585 586 587 588 589 590 591 592 593 594 595 596
/**
 * 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;

597 598 599 600 601 602
    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
603 604 605 606

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

607
    if(UpdatePersistentStorage(gCred))
Sachin Agrawal's avatar
Sachin Agrawal committed
608
    {
609 610 611 612 613 614 615 616 617 618 619 620 621
        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
622

623 624 625
    LL_FOREACH_SAFE(gCred, cred, tempCred)
    {
        if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
Sachin Agrawal's avatar
Sachin Agrawal committed
626
        {
627 628 629
            LL_DELETE(gCred, cred);
            FreeCred(cred);
            deleteFlag = 1;
Sachin Agrawal's avatar
Sachin Agrawal committed
630 631 632
        }
    }

633 634 635 636 637 638 639
    if(deleteFlag)
    {
        if(UpdatePersistentStorage(gCred))
        {
            ret = OC_STACK_RESOURCE_DELETED;
        }
    }
Sachin Agrawal's avatar
Sachin Agrawal committed
640
    return ret;
641

Sachin Agrawal's avatar
Sachin Agrawal committed
642 643
}

644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
/**
 * 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;
}

663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 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 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
#ifdef __WITH_DTLS__
/**
 * Internal function to verify recevied owner PSK.
 *
 * @param receviedCred recevied Owner Credential from OBT(PT)
 * @param ownerAdd address of OBT(PT)
 * @param doxm current device's doxm resource
 *
 * @retval
 *     true valid ower psk
 *     false Invalid owner psk or failed to owner psk verification
 */
static bool isValidOwnerPSK(const OicSecCred_t* receviedCred, const CAEndpoint_t* ownerAddr,
                           const OicSecDoxm_t* doxm)
{
    //Decode received PSK to verify OwnerPSKs match
    uint32_t privLen = strlen(receviedCred->privateData.data);
    size_t b64BufSize = B64DECODE_OUT_SAFESIZE((privLen + 1) * sizeof(char));
    uint8_t* decodeBuff = OICMalloc(b64BufSize);
    VERIFY_NON_NULL(TAG, decodeBuff, ERROR);
    uint32_t decodedSize = 0;
    B64Result b64Ret = b64Decode(receviedCred->privateData.data, privLen,
                                 decodeBuff, b64BufSize, &decodedSize);
    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);

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

    OIC_LOG_V(DEBUG, TAG, "Oxm Label = %s", oxmLabel);
    OIC_LOG_V(DEBUG, TAG, "PSK size compare : %s",
              OWNER_PSK_LENGTH_128 == decodedSize ? "TRUE" : "FALSE");
    OIC_LOG_V(DEBUG, TAG, "SubjectID compare = %s",
              memcmp(&(receviedCred->subject), &(doxm->owner), sizeof(OicUuid_t)) == 0 ?
              "TRUE" : "FALSE");
    OIC_LOG_V(DEBUG, TAG, "Owner PSK compare = %s",
              memcmp(ownerPSK, decodeBuff, OWNER_PSK_LENGTH_128) == 0 ? "TRUE" : "FALSE");

    //Verify OwnerPSKs match
    return (OWNER_PSK_LENGTH_128 == decodedSize &&
            memcmp(ownerPSK, decodeBuff, OWNER_PSK_LENGTH_128) == 0 &&
            memcmp(&(receviedCred->subject), &(doxm->owner), sizeof(OicUuid_t)) == 0);
exit:
    return false;
}

#endif //__WITH_DTLS__

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

    //Get binary representation of json
    OicSecCred_t * cred  = JSONToCredBin(((OCSecurityPayload*)ehRequest->payload)->securityData);

    if(cred)
    {
#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;
                    if(isValidOwnerPSK(cred, (CAEndpoint_t *)&request->devAddr, doxm))
                    {
                        OIC_LOG(ERROR, TAG, "OwnerPKS is matched");
                        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;
                    }

                    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;
                }
            }
        }
        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__
    }

    return ret;
}

Sachin Agrawal's avatar
Sachin Agrawal committed
802 803 804 805 806
static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
{
    OCEntityHandlerResult ret = OC_EH_ERROR;

    //Get binary representation of json
807
    OicSecCred_t * cred  = JSONToCredBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
Sachin Agrawal's avatar
Sachin Agrawal committed
808 809 810

    if(cred)
    {
811 812 813 814
        //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.
815
        ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
Sachin Agrawal's avatar
Sachin Agrawal committed
816
    }
817

Sachin Agrawal's avatar
Sachin Agrawal committed
818 819 820
    return ret;
}

821 822
static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *ehRequest)
{
823
    OIC_LOG(DEBUG, TAG, "Processing CredDeleteRequest");
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838

    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))
   {
839
       if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME,
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
               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
863 864 865 866 867
/*
 * This internal method is the entity handler for Cred resources
 * to handle REST request (PUT/POST/DEL)
 */
OCEntityHandlerResult CredEntityHandler (OCEntityHandlerFlag flag,
868 869
                                        OCEntityHandlerRequest * ehRequest,
                                        void* callbackParameter)
Sachin Agrawal's avatar
Sachin Agrawal committed
870
{
Jon A. Cruz's avatar
Jon A. Cruz committed
871
    (void)callbackParameter;
Sachin Agrawal's avatar
Sachin Agrawal committed
872 873 874 875 876 877 878 879
    OCEntityHandlerResult ret = OC_EH_ERROR;

    if(!ehRequest)
    {
        return OC_EH_ERROR;
    }
    if (flag & OC_REQUEST_FLAG)
    {
880
        OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
Sachin Agrawal's avatar
Sachin Agrawal committed
881 882 883 884 885 886
        //TODO :  Handle PUT/DEL methods
        switch(ehRequest->method)
        {
            case OC_REST_GET:
                ret = OC_EH_FORBIDDEN;
                break;
887 888 889
            case OC_REST_PUT:
                ret = HandlePutRequest(ehRequest);
                break;
Sachin Agrawal's avatar
Sachin Agrawal committed
890 891 892
            case OC_REST_POST:
                ret = HandlePostRequest(ehRequest);
                break;
893 894 895
            case OC_REST_DELETE:
                ret = HandleDeleteRequest(ehRequest);
                break;
Sachin Agrawal's avatar
Sachin Agrawal committed
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
            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,
921
                           NULL,
Sachin Agrawal's avatar
Sachin Agrawal committed
922 923 924 925
                           OC_RES_PROP_NONE);

    if (OC_STACK_OK != ret)
    {
926
        OIC_LOG (FATAL, TAG, "Unable to instantiate Cred resource");
Sachin Agrawal's avatar
Sachin Agrawal committed
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
        DeInitCredResource();
    }
    return ret;
}

/**
 * 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
949
        gCred = JSONToCredBin(jsonSVRDatabase);
Sachin Agrawal's avatar
Sachin Agrawal committed
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
    }
    /*
     * 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;

996
   if ( NULL == subject)
Sachin Agrawal's avatar
Sachin Agrawal committed
997
    {
998
       return NULL;
Sachin Agrawal's avatar
Sachin Agrawal committed
999 1000 1001 1002 1003 1004
    }

    LL_FOREACH(gCred, cred)
    {
        if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
        {
1005
            return cred;
Sachin Agrawal's avatar
Sachin Agrawal committed
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
        }
    }
    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.
 *
1017 1018 1019 1020 1021
 * @param[in]  type type of PSK data required by tinyDTLS layer during DTLS handshake.
 * @param[in]  desc Additional request information.
 * @param[in]  desc_len The actual length of desc.
 * @param[out] result  Must be filled with the requested information.
 * @param[in]  result_length  Maximum size of @p result.
Sachin Agrawal's avatar
Sachin Agrawal committed
1022
 *
1023 1024
 * @return The number of bytes written to @p result or a value
 *         less than zero on error.
Sachin Agrawal's avatar
Sachin Agrawal committed
1025
 */
1026 1027 1028
int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
              const unsigned char *desc, size_t desc_len,
              unsigned char *result, size_t result_length)
Sachin Agrawal's avatar
Sachin Agrawal committed
1029
{
1030
    int32_t ret = -1;
Sachin Agrawal's avatar
Sachin Agrawal committed
1031

1032 1033 1034 1035
    if (NULL == result)
    {
        return ret;
    }
Sachin Agrawal's avatar
Sachin Agrawal committed
1036

1037 1038 1039 1040
    switch (type)
    {
        case CA_DTLS_PSK_HINT:
        case CA_DTLS_PSK_IDENTITY:
Sachin Agrawal's avatar
Sachin Agrawal committed
1041
            {
1042 1043 1044
                OicUuid_t deviceID = {.id={}};
                // Retrieve Device ID from doxm resource
                if ( OC_STACK_OK != GetDoxmDeviceID(&deviceID) )
Sachin Agrawal's avatar
Sachin Agrawal committed
1045
                {
1046
                    OIC_LOG (ERROR, TAG, "Unable to retrieve doxm Device ID");
1047
                    return ret;
Sachin Agrawal's avatar
Sachin Agrawal committed
1048
                }
1049 1050 1051

                if (result_length < sizeof(deviceID.id))
                {
1052
                    OIC_LOG (ERROR, TAG, "Wrong value for result_length");
1053 1054 1055 1056
                    return ret;
                }
                memcpy(result, deviceID.id, sizeof(deviceID.id));
                return (sizeof(deviceID.id));
Sachin Agrawal's avatar
Sachin Agrawal committed
1057
            }
1058
            break;
Sachin Agrawal's avatar
Sachin Agrawal committed
1059

1060 1061 1062
        case CA_DTLS_PSK_KEY:
            {
                OicSecCred_t *cred = NULL;
Sachin Agrawal's avatar
Sachin Agrawal committed
1063 1064
                LL_FOREACH(gCred, cred)
                {
1065
                    if (cred->credType != SYMMETRIC_PAIR_WISE_KEY)
Sachin Agrawal's avatar
Sachin Agrawal committed
1066
                    {
1067 1068
                        continue;
                    }
Sachin Agrawal's avatar
Sachin Agrawal committed
1069

1070 1071 1072
                    if ((desc_len == sizeof(cred->subject.id)) &&
                        (memcmp(desc, cred->subject.id, sizeof(cred->subject.id)) == 0))
                    {
1073 1074 1075 1076 1077 1078 1079 1080
                        /*
                         * If the credentials are valid for limited time,
                         * check their expiry.
                         */
                        if (cred->period)
                        {
                            if(IOTVTICAL_VALID_ACCESS != IsRequestWithinValidTime(cred->period, NULL))
                            {
1081
                                OIC_LOG (INFO, TAG, "Credentials are expired.");
1082 1083 1084 1085 1086
                                ret = -1;
                                return ret;
                            }
                        }

1087
                        // Convert PSK from Base64 encoding to binary before copying
Sachin Agrawal's avatar
Sachin Agrawal committed
1088 1089
                        uint32_t outLen = 0;
                        B64Result b64Ret = b64Decode(cred->privateData.data,
1090 1091 1092 1093
                                strlen(cred->privateData.data), result,
                                result_length, &outLen);
                        if (B64_OK != b64Ret)
                        {
1094
                            OIC_LOG (ERROR, TAG, "Base64 decoding failed.");
1095 1096 1097 1098
                            ret = -1;
                            return ret;
                        }
                        return outLen;
Sachin Agrawal's avatar
Sachin Agrawal committed
1099 1100 1101
                    }
                }
            }
1102
            break;
Sachin Agrawal's avatar
Sachin Agrawal committed
1103

1104 1105
        default:
            {
1106
                OIC_LOG (ERROR, TAG, "Wrong value passed for CADtlsPskCredType_t.");
1107 1108 1109
                ret = -1;
            }
            break;
Sachin Agrawal's avatar
Sachin Agrawal committed
1110
    }
1111 1112

    return ret;
Sachin Agrawal's avatar
Sachin Agrawal committed
1113
}
1114

Sachin Agrawal's avatar
Sachin Agrawal committed
1115
#endif /* __WITH_DTLS__ */
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
#ifdef __WITH_X509__
#define CERT_LEN_PREFIX (3)
#define BYTE_SIZE (8) //bits
#define PUB_KEY_X_COORD ("x")
#define PUB_KEY_Y_COORD ("y")
#define CERTIFICATE ("x5c")
#define PRIVATE_KEY ("d")


static void WriteCertPrefix(uint8_t *prefix, uint32_t certLen)
{
    for (size_t i = 0; i < CERT_LEN_PREFIX; ++i)
    {
        prefix[i] = (certLen >> (BYTE_SIZE * (CERT_LEN_PREFIX - 1 - i))) & 0xFF;
    }
}

static uint32_t ParseCertPrefix(uint8_t *prefix)
{
    uint32_t res = 0;
    if(NULL != prefix)
    {
        for(int i=0; i < CERT_LEN_PREFIX; ++i)
        {
            res |= (((uint32_t) prefix[i]) << ((CERT_LEN_PREFIX - 1 -i) * BYTE_SIZE));
        }
    }
    return res;
}

static uint32_t appendCert2Chain(uint8_t *appendPoint, char *cert, uint32_t max_len)
{
    uint32_t ret = 0;
    VERIFY_NON_NULL(TAG, appendPoint, ERROR);
    VERIFY_NON_NULL(TAG, cert, ERROR);

    uint32_t certLen;
    VERIFY_SUCCESS(TAG, B64_OK == b64Decode(cert, strlen(cert), appendPoint + CERT_LEN_PREFIX,
                                            max_len - CERT_LEN_PREFIX, &certLen), ERROR);
    WriteCertPrefix(appendPoint, certLen);

    ret = certLen + CERT_LEN_PREFIX;
exit:
    return ret;
}

1162
static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo){
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    OCStackResult ret = OC_STACK_ERROR;
    uint8_t *ccPtr = credInfo->certificateChain;
    for(uint32_t i =0; i < credInfo->chainLen - 1; ++i)
    {
        ccPtr += CERT_LEN_PREFIX + ParseCertPrefix(ccPtr);
    }

    ByteArray cert = {
        .data = ccPtr + CERT_LEN_PREFIX,
        .len = ParseCertPrefix(ccPtr)
         };
    CertificateX509 certStruct;

    VERIFY_SUCCESS(TAG, PKI_SUCCESS == DecodeCertificate(cert, &certStruct), ERROR);

    INC_BYTE_ARRAY(certStruct.pubKey, 2);

    memcpy(credInfo->rootPublicKeyX, certStruct.pubKey.data, PUBLIC_KEY_SIZE / 2);
    memcpy(credInfo->rootPublicKeyY, certStruct.pubKey.data + PUBLIC_KEY_SIZE / 2, PUBLIC_KEY_SIZE / 2);

    ret = OC_STACK_OK;
    exit:
    return ret;
}

1188
static OCStackResult GetCertCredPublicData(CADtlsX509Creds_t *credInfo, OicSecCred_t *cred)
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
1189 1190
{
    OCStackResult ret = OC_STACK_ERROR;
1191 1192
    cJSON *jsonRoot = NULL;

Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
1193 1194 1195 1196
    VERIFY_NON_NULL(TAG, credInfo, ERROR);
    VERIFY_NON_NULL(TAG, cred, ERROR);
    VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
    //VERIFY_SUCCESS(TAG, NULL == credInfo->certificateChain.data, ERROR);
1197
    jsonRoot = cJSON_Parse(cred->publicData.data);
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
1198 1199 1200 1201 1202 1203
    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);

    //Get certificate chain
    cJSON *jsonObj = cJSON_GetObjectItem(jsonRoot, CERTIFICATE);//TODO define field names constants
    VERIFY_SUCCESS(TAG, NULL != jsonObj && cJSON_Array == jsonObj->type, ERROR);

1204
    size_t certChainLen = (size_t)cJSON_GetArraySize(jsonObj);
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
1205 1206 1207 1208 1209 1210 1211
    credInfo->chainLen = certChainLen;
    VERIFY_SUCCESS(TAG, MAX_CHAIN_LEN >= certChainLen, ERROR);

    uint32_t len = 0;
    for (size_t i = 0; i < certChainLen; ++i)
    {
        cJSON *item = cJSON_GetArrayItem(jsonObj, i);
1212
        VERIFY_NON_NULL(TAG, item, ERROR);
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
1213 1214
        VERIFY_SUCCESS(TAG, cJSON_String == item->type, ERROR);
        uint32_t appendedLen = appendCert2Chain(credInfo->certificateChain + len, item->valuestring,
1215
                                              MAX_CERT_MESSAGE_LEN - len);
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
        VERIFY_SUCCESS(TAG, 0 != appendedLen, ERROR);
        len += appendedLen;
    }
    credInfo->certificateChainLen = len;
    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCAPublicKeyData(credInfo), ERROR);
    ret = OC_STACK_OK;
exit:
    cJSON_Delete(jsonRoot);
    return ret;
}

1227
static OCStackResult GetCertCredPrivateData(CADtlsX509Creds_t *credInfo, OicSecCred_t *cred)
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
1228 1229
{
    OCStackResult ret = OC_STACK_ERROR;
1230
    cJSON *jsonRoot = NULL;
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
1231 1232 1233
    VERIFY_NON_NULL(TAG, credInfo, ERROR);
    VERIFY_NON_NULL(TAG, cred, ERROR);
    VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
1234
    jsonRoot = cJSON_Parse(cred->privateData.data);
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);

    cJSON *jsonObj = cJSON_GetObjectItem(jsonRoot, PRIVATE_KEY);//TODO define field names constants
    VERIFY_SUCCESS(TAG, NULL != jsonObj && cJSON_String == jsonObj->type, ERROR);

    uint32_t read = 0u;
    VERIFY_SUCCESS(TAG, B64_OK == b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring),
                                            credInfo->devicePrivateKey, PRIVATE_KEY_SIZE, &read)
                   && PRIVATE_KEY_SIZE == read, ERROR);

    ret = OC_STACK_OK;

exit:
    cJSON_Delete(jsonRoot);
    return ret;
}

1252
int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo)
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
1253
{
1254
    int ret = 1;
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
    VERIFY_NON_NULL(TAG, credInfo, ERROR);
    if (NULL == gCred)
    {
        VERIFY_SUCCESS(TAG, OC_STACK_OK == InitCredResource(), ERROR);
    }

    OicSecCred_t *cred = NULL;
    LL_SEARCH_SCALAR(gCred, cred, credType, SIGNED_ASYMMETRIC_KEY);
    VERIFY_NON_NULL(TAG, cred, ERROR);

    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCertCredPrivateData(credInfo, cred), ERROR);
    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCertCredPublicData(credInfo, cred), ERROR);

1268
    ret = 0;
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
1269 1270 1271 1272 1273 1274
exit:

    return ret;
}
#undef CERT_LEN_PREFIX
#endif /* __WITH_X509__ */