credresource.c 44.8 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
#include "ocstack.h"
leechul's avatar
leechul committed
23
#include "logger.h"
Sachin Agrawal's avatar
Sachin Agrawal committed
24
#include "oic_malloc.h"
leechul's avatar
leechul committed
25 26 27
#include "cJSON.h"
#include "resourcemanager.h"
#include "psinterface.h"
Sachin Agrawal's avatar
Sachin Agrawal committed
28
#include "utlist.h"
leechul's avatar
leechul committed
29
#include "srmresourcestrings.h"
Sachin Agrawal's avatar
Sachin Agrawal committed
30
#include "credresource.h"
leechul's avatar
leechul committed
31
#include "ocrandom.h"
Sachin Agrawal's avatar
Sachin Agrawal committed
32
#include "doxmresource.h"
leechul's avatar
leechul committed
33
#include "base64.h"
34
#include "srmutility.h"
leechul's avatar
leechul committed
35 36 37 38 39
#include "cainterface.h"
#include "pbkdf2.h"
#include <stdlib.h>
#include "iotvticalendar.h"
#include "ocserverrequest.h"
40

41 42
#ifdef __WITH_DTLS__
#include "global.h"
leechul's avatar
leechul committed
43 44 45 46 47 48
#endif //__WITH_DTLS__

#ifdef WITH_ARDUINO
#include <string.h>
#else
#include <strings.h>
49
#endif
leechul's avatar
leechul committed
50
#include <stdint.h>
51

52
#define TAG  "SRM-CREDL"
Sachin Agrawal's avatar
Sachin Agrawal committed
53

Shilpa Sodani's avatar
Shilpa Sodani committed
54

Sachin Agrawal's avatar
Sachin Agrawal committed
55 56 57
static OicSecCred_t        *gCred = NULL;
static OCResourceHandle    gCredHandle = NULL;

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

74 75
    //Clean PublicData
    OICFree(cred->publicData.data);
Sachin Agrawal's avatar
Sachin Agrawal committed
76

77 78
    //Clean PrivateData
    OICFree(cred->privateData.data);
Sachin Agrawal's avatar
Sachin Agrawal committed
79

80 81
    //Clean Period
    OICFree(cred->period);
Sachin Agrawal's avatar
Sachin Agrawal committed
82

83 84 85 86 87 88
    //Clean Owners
    OICFree(cred->owners);

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

90 91 92 93 94 95 96 97 98
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
99 100 101 102
        }
    }
}

leechul's avatar
leechul committed
103 104 105 106 107 108 109 110 111 112 113
/**
 * This function converts credential data into JSON format.
 * Caller needs to invoke 'free' when done using
 * returned string.
 * @param cred  pointer to instance of OicSecCred_t structure.
 *
 * @retval
 *      pointer to JSON credential representation - if credential for subjectId found
 *      NULL                                      - if credential for subjectId not found
 */
