credresource.c 50.6 KB
Newer Older
Sachin Agrawal's avatar
Sachin Agrawal committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
//******************************************************************
//
// Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

21
#define __STDC_LIMIT_MACROS
Sahil Bansal's avatar
Sahil Bansal committed
22 23 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"
Sahil Bansal's avatar
Sahil Bansal committed
34 35 36
#include "ocrandom.h"
#include "base64.h"
#include "ocserverrequest.h"
Sachin Agrawal's avatar
Sachin Agrawal committed
37
#include "oic_malloc.h"
Sahil Bansal's avatar
Sahil Bansal committed
38
#include "ocpayload.h"
Sachin Agrawal's avatar
Sachin Agrawal committed
39 40 41
#include "utlist.h"
#include "credresource.h"
#include "doxmresource.h"
Sahil Bansal's avatar
Sahil Bansal committed
42
#include "pstatresource.h"
leechul's avatar
leechul committed
43
#include "iotvticalendar.h"
Sahil Bansal's avatar
Sahil Bansal committed
44 45 46 47 48 49
#include "pbkdf2.h"
#include "resourcemanager.h"
#include "srmresourcestrings.h"
#include "srmutility.h"
#include "psinterface.h"
#include "pinoxmcommon.h"
50

51 52
#ifdef __WITH_DTLS__
#include "global.h"
Sahil Bansal's avatar
Sahil Bansal committed
53
#endif
leechul's avatar
leechul committed
54

Sahil Bansal's avatar
Sahil Bansal committed
55 56 57 58
#define TAG  "SRM-CREDL"

/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
 * The value of payload size is increased until reaching belox max cbor size. */
leechul's avatar
leechul committed
59
static const uint16_t CBOR_SIZE = 2048;
60

Sahil Bansal's avatar
Sahil Bansal committed
61 62
/** Max cbor size payload. */
static const uint16_t CBOR_MAX_SIZE = 4400;
Sachin Agrawal's avatar
Sachin Agrawal committed
63

leechul's avatar
leechul committed
64 65 66 67
/** CRED size - Number of mandatory items. */
static const uint8_t CRED_ROOT_MAP_SIZE = 2;
static const uint8_t CRED_MAP_SIZE = 3;

Shilpa Sodani's avatar
Shilpa Sodani committed
68

Sachin Agrawal's avatar
Sachin Agrawal committed
69 70 71
static OicSecCred_t        *gCred = NULL;
static OCResourceHandle    gCredHandle = NULL;

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

88
    //Clean PublicData
Sahil Bansal's avatar
Sahil Bansal committed
89
#ifdef __WITH_X509__
90
    OICFree(cred->publicData.data);
Sahil Bansal's avatar
Sahil Bansal committed
91
#endif
Sachin Agrawal's avatar
Sachin Agrawal committed
92

93 94
    //Clean PrivateData
    OICFree(cred->privateData.data);
Sachin Agrawal's avatar
Sachin Agrawal committed
95

96 97
    //Clean Period
    OICFree(cred->period);
Sachin Agrawal's avatar
Sachin Agrawal committed
98

99 100 101 102 103 104
    //Clean Owners
    OICFree(cred->owners);

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

106 107 108 109 110 111 112 113 114
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
115 116 117 118
        }
    }
}

Sahil Bansal's avatar
Sahil Bansal committed
119
static size_t OicSecCredCount(const OicSecCred_t *secCred)
Sachin Agrawal's avatar
Sachin Agrawal committed
120
{
Sahil Bansal's avatar
Sahil Bansal committed
121 122
    size_t size = 0;
    for (const OicSecCred_t *cred = secCred; cred; cred = cred->next)
Sachin Agrawal's avatar
Sachin Agrawal committed
123
    {
Sahil Bansal's avatar
Sahil Bansal committed
124 125 126 127
        size++;
    }
    return size;
}
128

