Merge branch 'master' into 'security-basecamp'
[platform/upstream/iotivity.git] / resource / csdk / security / src / credresource.c
1 //******************************************************************
2 //
3 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 #define __STDC_LIMIT_MACROS
22 #include "ocstack.h"
23 #include "logger.h"
24 #include "oic_malloc.h"
25 #include "cJSON.h"
26 #include "resourcemanager.h"
27 #include "psinterface.h"
28 #include "utlist.h"
29 #include "srmresourcestrings.h"
30 #include "credresource.h"
31 #include "ocrandom.h"
32 #include "doxmresource.h"
33 #include "base64.h"
34 #include "srmutility.h"
35 #include "cainterface.h"
36 #include <stdlib.h>
37 #ifdef WITH_ARDUINO
38 #include <string.h>
39 #else
40 #include <strings.h>
41 #endif
42 #include <stdint.h>
43
44
45 #define TAG  PCF("SRM-CREDL")
46
47 static OicSecCred_t        *gCred = NULL;
48 static OCResourceHandle    gCredHandle = NULL;
49
50 /**
51  * This function frees OicSecCred_t object's fields and object itself.
52  */
53 static void FreeCred(OicSecCred_t *cred)
54 {
55     if(NULL == cred)
56     {
57         OC_LOG (INFO, TAG, PCF("Invalid Parameter"));
58         return;
59     }
60     //Note: Need further clarification on roleID data type
61 #if 0
62     //Clean roleIds
63     OICFree(cred->roleIds);
64 #endif
65
66     //Clean PublicData
67     OICFree(cred->publicData.data);
68
69     //Clean PrivateData
70     OICFree(cred->privateData.data);
71
72     //Clean Period
73     OICFree(cred->period);
74
75     //Clean Owners
76     OICFree(cred->owners);
77
78     //Clean Cred node itself
79     OICFree(cred);
80 }
81
82 void DeleteCredList(OicSecCred_t* cred)
83 {
84     if (cred)
85     {
86         OicSecCred_t *credTmp1 = NULL, *credTmp2 = NULL;
87         LL_FOREACH_SAFE(cred, credTmp1, credTmp2)
88         {
89             LL_DELETE(cred, credTmp1);
90             FreeCred(credTmp1);
91         }
92     }
93 }
94
95 /**
96  * This function converts credential data into JSON format.
97  * Caller needs to invoke 'free' when done using
98  * returned string.
99  * @param cred  pointer to instance of OicSecCred_t structure.
100  *
101  * @retval
102  *      pointer to JSON credential representation - if credential for subjectId found
103  *      NULL                                      - if credential for subjectId not found
104  */
105 char * BinToCredJSON(const OicSecCred_t * cred)
106 {
107     cJSON *jsonRoot = NULL;
108     char *jsonStr = NULL;
109
110     if (cred)
111     {
112         char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
113         uint32_t outLen = 0;
114         B64Result b64Ret = B64_OK;
115
116         jsonRoot = cJSON_CreateObject();
117         VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
118
119         cJSON *jsonCredArray = NULL;
120         cJSON_AddItemToObject(jsonRoot, OIC_JSON_CRED_NAME,
121                 jsonCredArray = cJSON_CreateArray());
122         VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
123
124         while(cred)
125         {
126             cJSON *jsonCred = cJSON_CreateObject();
127             VERIFY_NON_NULL(TAG, jsonCred, ERROR);
128
129             //CredID -- Mandatory
130             cJSON_AddNumberToObject(jsonCred, OIC_JSON_CREDID_NAME, (int)cred->credId);
131
132             //Subject -- Mandatory
133             outLen = 0;
134             memset(base64Buff, 0, sizeof(base64Buff));
135             b64Ret = b64Encode(cred->subject.id, sizeof(cred->subject.id), base64Buff,
136                    sizeof(base64Buff), &outLen);
137             VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
138             cJSON_AddStringToObject(jsonCred, OIC_JSON_SUBJECT_NAME, base64Buff);
139
140             //Note: Need further clarification on roleID data type
141 #if 0
142             //RoleId -- Not Mandatory
143             if(cred->roleIdsLen > 0)
144             {
145                 cJSON *jsonRoleIdsArray = NULL;
146                 cJSON_AddItemToObject (jsonCred, OIC_JSON_ROLEIDS_NAME,
147                                          jsonRoleIdsArray = cJSON_CreateArray());
148                 VERIFY_NON_NULL(TAG, jsonRoleIdsArray, ERROR);
149                 for (size_t i = 0; i < cred->roleIdsLen; i++)
150                 {
151                     cJSON_AddItemToArray (jsonRoleIdsArray,
152                             cJSON_CreateString((char *)cred->roleIds[i].id));
153                 }
154             }
155 #endif
156
157             //CredType -- Mandatory
158             cJSON_AddNumberToObject(jsonCred, OIC_JSON_CREDTYPE_NAME,(int)cred->credType);
159
160 #if 0
161             //PublicData -- Not Mandatory
162             if(cred->publicData.data)
163             {
164                 cJSON_AddStringToObject(jsonCred, OIC_JSON_PUBLICDATA_NAME, cred->publicData.data);
165             }
166 #endif
167             //PrivateData -- Not Mandatory
168             if(cred->privateData.data)
169             {
170                 cJSON_AddStringToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME, cred->privateData.data);
171             }
172
173             //Period -- Not Mandatory
174             if(cred->period)
175             {
176                 cJSON_AddStringToObject(jsonCred, OIC_JSON_PERIOD_NAME,
177                                         cred->period);
178             }
179
180             //Owners -- Mandatory
181             cJSON *jsonOwnrArray = NULL;
182             cJSON_AddItemToObject (jsonCred, OIC_JSON_OWNERS_NAME,
183                                              jsonOwnrArray = cJSON_CreateArray());
184             VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
185             for (size_t i = 0; i < cred->ownersLen; i++)
186             {
187                 outLen = 0;
188                 memset(base64Buff, 0, sizeof(base64Buff));
189                 b64Ret = b64Encode(cred->owners[i].id, sizeof(cred->owners[i].id),
190                         base64Buff, sizeof(base64Buff), &outLen);
191                 VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
192                 cJSON_AddItemToArray (jsonOwnrArray,
193                                        cJSON_CreateString((char *)(base64Buff)));
194             }
195
196             /* Attach current cred node to cred Array */
197             cJSON_AddItemToArray(jsonCredArray, jsonCred);
198             cred = cred->next;
199         }
200
201         jsonStr = cJSON_PrintUnformatted(jsonRoot);
202     }
203
204 exit:
205     if (jsonRoot)
206     {
207         cJSON_Delete(jsonRoot);
208     }
209     return jsonStr;
210 }
211
212 /*
213  * This internal method converts JSON cred into binary cred.
214  */
215 OicSecCred_t * JSONToCredBin(const char * jsonStr)
216 {
217     OCStackResult ret = OC_STACK_ERROR;
218     OicSecCred_t * headCred = NULL;
219     OicSecCred_t * prevCred = NULL;
220     cJSON *jsonCredArray = NULL;
221
222     cJSON *jsonRoot = cJSON_Parse(jsonStr);
223     VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
224
225     jsonCredArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
226     VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
227     if (cJSON_Array == jsonCredArray->type)
228     {
229         int numCred = cJSON_GetArraySize(jsonCredArray);
230         int idx = 0;
231
232         unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
233         uint32_t outLen = 0;
234         B64Result b64Ret = B64_OK;
235
236         VERIFY_SUCCESS(TAG, numCred > 0, ERROR);
237         do
238         {
239             cJSON *jsonCred = cJSON_GetArrayItem(jsonCredArray, idx);
240             VERIFY_NON_NULL(TAG, jsonCred, ERROR);
241
242             OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
243             VERIFY_NON_NULL(TAG, cred, ERROR);
244
245             headCred = (headCred) ? headCred : cred;
246             if (prevCred)
247             {
248                 prevCred->next = cred;
249             }
250             size_t jsonObjLen = 0;
251             cJSON *jsonObj = NULL;
252
253             //CredId -- Mandatory
254             jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDID_NAME);
255             if(jsonObj)
256             {
257                 VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
258                 cred->credId = jsonObj->valueint;
259             }
260
261             //subject -- Mandatory
262             jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_SUBJECT_NAME);
263             VERIFY_NON_NULL(TAG, jsonObj, ERROR);
264             VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
265             outLen = 0;
266             memset(base64Buff, 0, sizeof(base64Buff));
267             b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring),
268                     base64Buff, sizeof(base64Buff), &outLen);
269             VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(cred->subject.id)),
270                            ERROR);
271             memcpy(cred->subject.id, base64Buff, outLen);
272
273             //CredType -- Mandatory
274             jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDTYPE_NAME);
275             VERIFY_NON_NULL(TAG, jsonObj, ERROR);
276             VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
277             cred->credType = jsonObj->valueint;
278
279             //PrivateData is mandatory for some of the credential types listed below.
280             jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PRIVATEDATA_NAME);
281             if ((cred->credType & SYMMETRIC_PAIR_WISE_KEY) ||
282                 (cred->credType & SYMMETRIC_GROUP_KEY) ||
283                 (cred->credType & PIN_PASSWORD))
284             {
285                 VERIFY_NON_NULL(TAG, jsonObj, ERROR);
286                 VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
287             }
288             if(jsonObj && cJSON_String == jsonObj->type)
289             {
290                 jsonObjLen = strlen(jsonObj->valuestring) + 1;
291                 cred->privateData.data = (char *)OICMalloc(jsonObjLen);
292                 VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
293                 strncpy((char *)cred->privateData.data, (char *)jsonObj->valuestring, jsonObjLen);
294             }
295
296             //Period -- Not Mandatory
297             jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PERIOD_NAME);
298             if(jsonObj && cJSON_String == jsonObj->type)
299             {
300                 jsonObjLen = strlen(jsonObj->valuestring) + 1;
301                 cred->period = (char *)OICMalloc(jsonObjLen);
302                 VERIFY_NON_NULL(TAG, cred->period, ERROR);
303                 strncpy(cred->period, jsonObj->valuestring, jsonObjLen);
304             }
305
306             //Owners -- Mandatory
307             jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_OWNERS_NAME);
308             VERIFY_NON_NULL(TAG, jsonObj, ERROR);
309             VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR)
310             cred->ownersLen = cJSON_GetArraySize(jsonObj);
311             VERIFY_SUCCESS(TAG, cred->ownersLen > 0, ERROR);
312             cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
313             VERIFY_NON_NULL(TAG, (cred->owners), ERROR);
314             for(size_t i = 0; i < cred->ownersLen; i++)
315             {
316                 cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, i);
317                 VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
318                 VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
319                 outLen = 0;
320                 memset(base64Buff, 0, sizeof(base64Buff));
321                 b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring),
322                          base64Buff, sizeof(base64Buff), &outLen);
323                 VERIFY_SUCCESS(TAG, (b64Ret == B64_OK &&
324                                outLen <= sizeof(cred->owners[i].id)), ERROR);
325                 memcpy(cred->owners[i].id, base64Buff, outLen);
326             }
327             prevCred = cred;
328         } while( ++idx < numCred);
329     }
330
331     ret = OC_STACK_OK;
332
333 exit:
334     cJSON_Delete(jsonRoot);
335     if (OC_STACK_OK != ret)
336     {
337         DeleteCredList(headCred);
338         headCred = NULL;
339     }
340     return headCred;
341 }
342
343 /**
344  * This function generates the bin credential data.
345  *
346  * @param subject pointer to subject of this credential.
347  * @param credType credential type.
348  * @param publicData public data such as public key.
349  * @param privateData private data such as private key.
350  *        The privateData is expected in base64 encoded format.
351  * @param ownersLen length of owners array
352  * @param owners array of owners.
353  *
354  * @retval
355  *      pointer to instance of OicSecCred_t  - success
356  *      NULL                                 - error
357  */
358 OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t credType,
359                                  const char * publicData, const char * privateData,
360                                  size_t ownersLen, const OicUuid_t * owners)
361 {
362     (void)publicData;
363     OCStackResult ret = OC_STACK_ERROR;
364
365     OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
366     VERIFY_NON_NULL(TAG, cred, ERROR);
367
368     //CredId is assigned before appending new cred to the existing
369     //credential list and updating svr database in AddCredential().
370     cred->credId = 0;
371
372     VERIFY_NON_NULL(TAG, subject, ERROR);
373     memcpy(cred->subject.id, subject->id , sizeof(cred->subject.id));
374
375     VERIFY_SUCCESS(TAG, credType < (NO_SECURITY_MODE | SYMMETRIC_PAIR_WISE_KEY |
376             SYMMETRIC_GROUP_KEY | ASYMMETRIC_KEY | SIGNED_ASYMMETRIC_KEY | PIN_PASSWORD), ERROR);
377     cred->credType = credType;
378
379 #if 0
380     if(publicData)
381     {
382         cred->publicData.data = (char *)OICMalloc(strlen(publicData)+1);
383         VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
384         strncpy((char *)cred->publicData.data, publicData, strlen(publicData)+1);
385     }
386 #endif
387
388     if(privateData)
389     {
390         cred->privateData.data = (char *)OICMalloc(strlen(privateData)+1);
391         VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
392         strncpy((char *)cred->privateData.data, privateData, strlen(privateData)+1);
393     }
394
395     VERIFY_SUCCESS(TAG, ownersLen > 0, ERROR);
396     cred->ownersLen = ownersLen;
397
398     cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
399     VERIFY_NON_NULL(TAG, cred->owners, ERROR);
400     for(size_t i = 0; i < cred->ownersLen; i++)
401     {
402         memcpy(cred->owners[i].id, owners[i].id, sizeof(cred->owners[i].id));
403     }
404
405     ret = OC_STACK_OK;
406 exit:
407     if (OC_STACK_OK != ret)
408     {
409         DeleteCredList(cred);
410         cred = NULL;
411     }
412     return cred;
413 }
414
415 static bool UpdatePersistentStorage(const OicSecCred_t *cred)
416 {
417     bool ret = false;
418
419     // Convert Cred data into JSON for update to persistent storage
420     char *jsonStr = BinToCredJSON(cred);
421     if (jsonStr)
422     {
423         cJSON *jsonCred = cJSON_Parse(jsonStr);
424         OICFree(jsonStr);
425
426         if ((jsonCred) &&
427           (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, jsonCred)))
428         {
429             ret = true;
430         }
431         cJSON_Delete(jsonCred );
432     }
433     else //Empty cred list
434     {
435         if (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, NULL))
436         {
437             ret = true;
438         }
439     }
440     return ret;
441 }
442
443 /**
444  * Compare function used LL_SORT for sorting credentials
445  *
446  * @param first   pointer to OicSecCred_t struct
447  * @param second  pointer to OicSecCred_t struct
448  *
449  *@retval
450  *  -1    if credId of first is less than credId of second
451  *   0    if credId of first is equal to credId of second
452  *   1    if credId of first is greater than credId of second
453  */
454 static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
455 {
456     if(first->credId < second->credId)
457     {
458         return -1;
459     }
460     else if(first->credId > second->credId)
461     {
462         return 1;
463     }
464     else
465         return 0;
466 }
467
468 /**
469  * GetCredId goes through the cred list and returns the next
470  * available credId. The next credId could be the credId that is
471  * available due deletion of OicSecCred_t object or one more than
472  * credId of last credential in the list.
473  *
474  * @retval
475  *      next available credId  - success
476  *      0                      - error
477  */
478
479 static uint16_t GetCredId()
480 {
481     //Sorts credential list in incremental order of credId
482     LL_SORT(gCred, CmpCredId);
483
484
485     OicSecCred_t *currentCred = NULL, *credTmp = NULL;
486     uint16_t nextCredId = 1;
487
488     LL_FOREACH_SAFE(gCred, currentCred, credTmp)
489     {
490         if(currentCred->credId == nextCredId)
491         {
492             nextCredId += 1;
493         }
494         else
495         {
496             break;
497         }
498     }
499
500     VERIFY_SUCCESS(TAG, nextCredId < UINT16_MAX, ERROR);
501     return nextCredId;
502
503 exit:
504     return 0;
505 }
506
507
508 /**
509  * This function adds the new cred to the credential list.
510  *
511  * @param cred pointer to new credential.
512  *
513  * @retval
514  *      OC_STACK_OK     - cred not NULL and persistent storage gets updated
515  *      OC_STACK_ERROR  - cred is NULL or fails to update persistent storage
516  */
517 OCStackResult AddCredential(OicSecCred_t * newCred)
518 {
519     OCStackResult ret = OC_STACK_ERROR;
520     char * jsonStr = NULL;
521
522     VERIFY_SUCCESS(TAG, NULL != newCred, ERROR);
523
524     //Assigning credId to the newCred
525     newCred->credId = GetCredId();
526
527     VERIFY_SUCCESS(TAG, newCred->credId != 0, ERROR);
528
529     //Append the new Cred to existing list
530     LL_APPEND(gCred, newCred);
531
532     if(UpdatePersistentStorage(gCred))
533     {
534         ret = OC_STACK_OK;
535     }
536
537 exit:
538     return ret;
539 }
540
541 OCStackResult RemoveCredential(const OicUuid_t *subject)
542 {
543     OCStackResult ret = OC_STACK_ERROR;
544     OicSecCred_t *cred = NULL;
545     OicSecCred_t *tempCred = NULL;
546     bool deleteFlag = false;
547
548     LL_FOREACH_SAFE(gCred, cred, tempCred)
549     {
550         if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
551         {
552             LL_DELETE(gCred, cred);
553             FreeCred(cred);
554             deleteFlag = 1;
555         }
556     }
557
558     if(deleteFlag)
559     {
560         if(UpdatePersistentStorage(gCred))
561         {
562             ret = OC_STACK_RESOURCE_DELETED;
563         }
564     }
565     return ret;
566
567 }
568
569 static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
570 {
571     OCEntityHandlerResult ret = OC_EH_ERROR;
572
573     //Get binary representation of json
574     OicSecCred_t * cred  = JSONToCredBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
575
576     if(cred)
577     {
578         //If the Post request credential has credId, it will be
579         //discarded and the next available credId will be assigned
580         //to it before getting appended to the existing credential
581         //list and updating svr database.
582         ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
583     }
584
585     return ret;
586 }
587
588 static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *ehRequest)
589 {
590     OC_LOG_V (INFO, TAG, PCF("Processing CredDeleteRequest"));
591
592     OCEntityHandlerResult ehRet = OC_EH_ERROR;
593
594     if(NULL == ehRequest->query)
595    {
596        return ehRet;
597    }
598
599    OicParseQueryIter_t parseIter = {.attrPos=NULL};
600    OicUuid_t subject = {.id={0}};
601
602    //Parsing REST query to get the subject
603    ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
604    while(GetNextQuery(&parseIter))
605    {
606        if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME,
607                parseIter.attrLen) == 0)
608        {
609            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
610            uint32_t outLen = 0;
611            B64Result b64Ret = B64_OK;
612
613            b64Ret = b64Decode((char *)parseIter.valPos, parseIter.valLen,
614                    base64Buff, sizeof(base64Buff), &outLen);
615
616            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(subject.id)), ERROR);
617            memcpy(subject.id, base64Buff, outLen);
618        }
619    }
620
621    if(OC_STACK_RESOURCE_DELETED == RemoveCredential(&subject))
622    {
623        ehRet = OC_EH_RESOURCE_DELETED;
624    }
625
626 exit:
627     return ehRet;
628 }
629
630
631 /*
632  * This internal method is the entity handler for Cred resources
633  * to handle REST request (PUT/POST/DEL)
634  */
635 OCEntityHandlerResult CredEntityHandler (OCEntityHandlerFlag flag,
636                                         OCEntityHandlerRequest * ehRequest,
637                                         void* callbackParameter)
638 {
639     (void)callbackParameter;
640     OCEntityHandlerResult ret = OC_EH_ERROR;
641
642     if(!ehRequest)
643     {
644         return OC_EH_ERROR;
645     }
646     if (flag & OC_REQUEST_FLAG)
647     {
648         OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
649         //TODO :  Handle PUT/DEL methods
650         switch(ehRequest->method)
651         {
652             case OC_REST_GET:
653                 ret = OC_EH_FORBIDDEN;
654                 break;
655             case OC_REST_POST:
656                 ret = HandlePostRequest(ehRequest);
657                 break;
658             case OC_REST_DELETE:
659                 ret = HandleDeleteRequest(ehRequest);
660                 break;
661             default:
662                 ret = OC_EH_ERROR;
663                 break;
664         }
665     }
666
667     //Send payload to request originator
668     ret = (SendSRMResponse(ehRequest, ret, NULL) == OC_STACK_OK ?
669                        ret : OC_EH_ERROR);
670
671     return ret;
672 }
673
674 /*
675  * This internal method is used to create '/oic/sec/Cred' resource.
676  */
677 OCStackResult CreateCredResource()
678 {
679     OCStackResult ret;
680
681     ret = OCCreateResource(&gCredHandle,
682                            OIC_RSRC_TYPE_SEC_CRED,
683                            OIC_MI_DEF,
684                            OIC_RSRC_CRED_URI,
685                            CredEntityHandler,
686                            NULL,
687                            OC_RES_PROP_NONE);
688
689     if (OC_STACK_OK != ret)
690     {
691         OC_LOG (FATAL, TAG, PCF("Unable to instantiate Cred resource"));
692         DeInitCredResource();
693     }
694     return ret;
695 }
696
697 /**
698  * Get the default value
699  * @retval  NULL for now. Update it when we finalize the default info.
700  */
701 static OicSecCred_t* GetCredDefault()
702 {
703     return NULL;
704 }
705
706 /**
707  * Initialize Cred resource by loading data from persistent storage.
708  *
709  * @retval
710  *     OC_STACK_OK    - no errors
711  *     OC_STACK_ERROR - stack process error
712  */
713 OCStackResult InitCredResource()
714 {
715     OCStackResult ret = OC_STACK_ERROR;
716
717     //Read Cred resource from PS
718     char* jsonSVRDatabase = GetSVRDatabase();
719
720     if (jsonSVRDatabase)
721     {
722         //Convert JSON Cred into binary format
723         gCred = JSONToCredBin(jsonSVRDatabase);
724     }
725     /*
726      * If SVR database in persistent storage got corrupted or
727      * is not available for some reason, a default Cred is created
728      * which allows user to initiate Cred provisioning again.
729      */
730     if (!jsonSVRDatabase || !gCred)
731     {
732         gCred = GetCredDefault();
733     }
734     //Instantiate 'oic.sec.cred'
735     ret = CreateCredResource();
736     OICFree(jsonSVRDatabase);
737     return ret;
738 }
739
740 /**
741  * Perform cleanup for Cred resources.
742  *
743  * @return
744  *     OC_STACK_OK              - no errors
745  *     OC_STACK_ERROR           - stack process error
746  *     OC_STACK_NO_RESOURCE     - resource not found
747  *     OC_STACK_INVALID_PARAM   - invalid param
748  */
749 OCStackResult DeInitCredResource()
750 {
751     OCStackResult result = OCDeleteResource(gCredHandle);
752     DeleteCredList(gCred);
753     gCred = NULL;
754     return result;
755 }
756
757 /**
758  * This method is used by tinydtls/SRM to retrieve credential for given Subject.
759  *
760  * @param subject - subject for which credential is required.
761  *
762  * @retval
763  *     reference to OicSecCred_t - if credential is found
764  *     NULL                      - if credential not found
765  */
766 const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject)
767 {
768     OicSecCred_t *cred = NULL;
769
770    if ( NULL == subject)
771     {
772        return NULL;
773     }
774
775     LL_FOREACH(gCred, cred)
776     {
777         if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
778         {
779             return cred;
780         }
781     }
782     return NULL;
783 }
784
785
786 #if defined(__WITH_DTLS__)
787 /**
788  * This internal callback is used by lower stack (i.e. CA layer) to
789  * retrieve PSK credentials from RI security layer.
790  *
791  * Note: When finished, caller should initialize memory to zeros and
792  * invoke OICFree to delete @p credInfo.
793  *
794  * @param credInfo
795  *     binary blob containing PSK credentials
796  *
797  * @retval none
798  */
799 void GetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
800 {
801     CADtlsPskCredsBlob_t * caBlob = NULL;
802     if(credInfo)
803     {
804         caBlob = (CADtlsPskCredsBlob_t *)OICCalloc(sizeof(CADtlsPskCredsBlob_t), 1);
805         if (caBlob)
806         {
807             OicUuid_t deviceID = {};
808
809             // Retrieve Device ID from doxm resource and copy in PSK creds blob
810             VERIFY_SUCCESS(TAG, GetDoxmDeviceID(&deviceID) == OC_STACK_OK, ERROR);
811             memcpy(caBlob->identity, deviceID.id, sizeof(caBlob->identity));
812
813             OicSecCred_t *cred = NULL;
814             size_t count = 0;
815             LL_FOREACH(gCred, cred)
816             {
817                 // Currently, Iotivity supports only symmetric pair wise key credentials
818                 if (cred->credType == SYMMETRIC_PAIR_WISE_KEY)
819                 {
820                     ++count;
821                 }
822             }
823             caBlob->num = count;
824             if (caBlob->num)
825             {
826                 caBlob->creds =
827                     (OCDtlsPskCreds*) OICMalloc(caBlob->num * sizeof(OCDtlsPskCreds));
828                 VERIFY_NON_NULL(TAG, caBlob->creds, ERROR);
829
830                 unsigned int i = 0;
831                 LL_FOREACH(gCred, cred)
832                 {
833                     if ((cred->credType == SYMMETRIC_PAIR_WISE_KEY) &&
834                             (i < count))
835
836                     {
837                         // Copy subject ID
838                         memcpy(caBlob->creds[i].id, cred->subject.id,
839                                 sizeof(caBlob->creds[i].id));
840
841                         // Convert PSK from JSON to binary before copying
842                         uint32_t outLen = 0;
843                         B64Result b64Ret = b64Decode(cred->privateData.data,
844                                 strlen(cred->privateData.data), caBlob->creds[i].psk,
845                                 sizeof(caBlob->creds[i].psk), &outLen);
846                         VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
847                         i++;
848                     }
849                 }
850             }
851         }
852         *credInfo = caBlob;
853         // Return from here after making the credential list
854         return;
855     }
856
857 exit:
858     if (caBlob)
859     {
860         memset(caBlob->creds, 0, caBlob->num * sizeof(OCDtlsPskCreds));
861         OICFree(caBlob->creds);
862     }
863     OICFree(caBlob);
864 }
865 #endif /* __WITH_DTLS__ */