char * BinToCredJSON(const OicSecCred_t * cred)
Sachin Agrawal's avatar
Sachin Agrawal committed
114
{
leechul's avatar
leechul committed
115 116
    cJSON *jsonRoot = NULL;
    char *jsonStr = NULL;
Sachin Agrawal's avatar
Sachin Agrawal committed
117

leechul's avatar
leechul committed
118
    if (cred)
Sachin Agrawal's avatar
Sachin Agrawal committed
119
    {
leechul's avatar
leechul committed
120 121 122
        char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
        uint32_t outLen = 0;
        B64Result b64Ret = B64_OK;
123

leechul's avatar
leechul committed
124 125
        jsonRoot = cJSON_CreateObject();
        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
126

leechul's avatar
leechul committed
127 128 129 130
        cJSON *jsonCredArray = NULL;
        cJSON_AddItemToObject(jsonRoot, OIC_JSON_CRED_NAME,
                jsonCredArray = cJSON_CreateArray());
        VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
Sachin Agrawal's avatar
Sachin Agrawal committed
131

leechul's avatar
leechul committed
132 133 134 135
        while(cred)
        {
            cJSON *jsonCred = cJSON_CreateObject();
            VERIFY_NON_NULL(TAG, jsonCred, ERROR);
Sachin Agrawal's avatar
Sachin Agrawal committed
136

leechul's avatar
leechul committed
137 138
            //CredID -- Mandatory
            cJSON_AddNumberToObject(jsonCred, OIC_JSON_CREDID_NAME, (int)cred->credId);
Sachin Agrawal's avatar
Sachin Agrawal committed
139

leechul's avatar
leechul committed
140 141 142 143 144 145 146
            //Subject -- Mandatory
            outLen = 0;
            memset(base64Buff, 0, sizeof(base64Buff));
            b64Ret = b64Encode(cred->subject.id, sizeof(cred->subject.id), base64Buff,
                   sizeof(base64Buff), &outLen);
            VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
            cJSON_AddStringToObject(jsonCred, OIC_JSON_SUBJECT_NAME, base64Buff);
Sachin Agrawal's avatar
Sachin Agrawal committed
147

leechul's avatar
leechul committed
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
            //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);
Sachin Agrawal's avatar
Sachin Agrawal committed
167

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

leechul's avatar
leechul committed
201 202 203 204 205 206
            //Period -- Not Mandatory
            if(cred->period)
            {
                cJSON_AddStringToObject(jsonCred, OIC_JSON_PERIOD_NAME,
                                        cred->period);
            }
Sachin Agrawal's avatar
Sachin Agrawal committed
207

leechul's avatar
leechul committed
208 209 210 211 212
            //Owners -- Mandatory
            cJSON *jsonOwnrArray = NULL;
            cJSON_AddItemToObject (jsonCred, OIC_JSON_OWNERS_NAME,
                                             jsonOwnrArray = cJSON_CreateArray());
            VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
Sachin Agrawal's avatar
Sachin Agrawal committed
213 214
            for (size_t i = 0; i < cred->ownersLen; i++)
            {
leechul's avatar
leechul committed
215 216 217 218 219 220 221
                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)));
Sachin Agrawal's avatar
Sachin Agrawal committed
222 223
            }

leechul's avatar
leechul committed
224 225 226 227
            /* Attach current cred node to cred Array */
            cJSON_AddItemToArray(jsonCredArray, jsonCred);
            cred = cred->next;
        }
228

leechul's avatar
leechul committed
229
        jsonStr = cJSON_PrintUnformatted(jsonRoot);
Sachin Agrawal's avatar
Sachin Agrawal committed
230 231 232
    }

exit:
leechul's avatar
leechul committed
233
    if (jsonRoot)
234
    {
leechul's avatar
leechul committed
235
        cJSON_Delete(jsonRoot);
236
    }
leechul's avatar
leechul committed
237
    return jsonStr;
Sachin Agrawal's avatar
Sachin Agrawal committed
238 239
}

leechul's avatar
leechul committed
240 241 242 243
/*
 * This internal method converts JSON cred into binary cred.
 */
OicSecCred_t * JSONToCredBin(const char * jsonStr)
Sachin Agrawal's avatar
Sachin Agrawal committed
244 245
{
    OCStackResult ret = OC_STACK_ERROR;
leechul's avatar
leechul committed
246 247 248
    OicSecCred_t * headCred = NULL;
    OicSecCred_t * prevCred = NULL;
    cJSON *jsonCredArray = NULL;
Sachin Agrawal's avatar
Sachin Agrawal committed
249

leechul's avatar
leechul committed
250 251
    cJSON *jsonRoot = cJSON_Parse(jsonStr);
    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
Sachin Agrawal's avatar
Sachin Agrawal committed
252

leechul's avatar
leechul committed
253 254 255
    jsonCredArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
    VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
    if (cJSON_Array == jsonCredArray->type)
256
    {
leechul's avatar
leechul committed
257 258
        int numCred = cJSON_GetArraySize(jsonCredArray);
        int idx = 0;
Sachin Agrawal's avatar
Sachin Agrawal committed
259

leechul's avatar
leechul committed
260 261 262
        unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
        uint32_t outLen = 0;
        B64Result b64Ret = B64_OK;
263

leechul's avatar
leechul committed
264 265
        VERIFY_SUCCESS(TAG, numCred > 0, ERROR);
        do
266
        {
leechul's avatar
leechul committed
267 268 269 270 271
            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);
272

leechul's avatar
leechul committed
273 274 275 276 277 278 279
            headCred = (headCred) ? headCred : cred;
            if (prevCred)
            {
                prevCred->next = cred;
            }
            size_t jsonObjLen = 0;
            cJSON *jsonObj = NULL;
Sachin Agrawal's avatar
Sachin Agrawal committed
280 281

            //CredId -- Mandatory
leechul's avatar
leechul committed
282 283
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDID_NAME);
            if(jsonObj)
284
            {
leechul's avatar
leechul committed
285 286
                VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
                cred->credId = jsonObj->valueint;
287
            }
leechul's avatar
leechul committed
288

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

            //PrivateData is mandatory for some of the credential types listed below.
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PRIVATEDATA_NAME);
            if ((cred->credType & SYMMETRIC_PAIR_WISE_KEY) ||
                (cred->credType & SYMMETRIC_GROUP_KEY) ||
                (cred->credType & PIN_PASSWORD))