Sahil Bansal's avatar
Sahil Bansal committed
129 130 131 132 133 134 135
OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload,
                                size_t *cborSize)
{
    if (NULL == credS || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
    {
        return OC_STACK_INVALID_PARAM;
    }
136

Sahil Bansal's avatar
Sahil Bansal committed
137
    OCStackResult ret = OC_STACK_ERROR;
Sachin Agrawal's avatar
Sachin Agrawal committed
138

leechul's avatar
leechul committed
139 140 141
    CborError cborEncoderResult = CborNoError;
    uint8_t *outPayload = NULL;
    size_t cborLen = *cborSize;
Sahil Bansal's avatar
Sahil Bansal committed
142 143
    *cborSize = 0;
    *cborPayload = NULL;
leechul's avatar
leechul committed
144
    const OicSecCred_t *cred = credS;
Sahil Bansal's avatar
Sahil Bansal committed
145 146
    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
    CborEncoder credArray = { {.ptr = NULL }, .end = 0 };
leechul's avatar
leechul committed
147
    CborEncoder credRootMap = { {.ptr = NULL }, .end = 0 };
Sachin Agrawal's avatar
Sachin Agrawal committed
148

leechul's avatar
leechul committed
149 150 151 152 153 154
    if (0 == cborLen)
    {
        cborLen = CBOR_SIZE;
    }

    outPayload = (uint8_t *)OICCalloc(1, cborLen);
Sahil Bansal's avatar
Sahil Bansal committed
155 156
    VERIFY_NON_NULL(TAG, outPayload, ERROR);
    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
Sachin Agrawal's avatar
Sachin Agrawal committed
157

leechul's avatar
leechul committed
158 159 160 161 162 163 164 165 166 167 168 169
    // Create CRED Root Map (creds, rownerid)
    cborEncoderResult = cbor_encoder_create_map(&encoder, &credRootMap, CRED_ROOT_MAP_SIZE);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Root Map");

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

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

Sahil Bansal's avatar
Sahil Bansal committed
171 172 173 174
    while (cred)
    {
        CborEncoder credMap = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
        size_t mapSize = CRED_MAP_SIZE;
leechul's avatar
leechul committed
175
        char *subject = NULL;
Sahil Bansal's avatar
Sahil Bansal committed
176 177 178 179 180
        if (cred->period)
        {
            mapSize++;
        }
#ifdef __WITH_X509__
Dmitriy Zhuravlev's avatar
Dmitriy Zhuravlev committed
181
        if (SIGNED_ASYMMETRIC_KEY == cred->credType && cred->publicData.data)
Sahil Bansal's avatar
Sahil Bansal committed
182 183 184 185 186 187 188 189
        {
            mapSize++;
        }
#endif /* __WITH_X509__ */
        if (cred->privateData.data)
        {
            mapSize++;
        }
leechul's avatar
leechul committed
190
        cborEncoderResult = cbor_encoder_create_map(&credArray, &credMap, mapSize);
Sahil Bansal's avatar
Sahil Bansal committed
191 192 193
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Map");

        //CredID -- Mandatory
leechul's avatar
leechul committed
194
        cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_CREDID_NAME,
Sahil Bansal's avatar
Sahil Bansal committed
195 196
            strlen(OIC_JSON_CREDID_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Id Tag. ");
leechul's avatar
leechul committed
197
        cborEncoderResult = cbor_encode_int(&credMap, cred->credId);
Sahil Bansal's avatar
Sahil Bansal committed
198 199 200
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Id Value.");

        //Subject -- Mandatory
leechul's avatar
leechul committed
201 202
        cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_SUBJECTID_NAME,
            strlen(OIC_JSON_SUBJECTID_NAME));
Sahil Bansal's avatar
Sahil Bansal committed
203
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Tag.");
leechul's avatar
leechul committed
204 205 206 207 208
        ret = ConvertUuidToStr(&cred->subject, &subject);
        VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
        cborEncoderResult = cbor_encode_text_string(&credMap, subject, strlen(subject));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Subject Id Value.");
        OICFree(subject);
Sahil Bansal's avatar
Sahil Bansal committed
209 210

        //CredType -- Mandatory
leechul's avatar
leechul committed
211
        cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_CREDTYPE_NAME,
Sahil Bansal's avatar
Sahil Bansal committed
212 213
            strlen(OIC_JSON_CREDTYPE_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag.");
leechul's avatar
leechul committed
214
        cborEncoderResult = cbor_encode_int(&credMap, cred->credType);
Sahil Bansal's avatar
Sahil Bansal committed
215
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
Sachin Agrawal's avatar
Sachin Agrawal committed
216

Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
217
#ifdef __WITH_X509__
Sahil Bansal's avatar
Sahil Bansal committed
218
        //PublicData -- Not Mandatory
Dmitriy Zhuravlev's avatar
Dmitriy Zhuravlev committed
219
        if (SIGNED_ASYMMETRIC_KEY == cred->credType && cred->publicData.data)
Sahil Bansal's avatar
Sahil Bansal committed
220
        {
leechul's avatar
leechul committed
221 222 223 224 225 226 227 228 229 230
            CborEncoder publicMap = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
            const size_t publicMapSize = 2;

            cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_PUBLICDATA_NAME,
                strlen(OIC_JSON_PUBLICDATA_NAME));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PublicData Tag.");

            cborEncoderResult = cbor_encoder_create_map(&credMap, &publicMap, publicMapSize);
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PublicData Map");

231 232
            cborEncoderResult = cbor_encode_text_string(&publicMap, OIC_JSON_DATA_NAME,
                strlen(OIC_JSON_DATA_NAME));
leechul's avatar
leechul committed
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Pub Data Tag.");
            cborEncoderResult = cbor_encode_byte_string(&publicMap, cred->publicData.data,
                cred->publicData.len);
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Pub Value.");

            // TODO: Need to data strucure modification for OicSecCert_t.
            cborEncoderResult = cbor_encode_text_string(&publicMap, OIC_JSON_ENCODING_NAME,
                strlen(OIC_JSON_ENCODING_NAME));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Public Encoding Tag.");
            cborEncoderResult = cbor_encode_text_string(&publicMap, OIC_SEC_ENCODING_BYTESTREAM,
                strlen(OIC_SEC_ENCODING_BYTESTREAM));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Public Encoding Value.");

            cborEncoderResult = cbor_encoder_close_container(&credMap, &publicMap);
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing PublicData Map.");
Sahil Bansal's avatar
Sahil Bansal committed
248
        }
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
249
#endif /*__WITH_X509__*/
Sahil Bansal's avatar
Sahil Bansal committed
250 251 252
        //PrivateData -- Not Mandatory
        if(cred->privateData.data)
        {
leechul's avatar
leechul committed
253 254 255 256 257 258 259 260 261 262
            CborEncoder privateMap = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
            const size_t privateMapSize = 2;

            cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_PRIVATEDATA_NAME,
                strlen(OIC_JSON_PRIVATEDATA_NAME));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PrivateData Tag.");

            cborEncoderResult = cbor_encoder_create_map(&credMap, &privateMap, privateMapSize);
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PrivateData Map");

263 264
            cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_JSON_DATA_NAME,
                strlen(OIC_JSON_DATA_NAME));
leechul's avatar
leechul committed
265 266
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Priv Tag.");
            cborEncoderResult = cbor_encode_byte_string(&privateMap, cred->privateData.data,
Sahil Bansal's avatar
Sahil Bansal committed
267
                cred->privateData.len);
leechul's avatar
leechul committed
268 269 270 271 272 273 274 275 276 277 278 279
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Priv Value.");

            // TODO: Need to data strucure modification for OicSecKey_t.
            cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_JSON_ENCODING_NAME,
                strlen(OIC_JSON_ENCODING_NAME));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Encoding Tag.");
            cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_SEC_ENCODING_BYTESTREAM,
                strlen(OIC_SEC_ENCODING_BYTESTREAM));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Encoding Value.");

            cborEncoderResult = cbor_encoder_close_container(&credMap, &privateMap);
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing PrivateData Map.");
Sahil Bansal's avatar
Sahil Bansal committed
280
        }
