e7235b5eeee6d268a601409253ed303c9d843e12
[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 "pbkdf2.h"
37 #include <stdlib.h>
38 #include "iotvticalendar.h"
39 #ifdef WITH_ARDUINO
40 #include <string.h>
41 #else
42 #include <strings.h>
43 #endif
44 #include <stdint.h>
45
46 #define TAG  "SRM-CREDL"
47
48
49 static OicSecCred_t        *gCred = NULL;
50 static OCResourceHandle    gCredHandle = NULL;
51
52 /**
53  * This function frees OicSecCred_t object's fields and object itself.
54  */
55 static void FreeCred(OicSecCred_t *cred)
56 {
57     if(NULL == cred)
58     {
59         OC_LOG (ERROR, TAG, "Invalid Parameter");
60         return;
61     }
62     //Note: Need further clarification on roleID data type
63 #if 0
64     //Clean roleIds
65     OICFree(cred->roleIds);
66 #endif
67
68     //Clean PublicData
69     OICFree(cred->publicData.data);
70
71     //Clean PrivateData
72     OICFree(cred->privateData.data);
73
74     //Clean Period
75     OICFree(cred->period);
76
77     //Clean Owners
78     OICFree(cred->owners);
79
80     //Clean Cred node itself
81     OICFree(cred);
82 }
83
84 void DeleteCredList(OicSecCred_t* cred)
85 {
86     if (cred)
87     {
88         OicSecCred_t *credTmp1 = NULL, *credTmp2 = NULL;
89         LL_FOREACH_SAFE(cred, credTmp1, credTmp2)
90         {
91             LL_DELETE(cred, credTmp1);
92             FreeCred(credTmp1);
93         }
94     }
95 }
96
97 /**
98  * This function converts credential data into JSON format.
99  * Caller needs to invoke 'free' when done using
100  * returned string.
101  * @param cred  pointer to instance of OicSecCred_t structure.
102  *
103  * @retval
104  *      pointer to JSON credential representation - if credential for subjectId found
105  *      NULL                                      - if credential for subjectId not found
106  */
107 char * BinToCredJSON(const OicSecCred_t * cred)
108 {
109     cJSON *jsonRoot = NULL;
110     char *jsonStr = NULL;
111
112     if (cred)
113     {
114         char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
115         uint32_t outLen = 0;
116         B64Result b64Ret = B64_OK;
117
118         jsonRoot = cJSON_CreateObject();
119         VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
120
121         cJSON *jsonCredArray = NULL;
122         cJSON_AddItemToObject(jsonRoot, OIC_JSON_CRED_NAME,
123                 jsonCredArray = cJSON_CreateArray());
124         VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
125
126         while(cred)
127         {
128             cJSON *jsonCred = cJSON_CreateObject();
129             VERIFY_NON_NULL(TAG, jsonCred, ERROR);
130
131             //CredID -- Mandatory
132             cJSON_AddNumberToObject(jsonCred, OIC_JSON_CREDID_NAME, (int)cred->credId);
133
134             //Subject -- Mandatory
135             outLen = 0;
136             memset(base64Buff, 0, sizeof(base64Buff));
137             b64Ret = b64Encode(cred->subject.id, sizeof(cred->subject.id), base64Buff,
138                    sizeof(base64Buff), &outLen);
139             VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
140             cJSON_AddStringToObject(jsonCred, OIC_JSON_SUBJECT_NAME, base64Buff);
141
142             //Note: Need further clarification on roleID data type
143 #if 0
144             //RoleId -- Not Mandatory
145             if(cred->roleIdsLen > 0)
146             {
147                 cJSON *jsonRoleIdsArray = NULL;
148                 cJSON_AddItemToObject (jsonCred, OIC_JSON_ROLEIDS_NAME,
149                                          jsonRoleIdsArray = cJSON_CreateArray());
150                 VERIFY_NON_NULL(TAG, jsonRoleIdsArray, ERROR);
151                 for (size_t i = 0; i < cred->roleIdsLen; i++)
152                 {
153                     cJSON_AddItemToArray (jsonRoleIdsArray,
154                             cJSON_CreateString((char *)cred->roleIds[i].id));
155                 }
156             }
157 #endif
158
159             //CredType -- Mandatory
160             cJSON_AddNumberToObject(jsonCred, OIC_JSON_CREDTYPE_NAME,(int)cred->credType);
161
162 #ifdef __WITH_X509__
163             //PublicData -- Not Mandatory
164             if(cred->publicData.data)
165             {
166                 if (SIGNED_ASYMMETRIC_KEY == cred->credType)
167                 {
168                     cJSON_AddItemToObject(jsonCred, OIC_JSON_PUBLICDATA_NAME,
169                                           cJSON_Parse(cred->publicData.data));
170                 }
171                 else
172                 {
173                 cJSON_AddStringToObject(jsonCred, OIC_JSON_PUBLICDATA_NAME, cred->publicData.data);
174                 }
175             }
176 #endif /*__WITH_X509__*/
177             //PrivateData -- Not Mandatory
178             if(cred->privateData.data)
179             {
180 #ifdef __WITH_X509__
181                 if (SIGNED_ASYMMETRIC_KEY == cred->credType)
182                 {
183                     cJSON_AddItemToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME,
184                                           cJSON_Parse(cred->privateData.data));
185                 }
186                 else
187                 {
188                     cJSON_AddStringToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME, cred->privateData.data);
189                 }
190 #else
191                 cJSON_AddStringToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME, cred->privateData.data);
192 #endif
193             }
194
195             //Period -- Not Mandatory
196             if(cred->period)
197             {
198                 cJSON_AddStringToObject(jsonCred, OIC_JSON_PERIOD_NAME,
199                                         cred->period);
200             }
201
202             //Owners -- Mandatory
203             cJSON *jsonOwnrArray = NULL;
204             cJSON_AddItemToObject (jsonCred, OIC_JSON_OWNERS_NAME,
205                                              jsonOwnrArray = cJSON_CreateArray());
206             VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
207             for (size_t i = 0; i < cred->ownersLen; i++)
208             {
209                 outLen = 0;
210                 memset(base64Buff, 0, sizeof(base64Buff));
211                 b64Ret = b64Encode(cred->owners[i].id, sizeof(cred->owners[i].id),
212                         base64Buff, sizeof(base64Buff), &outLen);
213                 VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
214                 cJSON_AddItemToArray (jsonOwnrArray,
215                                        cJSON_CreateString((char *)(base64Buff)));
216             }
217
218             /* Attach current cred node to cred Array */
219             cJSON_AddItemToArray(jsonCredArray, jsonCred);
220             cred = cred->next;
221         }
222
223         jsonStr = cJSON_PrintUnformatted(jsonRoot);
224     }
225
226 exit:
227     if (jsonRoot)
228     {
229         cJSON_Delete(jsonRoot);
230     }
231     return jsonStr;
232 }
233
234 /*
235  * This internal method converts JSON cred into binary cred.
236  */
237 OicSecCred_t * JSONToCredBin(const char * jsonStr)
238 {
239     OCStackResult ret = OC_STACK_ERROR;
240     OicSecCred_t * headCred = NULL;
241     OicSecCred_t * prevCred = NULL;
242     cJSON *jsonCredArray = NULL;
243
244     cJSON *jsonRoot = cJSON_Parse(jsonStr);
245     VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
246
247     jsonCredArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
248     VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
249     if (cJSON_Array == jsonCredArray->type)
250     {
251         int numCred = cJSON_GetArraySize(jsonCredArray);
252         int idx = 0;
253
254         unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
255         uint32_t outLen = 0;
256         B64Result b64Ret = B64_OK;
257
258         VERIFY_SUCCESS(TAG, numCred > 0, ERROR);
259         do
260         {
261             cJSON *jsonCred = cJSON_GetArrayItem(jsonCredArray, idx);
262             VERIFY_NON_NULL(TAG, jsonCred, ERROR);
263
264             OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
265             VERIFY_NON_NULL(TAG, cred, ERROR);
266
267             headCred = (headCred) ? headCred : cred;
268             if (prevCred)
269             {
270                 prevCred->next = cred;
271             }
272             size_t jsonObjLen = 0;
273             cJSON *jsonObj = NULL;
274
275             //CredId -- Mandatory
276             jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDID_NAME);
277             if(jsonObj)
278             {
279                 VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
280                 cred->credId = jsonObj->valueint;
281             }
282
283             //subject -- Mandatory
284             jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_SUBJECT_NAME);
285             VERIFY_NON_NULL(TAG, jsonObj, ERROR);
286             VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
287             outLen = 0;
288             memset(base64Buff, 0, sizeof(base64Buff));
289             b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring),
290                     base64Buff, sizeof(base64Buff), &outLen);
291             VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(cred->subject.id)),
292                            ERROR);
293             memcpy(cred->subject.id, base64Buff, outLen);
294
295             //CredType -- Mandatory
296             jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDTYPE_NAME);
297             VERIFY_NON_NULL(TAG, jsonObj, ERROR);
298             VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
299             cred->credType = (OicSecCredType_t)jsonObj->valueint;
300
301             //PrivateData is mandatory for some of the credential types listed below.
302             jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PRIVATEDATA_NAME);
303             if ((cred->credType & SYMMETRIC_PAIR_WISE_KEY) ||
304                 (cred->credType & SYMMETRIC_GROUP_KEY) ||
305                 (cred->credType & PIN_PASSWORD))
306             {
307                 VERIFY_NON_NULL(TAG, jsonObj, ERROR);
308                 VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
309             }
310 #ifdef __WITH_X509__
311             else if (cred->credType & SIGNED_ASYMMETRIC_KEY)
312             {
313                 VERIFY_NON_NULL(TAG, jsonObj, ERROR);
314                 VERIFY_SUCCESS(TAG, cJSON_Object == jsonObj->type, ERROR);
315             }
316 #endif //  __WITH_X509__
317             if (NULL != jsonObj)
318             {
319                 if (cJSON_String == jsonObj->type)
320                 {
321                     jsonObjLen = strlen(jsonObj->valuestring) + 1;
322                     cred->privateData.data = (char *)OICMalloc(jsonObjLen);
323                     VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
324                     strncpy((char *)cred->privateData.data, (char *)jsonObj->valuestring, jsonObjLen);
325                 }
326 #ifdef __WITH_X509__
327                 else if (SIGNED_ASYMMETRIC_KEY == cred->credType && cJSON_Object == jsonObj->type)
328                 {
329                     cred->privateData.data = cJSON_PrintUnformatted(jsonObj);
330                     VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
331                 }
332 #endif // __WITH_X509__
333             }
334
335             //PublicData is mandatory only for SIGNED_ASYMMETRIC_KEY credentials type.
336             jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PUBLICDATA_NAME);
337 #ifdef __WITH_X509__
338             if (cred->credType & SIGNED_ASYMMETRIC_KEY)
339             {
340                 VERIFY_NON_NULL(TAG, jsonObj, ERROR);
341                 VERIFY_SUCCESS(TAG, cJSON_Object == jsonObj->type, ERROR);
342             }
343 #endif //  __WITH_X509__
344             if (NULL != jsonObj)
345             {
346                 if (cJSON_String == jsonObj->type)
347                 {
348                     jsonObjLen = strlen(jsonObj->valuestring) + 1;
349                     cred->publicData.data = (char *)OICMalloc(jsonObjLen);
350                     VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
351                     strncpy((char *)cred->publicData.data, (char *)jsonObj->valuestring, jsonObjLen);
352                 }
353 #ifdef __WITH_X509__
354                 else if (SIGNED_ASYMMETRIC_KEY == cred->credType && cJSON_Object == jsonObj->type)
355                 {
356                     cred->publicData.data = cJSON_PrintUnformatted(jsonObj);
357                     VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
358                 }
359 #endif //  __WITH_X509__
360             }
361
362             //Period -- Not Mandatory
363             jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PERIOD_NAME);
364             if(jsonObj && cJSON_String == jsonObj->type)
365             {
366                 jsonObjLen = strlen(jsonObj->valuestring) + 1;
367                 cred->period = (char *)OICMalloc(jsonObjLen);
368                 VERIFY_NON_NULL(TAG, cred->period, ERROR);
369                 strncpy(cred->period, jsonObj->valuestring, jsonObjLen);
370             }
371
372             //Owners -- Mandatory
373             jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_OWNERS_NAME);
374             VERIFY_NON_NULL(TAG, jsonObj, ERROR);
375             VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
376             cred->ownersLen = cJSON_GetArraySize(jsonObj);
377             VERIFY_SUCCESS(TAG, cred->ownersLen > 0, ERROR);
378             cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
379             VERIFY_NON_NULL(TAG, (cred->owners), ERROR);
380             for(size_t i = 0; i < cred->ownersLen; i++)
381             {
382                 cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, i);
383                 VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
384                 VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
385                 outLen = 0;
386                 memset(base64Buff, 0, sizeof(base64Buff));
387                 b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring),
388                          base64Buff, sizeof(base64Buff), &outLen);
389                 VERIFY_SUCCESS(TAG, (b64Ret == B64_OK &&
390                                outLen <= sizeof(cred->owners[i].id)), ERROR);
391                 memcpy(cred->owners[i].id, base64Buff, outLen);
392             }
393             prevCred = cred;
394         } while( ++idx < numCred);
395     }
396
397     ret = OC_STACK_OK;
398
399 exit:
400     cJSON_Delete(jsonRoot);
401     if (OC_STACK_OK != ret)
402     {
403         DeleteCredList(headCred);
404         headCred = NULL;
405     }
406     return headCred;
407 }
408
409 /**
410  * This function generates the bin credential data.
411  *
412  * @param subject pointer to subject of this credential.
413  * @param credType credential type.
414  * @param publicData public data such as public key.
415  * @param privateData private data such as private key.
416  *        The privateData is expected in base64 encoded format.
417  * @param ownersLen length of owners array
418  * @param owners array of owners.
419  *
420  * @retval
421  *      pointer to instance of OicSecCred_t  - success
422  *      NULL                                 - error
423  */
424 OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t credType,
425                                  const char * publicData, const char * privateData,
426                                  size_t ownersLen, const OicUuid_t * owners)
427 {
428     (void)publicData;
429     OCStackResult ret = OC_STACK_ERROR;
430
431     OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
432     VERIFY_NON_NULL(TAG, cred, ERROR);
433
434     //CredId is assigned before appending new cred to the existing
435     //credential list and updating svr database in AddCredential().
436     cred->credId = 0;
437
438     VERIFY_NON_NULL(TAG, subject, ERROR);
439     memcpy(cred->subject.id, subject->id , sizeof(cred->subject.id));
440
441     VERIFY_SUCCESS(TAG, credType < (NO_SECURITY_MODE | SYMMETRIC_PAIR_WISE_KEY |
442             SYMMETRIC_GROUP_KEY | ASYMMETRIC_KEY | SIGNED_ASYMMETRIC_KEY | PIN_PASSWORD), ERROR);
443     cred->credType = credType;
444
445 #ifdef __WITH_X509__
446     if(publicData)
447     {
448         cred->publicData.data = (char *)OICMalloc(strlen(publicData)+1);
449         VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
450         strncpy((char *)cred->publicData.data, publicData, strlen(publicData)+1);
451     }
452 #endif // __WITH_X509__
453
454     if(privateData)
455     {
456         cred->privateData.data = (char *)OICMalloc(strlen(privateData)+1);
457         VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
458         strncpy((char *)cred->privateData.data, privateData, strlen(privateData)+1);
459     }
460
461     VERIFY_SUCCESS(TAG, ownersLen > 0, ERROR);
462     cred->ownersLen = ownersLen;
463
464     cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
465     VERIFY_NON_NULL(TAG, cred->owners, ERROR);
466     for(size_t i = 0; i < cred->ownersLen; i++)
467     {
468         memcpy(cred->owners[i].id, owners[i].id, sizeof(cred->owners[i].id));
469     }
470
471     ret = OC_STACK_OK;
472 exit:
473     if (OC_STACK_OK != ret)
474     {
475         DeleteCredList(cred);
476         cred = NULL;
477     }
478     return cred;
479 }
480
481 static bool UpdatePersistentStorage(const OicSecCred_t *cred)
482 {
483     bool ret = false;
484
485     // Convert Cred data into JSON for update to persistent storage
486     char *jsonStr = BinToCredJSON(cred);
487     if (jsonStr)
488     {
489         cJSON *jsonCred = cJSON_Parse(jsonStr);
490         OICFree(jsonStr);
491
492         if ((jsonCred) &&
493           (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, jsonCred)))
494         {
495             ret = true;
496         }
497         cJSON_Delete(jsonCred );
498     }
499     else //Empty cred list
500     {
501         if (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, NULL))
502         {
503             ret = true;
504         }
505     }
506     return ret;
507 }
508
509 /**
510  * Compare function used LL_SORT for sorting credentials
511  *
512  * @param first   pointer to OicSecCred_t struct
513  * @param second  pointer to OicSecCred_t struct
514  *
515  *@retval
516  *  -1    if credId of first is less than credId of second
517  *   0    if credId of first is equal to credId of second
518  *   1    if credId of first is greater than credId of second
519  */
520 static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
521 {
522     if(first->credId < second->credId)
523     {
524         return -1;
525     }
526     else if(first->credId > second->credId)
527     {
528         return 1;
529     }
530     else
531         return 0;
532 }
533
534 /**
535  * GetCredId goes through the cred list and returns the next
536  * available credId. The next credId could be the credId that is
537  * available due deletion of OicSecCred_t object or one more than
538  * credId of last credential in the list.
539  *
540  * @retval
541  *      next available credId  - success
542  *      0                      - error
543  */
544
545 static uint16_t GetCredId()
546 {
547     //Sorts credential list in incremental order of credId
548     LL_SORT(gCred, CmpCredId);
549
550
551     OicSecCred_t *currentCred = NULL, *credTmp = NULL;
552     uint16_t nextCredId = 1;
553
554     LL_FOREACH_SAFE(gCred, currentCred, credTmp)
555     {
556         if(currentCred->credId == nextCredId)
557         {
558             nextCredId += 1;
559         }
560         else
561         {
562             break;
563         }
564     }
565
566     VERIFY_SUCCESS(TAG, nextCredId < UINT16_MAX, ERROR);
567     return nextCredId;
568
569 exit:
570     return 0;
571 }
572
573
574 /**
575  * This function adds the new cred to the credential list.
576  *
577  * @param cred pointer to new credential.
578  *
579  * @retval
580  *      OC_STACK_OK     - cred not NULL and persistent storage gets updated
581  *      OC_STACK_ERROR  - cred is NULL or fails to update persistent storage
582  */
583 OCStackResult AddCredential(OicSecCred_t * newCred)
584 {
585     OCStackResult ret = OC_STACK_ERROR;
586
587     VERIFY_SUCCESS(TAG, NULL != newCred, ERROR);
588
589     //Assigning credId to the newCred
590     newCred->credId = GetCredId();
591
592     VERIFY_SUCCESS(TAG, newCred->credId != 0, ERROR);
593
594     //Append the new Cred to existing list
595     LL_APPEND(gCred, newCred);
596
597     if(UpdatePersistentStorage(gCred))
598     {
599         ret = OC_STACK_OK;
600     }
601
602 exit:
603     return ret;
604 }
605
606 OCStackResult RemoveCredential(const OicUuid_t *subject)
607 {
608     OCStackResult ret = OC_STACK_ERROR;
609     OicSecCred_t *cred = NULL;
610     OicSecCred_t *tempCred = NULL;
611     bool deleteFlag = false;
612
613     LL_FOREACH_SAFE(gCred, cred, tempCred)
614     {
615         if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
616         {
617             LL_DELETE(gCred, cred);
618             FreeCred(cred);
619             deleteFlag = 1;
620         }
621     }
622
623     if(deleteFlag)
624     {
625         if(UpdatePersistentStorage(gCred))
626         {
627             ret = OC_STACK_RESOURCE_DELETED;
628         }
629     }
630     return ret;
631
632 }
633
634 static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
635 {
636     OCEntityHandlerResult ret = OC_EH_ERROR;
637
638     //Get binary representation of json
639     OicSecCred_t * cred  = JSONToCredBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
640
641     if(cred)
642     {
643         //If the Post request credential has credId, it will be
644         //discarded and the next available credId will be assigned
645         //to it before getting appended to the existing credential
646         //list and updating svr database.
647         ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
648     }
649     return ret;
650 }
651
652 static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *ehRequest)
653 {
654     OC_LOG(DEBUG, TAG, "Processing CredDeleteRequest");
655
656     OCEntityHandlerResult ehRet = OC_EH_ERROR;
657
658     if(NULL == ehRequest->query)
659    {
660        return ehRet;
661    }
662
663    OicParseQueryIter_t parseIter = {.attrPos=NULL};
664    OicUuid_t subject = {.id={0}};
665
666    //Parsing REST query to get the subject
667    ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
668    while(GetNextQuery(&parseIter))
669    {
670        if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME,
671                parseIter.attrLen) == 0)
672        {
673            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
674            uint32_t outLen = 0;
675            B64Result b64Ret = B64_OK;
676
677            b64Ret = b64Decode((char *)parseIter.valPos, parseIter.valLen,
678                    base64Buff, sizeof(base64Buff), &outLen);
679
680            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(subject.id)), ERROR);
681            memcpy(subject.id, base64Buff, outLen);
682        }
683    }
684
685    if(OC_STACK_RESOURCE_DELETED == RemoveCredential(&subject))
686    {
687        ehRet = OC_EH_RESOURCE_DELETED;
688    }
689
690 exit:
691     return ehRet;
692 }
693
694 /*
695  * This internal method is the entity handler for Cred resources
696  * to handle REST request (PUT/POST/DEL)
697  */
698 OCEntityHandlerResult CredEntityHandler (OCEntityHandlerFlag flag,
699                                         OCEntityHandlerRequest * ehRequest,
700                                         void* callbackParameter)
701 {
702     (void)callbackParameter;
703     OCEntityHandlerResult ret = OC_EH_ERROR;
704
705     if(!ehRequest)
706     {
707         return OC_EH_ERROR;
708     }
709     if (flag & OC_REQUEST_FLAG)
710     {
711         OC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
712         //TODO :  Handle PUT/DEL methods
713         switch(ehRequest->method)
714         {
715             case OC_REST_GET:
716                 ret = OC_EH_FORBIDDEN;
717                 break;
718             case OC_REST_POST:
719                 ret = HandlePostRequest(ehRequest);
720                 break;
721             case OC_REST_DELETE:
722                 ret = HandleDeleteRequest(ehRequest);
723                 break;
724             default:
725                 ret = OC_EH_ERROR;
726                 break;
727         }
728     }
729
730     //Send payload to request originator
731     ret = (SendSRMResponse(ehRequest, ret, NULL) == OC_STACK_OK ?
732                        ret : OC_EH_ERROR);
733
734     return ret;
735 }
736
737 /*
738  * This internal method is used to create '/oic/sec/Cred' resource.
739  */
740 OCStackResult CreateCredResource()
741 {
742     OCStackResult ret;
743
744     ret = OCCreateResource(&gCredHandle,
745                            OIC_RSRC_TYPE_SEC_CRED,
746                            OIC_MI_DEF,
747                            OIC_RSRC_CRED_URI,
748                            CredEntityHandler,
749                            NULL,
750                            OC_RES_PROP_NONE);
751
752     if (OC_STACK_OK != ret)
753     {
754         OC_LOG (FATAL, TAG, "Unable to instantiate Cred resource");
755         DeInitCredResource();
756     }
757     return ret;
758 }
759
760 /**
761  * Get the default value
762  * @retval  NULL for now. Update it when we finalize the default info.
763  */
764 static OicSecCred_t* GetCredDefault()
765 {
766     return NULL;
767 }
768
769 /**
770  * Initialize Cred resource by loading data from persistent storage.
771  *
772  * @retval
773  *     OC_STACK_OK    - no errors
774  *     OC_STACK_ERROR - stack process error
775  */
776 OCStackResult InitCredResource()
777 {
778     OCStackResult ret = OC_STACK_ERROR;
779
780     //Read Cred resource from PS
781     char* jsonSVRDatabase = GetSVRDatabase();
782
783     if (jsonSVRDatabase)
784     {
785         //Convert JSON Cred into binary format
786         gCred = JSONToCredBin(jsonSVRDatabase);
787     }
788     /*
789      * If SVR database in persistent storage got corrupted or
790      * is not available for some reason, a default Cred is created
791      * which allows user to initiate Cred provisioning again.
792      */
793     if (!jsonSVRDatabase || !gCred)
794     {
795         gCred = GetCredDefault();
796     }
797     //Instantiate 'oic.sec.cred'
798     ret = CreateCredResource();
799     OICFree(jsonSVRDatabase);
800     return ret;
801 }
802
803 /**
804  * Perform cleanup for Cred resources.
805  *
806  * @return
807  *     OC_STACK_OK              - no errors
808  *     OC_STACK_ERROR           - stack process error
809  *     OC_STACK_NO_RESOURCE     - resource not found
810  *     OC_STACK_INVALID_PARAM   - invalid param
811  */
812 OCStackResult DeInitCredResource()
813 {
814     OCStackResult result = OCDeleteResource(gCredHandle);
815     DeleteCredList(gCred);
816     gCred = NULL;
817     return result;
818 }
819
820 /**
821  * This method is used by tinydtls/SRM to retrieve credential for given Subject.
822  *
823  * @param subject - subject for which credential is required.
824  *
825  * @retval
826  *     reference to OicSecCred_t - if credential is found
827  *     NULL                      - if credential not found
828  */
829 const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject)
830 {
831     OicSecCred_t *cred = NULL;
832
833    if ( NULL == subject)
834     {
835        return NULL;
836     }
837
838     LL_FOREACH(gCred, cred)
839     {
840         if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
841         {
842             return cred;
843         }
844     }
845     return NULL;
846 }
847
848
849 #if defined(__WITH_DTLS__)
850 /**
851  * This internal callback is used by lower stack (i.e. CA layer) to
852  * retrieve PSK credentials from RI security layer.
853  *
854  * @param[in]  type type of PSK data required by tinyDTLS layer during DTLS handshake.
855  * @param[in]  desc Additional request information.
856  * @param[in]  desc_len The actual length of desc.
857  * @param[out] result  Must be filled with the requested information.
858  * @param[in]  result_length  Maximum size of @p result.
859  *
860  * @return The number of bytes written to @p result or a value
861  *         less than zero on error.
862  */
863 int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
864               const unsigned char *desc, size_t desc_len,
865               unsigned char *result, size_t result_length)
866 {
867     int32_t ret = -1;
868
869     if (NULL == result)
870     {
871         return ret;
872     }
873
874     switch (type)
875     {
876         case CA_DTLS_PSK_HINT:
877         case CA_DTLS_PSK_IDENTITY:
878             {
879                 OicUuid_t deviceID = {.id={}};
880                 // Retrieve Device ID from doxm resource
881                 if ( OC_STACK_OK != GetDoxmDeviceID(&deviceID) )
882                 {
883                     OC_LOG (ERROR, TAG, "Unable to retrieve doxm Device ID");
884                     return ret;
885                 }
886
887                 if (result_length < sizeof(deviceID.id))
888                 {
889                     OC_LOG (ERROR, TAG, "Wrong value for result_length");
890                     return ret;
891                 }
892                 memcpy(result, deviceID.id, sizeof(deviceID.id));
893                 return (sizeof(deviceID.id));
894             }
895             break;
896
897         case CA_DTLS_PSK_KEY:
898             {
899                 OicSecCred_t *cred = NULL;
900                 LL_FOREACH(gCred, cred)
901                 {
902                     if (cred->credType != SYMMETRIC_PAIR_WISE_KEY)
903                     {
904                         continue;
905                     }
906
907                     if ((desc_len == sizeof(cred->subject.id)) &&
908                         (memcmp(desc, cred->subject.id, sizeof(cred->subject.id)) == 0))
909                     {
910                         /*
911                          * If the credentials are valid for limited time,
912                          * check their expiry.
913                          */
914                         if (cred->period)
915                         {
916                             if(IOTVTICAL_VALID_ACCESS != IsRequestWithinValidTime(cred->period, NULL))
917                             {
918                                 OC_LOG (INFO, TAG, "Credentials are expired.");
919                                 ret = -1;
920                                 return ret;
921                             }
922                         }
923
924                         // Convert PSK from Base64 encoding to binary before copying
925                         uint32_t outLen = 0;
926                         B64Result b64Ret = b64Decode(cred->privateData.data,
927                                 strlen(cred->privateData.data), result,
928                                 result_length, &outLen);
929                         if (B64_OK != b64Ret)
930                         {
931                             OC_LOG (ERROR, TAG, "Base64 decoding failed.");
932                             ret = -1;
933                             return ret;
934                         }
935                         return outLen;
936                     }
937                 }
938             }
939             break;
940
941         default:
942             {
943                 OC_LOG (ERROR, TAG, "Wrong value passed for CADtlsPskCredType_t.");
944                 ret = -1;
945             }
946             break;
947     }
948
949     return ret;
950 }
951
952 /**
953  * Add temporal PSK to PIN based OxM
954  *
955  * @param[in] tmpSubject UUID of target device
956  * @param[in] credType Type of credential to be added
957  * @param[in] pin numeric characters
958  * @param[in] pinSize length of 'pin'
959  * @param[in] ownersLen Number of owners
960  * @param[in] owners Array of owners
961  * @param[out] tmpCredSubject Generated credential's subject.
962  *
963  * @return OC_STACK_OK for success and errorcode otherwise.
964  */
965 OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t credType,
966                             const char * pin, size_t pinSize,
967                             size_t ownersLen, const OicUuid_t * owners, OicUuid_t* tmpCredSubject)
968 {
969     OCStackResult ret = OC_STACK_ERROR;
970
971     if(tmpSubject == NULL || pin == NULL || pinSize == 0 || tmpCredSubject == NULL)
972     {
973         return OC_STACK_INVALID_PARAM;
974     }
975
976     uint8_t privData[OWNER_PSK_LENGTH_128] = {0,};
977     int dtlsRes = DeriveCryptoKeyFromPassword((const unsigned char *)pin, pinSize, owners->id,
978                                               UUID_LENGTH, PBKDF_ITERATIONS,
979                                               OWNER_PSK_LENGTH_128, privData);
980     VERIFY_SUCCESS(TAG, (dtlsRes == 0) , ERROR);
981
982     uint32_t outLen = 0;
983     char base64Buff[B64ENCODE_OUT_SAFESIZE(OWNER_PSK_LENGTH_128) + 1] = {};
984     B64Result b64Ret = b64Encode(privData, OWNER_PSK_LENGTH_128, base64Buff,
985                                 sizeof(base64Buff), &outLen);
986     VERIFY_SUCCESS(TAG, (B64_OK == b64Ret), ERROR);
987
988     OicSecCred_t* cred = GenerateCredential(tmpSubject, credType, NULL,
989                                             base64Buff, ownersLen, owners);
990     if(NULL == cred)
991     {
992         OC_LOG(ERROR, TAG, "GeneratePskWithPIN() : Failed to generate credential");
993         return OC_STACK_ERROR;
994     }
995
996     memcpy(tmpCredSubject->id, cred->subject.id, UUID_LENGTH);
997
998     ret = AddCredential(cred);
999     if( OC_STACK_OK != ret)
1000     {
1001         OC_LOG(ERROR, TAG, "GeneratePskWithPIN() : Failed to add credential");
1002     }
1003
1004 exit:
1005     return ret;
1006 }
1007
1008 #endif /* __WITH_DTLS__ */
1009 #ifdef __WITH_X509__
1010 #define CERT_LEN_PREFIX (3)
1011 #define BYTE_SIZE (8) //bits
1012 #define PUB_KEY_X_COORD ("x")
1013 #define PUB_KEY_Y_COORD ("y")
1014 #define CERTIFICATE ("x5c")
1015 #define PRIVATE_KEY ("d")
1016
1017
1018 static void WriteCertPrefix(uint8_t *prefix, uint32_t certLen)
1019 {
1020     for (size_t i = 0; i < CERT_LEN_PREFIX; ++i)
1021     {
1022         prefix[i] = (certLen >> (BYTE_SIZE * (CERT_LEN_PREFIX - 1 - i))) & 0xFF;
1023     }
1024 }
1025
1026 static uint32_t ParseCertPrefix(uint8_t *prefix)
1027 {
1028     uint32_t res = 0;
1029     if(NULL != prefix)
1030     {
1031         for(int i=0; i < CERT_LEN_PREFIX; ++i)
1032         {
1033             res |= (((uint32_t) prefix[i]) << ((CERT_LEN_PREFIX - 1 -i) * BYTE_SIZE));
1034         }
1035     }
1036     return res;
1037 }
1038
1039 static uint32_t appendCert2Chain(uint8_t *appendPoint, char *cert, uint32_t max_len)
1040 {
1041     uint32_t ret = 0;
1042     VERIFY_NON_NULL(TAG, appendPoint, ERROR);
1043     VERIFY_NON_NULL(TAG, cert, ERROR);
1044
1045     uint32_t certLen;
1046     VERIFY_SUCCESS(TAG, B64_OK == b64Decode(cert, strlen(cert), appendPoint + CERT_LEN_PREFIX,
1047                                             max_len - CERT_LEN_PREFIX, &certLen), ERROR);
1048     WriteCertPrefix(appendPoint, certLen);
1049
1050     ret = certLen + CERT_LEN_PREFIX;
1051 exit:
1052     return ret;
1053 }
1054
1055 static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo){
1056     OCStackResult ret = OC_STACK_ERROR;
1057     uint8_t *ccPtr = credInfo->certificateChain;
1058     for(uint32_t i =0; i < credInfo->chainLen - 1; ++i)
1059     {
1060         ccPtr += CERT_LEN_PREFIX + ParseCertPrefix(ccPtr);
1061     }
1062
1063     ByteArray cert = {
1064         .data = ccPtr + CERT_LEN_PREFIX,
1065         .len = ParseCertPrefix(ccPtr)
1066          };
1067     CertificateX509 certStruct;
1068
1069     VERIFY_SUCCESS(TAG, PKI_SUCCESS == DecodeCertificate(cert, &certStruct), ERROR);
1070
1071     INC_BYTE_ARRAY(certStruct.pubKey, 2);
1072
1073     memcpy(credInfo->rootPublicKeyX, certStruct.pubKey.data, PUBLIC_KEY_SIZE / 2);
1074     memcpy(credInfo->rootPublicKeyY, certStruct.pubKey.data + PUBLIC_KEY_SIZE / 2, PUBLIC_KEY_SIZE / 2);
1075
1076     ret = OC_STACK_OK;
1077     exit:
1078     return ret;
1079 }
1080
1081 static OCStackResult GetCertCredPublicData(CADtlsX509Creds_t *credInfo, OicSecCred_t *cred)
1082 {
1083     OCStackResult ret = OC_STACK_ERROR;
1084     VERIFY_NON_NULL(TAG, credInfo, ERROR);
1085     VERIFY_NON_NULL(TAG, cred, ERROR);
1086     VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
1087     //VERIFY_SUCCESS(TAG, NULL == credInfo->certificateChain.data, ERROR);
1088     cJSON *jsonRoot = cJSON_Parse(cred->publicData.data);
1089     VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
1090
1091     //Get certificate chain
1092     cJSON *jsonObj = cJSON_GetObjectItem(jsonRoot, CERTIFICATE);//TODO define field names constants
1093     VERIFY_SUCCESS(TAG, NULL != jsonObj && cJSON_Array == jsonObj->type, ERROR);
1094
1095     size_t certChainLen = cJSON_GetArraySize(jsonObj);
1096     credInfo->chainLen = certChainLen;
1097     VERIFY_SUCCESS(TAG, MAX_CHAIN_LEN >= certChainLen, ERROR);
1098
1099     uint32_t len = 0;
1100     for (size_t i = 0; i < certChainLen; ++i)
1101     {
1102         cJSON *item = cJSON_GetArrayItem(jsonObj, i);
1103         VERIFY_SUCCESS(TAG, cJSON_String == item->type, ERROR);
1104         uint32_t appendedLen = appendCert2Chain(credInfo->certificateChain + len, item->valuestring,
1105                                               MAX_CERT_MESSAGE_LEN - len);
1106         VERIFY_SUCCESS(TAG, 0 != appendedLen, ERROR);
1107         len += appendedLen;
1108     }
1109     credInfo->certificateChainLen = len;
1110     VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCAPublicKeyData(credInfo), ERROR);
1111     ret = OC_STACK_OK;
1112 exit:
1113     cJSON_Delete(jsonRoot);
1114     return ret;
1115 }
1116
1117 static OCStackResult GetCertCredPrivateData(CADtlsX509Creds_t *credInfo, OicSecCred_t *cred)
1118 {
1119     OCStackResult ret = OC_STACK_ERROR;
1120     VERIFY_NON_NULL(TAG, credInfo, ERROR);
1121     VERIFY_NON_NULL(TAG, cred, ERROR);
1122     VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
1123     cJSON *jsonRoot = cJSON_Parse(cred->privateData.data);
1124     VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
1125
1126     cJSON *jsonObj = cJSON_GetObjectItem(jsonRoot, PRIVATE_KEY);//TODO define field names constants
1127     VERIFY_SUCCESS(TAG, NULL != jsonObj && cJSON_String == jsonObj->type, ERROR);
1128
1129     uint32_t read = 0u;
1130     VERIFY_SUCCESS(TAG, B64_OK == b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring),
1131                                             credInfo->devicePrivateKey, PRIVATE_KEY_SIZE, &read)
1132                    && PRIVATE_KEY_SIZE == read, ERROR);
1133
1134     ret = OC_STACK_OK;
1135
1136 exit:
1137     cJSON_Delete(jsonRoot);
1138     return ret;
1139 }
1140
1141 int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo)
1142 {
1143     int ret = 1;
1144     VERIFY_NON_NULL(TAG, credInfo, ERROR);
1145     if (NULL == gCred)
1146     {
1147         VERIFY_SUCCESS(TAG, OC_STACK_OK == InitCredResource(), ERROR);
1148     }
1149
1150     OicSecCred_t *cred = NULL;
1151     LL_SEARCH_SCALAR(gCred, cred, credType, SIGNED_ASYMMETRIC_KEY);
1152     VERIFY_NON_NULL(TAG, cred, ERROR);
1153
1154     VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCertCredPrivateData(credInfo, cred), ERROR);
1155     VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCertCredPublicData(credInfo, cred), ERROR);
1156
1157     ret = 0;
1158 exit:
1159
1160     return ret;
1161 }
1162 #undef CERT_LEN_PREFIX
1163 #endif /* __WITH_X509__ */