Sachin Agrawal's avatar
Sachin Agrawal committed
312
            {
leechul's avatar
leechul committed
313 314 315 316
                if(jsonObj)
                {
                    VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
                }
Sachin Agrawal's avatar
Sachin Agrawal committed
317
            }
leechul's avatar
leechul committed
318 319
#ifdef __WITH_X509__
            else if (cred->credType & SIGNED_ASYMMETRIC_KEY)
Sachin Agrawal's avatar
Sachin Agrawal committed
320
            {
leechul's avatar
leechul committed
321 322
                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
                VERIFY_SUCCESS(TAG, cJSON_Object == jsonObj->type, ERROR);
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
323
            }
leechul's avatar
leechul committed
324 325
#endif //  __WITH_X509__
            if (NULL != jsonObj)
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
326
            {
leechul's avatar
leechul committed
327
                if (cJSON_String == jsonObj->type)
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
328
                {
leechul's avatar
leechul committed
329 330 331 332
                    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);
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
333
                }
leechul's avatar
leechul committed
334 335
#ifdef __WITH_X509__
                else if (SIGNED_ASYMMETRIC_KEY == cred->credType && cJSON_Object == jsonObj->type)
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
336
                {
leechul's avatar
leechul committed
337 338
                    cred->privateData.data = cJSON_PrintUnformatted(jsonObj);
                    VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
339
                }
leechul's avatar
leechul committed
340
#endif // __WITH_X509__
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
341
            }
342 343 344 345
            else
            {
                cred->privateData.data = NULL;
            }
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
346 347

            //PublicData is mandatory only for SIGNED_ASYMMETRIC_KEY credentials type.
leechul's avatar
leechul committed
348 349 350
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PUBLICDATA_NAME);
#ifdef __WITH_X509__
            if (cred->credType & SIGNED_ASYMMETRIC_KEY)
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
351
            {
leechul's avatar
leechul committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
                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)
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
367
                {
leechul's avatar
leechul committed
368 369
                    cred->publicData.data = cJSON_PrintUnformatted(jsonObj);
                    VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
370
                }
leechul's avatar
leechul committed
371
#endif //  __WITH_X509__
Sachin Agrawal's avatar
Sachin Agrawal committed
372
            }
leechul's avatar
leechul committed
373

Sachin Agrawal's avatar
Sachin Agrawal committed
374
            //Period -- Not Mandatory
leechul's avatar
leechul committed
375 376
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PERIOD_NAME);
            if(jsonObj && cJSON_String == jsonObj->type)
377
            {
leechul's avatar
leechul committed
378 379 380 381
                jsonObjLen = strlen(jsonObj->valuestring) + 1;
                cred->period = (char *)OICMalloc(jsonObjLen);
                VERIFY_NON_NULL(TAG, cred->period, ERROR);
                strncpy(cred->period, jsonObj->valuestring, jsonObjLen);
382
            }
Sachin Agrawal's avatar
Sachin Agrawal committed
383