Sachin Agrawal's avatar
Sachin Agrawal committed
281

Sahil Bansal's avatar
Sahil Bansal committed
282 283 284
        //Period -- Not Mandatory
        if(cred->period)
        {
leechul's avatar
leechul committed
285
            cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_PERIOD_NAME,
Sahil Bansal's avatar
Sahil Bansal committed
286 287
                strlen(OIC_JSON_PERIOD_NAME));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Name Tag.");
leechul's avatar
leechul committed
288
            cborEncoderResult = cbor_encode_text_string(&credMap, cred->period,
Sahil Bansal's avatar
Sahil Bansal committed
289 290 291
                strlen(cred->period));
            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Name Value.");
        }
Sachin Agrawal's avatar
Sachin Agrawal committed
292

leechul's avatar
leechul committed
293 294

        cborEncoderResult = cbor_encoder_close_container(&credArray, &credMap);
Sahil Bansal's avatar
Sahil Bansal committed
295
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Map.");
Dmitriy Zhuravlev's avatar
Dmitriy Zhuravlev committed
296
        
Sahil Bansal's avatar
Sahil Bansal committed
297
        cred = cred->next;
leechul's avatar
leechul committed
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    }
    cborEncoderResult = cbor_encoder_close_container(&credRootMap, &credArray);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Array.");

    cred = credS;
    // TODO : Need to modify cred->owners[0] to cred->rownerid based on RAML spec.
    // Rownerid
    if(cred->owners && cred->ownersLen > 0)
    {
        char *rowner = NULL;
        cborEncoderResult = cbor_encode_text_string(&credRootMap, OIC_JSON_ROWNERID_NAME,
            strlen(OIC_JSON_ROWNERID_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding rownerid Name.");
        ret = ConvertUuidToStr(&cred->owners[0], &rowner);
        VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
        cborEncoderResult = cbor_encode_text_string(&credRootMap, rowner, strlen(rowner));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding rownerid Value.");
        OICFree(rowner);
    }

    // Close CRED Root Map
    cborEncoderResult = cbor_encoder_close_container(&encoder, &credRootMap);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing CRED Root Map.");

    if (CborNoError == cborEncoderResult)
    {
        OIC_LOG(DEBUG, TAG, "CredToCBORPayload Successed");
        *cborPayload = outPayload;
        *cborSize = encoder.ptr - outPayload;
Sahil Bansal's avatar
Sahil Bansal committed
327 328 329
        ret = OC_STACK_OK;
    }
    OIC_LOG(DEBUG, TAG, "CredToCBORPayload OUT");
Sachin Agrawal's avatar
Sachin Agrawal committed
330
exit:
leechul's avatar
leechul committed
331
    if (CborErrorOutOfMemory == cborEncoderResult)
332
    {
leechul's avatar
leechul committed
333 334 335 336 337 338 339 340
        OIC_LOG(DEBUG, TAG, "CredToCBORPayload:CborErrorOutOfMemory : retry with more memory");
        // reallocate and try again!
        OICFree(outPayload);
        // Since the allocated initial memory failed, double the memory.
        cborLen += encoder.ptr - encoder.end;
        cborEncoderResult = CborNoError;
        ret = CredToCBORPayload(credS, cborPayload, &cborLen);
        *cborSize = cborLen;
341
    }
Sahil Bansal's avatar
Sahil Bansal committed
342 343 344

    if (CborNoError != cborEncoderResult)
    {
leechul's avatar
leechul committed
345 346 347 348 349 350
        OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
        OICFree(outPayload);
        outPayload = NULL;
        *cborSize = 0;
        *cborPayload = NULL;
        ret = OC_STACK_ERROR;
Sahil Bansal's avatar
Sahil Bansal committed
351 352 353
    }

    return ret;
Sachin Agrawal's avatar
Sachin Agrawal committed
354 355
}

Sahil Bansal's avatar
Sahil Bansal committed
356 357
OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                                OicSecCred_t **secCred)
Sachin Agrawal's avatar
Sachin Agrawal committed
358
{
Sahil Bansal's avatar
Sahil Bansal committed
359 360 361 362
    if (NULL == cborPayload || NULL == secCred || NULL != *secCred)
    {
        return OC_STACK_INVALID_PARAM;
    }
Sachin Agrawal's avatar
Sachin Agrawal committed
363

Sahil Bansal's avatar
Sahil Bansal committed
364
    OCStackResult ret = OC_STACK_ERROR;
leechul's avatar
leechul committed
365 366
    CborValue credCbor = { .parser = NULL };
    CborParser parser = { .end = NULL };
Sahil Bansal's avatar
Sahil Bansal committed
367
    CborError cborFindResult = CborNoError;
leechul's avatar
leechul committed
368
    cbor_parser_init(cborPayload, size, 0, &parser, &credCbor);
leechul's avatar
leechul committed
369

leechul's avatar
leechul committed
370
    OicSecCred_t *headCred = (OicSecCred_t *) OICCalloc(1, sizeof(OicSecCred_t));
371

leechul's avatar
leechul committed
372 373 374 375
    // Enter CRED Root Map
    CborValue CredRootMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
    cborFindResult = cbor_value_enter_container(&credCbor, &CredRootMap);
    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering CRED Root Map.");
Sachin Agrawal's avatar
Sachin Agrawal committed
376

leechul's avatar
leechul committed
377
    while (cbor_value_is_valid(&CredRootMap))
Sahil Bansal's avatar
Sahil Bansal committed
378
    {
leechul's avatar
leechul committed
379 380 381 382
        char* tagName = NULL;
        size_t len = 0;
        CborType type = cbor_value_get_type(&CredRootMap);
        if (type == CborTextStringType)
Sahil Bansal's avatar
Sahil Bansal committed
383
        {
leechul's avatar
leechul committed
384 385 386 387
            cborFindResult = cbor_value_dup_text_string(&CredRootMap, &tagName, &len, NULL);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in CRED Root Map.");
            cborFindResult = cbor_value_advance(&CredRootMap);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in CRED Root Map.");
Sahil Bansal's avatar
Sahil Bansal committed
388
        }
leechul's avatar
leechul committed
389
        if(tagName)
Sahil Bansal's avatar
Sahil Bansal committed
390
        {
leechul's avatar
leechul committed
391
            if (strcmp(tagName, OIC_JSON_CREDS_NAME)  == 0)
392
            {
leechul's avatar
leechul committed
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 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 445 446 447 448 449 450 451 452 453 454
                // Enter CREDS Array
                size_t len = 0;
                int credCount = 0;
                CborValue credArray = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
                cborFindResult = cbor_value_enter_container(&CredRootMap, &credArray);
                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Array.");

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

                    if(1 == credCount)
                    {
                        cred = headCred;
                    }
                    else
                    {
                        cred = (OicSecCred_t *) OICCalloc(1, sizeof(OicSecCred_t));
                        OicSecCred_t *temp = headCred;
                        while (temp->next)
                        {
                            temp = temp->next;
                        }
                        temp->next = cred;
                    }

                    VERIFY_NON_NULL(TAG, cred, ERROR);

                    while(cbor_value_is_valid(&credMap))
                    {
                        char* name = NULL;
                        CborType type = cbor_value_get_type(&credMap);
                        if (type == CborTextStringType)
                        {
                            cborFindResult = cbor_value_dup_text_string(&credMap, &name, &len, NULL);
                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in CRED Map.");
                            cborFindResult = cbor_value_advance(&credMap);
                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in CRED Map.");
                        }
                        if(name)
                        {
                            //credid
                            if (strcmp(name, OIC_JSON_CREDID_NAME)  == 0)
                            {
                                cborFindResult = cbor_value_get_uint64(&credMap, (uint64_t *) &cred->credId);
                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CredId.");
                            }
                            // subjectid
                            if (strcmp(name, OIC_JSON_SUBJECTID_NAME)  == 0)
                            {
                                char *subjectid = NULL;
                                cborFindResult = cbor_value_dup_text_string(&credMap, &subjectid, &len, NULL);
                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding subjectid Value.");
                                ret = ConvertStrToUuid(subjectid, &cred->subject);
                                VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
                                OICFree(subjectid);
                            }
455
                            // credtype
leechul's avatar
leechul committed
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
                            if (strcmp(name, OIC_JSON_CREDTYPE_NAME)  == 0)
                            {
                                cborFindResult = cbor_value_get_uint64(&credMap, (uint64_t *) &cred->credType);
                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CredType.");
                            }
                            // privatedata
                            if (strcmp(name, OIC_JSON_PRIVATEDATA_NAME)  == 0)
                            {
                                CborValue privateMap = { .parser = NULL };
                                cborFindResult = cbor_value_enter_container(&credMap, &privateMap);

                                while (cbor_value_is_valid(&privateMap))
                                {
                                    char* privname = NULL;
                                    CborType type = cbor_value_get_type(&privateMap);
                                    if (type == CborTextStringType)
                                    {
                                        cborFindResult = cbor_value_dup_text_string(&privateMap, &privname,
                                                &len, NULL);
                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get text");
                                        cborFindResult = cbor_value_advance(&privateMap);
                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance value");
                                    }
                                    if (privname)
                                    {
                                        // PrivateData::privdata -- Mandatory
482
                                        if (strcmp(privname, OIC_JSON_DATA_NAME) == 0)
leechul's avatar
leechul committed
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
                                        {
                                            cborFindResult = cbor_value_dup_byte_string(&privateMap, &cred->privateData.data,
                                                &cred->privateData.len, NULL);
                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PrivateData.");
                                        }
                                        // PrivateData::encoding -- Mandatory
                                        if (strcmp(privname, OIC_JSON_ENCODING_NAME) == 0)
                                        {
                                            // TODO: Need to update data structure, just ignore encoding value now.
                                        }
                                    }
                                    if (cbor_value_is_valid(&privateMap))
                                    {
                                        cborFindResult = cbor_value_advance(&privateMap);
                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing privatedata Map.");
                                    }
                                    OICFree(privname);
                                }

                            }
leechul's avatar
leechul committed
503
#ifdef __WITH_X509__
leechul's avatar
leechul committed
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
                            if (strcmp(name, OIC_JSON_PUBLICDATA_NAME)  == 0)
                            {
                                CborValue pubMap = { .parser = NULL };
                                cborFindResult = cbor_value_enter_container(&credMap, &pubMap);

                                while (cbor_value_is_valid(&pubMap))
                                {
                                    char* pubname = NULL;
                                    CborType type = cbor_value_get_type(&pubMap);
                                    if (type == CborTextStringType)
                                    {
                                        cborFindResult = cbor_value_dup_text_string(&pubMap, &pubname,
                                                &len, NULL);
                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get text");
                                        cborFindResult = cbor_value_advance(&pubMap);
                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance value");
                                    }
                                    if (pubname)
                                    {
                                        // PrivateData::privdata -- Mandatory
524
                                        if (strcmp(pubname, OIC_JSON_DATA_NAME) == 0)
leechul's avatar
leechul committed
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
                                        {
                                            cborFindResult = cbor_value_dup_byte_string(&pubMap, &cred->publicData.data,
                                                &cred->publicData.len, NULL);
                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PubData.");
                                        }
                                        // PublicData::encoding -- Mandatory
                                        if (strcmp(pubname, OIC_JSON_ENCODING_NAME) == 0)
                                        {
                                            // TODO: Need to update data structure, just ignore encoding value now.
                                        }
                                    }
                                    if (cbor_value_is_valid(&pubMap))
                                    {
                                        cborFindResult = cbor_value_advance(&pubMap);
                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing publicdata Map.");
                                    }
                                    OICFree(pubname);
                                }
                            }
Sahil Bansal's avatar
Sahil Bansal committed
544
#endif  //__WITH_X509__
leechul's avatar
leechul committed
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

                            if (0 == strcmp(OIC_JSON_PERIOD_NAME, name))
                            {
                                cborFindResult = cbor_value_dup_text_string(&credMap, &cred->period, &len, NULL);
                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Period.");
                            }

                            if (cbor_value_is_valid(&credMap))
                            {
                                cborFindResult = cbor_value_advance(&credMap);
                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing CRED Map.");
                            }
                            OICFree(name);
                        }
                    }
                    cred->next = NULL;
                    if (cbor_value_is_valid(&credArray))
                    {
                        cborFindResult = cbor_value_advance(&credArray);
                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing CRED Array.");
                    }
                }
            }

            // TODO : Need to modify headCred->owners[0].id to headCred->rowner based on RAML spec.
            if (strcmp(tagName, OIC_JSON_ROWNERID_NAME)  == 0)
Sachin Agrawal's avatar
Sachin Agrawal committed
571
            {
leechul's avatar
leechul committed
572 573 574 575 576 577 578 579 580
                char *stRowner = NULL;
                cborFindResult = cbor_value_dup_text_string(&CredRootMap, &stRowner, &len, NULL);
                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Rownerid Value.");
                headCred->ownersLen = 1;
                headCred->owners = (OicUuid_t *)OICCalloc(headCred->ownersLen, sizeof(*headCred->owners));
                VERIFY_NON_NULL(TAG, headCred->owners, ERROR);
                ret = ConvertStrToUuid(stRowner, &headCred->owners[0]);
                VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
                OICFree(stRowner);
Sachin Agrawal's avatar
Sachin Agrawal committed
581
            }
leechul's avatar
leechul committed
582
            OICFree(tagName);
Sahil Bansal's avatar
Sahil Bansal committed
583
        }
leechul's avatar
leechul committed
584
        if (cbor_value_is_valid(&CredRootMap))
Sahil Bansal's avatar
Sahil Bansal committed
585
        {
leechul's avatar
leechul committed
586 587
            cborFindResult = cbor_value_advance(&CredRootMap);
            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing CRED Root Map.");
Sahil Bansal's avatar
Sahil Bansal committed
588
        }
Sachin Agrawal's avatar
Sachin Agrawal committed
589
    }
