1 //******************************************************************
3 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21 #define __STDC_LIMIT_MACROS
31 #include "cainterface.h"
32 #include "payload_logging.h"
36 #include "ocserverrequest.h"
37 #include "oic_malloc.h"
38 #include "ocpayload.h"
40 #include "credresource.h"
41 #include "doxmresource.h"
42 #include "pstatresource.h"
43 #include "iotvticalendar.h"
45 #include "resourcemanager.h"
46 #include "srmresourcestrings.h"
47 #include "srmutility.h"
48 #include "psinterface.h"
49 #include "pinoxmcommon.h"
55 #define TAG "SRM-CREDL"
57 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
58 * The value of payload size is increased until reaching belox max cbor size. */
59 static const uint16_t CBOR_SIZE = 2048;
61 /** Max cbor size payload. */
62 static const uint16_t CBOR_MAX_SIZE = 4400;
64 /** CRED size - Number of mandatory items. */
65 static const uint8_t CRED_ROOT_MAP_SIZE = 2;
66 static const uint8_t CRED_MAP_SIZE = 3;
69 static OicSecCred_t *gCred = NULL;
70 static OCResourceHandle gCredHandle = NULL;
73 * This function frees OicSecCred_t object's fields and object itself.
75 static void FreeCred(OicSecCred_t *cred)
79 OIC_LOG(ERROR, TAG, "Invalid Parameter");
82 //Note: Need further clarification on roleID data type
85 OICFree(cred->roleIds);
90 OICFree(cred->publicData.data);
94 OICFree(cred->privateData.data);
97 OICFree(cred->period);
100 OICFree(cred->owners);
102 //Clean Cred node itself
106 void DeleteCredList(OicSecCred_t* cred)
110 OicSecCred_t *credTmp1 = NULL, *credTmp2 = NULL;
111 LL_FOREACH_SAFE(cred, credTmp1, credTmp2)
113 LL_DELETE(cred, credTmp1);
119 static size_t OicSecCredCount(const OicSecCred_t *secCred)
122 for (const OicSecCred_t *cred = secCred; cred; cred = cred->next)
129 OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload,
132 if (NULL == credS || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
134 return OC_STACK_INVALID_PARAM;
136 OIC_LOG(DEBUG, TAG, "CredToCBORPayload IN");
137 OCStackResult ret = OC_STACK_ERROR;
139 CborError cborEncoderResult = CborNoError;
140 uint8_t *outPayload = NULL;
141 size_t cborLen = *cborSize;
144 const OicSecCred_t *cred = credS;
145 CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
146 CborEncoder credArray = { {.ptr = NULL }, .end = 0 };
147 CborEncoder credRootMap = { {.ptr = NULL }, .end = 0 };
154 outPayload = (uint8_t *)OICCalloc(1, cborLen);
155 VERIFY_NON_NULL(TAG, outPayload, ERROR);
156 cbor_encoder_init(&encoder, outPayload, cborLen, 0);
158 // Create CRED Root Map (creds, rownerid)
159 cborEncoderResult = cbor_encoder_create_map(&encoder, &credRootMap, CRED_ROOT_MAP_SIZE);
160 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Root Map");
163 cborEncoderResult = cbor_encode_text_string(&credRootMap, OIC_JSON_CREDS_NAME,
164 strlen(OIC_JSON_CREDS_NAME));
165 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding creds Name Tag.");
168 cborEncoderResult = cbor_encoder_create_array(&credRootMap, &credArray, OicSecCredCount(cred));
169 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Array.");
173 CborEncoder credMap = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
174 size_t mapSize = CRED_MAP_SIZE;
175 char *subject = NULL;
181 if (SIGNED_ASYMMETRIC_KEY == cred->credType && cred->publicData.data)
185 #endif /* __WITH_X509__ */
186 if (cred->privateData.data)
190 cborEncoderResult = cbor_encoder_create_map(&credArray, &credMap, mapSize);
191 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Map");
193 //CredID -- Mandatory
194 cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_CREDID_NAME,
195 strlen(OIC_JSON_CREDID_NAME));
196 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Id Tag. ");
197 cborEncoderResult = cbor_encode_int(&credMap, cred->credId);
198 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Id Value.");
200 //Subject -- Mandatory
201 cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_SUBJECTID_NAME,
202 strlen(OIC_JSON_SUBJECTID_NAME));
203 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Tag.");
204 ret = ConvertUuidToStr(&cred->subject, &subject);
205 VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
206 cborEncoderResult = cbor_encode_text_string(&credMap, subject, strlen(subject));
207 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Subject Id Value.");
210 //CredType -- Mandatory
211 cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_CREDTYPE_NAME,
212 strlen(OIC_JSON_CREDTYPE_NAME));
213 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag.");
214 cborEncoderResult = cbor_encode_int(&credMap, cred->credType);
215 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
218 //PublicData -- Not Mandatory
219 if (SIGNED_ASYMMETRIC_KEY == cred->credType && cred->publicData.data)
221 CborEncoder publicMap = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
222 const size_t publicMapSize = 2;
224 cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_PUBLICDATA_NAME,
225 strlen(OIC_JSON_PUBLICDATA_NAME));
226 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PublicData Tag.");
228 cborEncoderResult = cbor_encoder_create_map(&credMap, &publicMap, publicMapSize);
229 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PublicData Map");
231 cborEncoderResult = cbor_encode_text_string(&publicMap, OIC_JSON_DATA_NAME,
232 strlen(OIC_JSON_DATA_NAME));
233 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Pub Data Tag.");
234 cborEncoderResult = cbor_encode_byte_string(&publicMap, cred->publicData.data,
235 cred->publicData.len);
236 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Pub Value.");
238 // TODO: Need to data strucure modification for OicSecCert_t.
239 cborEncoderResult = cbor_encode_text_string(&publicMap, OIC_JSON_ENCODING_NAME,
240 strlen(OIC_JSON_ENCODING_NAME));
241 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Public Encoding Tag.");
242 cborEncoderResult = cbor_encode_text_string(&publicMap, OIC_SEC_ENCODING_BYTESTREAM,
243 strlen(OIC_SEC_ENCODING_BYTESTREAM));
244 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Public Encoding Value.");
246 cborEncoderResult = cbor_encoder_close_container(&credMap, &publicMap);
247 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing PublicData Map.");
249 #endif /*__WITH_X509__*/
250 //PrivateData -- Not Mandatory
251 if(cred->privateData.data)
253 CborEncoder privateMap = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
254 const size_t privateMapSize = 2;
256 cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_PRIVATEDATA_NAME,
257 strlen(OIC_JSON_PRIVATEDATA_NAME));
258 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PrivateData Tag.");
260 cborEncoderResult = cbor_encoder_create_map(&credMap, &privateMap, privateMapSize);
261 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PrivateData Map");
263 cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_JSON_DATA_NAME,
264 strlen(OIC_JSON_DATA_NAME));
265 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Priv Tag.");
266 cborEncoderResult = cbor_encode_byte_string(&privateMap, cred->privateData.data,
267 cred->privateData.len);
268 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Priv Value.");
270 // TODO: Need to data strucure modification for OicSecKey_t.
271 cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_JSON_ENCODING_NAME,
272 strlen(OIC_JSON_ENCODING_NAME));
273 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Encoding Tag.");
274 cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_SEC_ENCODING_BYTESTREAM,
275 strlen(OIC_SEC_ENCODING_BYTESTREAM));
276 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Encoding Value.");
278 cborEncoderResult = cbor_encoder_close_container(&credMap, &privateMap);
279 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing PrivateData Map.");
282 //Period -- Not Mandatory
285 cborEncoderResult = cbor_encode_text_string(&credMap, OIC_JSON_PERIOD_NAME,
286 strlen(OIC_JSON_PERIOD_NAME));
287 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Name Tag.");
288 cborEncoderResult = cbor_encode_text_string(&credMap, cred->period,
289 strlen(cred->period));
290 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Name Value.");
294 cborEncoderResult = cbor_encoder_close_container(&credArray, &credMap);
295 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Map.");
299 cborEncoderResult = cbor_encoder_close_container(&credRootMap, &credArray);
300 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Array.");
303 // TODO : Need to modify cred->owners[0] to cred->rownerid based on RAML spec.
305 if(cred->owners && cred->ownersLen > 0)
308 cborEncoderResult = cbor_encode_text_string(&credRootMap, OIC_JSON_ROWNERID_NAME,
309 strlen(OIC_JSON_ROWNERID_NAME));
310 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding rownerid Name.");
311 ret = ConvertUuidToStr(&cred->owners[0], &rowner);
312 VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
313 cborEncoderResult = cbor_encode_text_string(&credRootMap, rowner, strlen(rowner));
314 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding rownerid Value.");
318 // Close CRED Root Map
319 cborEncoderResult = cbor_encoder_close_container(&encoder, &credRootMap);
320 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing CRED Root Map.");
322 if (CborNoError == cborEncoderResult)
324 OIC_LOG(DEBUG, TAG, "CredToCBORPayload Successed");
325 *cborPayload = outPayload;
326 *cborSize = encoder.ptr - outPayload;
329 OIC_LOG(DEBUG, TAG, "CredToCBORPayload OUT");
331 if (CborErrorOutOfMemory == cborEncoderResult)
333 OIC_LOG(DEBUG, TAG, "CredToCBORPayload:CborErrorOutOfMemory : retry with more memory");
334 // reallocate and try again!
336 // Since the allocated initial memory failed, double the memory.
337 cborLen += encoder.ptr - encoder.end;
338 cborEncoderResult = CborNoError;
339 ret = CredToCBORPayload(credS, cborPayload, &cborLen);
343 if (CborNoError != cborEncoderResult)
345 OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
350 ret = OC_STACK_ERROR;
356 OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
357 OicSecCred_t **secCred)
359 if (NULL == cborPayload || NULL == secCred || NULL != *secCred)
361 return OC_STACK_INVALID_PARAM;
363 OIC_LOG(DEBUG, TAG, "CBORPayloadToCred IN");
367 OCStackResult ret = OC_STACK_ERROR;
368 CborValue credCbor = { .parser = NULL };
369 CborParser parser = { .end = NULL };
370 CborError cborFindResult = CborNoError;
371 cbor_parser_init(cborPayload, size, 0, &parser, &credCbor);
373 OicSecCred_t *headCred = (OicSecCred_t *) OICCalloc(1, sizeof(OicSecCred_t));
375 // Enter CRED Root Map
376 CborValue CredRootMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
377 cborFindResult = cbor_value_enter_container(&credCbor, &CredRootMap);
378 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering CRED Root Map.");
380 while (cbor_value_is_valid(&CredRootMap))
382 char* tagName = NULL;
384 CborType type = cbor_value_get_type(&CredRootMap);
385 if (type == CborTextStringType)
387 cborFindResult = cbor_value_dup_text_string(&CredRootMap, &tagName, &len, NULL);
388 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in CRED Root Map.");
389 cborFindResult = cbor_value_advance(&CredRootMap);
390 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in CRED Root Map.");
394 if (strcmp(tagName, OIC_JSON_CREDS_NAME) == 0)
399 CborValue credArray = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
400 cborFindResult = cbor_value_enter_container(&CredRootMap, &credArray);
401 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Array.");
403 while (cbor_value_is_valid(&credArray))
406 //CredId -- Mandatory
407 CborValue credMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
408 cborFindResult = cbor_value_enter_container(&credArray, &credMap);
409 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Map.");
410 OicSecCred_t *cred = NULL;
418 cred = (OicSecCred_t *) OICCalloc(1, sizeof(OicSecCred_t));
419 OicSecCred_t *temp = headCred;
427 VERIFY_NON_NULL(TAG, cred, ERROR);
429 while(cbor_value_is_valid(&credMap))
432 CborType type = cbor_value_get_type(&credMap);
433 if (type == CborTextStringType)
435 cborFindResult = cbor_value_dup_text_string(&credMap, &name, &len, NULL);
436 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in CRED Map.");
437 cborFindResult = cbor_value_advance(&credMap);
438 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in CRED Map.");
443 if (strcmp(name, OIC_JSON_CREDID_NAME) == 0)
445 cborFindResult = cbor_value_get_uint64(&credMap, (uint64_t *) &cred->credId);
446 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CredId.");
449 if (strcmp(name, OIC_JSON_SUBJECTID_NAME) == 0)
451 char *subjectid = NULL;
452 cborFindResult = cbor_value_dup_text_string(&credMap, &subjectid, &len, NULL);
453 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding subjectid Value.");
454 ret = ConvertStrToUuid(subjectid, &cred->subject);
455 VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
459 if (strcmp(name, OIC_JSON_CREDTYPE_NAME) == 0)
461 cborFindResult = cbor_value_get_uint64(&credMap, (uint64_t *) &cred->credType);
462 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CredType.");
465 if (strcmp(name, OIC_JSON_PRIVATEDATA_NAME) == 0)
467 CborValue privateMap = { .parser = NULL };
468 cborFindResult = cbor_value_enter_container(&credMap, &privateMap);
470 while (cbor_value_is_valid(&privateMap))
472 char* privname = NULL;
473 CborType type = cbor_value_get_type(&privateMap);
474 if (type == CborTextStringType)
476 cborFindResult = cbor_value_dup_text_string(&privateMap, &privname,
478 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get text");
479 cborFindResult = cbor_value_advance(&privateMap);
480 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance value");
484 // PrivateData::privdata -- Mandatory
485 if (strcmp(privname, OIC_JSON_DATA_NAME) == 0)
487 cborFindResult = cbor_value_dup_byte_string(&privateMap, &cred->privateData.data,
488 &cred->privateData.len, NULL);
489 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PrivateData.");
491 // PrivateData::encoding -- Mandatory
492 if (strcmp(privname, OIC_JSON_ENCODING_NAME) == 0)
494 // TODO: Need to update data structure, just ignore encoding value now.
497 if (cbor_value_is_valid(&privateMap))
499 cborFindResult = cbor_value_advance(&privateMap);
500 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing privatedata Map.");
507 if (strcmp(name, OIC_JSON_PUBLICDATA_NAME) == 0)
509 CborValue pubMap = { .parser = NULL };
510 cborFindResult = cbor_value_enter_container(&credMap, &pubMap);
512 while (cbor_value_is_valid(&pubMap))
514 char* pubname = NULL;
515 CborType type = cbor_value_get_type(&pubMap);
516 if (type == CborTextStringType)
518 cborFindResult = cbor_value_dup_text_string(&pubMap, &pubname,
520 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get text");
521 cborFindResult = cbor_value_advance(&pubMap);
522 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance value");
526 // PrivateData::privdata -- Mandatory
527 if (strcmp(pubname, OIC_JSON_DATA_NAME) == 0)
529 cborFindResult = cbor_value_dup_byte_string(&pubMap, &cred->publicData.data,
530 &cred->publicData.len, NULL);
531 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PubData.");
533 // PublicData::encoding -- Mandatory
534 if (strcmp(pubname, OIC_JSON_ENCODING_NAME) == 0)
536 // TODO: Need to update data structure, just ignore encoding value now.
539 if (cbor_value_is_valid(&pubMap))
541 cborFindResult = cbor_value_advance(&pubMap);
542 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing publicdata Map.");
547 #endif //__WITH_X509__
549 if (0 == strcmp(OIC_JSON_PERIOD_NAME, name))
551 cborFindResult = cbor_value_dup_text_string(&credMap, &cred->period, &len, NULL);
552 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Period.");
555 if (cbor_value_is_valid(&credMap))
557 cborFindResult = cbor_value_advance(&credMap);
558 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing CRED Map.");
564 if (cbor_value_is_valid(&credArray))
566 cborFindResult = cbor_value_advance(&credArray);
567 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing CRED Array.");
572 // TODO : Need to modify headCred->owners[0].id to headCred->rowner based on RAML spec.
573 if (strcmp(tagName, OIC_JSON_ROWNERID_NAME) == 0)
575 char *stRowner = NULL;
576 cborFindResult = cbor_value_dup_text_string(&CredRootMap, &stRowner, &len, NULL);
577 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Rownerid Value.");
578 headCred->ownersLen = 1;
579 headCred->owners = (OicUuid_t *)OICCalloc(headCred->ownersLen, sizeof(*headCred->owners));
580 VERIFY_NON_NULL(TAG, headCred->owners, ERROR);
581 ret = ConvertStrToUuid(stRowner, &headCred->owners[0]);
582 VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
587 if (cbor_value_is_valid(&CredRootMap))
589 cborFindResult = cbor_value_advance(&CredRootMap);
590 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing CRED Root Map.");
597 OIC_LOG(DEBUG, TAG, "CBORPayloadToCred OUT");
600 if (CborNoError != cborFindResult)
602 DeleteCredList(headCred);
605 ret = OC_STACK_ERROR;
611 OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t credType,
612 const OicSecCert_t * publicData, const OicSecKey_t* privateData,
613 size_t ownersLen, const OicUuid_t * owners)
616 OCStackResult ret = OC_STACK_ERROR;
618 OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
619 VERIFY_NON_NULL(TAG, cred, ERROR);
621 //CredId is assigned before appending new cred to the existing
622 //credential list and updating svr database in AddCredential().
625 VERIFY_NON_NULL(TAG, subject, ERROR);
626 memcpy(cred->subject.id, subject->id , sizeof(cred->subject.id));
628 VERIFY_SUCCESS(TAG, credType < (NO_SECURITY_MODE | SYMMETRIC_PAIR_WISE_KEY |
629 SYMMETRIC_GROUP_KEY | ASYMMETRIC_KEY | SIGNED_ASYMMETRIC_KEY | PIN_PASSWORD), ERROR);
630 cred->credType = credType;
633 if (publicData && publicData->data)
635 cred->publicData.data = (uint8_t *)OICCalloc(1, publicData->len);
636 VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
637 memcpy(cred->publicData.data, publicData->data, publicData->len);
638 cred->publicData.len = publicData->len;
640 #endif // __WITH_X509__
642 if (privateData && privateData->data)
644 cred->privateData.data = (uint8_t *)OICCalloc(1, privateData->len);
645 VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
646 memcpy(cred->privateData.data, privateData->data, privateData->len);
647 cred->privateData.len = privateData->len;
650 VERIFY_SUCCESS(TAG, ownersLen > 0, ERROR);
651 cred->ownersLen = ownersLen;
653 cred->owners = (OicUuid_t *)OICCalloc(cred->ownersLen, sizeof(*cred->owners));
654 VERIFY_NON_NULL(TAG, cred->owners, ERROR);
655 for (size_t i = 0; i < cred->ownersLen; i++)
657 memcpy(cred->owners[i].id, owners[i].id, sizeof(cred->owners[i].id));
662 if (OC_STACK_OK != ret)
664 DeleteCredList(cred);
670 static bool UpdatePersistentStorage(const OicSecCred_t *cred)
674 // Convert Cred data into JSON for update to persistent storage
677 uint8_t *payload = NULL;
679 OCStackResult res = CredToCBORPayload(cred, &payload, &size);
680 if ((OC_STACK_OK == res) && payload)
682 if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, payload, size))
689 else //Empty cred list
691 if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, NULL, 0))
700 * Compare function used LL_SORT for sorting credentials.
702 * @param first pointer to OicSecCred_t struct.
703 * @param second pointer to OicSecCred_t struct.
705 *@return -1, if credId of first is less than credId of second.
706 * 0, if credId of first is equal to credId of second.
707 * 1, if credId of first is greater than credId of second.
709 static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
711 if (first->credId < second->credId)
715 else if (first->credId > second->credId)
724 * GetCredId goes through the cred list and returns the next
725 * available credId. The next credId could be the credId that is
726 * available due deletion of OicSecCred_t object or one more than
727 * credId of last credential in the list.
729 * @return next available credId if successful, else 0 for error.
731 static uint16_t GetCredId()
733 //Sorts credential list in incremental order of credId
734 LL_SORT(gCred, CmpCredId);
736 OicSecCred_t *currentCred = NULL, *credTmp = NULL;
737 uint16_t nextCredId = 1;
739 LL_FOREACH_SAFE(gCred, currentCred, credTmp)
741 if (currentCred->credId == nextCredId)
751 VERIFY_SUCCESS(TAG, nextCredId < UINT16_MAX, ERROR);
759 * Get the default value.
761 * @return NULL for now.
763 static OicSecCred_t* GetCredDefault()
765 // TODO:Update it when we finalize the default info.
769 OCStackResult AddCredential(OicSecCred_t * newCred)
771 OCStackResult ret = OC_STACK_ERROR;
772 VERIFY_SUCCESS(TAG, NULL != newCred, ERROR);
774 //Assigning credId to the newCred
775 newCred->credId = GetCredId();
776 VERIFY_SUCCESS(TAG, newCred->credId != 0, ERROR);
778 //Append the new Cred to existing list
779 LL_APPEND(gCred, newCred);
781 if (UpdatePersistentStorage(gCred))
790 OCStackResult RemoveCredential(const OicUuid_t *subject)
792 OCStackResult ret = OC_STACK_ERROR;
793 OicSecCred_t *cred = NULL;
794 OicSecCred_t *tempCred = NULL;
795 bool deleteFlag = false;
797 LL_FOREACH_SAFE(gCred, cred, tempCred)
799 if (memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
801 LL_DELETE(gCred, cred);
809 if (UpdatePersistentStorage(gCred))
811 ret = OC_STACK_RESOURCE_DELETED;
819 * Remove all credential data on credential resource and persistent storage
822 * OC_STACK_OK - no errors
823 * OC_STACK_ERROR - stack process error
825 OCStackResult RemoveAllCredentials(void)
827 DeleteCredList(gCred);
828 gCred = GetCredDefault();
830 if (!UpdatePersistentStorage(gCred))
832 return OC_STACK_ERROR;
839 * Internal function to fill private data of owner PSK.
841 * @param receviedCred recevied owner credential from OBT(PT)
842 * @param ownerAdd address of OBT(PT)
843 * @param doxm current device's doxm resource
846 * true successfully done and valid ower psk information
847 * false Invalid owner psk information or failed to owner psk generation
849 static bool FillPrivateDataOfOwnerPSK(OicSecCred_t* receviedCred, const CAEndpoint_t* ownerAddr,
850 const OicSecDoxm_t* doxm)
852 //Derive OwnerPSK locally
853 const char* oxmLabel = GetOxmString(doxm->oxmSel);
854 VERIFY_NON_NULL(TAG, oxmLabel, ERROR);
856 uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
857 CAResult_t pskRet = CAGenerateOwnerPSK(ownerAddr,
858 (uint8_t*)oxmLabel, strlen(oxmLabel),
859 doxm->owner.id, sizeof(doxm->owner.id),
860 doxm->deviceID.id, sizeof(doxm->deviceID.id),
861 ownerPSK, OWNER_PSK_LENGTH_128);
862 VERIFY_SUCCESS(TAG, pskRet == CA_STATUS_OK, ERROR);
864 OIC_LOG(DEBUG, TAG, "OwnerPSK dump :");
865 OIC_LOG_BUFFER(DEBUG, TAG, ownerPSK, OWNER_PSK_LENGTH_128);
867 //Generate owner credential based on recevied credential information
868 receviedCred->privateData.data = (uint8_t *)OICCalloc(1, OWNER_PSK_LENGTH_128);
869 VERIFY_NON_NULL(TAG, receviedCred->privateData.data, ERROR);
870 receviedCred->privateData.len = OWNER_PSK_LENGTH_128;
871 memcpy(receviedCred->privateData.data, ownerPSK, OWNER_PSK_LENGTH_128);
873 OIC_LOG(INFO, TAG, "PrivateData of OwnerPSK was calculated successfully");
875 //Verify OwnerPSK information
876 return (memcmp(&(receviedCred->subject), &(doxm->owner), sizeof(OicUuid_t)) == 0 &&
877 receviedCred->credType == SYMMETRIC_PAIR_WISE_KEY);
879 //receviedCred->privateData.data will be deallocated when deleting credential.
883 #endif //__WITH_DTLS__
885 static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehRequest)
887 OCEntityHandlerResult ret = OC_EH_ERROR;
888 OIC_LOG(DEBUG, TAG, "HandleCREDPutRequest IN");
890 //Get binary representation of cbor
891 OicSecCred_t *cred = NULL;
892 uint8_t *payload = (((OCSecurityPayload*)ehRequest->payload)->securityData1);
893 size_t size = (((OCSecurityPayload*)ehRequest->payload)->payloadSize);
894 OCStackResult res = CBORPayloadToCred(payload, size, &cred);
895 if (res == OC_STACK_OK)
898 OicUuid_t emptyUuid = {.id={0}};
899 const OicSecDoxm_t* doxm = GetDoxmResourceData();
900 if(false == doxm->owned && memcmp(&(doxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0)
902 //in case of owner PSK
903 switch(cred->credType)
905 case SYMMETRIC_PAIR_WISE_KEY:
907 OCServerRequest *request = (OCServerRequest *)ehRequest->requestHandle;
908 if(FillPrivateDataOfOwnerPSK(cred, (CAEndpoint_t *)&request->devAddr, doxm))
910 if(OC_STACK_RESOURCE_DELETED == RemoveCredential(&cred->subject))
912 OIC_LOG(WARNING, TAG, "The credential with the same subject ID was detected!");
915 OIC_LOG(ERROR, TAG, "OwnerPSK was generated successfully.");
916 if(OC_STACK_OK == AddCredential(cred))
918 ret = OC_EH_RESOURCE_CREATED;
922 OIC_LOG(ERROR, TAG, "Failed to save the OwnerPSK as cred resource");
928 OIC_LOG(ERROR, TAG, "Failed to verify receviced OwnerPKS.");
932 if(OC_EH_RESOURCE_CREATED == ret)
935 * in case of random PIN based OxM,
936 * revert get_psk_info callback of tinyDTLS to use owner credential.
938 if(OIC_RANDOM_DEVICE_PIN == doxm->oxmSel)
940 OicUuid_t emptyUuid = { .id={0}};
941 SetUuidForRandomPinOxm(&emptyUuid);
943 if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
945 OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
951 //Select cipher suite to use owner PSK
952 if(CA_STATUS_OK != CAEnableAnonECDHCipherSuite(false))
954 OIC_LOG(ERROR, TAG, "Failed to disable anonymous cipher suite");
959 OIC_LOG(INFO, TAG, "Anonymous cipher suite is DISABLED");
963 CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256))
965 OIC_LOG(ERROR, TAG, "Failed to select cipher suite");
972 case SYMMETRIC_GROUP_KEY:
974 case SIGNED_ASYMMETRIC_KEY:
976 case ASYMMETRIC_ENCRYPTION_KEY:
978 OIC_LOG(WARNING, TAG, "Unsupported credential type for owner credential.");
984 OIC_LOG(WARNING, TAG, "Unknow credential type for owner credential.");
990 if(OC_EH_RESOURCE_CREATED != ret)
993 * If some error is occured while ownership transfer,
994 * ownership transfer related resource should be revert back to initial status.
996 RestoreDoxmToInitState();
997 RestorePstatToInitState();
1003 * If the post request credential has credId, it will be
1004 * discarded and the next available credId will be assigned
1005 * to it before getting appended to the existing credential
1006 * list and updating svr database.
1008 ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
1010 #else //not __WITH_DTLS__
1012 * If the post request credential has credId, it will be
1013 * discarded and the next available credId will be assigned
1014 * to it before getting appended to the existing credential
1015 * list and updating svr database.
1017 ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
1018 #endif//__WITH_DTLS__
1021 if (OC_EH_RESOURCE_CREATED != ret)
1023 if(OC_STACK_OK != RemoveCredential(&cred->subject))
1025 OIC_LOG(WARNING, TAG, "Failed to remove the invalid credential");
1029 OIC_LOG(DEBUG, TAG, "HandleCREDPutRequest OUT");
1033 static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
1035 OCEntityHandlerResult ret = OC_EH_ERROR;
1037 //Get binary representation of CBOR
1038 OicSecCred_t *cred = NULL;
1039 uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData1;
1040 size_t size = ((OCSecurityPayload*)ehRequest->payload)->payloadSize;
1041 OCStackResult res = CBORPayloadToCred(payload, size, &cred);
1042 if ((OC_STACK_OK == res) && cred)
1044 //If the Post request credential has credId, it will be
1045 //discarded and the next available credId will be assigned
1046 //to it before getting appended to the existing credential
1047 //list and updating svr database.
1048 ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
1054 static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *ehRequest)
1056 OIC_LOG(DEBUG, TAG, "Processing CredDeleteRequest");
1058 OCEntityHandlerResult ehRet = OC_EH_ERROR;
1060 if (NULL == ehRequest->query)
1065 OicParseQueryIter_t parseIter = { .attrPos=NULL };
1066 OicUuid_t subject = {.id={0}};
1068 //Parsing REST query to get the subject
1069 ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
1070 while (GetNextQuery(&parseIter))
1072 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECTID_NAME,
1073 parseIter.attrLen) == 0)
1075 OCStackResult ret = ConvertStrToUuid((const char*)parseIter.valPos, &subject);
1076 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
1080 if (OC_STACK_RESOURCE_DELETED == RemoveCredential(&subject))
1082 ehRet = OC_EH_RESOURCE_DELETED;
1089 OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
1090 OCEntityHandlerRequest * ehRequest,
1091 void* callbackParameter)
1093 (void)callbackParameter;
1094 OCEntityHandlerResult ret = OC_EH_ERROR;
1100 if (flag & OC_REQUEST_FLAG)
1102 OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1103 //TODO : Handle PUT/DEL methods
1104 switch (ehRequest->method)
1107 ret = OC_EH_FORBIDDEN;
1110 ret = HandlePutRequest(ehRequest);
1113 ret = HandlePostRequest(ehRequest);
1115 case OC_REST_DELETE:
1116 ret = HandleDeleteRequest(ehRequest);
1124 //Send payload to request originator
1125 ret = (SendSRMCBORResponse(ehRequest, ret, NULL, 0) == OC_STACK_OK) ?
1131 OCStackResult CreateCredResource()
1133 OCStackResult ret = OCCreateResource(&gCredHandle,
1134 OIC_RSRC_TYPE_SEC_CRED,
1141 if (OC_STACK_OK != ret)
1143 OIC_LOG (FATAL, TAG, "Unable to instantiate Cred resource");
1144 DeInitCredResource();
1149 OCStackResult InitCredResource()
1151 OCStackResult ret = OC_STACK_ERROR;
1153 //Read Cred resource from PS
1154 uint8_t *data = NULL;
1156 ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_CRED_NAME, &data, &size);
1157 // If database read failed
1158 if (ret != OC_STACK_OK)
1160 OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
1164 // Read ACL resource from PS
1165 ret = CBORPayloadToCred(data, size, &gCred);
1169 * If SVR database in persistent storage got corrupted or
1170 * is not available for some reason, a default Cred is created
1171 * which allows user to initiate Cred provisioning again.
1173 if (ret != OC_STACK_OK || !data || !gCred)
1175 gCred = GetCredDefault();
1177 //Instantiate 'oic.sec.cred'
1178 ret = CreateCredResource();
1183 OCStackResult DeInitCredResource()
1185 OCStackResult result = OCDeleteResource(gCredHandle);
1186 DeleteCredList(gCred);
1191 const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject)
1193 OicSecCred_t *cred = NULL;
1195 if ( NULL == subject)
1200 LL_FOREACH(gCred, cred)
1202 if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
1211 #if defined(__WITH_DTLS__)
1212 int32_t GetDtlsPskCredentials(CADtlsPskCredType_t type,
1213 const uint8_t *desc, size_t desc_len,
1214 uint8_t *result, size_t result_length)
1225 case CA_DTLS_PSK_HINT:
1226 case CA_DTLS_PSK_IDENTITY:
1228 OicUuid_t deviceID = {.id={}};
1229 // Retrieve Device ID from doxm resource
1230 if ( OC_STACK_OK != GetDoxmDeviceID(&deviceID) )
1232 OIC_LOG (ERROR, TAG, "Unable to retrieve doxm Device ID");
1236 if (result_length < sizeof(deviceID.id))
1238 OIC_LOG (ERROR, TAG, "Wrong value for result_length");
1241 memcpy(result, deviceID.id, sizeof(deviceID.id));
1242 return (sizeof(deviceID.id));
1246 case CA_DTLS_PSK_KEY:
1248 OicSecCred_t *cred = NULL;
1249 LL_FOREACH(gCred, cred)
1251 if (cred->credType != SYMMETRIC_PAIR_WISE_KEY)
1256 if ((desc_len == sizeof(cred->subject.id)) &&
1257 (memcmp(desc, cred->subject.id, sizeof(cred->subject.id)) == 0))
1260 * If the credentials are valid for limited time,
1261 * check their expiry.
1265 if(IOTVTICAL_VALID_ACCESS != IsRequestWithinValidTime(cred->period, NULL))
1267 OIC_LOG (INFO, TAG, "Credentials are expired.");
1274 result_length = cred->privateData.len;
1275 memcpy(result, cred->privateData.data, result_length);
1276 return result_length;
1284 OIC_LOG (ERROR, TAG, "Wrong value passed for CADtlsPskCredType_t.");
1294 * Add temporal PSK to PIN based OxM
1296 * @param[in] tmpSubject UUID of target device
1297 * @param[in] credType Type of credential to be added
1298 * @param[in] pin numeric characters
1299 * @param[in] pinSize length of 'pin'
1300 * @param[in] ownersLen Number of owners
1301 * @param[in] owners Array of owners
1302 * @param[out] tmpCredSubject Generated credential's subject.
1304 * @return OC_STACK_OK for success and errorcode otherwise.
1306 OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t credType,
1307 const char * pin, size_t pinSize,
1308 size_t ownersLen, const OicUuid_t * owners, OicUuid_t* tmpCredSubject)
1310 OCStackResult ret = OC_STACK_ERROR;
1311 OIC_LOG(DEBUG, TAG, "AddTmpPskWithPIN IN");
1313 if(NULL == tmpSubject || NULL == pin || 0 == pinSize || NULL == tmpCredSubject)
1315 return OC_STACK_INVALID_PARAM;
1318 uint8_t privData[OWNER_PSK_LENGTH_128] = {0,};
1319 OicSecKey_t privKey = {privData, OWNER_PSK_LENGTH_128};
1320 OicSecCred_t* cred = NULL;
1321 int dtlsRes = DeriveCryptoKeyFromPassword((const unsigned char *)pin, pinSize, owners->id,
1322 UUID_LENGTH, PBKDF_ITERATIONS,
1323 OWNER_PSK_LENGTH_128, privData);
1324 VERIFY_SUCCESS(TAG, (0 == dtlsRes) , ERROR);
1326 cred = GenerateCredential(tmpSubject, credType, NULL,
1327 &privKey, ownersLen, owners);
1330 OIC_LOG(ERROR, TAG, "GeneratePskWithPIN() : Failed to generate credential");
1331 return OC_STACK_ERROR;
1334 memcpy(tmpCredSubject->id, cred->subject.id, UUID_LENGTH);
1336 ret = AddCredential(cred);
1337 if( OC_STACK_OK != ret)
1339 RemoveCredential(tmpSubject);
1340 OIC_LOG(ERROR, TAG, "GeneratePskWithPIN() : Failed to add credential");
1342 OIC_LOG(DEBUG, TAG, "AddTmpPskWithPIN OUT");
1348 #endif /* __WITH_DTLS__ */
1349 #ifdef __WITH_X509__
1350 #define CERT_LEN_PREFIX (3)
1351 #define BYTE_SIZE (8) //bits
1352 #define PUB_KEY_X_COORD ("x")
1353 #define PUB_KEY_Y_COORD ("y")
1354 #define CERTIFICATE ("x5c")
1355 #define PRIVATE_KEY ("d")
1357 static uint32_t parseCertPrefix(uint8_t *prefix)
1362 for (int i = 0; i < CERT_LEN_PREFIX; ++i)
1364 res |= (((uint32_t) prefix[i]) << ((CERT_LEN_PREFIX - 1 -i) * BYTE_SIZE));
1370 static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo)
1372 OCStackResult ret = OC_STACK_ERROR;
1373 uint8_t *ccPtr = credInfo->certificateChain;
1374 for (uint8_t i = 0; i < credInfo->chainLen - 1; ++i)
1376 ccPtr += CERT_LEN_PREFIX + parseCertPrefix(ccPtr);
1379 ByteArray cert = { .data = ccPtr + CERT_LEN_PREFIX, .len = parseCertPrefix(ccPtr) };
1380 CertificateX509 certStruct;
1382 VERIFY_SUCCESS(TAG, PKI_SUCCESS == DecodeCertificate(cert, &certStruct), ERROR);
1384 INC_BYTE_ARRAY(certStruct.pubKey, 2);
1386 memcpy(credInfo->rootPublicKeyX, certStruct.pubKey.data, PUBLIC_KEY_SIZE / 2);
1387 memcpy(credInfo->rootPublicKeyY, certStruct.pubKey.data + PUBLIC_KEY_SIZE / 2, PUBLIC_KEY_SIZE / 2);
1394 int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo)
1397 VERIFY_NON_NULL(TAG, credInfo, ERROR);
1400 VERIFY_SUCCESS(TAG, OC_STACK_OK == InitCredResource(), ERROR);
1403 OicSecCred_t *cred = NULL;
1404 LL_SEARCH_SCALAR(gCred, cred, credType, SIGNED_ASYMMETRIC_KEY);
1405 VERIFY_NON_NULL(TAG, cred, ERROR);
1407 if (cred->publicData.len > MAX_CERT_MESSAGE_LEN || cred->privateData.len > PRIVATE_KEY_SIZE)
1411 credInfo->chainLen = 2;
1412 memcpy(credInfo->certificateChain, cred->publicData.data, cred->publicData.len);
1413 memcpy(credInfo->devicePrivateKey, cred->privateData.data, cred->privateData.len);
1414 credInfo->certificateChainLen = cred->publicData.len;
1415 GetCAPublicKeyData(credInfo);
1421 #undef CERT_LEN_PREFIX
1422 #endif /* __WITH_X509__ */