leechul's avatar
leechul committed
384 385 386 387 388 389 390 391 392
            //Owners -- Mandatory
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_OWNERS_NAME);
            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
            cred->ownersLen = (size_t)cJSON_GetArraySize(jsonObj);
            VERIFY_SUCCESS(TAG, cred->ownersLen > 0, ERROR);
            cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
            VERIFY_NON_NULL(TAG, (cred->owners), ERROR);
            for(size_t i = 0; i < cred->ownersLen; i++)
Sachin Agrawal's avatar
Sachin Agrawal committed
393
            {
leechul's avatar
leechul committed
394 395 396 397 398 399 400 401 402 403
                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);
Sachin Agrawal's avatar
Sachin Agrawal committed
404
            }
leechul's avatar
leechul committed
405 406
            prevCred = cred;
        } while( ++idx < numCred);
Sachin Agrawal's avatar
Sachin Agrawal committed
407
    }
leechul's avatar
leechul committed
408

Sachin Agrawal's avatar
Sachin Agrawal committed
409
    ret = OC_STACK_OK;
leechul's avatar
leechul committed
410

Sachin Agrawal's avatar
Sachin Agrawal committed
411
exit:
leechul's avatar
leechul committed
412 413
    cJSON_Delete(jsonRoot);
    if (OC_STACK_OK != ret)
Sachin Agrawal's avatar
Sachin Agrawal committed
414 415 416
    {
        DeleteCredList(headCred);
        headCred = NULL;
417
    }
leechul's avatar
leechul committed
418
    return headCred;
Sachin Agrawal's avatar
Sachin Agrawal committed
419 420
}

leechul's avatar
leechul committed
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
/**
 * 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.
 *        The privateData is expected in base64 encoded format.
 * @param ownersLen length of owners array
 * @param owners array of owners.
 *
 * @retval
 *      pointer to instance of OicSecCred_t  - success
 *      NULL                                 - error
 */
Sachin Agrawal's avatar
Sachin Agrawal committed
436
OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t credType,
leechul's avatar
leechul committed
437 438
                                 const char * publicData, const char * privateData,
                                 size_t ownersLen, const OicUuid_t * owners)
Sachin Agrawal's avatar
Sachin Agrawal committed
439
{
Jon A. Cruz's avatar
Jon A. Cruz committed
440
    (void)publicData;
Sachin Agrawal's avatar
Sachin Agrawal committed
441 442
    OCStackResult ret = OC_STACK_ERROR;

leechul's avatar
leechul committed
443
    OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
Sachin Agrawal's avatar
Sachin Agrawal committed
444 445
    VERIFY_NON_NULL(TAG, cred, ERROR);

446 447 448
    //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
449 450 451 452

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

453 454
    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
455 456
    cred->credType = credType;

Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
457
#ifdef __WITH_X509__
leechul's avatar
leechul committed
458
    if(publicData)
Sachin Agrawal's avatar
Sachin Agrawal committed
459
    {
leechul's avatar
leechul committed
460
        cred->publicData.data = (char *)OICMalloc(strlen(publicData)+1);
Sachin Agrawal's avatar
Sachin Agrawal committed
461
        VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
leechul's avatar
leechul committed
462
        strncpy((char *)cred->publicData.data, publicData, strlen(publicData)+1);
Sachin Agrawal's avatar
Sachin Agrawal committed
463
    }
Dmitrii Zhuravlev's avatar
Dmitrii Zhuravlev committed
464
#endif // __WITH_X509__
Sachin Agrawal's avatar
Sachin Agrawal committed
465

leechul's avatar
leechul committed
466
    if(privateData)
Sachin Agrawal's avatar
Sachin Agrawal committed
467
    {
leechul's avatar
leechul committed
468
        cred->privateData.data = (char *)OICMalloc(strlen(privateData)+1);
Sachin Agrawal's avatar
Sachin Agrawal committed
469
        VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
leechul's avatar
leechul committed
470
        strncpy((char *)cred->privateData.data, privateData, strlen(privateData)+1);
Sachin Agrawal's avatar
Sachin Agrawal committed
471 472 473 474 475
    }

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

leechul's avatar
leechul committed
476
    cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
Sachin Agrawal's avatar
Sachin Agrawal committed
477
    VERIFY_NON_NULL(TAG, cred->owners, ERROR);
leechul's avatar
leechul committed
478
    for(size_t i = 0; i < cred->ownersLen; i++)
Sachin Agrawal's avatar
Sachin Agrawal committed
479 480 481 482 483 484 485 486 487 488 489 490 491 492
    {
        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;
}

493 494 495 496 497
static bool UpdatePersistentStorage(const OicSecCred_t *cred)
{
    bool ret = false;

    // Convert Cred data into JSON for update to persistent storage
leechul's avatar
leechul committed
498 499
    char *jsonStr = BinToCredJSON(cred);
    if (jsonStr)
500
    {
leechul's avatar
leechul committed
501 502 503 504 505
        cJSON *jsonCred = cJSON_Parse(jsonStr);
        OICFree(jsonStr);

        if ((jsonCred) &&
          (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, jsonCred)))
506 507 508
        {
            ret = true;
        }
leechul's avatar
leechul committed
509
        cJSON_Delete(jsonCred );
510 511 512
    }
    else //Empty cred list
    {
leechul's avatar
leechul committed
513
        if (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, NULL))
514 515 516 517 518 519 520 521
        {
            ret = true;
        }
    }
    return ret;
}