leechul's avatar
leechul committed
590

Sahil Bansal's avatar
Sahil Bansal committed
591
    *secCred = headCred;
Sachin Agrawal's avatar
Sachin Agrawal committed
592
    ret = OC_STACK_OK;
leechul's avatar
leechul committed
593

Sachin Agrawal's avatar
Sachin Agrawal committed
594
exit:
Sahil Bansal's avatar
Sahil Bansal committed
595
    if (CborNoError != cborFindResult)
Sachin Agrawal's avatar
Sachin Agrawal committed
596 597 598
    {
        DeleteCredList(headCred);
        headCred = NULL;
leechul's avatar
leechul committed
599
        *secCred = NULL;
Sahil Bansal's avatar
Sahil Bansal committed
600
        ret = OC_STACK_ERROR;
601
    }
Sahil Bansal's avatar
Sahil Bansal committed
602 603

    return ret;
Sachin Agrawal's avatar
Sachin Agrawal committed
604 605 606
}

OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t credType,
Sahil Bansal's avatar
Sahil Bansal committed
607 608
                                  const OicSecCert_t * publicData, const OicSecKey_t* privateData,
                                  size_t ownersLen, const OicUuid_t * owners)
Sachin Agrawal's avatar
Sachin Agrawal committed
609
{
Jon A. Cruz's avatar
Jon A. Cruz committed
610
    (void)publicData;
Sachin Agrawal's avatar
Sachin Agrawal committed
611 612
    OCStackResult ret = OC_STACK_ERROR;

Sahil Bansal's avatar
Sahil Bansal committed
613
    OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
Sachin Agrawal's avatar
Sachin Agrawal committed
614 615
    VERIFY_NON_NULL(TAG, cred, ERROR);

616 617 618
    //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
619 620 621 622

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

623 624
    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
625 626
    cred->credType = credType;

Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
627
#ifdef __WITH_X509__
Sahil Bansal's avatar
Sahil Bansal committed
628
    if (publicData && publicData->data)
Sachin Agrawal's avatar
Sachin Agrawal committed
629
    {
Sahil Bansal's avatar
Sahil Bansal committed
630
        cred->publicData.data = (uint8_t *)OICCalloc(1, publicData->len);
Sachin Agrawal's avatar
Sachin Agrawal committed
631
        VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
Sahil Bansal's avatar
Sahil Bansal committed
632 633
        memcpy(cred->publicData.data, publicData->data, publicData->len);
        cred->publicData.len = publicData->len;
Sachin Agrawal's avatar
Sachin Agrawal committed
634
    }
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
635
#endif // __WITH_X509__
Sachin Agrawal's avatar
Sachin Agrawal committed
636

Sahil Bansal's avatar
Sahil Bansal committed
637
    if (privateData && privateData->data)
Sachin Agrawal's avatar
Sachin Agrawal committed
638
    {
Sahil Bansal's avatar
Sahil Bansal committed
639
        cred->privateData.data = (uint8_t *)OICCalloc(1, privateData->len);
Sachin Agrawal's avatar
Sachin Agrawal committed
640
        VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
Sahil Bansal's avatar
Sahil Bansal committed
641 642
        memcpy(cred->privateData.data, privateData->data, privateData->len);
        cred->privateData.len = privateData->len;
Sachin Agrawal's avatar
Sachin Agrawal committed
643 644 645 646 647
    }

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

Sahil Bansal's avatar
Sahil Bansal committed
648
    cred->owners = (OicUuid_t *)OICCalloc(cred->ownersLen, sizeof(*cred->owners));
Sachin Agrawal's avatar
Sachin Agrawal committed
649
    VERIFY_NON_NULL(TAG, cred->owners, ERROR);
Sahil Bansal's avatar
Sahil Bansal committed
650
    for (size_t i = 0; i < cred->ownersLen; i++)
Sachin Agrawal's avatar
Sachin Agrawal committed
651 652 653 654 655 656 657 658 659 660 661 662 663 664
    {
        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;
}

665 666 667 668 669
static bool UpdatePersistentStorage(const OicSecCred_t *cred)
{
    bool ret = false;

    // Convert Cred data into JSON for update to persistent storage
Sahil Bansal's avatar
Sahil Bansal committed
670
    if (cred)
671
    {
Sahil Bansal's avatar
Sahil Bansal committed
672 673 674 675
        uint8_t *payload = NULL;
        size_t size = 0;
        OCStackResult res = CredToCBORPayload(cred, &payload, &size);
        if ((OC_STACK_OK == res) && payload)
676
        {
Sahil Bansal's avatar
Sahil Bansal committed
677 678 679 680 681
            if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, payload, size))
            {
                ret = true;
            }
            OICFree(payload);
682 683 684 685
        }
    }
    else //Empty cred list
    {
Sahil Bansal's avatar
Sahil Bansal committed
686
        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, NULL, 0))