/**
leechul's avatar
leechul committed
522
 * Compare function used LL_SORT for sorting credentials
523
 *
leechul's avatar
leechul committed
524 525
 * @param first   pointer to OicSecCred_t struct
 * @param second  pointer to OicSecCred_t struct
526
 *
leechul's avatar
leechul committed
527 528 529 530
 *@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
531 532 533
 */
static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
{
leechul's avatar
leechul committed
534
    if(first->credId < second->credId)
535 536 537
    {
        return -1;
    }
leechul's avatar
leechul committed
538
    else if(first->credId > second->credId)
539 540 541 542 543 544 545 546 547 548 549 550 551
    {
        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.
 *
leechul's avatar
leechul committed
552 553 554
 * @retval
 *      next available credId  - success
 *      0                      - error
555
 */
leechul's avatar
leechul committed
556

557 558 559 560 561
static uint16_t GetCredId()
{
    //Sorts credential list in incremental order of credId
    LL_SORT(gCred, CmpCredId);

leechul's avatar
leechul committed
562

563 564 565 566 567
    OicSecCred_t *currentCred = NULL, *credTmp = NULL;
    uint16_t nextCredId = 1;

    LL_FOREACH_SAFE(gCred, currentCred, credTmp)
    {
leechul's avatar
leechul committed
568
        if(currentCred->credId == nextCredId)
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
        {
            nextCredId += 1;
        }
        else
        {
            break;
        }
    }

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

exit:
    return 0;
}
584

585
/**
leechul's avatar
leechul committed
586 587
 * Get the default value
 * @retval  NULL for now. Update it when we finalize the default info.
588 589 590 591 592
 */
static OicSecCred_t* GetCredDefault()
{
    return NULL;
}
593

leechul's avatar
leechul committed
594 595 596 597 598 599 600 601 602
/**
 * 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
 */
Sachin Agrawal's avatar
Sachin Agrawal committed
603 604 605
OCStackResult AddCredential(OicSecCred_t * newCred)
{
    OCStackResult ret = OC_STACK_ERROR;
leechul's avatar
leechul committed
606

607 608 609 610
    VERIFY_SUCCESS(TAG, NULL != newCred, ERROR);

    //Assigning credId to the newCred
    newCred->credId = GetCredId();
leechul's avatar
leechul committed
611

612
    VERIFY_SUCCESS(TAG, newCred->credId != 0, ERROR);
Sachin Agrawal's avatar
Sachin Agrawal committed
613 614 615

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

leechul's avatar
leechul committed
617
    if(UpdatePersistentStorage(gCred))
Sachin Agrawal's avatar
Sachin Agrawal committed
618
    {
619 620 621 622 623 624 625 626 627 628 629 630 631
        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
632

633 634
    LL_FOREACH_SAFE(gCred, cred, tempCred)
    {
leechul's avatar
leechul committed
635
        if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
Sachin Agrawal's avatar
Sachin Agrawal committed
636
        {
637 638 639
            LL_DELETE(gCred, cred);
            FreeCred(cred);
            deleteFlag = 1;
Sachin Agrawal's avatar
Sachin Agrawal committed
640 641 642
        }
    }

leechul's avatar
leechul committed
643
    if(deleteFlag)
644
    {
leechul's avatar
leechul committed
645
        if(UpdatePersistentStorage(gCred))
646 647 648 649
        {
            ret = OC_STACK_RESOURCE_DELETED;
        }
    }
Sachin Agrawal's avatar
Sachin Agrawal committed
650
    return ret;
651

Sachin Agrawal's avatar
Sachin Agrawal committed
652 653
}

654 655 656 657 658 659 660 661 662 663 664 665
/**
 * 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();

leechul's avatar
leechul committed
666
    if(!UpdatePersistentStorage(gCred))
667 668 669 670 671 672
    {
        return OC_STACK_ERROR;
    }
    return OC_STACK_OK;
}

673 674
#ifdef __WITH_DTLS__
/**
675
 * Internal function to fill private data of owner PSK.
676
 *
677
 * @param receviedCred recevied owner credential from OBT(PT)
678 679 680
 * @param ownerAdd address of OBT(PT)
 * @param doxm current device's doxm resource
 *
leechul's avatar
leechul committed
681
 * @retval
682 683
 *     true successfully done and valid ower psk information
 *     false Invalid owner psk information or failed to owner psk generation
684
 */
685
static bool FillPrivateDataOfOwnerPSK(OicSecCred_t* receviedCred, const CAEndpoint_t* ownerAddr,
686 687 688 689 690 691 692 693 694 695 696 697 698 699
                           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);

700 701 702 703
    OIC_LOG(DEBUG, TAG, "OwnerPSK dump :");
    OIC_LOG_BUFFER(DEBUG, TAG, ownerPSK, OWNER_PSK_LENGTH_128);

    //Generate owner credential based on recevied credential information
leechul's avatar
leechul committed
704 705 706 707 708 709 710 711 712 713 714 715
    size_t b64BufSize = B64ENCODE_OUT_SAFESIZE(OWNER_PSK_LENGTH_128 * sizeof(char));
    uint8_t* encodeBuff = OICMalloc((b64BufSize + 1) * sizeof(char));
    VERIFY_NON_NULL(TAG, encodeBuff, ERROR);
    uint32_t encodedSize = 0;
    B64Result b64Ret = b64Encode(ownerPSK, OWNER_PSK_LENGTH_128,
                                 (char*)encodeBuff, b64BufSize + 1, &encodedSize);
    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
    encodeBuff[encodedSize] = '\0';

    //memory re-allocation for private data
    OICFree(receviedCred->privateData.data);
    receviedCred->privateData.data = (char*)OICMalloc((encodedSize + 1) * sizeof(char));
716
    VERIFY_NON_NULL(TAG, receviedCred->privateData.data, ERROR);
leechul's avatar
leechul committed
717 718 719

    //fill the base64 encoded private data
    strncpy(receviedCred->privateData.data, (char*)encodeBuff, b64BufSize + 1);
720

721 722
    OIC_LOG(INFO, TAG, "PrivateData of OwnerPSK was calculated successfully");

leechul's avatar
leechul committed
723 724 725
    //deallocate local memory
    OICFree(encodeBuff);

726 727 728
    //Verify OwnerPSK information
    return (memcmp(&(receviedCred->subject), &(doxm->owner), sizeof(OicUuid_t)) == 0 &&
            receviedCred->credType == SYMMETRIC_PAIR_WISE_KEY);
729
exit:
730
    //receviedCred->privateData.data will be deallocated when deleting credential.
leechul's avatar
leechul committed
731
    OICFree(encodeBuff);
732 733 734 735 736 737 738 739 740 741
    return false;
}

#endif //__WITH_DTLS__

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

    //Get binary representation of json
leechul's avatar
leechul committed
742 743 744
    OicSecCred_t * cred  = JSONToCredBin(((OCSecurityPayload*)ehRequest->payload)->securityData);

    if(cred)
745 746 747 748 749 750 751 752 753 754 755 756
    {
#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;
757
                    if(FillPrivateDataOfOwnerPSK(cred, (CAEndpoint_t *)&request->devAddr, doxm))
758
                    {
759 760 761 762 763 764
                        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.");
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
                        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;
                    }

781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
                    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;
                        }
                    }

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

            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();
            }
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
        }
        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__
    }