687 688 689 690 691 692 693 694
        {
            ret = true;
        }
    }
    return ret;
}

/**
Sahil Bansal's avatar
Sahil Bansal committed
695
 * Compare function used LL_SORT for sorting credentials.
696
 *
Sahil Bansal's avatar
Sahil Bansal committed
697 698
 * @param first pointer to OicSecCred_t struct.
 * @param second  pointer to OicSecCred_t struct.
699
 *
Sahil Bansal's avatar
Sahil Bansal committed
700 701 702
 *@return -1, if credId of first is less than credId of second.
 * 0, if credId of first is equal to credId of second.
 * 1, if credId of first is greater than credId of second.
703 704 705
 */
static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
{
Sahil Bansal's avatar
Sahil Bansal committed
706
    if (first->credId < second->credId)
707 708 709
    {
        return -1;
    }
Sahil Bansal's avatar
Sahil Bansal committed
710
    else if (first->credId > second->credId)
711 712 713 714 715 716 717 718 719 720 721 722 723
    {
        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.
 *
Sahil Bansal's avatar
Sahil Bansal committed
724
 * @return next available credId if successful, else 0 for error.
725 726 727 728 729 730 731 732 733 734 735
 */
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)
    {
Sahil Bansal's avatar
Sahil Bansal committed
736
        if (currentCred->credId == nextCredId)
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
        {
            nextCredId += 1;
        }
        else
        {
            break;
        }
    }

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

exit:
    return 0;
}
752