leechul's avatar
leechul committed
870
    if(OC_EH_RESOURCE_CREATED != ret)
871 872 873 874 875 876 877 878
    {
        if(OC_STACK_OK != RemoveCredential(&cred->subject))
        {
            OIC_LOG(WARNING, TAG, "Failed to remove the invalid credential");
        }
        FreeCred(cred);
    }

879 880 881
    return ret;
}

Sachin Agrawal's avatar
Sachin Agrawal committed
882 883 884 885
static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
{
    OCEntityHandlerResult ret = OC_EH_ERROR;

leechul's avatar
leechul committed
886 887 888 889
    //Get binary representation of json
    OicSecCred_t * cred  = JSONToCredBin(((OCSecurityPayload*)ehRequest->payload)->securityData);

    if(cred)
Sachin Agrawal's avatar
Sachin Agrawal committed
890
    {
891 892 893 894
        //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.
895
        ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
Sachin Agrawal's avatar
Sachin Agrawal committed
896
    }
897

Sachin Agrawal's avatar
Sachin Agrawal committed
898 899 900
    return ret;
}

901 902
static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *ehRequest)
{
903
    OIC_LOG(DEBUG, TAG, "Processing CredDeleteRequest");
904 905 906

    OCEntityHandlerResult ehRet = OC_EH_ERROR;

leechul's avatar
leechul committed
907
    if(NULL == ehRequest->query)
908 909 910 911
   {
       return ehRet;
   }

leechul's avatar
leechul committed
912
   OicParseQueryIter_t parseIter = {.attrPos=NULL};
913 914 915 916
   OicUuid_t subject = {.id={0}};

   //Parsing REST query to get the subject
   ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
leechul's avatar
leechul committed
917
   while(GetNextQuery(&parseIter))
918
   {
leechul's avatar
leechul committed
919
       if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME,
920 921
               parseIter.attrLen) == 0)
       {
leechul's avatar
leechul committed
922 923 924 925 926 927 928 929 930
           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);