753
/**
Sahil Bansal's avatar
Sahil Bansal committed
754 755 756
 * Get the default value.
 *
 * @return  NULL for now.
757 758 759
 */
static OicSecCred_t* GetCredDefault()
{
Sahil Bansal's avatar
Sahil Bansal committed
760
    // TODO:Update it when we finalize the default info.
761 762
    return NULL;
}
763

Sachin Agrawal's avatar
Sachin Agrawal committed
764 765 766
OCStackResult AddCredential(OicSecCred_t * newCred)
{
    OCStackResult ret = OC_STACK_ERROR;
767 768 769 770 771
    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
772 773 774

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

Sahil Bansal's avatar
Sahil Bansal committed
776
    if (UpdatePersistentStorage(gCred))
Sachin Agrawal's avatar
Sachin Agrawal committed
777
    {
778 779 780 781 782 783 784 785 786 787 788 789 790
        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
791

792 793
    LL_FOREACH_SAFE(gCred, cred, tempCred)
    {
Sahil Bansal's avatar
Sahil Bansal committed
794
        if (memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
Sachin Agrawal's avatar
Sachin Agrawal committed
795
        {
796 797 798
            LL_DELETE(gCred, cred);
            FreeCred(cred);
            deleteFlag = 1;
Sachin Agrawal's avatar
Sachin Agrawal committed
799 800 801
        }
    }

Sahil Bansal's avatar
Sahil Bansal committed
802
    if (deleteFlag)
803
    {
Sahil Bansal's avatar
Sahil Bansal committed
804
        if (UpdatePersistentStorage(gCred))
805 806 807 808
        {
            ret = OC_STACK_RESOURCE_DELETED;
        }
    }
Sachin Agrawal's avatar
Sachin Agrawal committed
809
    return ret;
810

Sachin Agrawal's avatar
Sachin Agrawal committed
811 812
}

813 814 815 816 817 818 819 820 821 822 823 824
/**
 * 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();

Sahil Bansal's avatar
Sahil Bansal committed
825
    if (!UpdatePersistentStorage(gCred))
826 827 828 829 830 831
    {
        return OC_STACK_ERROR;
    }
    return OC_STACK_OK;
}

832 833
#ifdef __WITH_DTLS__
/**
834
 * Internal function to fill private data of owner PSK.
835
 *
836
 * @param receviedCred recevied owner credential from OBT(PT)
837 838 839
 * @param ownerAdd address of OBT(PT)
 * @param doxm current device's doxm resource
 *
Sahil Bansal's avatar
Sahil Bansal committed
840
 * @return
841 842
 *     true successfully done and valid ower psk information
 *     false Invalid owner psk information or failed to owner psk generation
843
 */
844
static bool FillPrivateDataOfOwnerPSK(OicSecCred_t* receviedCred, const CAEndpoint_t* ownerAddr,
845 846 847 848 849 850 851 852 853 854 855 856 857 858
                           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);

859 860 861 862
    OIC_LOG(DEBUG, TAG, "OwnerPSK dump :");
    OIC_LOG_BUFFER(DEBUG, TAG, ownerPSK, OWNER_PSK_LENGTH_128);

    //Generate owner credential based on recevied credential information
Sahil Bansal's avatar
Sahil Bansal committed
863
    receviedCred->privateData.data = (uint8_t *)OICCalloc(1, OWNER_PSK_LENGTH_128);
864
    VERIFY_NON_NULL(TAG, receviedCred->privateData.data, ERROR);
Sahil Bansal's avatar
Sahil Bansal committed
865 866
    receviedCred->privateData.len = OWNER_PSK_LENGTH_128;
    memcpy(receviedCred->privateData.data, ownerPSK, OWNER_PSK_LENGTH_128);
867

868 869 870 871 872
    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);
873
exit:
874
    //receviedCred->privateData.data will be deallocated when deleting credential.
875 876 877 878 879 880 881 882
    return false;
}