931 932 933
       }
   }

leechul's avatar
leechul committed
934
   if(OC_STACK_RESOURCE_DELETED == RemoveCredential(&subject))
935 936 937 938
   {
       ehRet = OC_EH_RESOURCE_DELETED;
   }

leechul's avatar
leechul committed
939
exit:
940 941 942
    return ehRet;
}

leechul's avatar
leechul committed
943 944 945 946 947
/*
 * This internal method is the entity handler for Cred resources
 * to handle REST request (PUT/POST/DEL)
 */
OCEntityHandlerResult CredEntityHandler (OCEntityHandlerFlag flag,
948 949
                                        OCEntityHandlerRequest * ehRequest,
                                        void* callbackParameter)
Sachin Agrawal's avatar
Sachin Agrawal committed
950
{
Jon A. Cruz's avatar
Jon A. Cruz committed
951
    (void)callbackParameter;
Sachin Agrawal's avatar
Sachin Agrawal committed
952 953
    OCEntityHandlerResult ret = OC_EH_ERROR;

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

    //Send payload to request originator
leechul's avatar
leechul committed
983 984
    ret = (SendSRMResponse(ehRequest, ret, NULL) == OC_STACK_OK ?
                       ret : OC_EH_ERROR);
Sachin Agrawal's avatar
Sachin Agrawal committed
985 986 987 988

    return ret;
}

leechul's avatar
leechul committed
989 990 991
/*
 * This internal method is used to create '/oic/sec/Cred' resource.
 */