#endif //__WITH_DTLS__

static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehRequest)
{
    OCEntityHandlerResult ret = OC_EH_ERROR;
Sahil Bansal's avatar
Sahil Bansal committed
883 884 885 886 887 888 889 890
    OIC_LOG(DEBUG, TAG, "HandleCREDPutRequest IN");

    //Get binary representation of cbor
    OicSecCred_t *cred  = NULL;
    uint8_t *payload = (((OCSecurityPayload*)ehRequest->payload)->securityData1);
    size_t size = (((OCSecurityPayload*)ehRequest->payload)->payloadSize);
    OCStackResult res = CBORPayloadToCred(payload, size, &cred);
    if (res == OC_STACK_OK)
891 892 893 894 895 896 897 898 899 900 901 902
    {
#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;
903
                    if(FillPrivateDataOfOwnerPSK(cred, (CAEndpoint_t *)&request->devAddr, doxm))
904
                    {
905 906 907 908 909 910
                        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.");
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
                        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;
                    }

927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
                    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;
                        }
                    }

965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
                    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;
                }
            }
984 985 986 987 988 989 990 991 992 993

            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();
            }
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        }
        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__
    }

Sahil Bansal's avatar
Sahil Bansal committed
1016
    if (OC_EH_RESOURCE_CREATED != ret)
1017 1018 1019 1020 1021 1022 1023
    {
        if(OC_STACK_OK != RemoveCredential(&cred->subject))
        {
            OIC_LOG(WARNING, TAG, "Failed to remove the invalid credential");
        }
        FreeCred(cred);
    }
Sahil Bansal's avatar
Sahil Bansal committed
1024
    OIC_LOG(DEBUG, TAG, "HandleCREDPutRequest OUT");
1025 1026 1027
    return ret;
}