Sachin Agrawal's avatar
Sachin Agrawal committed
992 993
OCStackResult CreateCredResource()
{
leechul's avatar
leechul committed
994 995 996 997 998 999 1000 1001 1002
    OCStackResult ret;

    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
1003 1004 1005

    if (OC_STACK_OK != ret)
    {
1006
        OIC_LOG (FATAL, TAG, "Unable to instantiate Cred resource");
Sachin Agrawal's avatar
Sachin Agrawal committed
1007 1008 1009 1010 1011
        DeInitCredResource();
    }
    return ret;
}

leechul's avatar
leechul committed
1012 1013 1014 1015 1016 1017 1018
/**
 * Initialize Cred resource by loading data from persistent storage.
 *
 * @retval
 *     OC_STACK_OK    - no errors
 *     OC_STACK_ERROR - stack process error
 */
Sachin Agrawal's avatar
Sachin Agrawal committed
1019 1020 1021 1022 1023
OCStackResult InitCredResource()
{
    OCStackResult ret = OC_STACK_ERROR;

    //Read Cred resource from PS
leechul's avatar
leechul committed
1024 1025 1026
    char* jsonSVRDatabase = GetSVRDatabase();

    if (jsonSVRDatabase)
Sachin Agrawal's avatar
Sachin Agrawal committed
1027
    {
leechul's avatar
leechul committed
1028 1029
        //Convert JSON Cred into binary format
        gCred = JSONToCredBin(jsonSVRDatabase);
Sachin Agrawal's avatar
Sachin Agrawal committed
1030 1031 1032 1033 1034 1035
    }
    /*
     * 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.
     */
leechul's avatar
leechul committed
1036
    if (!jsonSVRDatabase || !gCred)
Sachin Agrawal's avatar
Sachin Agrawal committed
1037 1038 1039 1040 1041
    {
        gCred = GetCredDefault();
    }
    //Instantiate 'oic.sec.cred'
    ret = CreateCredResource();
leechul's avatar
leechul committed
1042
    OICFree(jsonSVRDatabase);
Sachin Agrawal's avatar
Sachin Agrawal committed
1043 1044 1045
    return ret;
}

leechul's avatar
leechul committed
1046 1047 1048 1049 1050 1051 1052 1053 1054
/**
 * 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
 */
Sachin Agrawal's avatar
Sachin Agrawal committed
1055 1056 1057 1058 1059 1060 1061 1062
OCStackResult DeInitCredResource()
{
    OCStackResult result = OCDeleteResource(gCredHandle);
    DeleteCredList(gCred);
    gCred = NULL;
    return result;
}

leechul's avatar
leechul committed
1063 1064 1065 1066 1067 1068 1069 1070 1071
/**
 * 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
 */
Sachin Agrawal's avatar
Sachin Agrawal committed
1072 1073 1074 1075
const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject)
{
    OicSecCred_t *cred = NULL;

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

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


#if defined(__WITH_DTLS__)
leechul's avatar
leechul committed
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
/**
 * This internal callback is used by lower stack (i.e. CA layer) to
 * retrieve PSK credentials from RI security layer.
 *
 * @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.
 *
 * @return The number of bytes written to @p result or a value
 *         less than zero on error.
 */
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
1109
{
1110
    int32_t ret = -1;
Sachin Agrawal's avatar
Sachin Agrawal committed
1111

1112 1113 1114 1115
    if (NULL == result)
    {
        return ret;
    }
Sachin Agrawal's avatar
Sachin Agrawal committed
1116

1117 1118 1119 1120
    switch (type)
    {
        case CA_DTLS_PSK_HINT:
        case CA_DTLS_PSK_IDENTITY:
Sachin Agrawal's avatar
Sachin Agrawal committed
1121
            {
1122 1123 1124
                OicUuid_t deviceID = {.id={}};
                // Retrieve Device ID from doxm resource
                if ( OC_STACK_OK != GetDoxmDeviceID(&deviceID) )
Sachin Agrawal's avatar
Sachin Agrawal committed
1125
                {
1126
                    OIC_LOG (ERROR, TAG, "Unable to retrieve doxm Device ID");
1127
                    return ret;