Sachin Agrawal's avatar
Sachin Agrawal committed
1028 1029 1030 1031
static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
{
    OCEntityHandlerResult ret = OC_EH_ERROR;

Sahil Bansal's avatar
Sahil Bansal committed
1032 1033 1034 1035 1036 1037
    //Get binary representation of CBOR
    OicSecCred_t *cred  = NULL;
    uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData1;
    size_t size = ((OCSecurityPayload*)ehRequest->payload)->payloadSize;
    OCStackResult res = CBORPayloadToCred(payload, size, &cred);
    if ((OC_STACK_OK == res) && cred)
Sachin Agrawal's avatar
Sachin Agrawal committed
1038
    {
1039 1040 1041 1042
        //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.
1043
        ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
Sachin Agrawal's avatar
Sachin Agrawal committed
1044
    }
1045

Sachin Agrawal's avatar
Sachin Agrawal committed
1046 1047 1048
    return ret;
}

1049 1050
static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *ehRequest)
{
1051
    OIC_LOG(DEBUG, TAG, "Processing CredDeleteRequest");
1052 1053 1054

    OCEntityHandlerResult ehRet = OC_EH_ERROR;

Sahil Bansal's avatar
Sahil Bansal committed
1055
    if (NULL == ehRequest->query)
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    {
        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_SUBJECTID_NAME,
                parseIter.attrLen) == 0)
        {
            OCStackResult ret = ConvertStrToUuid((const char*)parseIter.valPos, &subject);
            VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
Sahil Bansal's avatar
Sahil Bansal committed
1072
        }
1073
    }
1074

1075 1076 1077 1078
    if (OC_STACK_RESOURCE_DELETED == RemoveCredential(&subject))
    {
        ehRet = OC_EH_RESOURCE_DELETED;
    }
1079

leechul's avatar
leechul committed
1080
exit:
1081 1082 1083
    return ehRet;
}

Sahil Bansal's avatar
Sahil Bansal committed
1084
OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
1085 1086
                                        OCEntityHandlerRequest * ehRequest,
                                        void* callbackParameter)
Sachin Agrawal's avatar
Sachin Agrawal committed
1087
{
Jon A. Cruz's avatar
Jon A. Cruz committed
1088
    (void)callbackParameter;
Sachin Agrawal's avatar
Sachin Agrawal committed
1089 1090
    OCEntityHandlerResult ret = OC_EH_ERROR;

Sahil Bansal's avatar
Sahil Bansal committed
1091
    if (!ehRequest)
Sachin Agrawal's avatar
Sachin Agrawal committed
1092 1093 1094 1095 1096
    {
        return OC_EH_ERROR;
    }
    if (flag & OC_REQUEST_FLAG)
    {
1097
        OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
Sachin Agrawal's avatar
Sachin Agrawal committed
1098
        //TODO :  Handle PUT/DEL methods
Sahil Bansal's avatar
Sahil Bansal committed
1099
        switch (ehRequest->method)
Sachin Agrawal's avatar
Sachin Agrawal committed
1100 1101 1102 1103
        {
            case OC_REST_GET:
                ret = OC_EH_FORBIDDEN;
                break;
1104 1105 1106
            case OC_REST_PUT:
                ret = HandlePutRequest(ehRequest);
                break;
Sachin Agrawal's avatar
Sachin Agrawal committed
1107 1108 1109
            case OC_REST_POST:
                ret = HandlePostRequest(ehRequest);
                break;
1110 1111 1112
            case OC_REST_DELETE:
                ret = HandleDeleteRequest(ehRequest);
                break;
Sachin Agrawal's avatar
Sachin Agrawal committed
1113 1114 1115 1116 1117 1118 1119
            default:
                ret = OC_EH_ERROR;
                break;
        }
    }

    //Send payload to request originator
Sahil Bansal's avatar
Sahil Bansal committed
1120 1121
    ret = (SendSRMCBORResponse(ehRequest, ret, NULL, 0) == OC_STACK_OK) ?
                       ret : OC_EH_ERROR;
Sachin Agrawal's avatar
Sachin Agrawal committed
1122 1123 1124 1125 1126 1127

    return ret;
}

OCStackResult CreateCredResource()
{
Sahil Bansal's avatar
Sahil Bansal committed
1128 1129 1130 1131 1132 1133 1134
    OCStackResult ret = OCCreateResource(&gCredHandle,
                                         OIC_RSRC_TYPE_SEC_CRED,
                                         OIC_MI_DEF,
                                         OIC_RSRC_CRED_URI,
                                         CredEntityHandler,
                                         NULL,
                                         OC_RES_PROP_NONE);
Sachin Agrawal's avatar
Sachin Agrawal committed
1135 1136 1137

    if (OC_STACK_OK != ret)
    {
1138
        OIC_LOG (FATAL, TAG, "Unable to instantiate Cred resource");
Sachin Agrawal's avatar
Sachin Agrawal committed
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
        DeInitCredResource();
    }
    return ret;
}

OCStackResult InitCredResource()
{
    OCStackResult ret = OC_STACK_ERROR;

    //Read Cred resource from PS
Sahil Bansal's avatar
Sahil Bansal committed
1149 1150 1151 1152 1153 1154 1155 1156 1157
    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
1158
    {
Sahil Bansal's avatar
Sahil Bansal committed
1159 1160
        // Read ACL resource from PS
        ret = CBORPayloadToCred(data, size, &gCred);
Sachin Agrawal's avatar
Sachin Agrawal committed
1161
    }
Sahil Bansal's avatar
Sahil Bansal committed
1162

Sachin Agrawal's avatar
Sachin Agrawal committed