1 /* *****************************************************************
3 * Copyright 2016 Samsung Electronics All Rights Reserved.
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 * *****************************************************************/
27 #ifdef HAVE_SYS_TIME_H
35 #include "oic_malloc.h"
36 #include "oic_string.h"
38 #include "cainterface.h"
43 #include "srmresourcestrings.h"
44 #include "doxmresource.h"
45 #include "pstatresource.h"
46 #include "credresource.h"
47 #include "aclresource.h"
48 #include "ownershiptransfermanager.h"
49 #include "securevirtualresourcetypes.h"
50 #include "oxmjustworks.h"
52 #include "pmutility.h"
53 #include "srmutility.h"
54 #include "provisioningdatabasemanager.h"
55 #include "oxmrandompin.h"
56 #include "ocpayload.h"
57 #include "payload_logging.h"
58 #include "oxmjustworks.h"
59 #include "oxmpreconfpin.h"
60 #include "oxmrandompin.h"
62 #define TAG "MULTIPLE_OTM"
64 /**********************************************************************
66 **********************************************************************/
69 * Structure to carry SuperOwner's multiple ownership transfer API data to callback.
71 typedef struct MOTContext MOTContext_t;
74 void *ctx; /**< Pointer to user context.**/
75 const OCProvisionDev_t *deviceInfo; /**< Pointer to OCProvisionDev_t.**/
76 OCProvisionResultCB resultCallback; /**< Pointer to result callback.**/
77 OCProvisionResult_t *resArr; /**< Result array.**/
78 int numOfResults; /**< Number of results in result array.**/
79 bool hasError; /**< Does MOT API have any error.. **/
83 * Callback handler of security resource's POST request.
85 * @param[in] ctx ctx value passed to callback from calling function.
86 * @param[in] UNUSED handle to an invocation
87 * @param[in] clientResponse Response from queries to remote servers.
88 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
89 * and OC_STACK_KEEP_TRANSACTION to keep it.
91 static OCStackApplicationResult MOTUpdateSecurityResourceCB(void *ctx, OCDoHandle UNUSED,
92 OCClientResponse *clientResponse)
94 OIC_LOG_V(INFO, TAG, "Inside MOTUpdateMomCB.");
96 MOTContext_t *motCtx = (MOTContext_t*)ctx;
97 VERIFY_NON_NULL(TAG, motCtx, ERROR);
98 VERIFY_NON_NULL(TAG, motCtx->resultCallback, ERROR);
99 VERIFY_NON_NULL(TAG, motCtx->resArr, ERROR);
103 memcpy(motCtx->resArr[0].deviceId.id, motCtx->deviceInfo->doxm->deviceID.id, sizeof(OicUuid_t));
104 motCtx->resArr[0].res = clientResponse->result;
106 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
108 motCtx->hasError = false;
112 motCtx->hasError = true;
117 OIC_LOG_V(ERROR, TAG, "SRPGetACLResourceCB received Null clientResponse");
118 motCtx->resArr[0].res = OC_STACK_ERROR;
119 motCtx->hasError = true;
122 motCtx->resultCallback(motCtx->ctx, motCtx->numOfResults, motCtx->resArr, motCtx->hasError);
127 OICFree(motCtx->resArr);
130 return OC_STACK_DELETE_TRANSACTION;
134 * Internal API to send POST doxm request
136 static OCStackResult MOTSendPostDoxm(void *ctx,
137 const OCProvisionDev_t *targetDeviceInfo,
138 OCProvisionResultCB resultCallback,
139 const OicSecDoxm_t* doxm)
141 OCStackResult postMomRes = OC_STACK_ERROR;
142 OCSecurityPayload* secPayload = NULL;
143 MOTContext_t *motCtx = NULL;
144 bool freeFlag = true;
146 OIC_LOG(DEBUG, TAG, "IN MOTSendPostDoxm");
148 //Generate the security payload using updated doxm
149 secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
150 VERIFY_NON_NULL(TAG, secPayload, ERROR);
151 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
153 postMomRes = DoxmToCBORPayload(doxm, &secPayload->securityData, &secPayload->payloadSize, true);
154 VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
156 OIC_LOG(DEBUG, TAG, "Created doxm payload to update doxm:");
157 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
159 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
160 bool queryGenRes = PMGenerateQuery(true,
161 targetDeviceInfo->endpoint.addr,
162 targetDeviceInfo->securePort,
163 targetDeviceInfo->connType,
164 query, sizeof(query), OIC_RSRC_DOXM_URI);
165 VERIFY_SUCCESS(TAG, (true == queryGenRes), ERROR);
166 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
168 //Create the MOT Context to handle the response message
169 motCtx = (MOTContext_t*)OICCalloc(1, sizeof(MOTContext_t));
170 VERIFY_NON_NULL(TAG, motCtx, ERROR);
171 motCtx->deviceInfo = targetDeviceInfo;
172 motCtx->resultCallback = resultCallback;
173 motCtx->numOfResults=1;
174 motCtx->hasError = false;
176 motCtx->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
177 VERIFY_NON_NULL(TAG, motCtx->resArr, ERROR);
180 OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
181 cbData.cb = &MOTUpdateSecurityResourceCB;
182 cbData.context = (void *)motCtx;
183 OIC_LOG(DEBUG, TAG, "Sending POST 'doxm' request to resource server");
184 postMomRes = OCDoResource(NULL, OC_REST_POST, query,
185 &targetDeviceInfo->endpoint, (OCPayload*)secPayload,
186 targetDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
187 VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
191 OIC_LOG(DEBUG, TAG, "OUT MOTSendPostDoxm");
194 //If POST request successfully sent, motCtx will be cleaned from response handler.
195 if(freeFlag && motCtx)
197 OICFree(motCtx->resArr);
205 * API to update 'doxm.mom' to resource server.
207 * @param[in] targetDeviceInfo Selected target device.
208 * @param[in] momType Mode of multiple ownership transfer (ref. oic.sec.mom)
209 * @param[in] resultCallback callback provided by API user, callback will be called when
210 * POST 'mom' request recieves a response from resource server.
211 * @return OC_STACK_OK in case of success and other value otherwise.
213 OCStackResult MOTChangeMode(void *ctx, const OCProvisionDev_t *targetDeviceInfo,
214 const OicSecMomType_t momType, OCProvisionResultCB resultCallback)
216 OCStackResult postMomRes = OC_STACK_INVALID_PARAM;
217 OicSecDoxm_t* doxm = NULL;
218 uint8_t* doxmPayload = NULL;
219 size_t doxmPayloadLen = 0;
221 OIC_LOG(DEBUG, TAG, "IN MOTChangeMode");
223 VERIFY_NON_NULL(TAG, targetDeviceInfo, ERROR);
224 VERIFY_NON_NULL(TAG, resultCallback, ERROR);
226 //Dulpicate doxm resource to update the 'mom' property
227 postMomRes = DoxmToCBORPayload(targetDeviceInfo->doxm, &doxmPayload, &doxmPayloadLen, false);
228 VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
230 postMomRes = CBORPayloadToDoxm(doxmPayload, doxmPayloadLen, &doxm);
231 VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
232 VERIFY_NON_NULL(TAG, doxm, ERROR);
234 if(NULL == doxm->mom)
236 doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
237 VERIFY_NON_NULL(TAG, (doxm->mom), ERROR);
239 doxm->mom->mode = momType;
241 //Send POST reuqest for update doxm
242 postMomRes = MOTSendPostDoxm(ctx, targetDeviceInfo, resultCallback, doxm);
243 VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
245 OIC_LOG(DEBUG, TAG, "OUT MOTChangeMode");
248 OICFree(doxmPayload);
249 DeleteDoxmBinData(doxm);
254 * API to add 'doxm.oxms' to resource server.
256 * @param[in] targetDeviceInfo Selected target device.
257 * @param[in] newOxm OxMs to be added (ref. oic.sec.oxm)
258 * @param[in] resultCallback callback provided by API user, callback will be called when
259 * POST 'oxms' request recieves a response from resource server.
260 * @return OC_STACK_OK in case of success and other value otherwise.
262 OCStackResult MOTAddMOTMethod(void *ctx, OCProvisionDev_t *targetDeviceInfo,
263 const OicSecOxm_t newOxm, OCProvisionResultCB resultCallback)
265 OCStackResult postOxmRes = OC_STACK_INVALID_PARAM;
266 OicSecOxm_t* newOxms = NULL;
267 uint8_t* doxmPayload = NULL;
268 size_t doxmPayloadLen = 0;
270 OIC_LOG(DEBUG, TAG, "IN MOTAddMOTMethod");
272 VERIFY_NON_NULL(TAG, targetDeviceInfo, ERROR);
273 VERIFY_NON_NULL(TAG, resultCallback, ERROR);
275 for(size_t i = 0; i < targetDeviceInfo->doxm->oxmLen; i++)
277 if(targetDeviceInfo->doxm->oxm[i] == newOxm)
279 OIC_LOG_V(INFO, TAG, "[%d] OxM already supported", (int)newOxm);
281 OCProvisionResult_t* resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
282 resArr->res = OC_STACK_OK;
283 memcpy(resArr->deviceId.id, targetDeviceInfo->doxm->deviceID.id, sizeof(resArr->deviceId.id));
284 resultCallback(ctx, 1, resArr, false);
290 newOxms = (OicSecOxm_t*)OICMalloc(sizeof(OicSecOxm_t) * (targetDeviceInfo->doxm->oxmLen + 1));
291 VERIFY_NON_NULL(TAG, newOxms , ERROR);
293 for(size_t i = 0; i < targetDeviceInfo->doxm->oxmLen; i++)
295 newOxms[i] = targetDeviceInfo->doxm->oxm[i];
297 newOxms[targetDeviceInfo->doxm->oxmLen] = newOxm;
298 targetDeviceInfo->doxm->oxmLen++;
299 OICFree(targetDeviceInfo->doxm->oxm);
300 targetDeviceInfo->doxm->oxm = newOxms;
302 //Send POST reuqest for update doxm
303 postOxmRes = MOTSendPostDoxm(ctx, targetDeviceInfo, resultCallback, targetDeviceInfo->doxm);
304 VERIFY_SUCCESS(TAG, (OC_STACK_OK == postOxmRes), ERROR);
306 OIC_LOG(DEBUG, TAG, "OUT MOTAddMOTMethod");
309 OICFree(doxmPayload);
314 * API to update 'doxm.oxmsel' to resource server.
316 * @param[in] targetDeviceInfo Selected target device.
317 * @param[in] oxmSelValue Method of multiple ownership transfer (ref. oic.sec.oxm)
318 * @param[in] resultCallback callback provided by API user, callback will be called when
319 * POST 'oxmsel' request recieves a response from resource server.
320 * @return OC_STACK_OK in case of success and other value otherwise.
322 OCStackResult MOTSelectMOTMethod(void *ctx, const OCProvisionDev_t *targetDeviceInfo,
323 const OicSecOxm_t oxmSelValue, OCProvisionResultCB resultCallback)
325 OCStackResult postMomRes = OC_STACK_INVALID_PARAM;
326 OicSecDoxm_t* doxm = NULL;
327 uint8_t* doxmPayload = NULL;
328 size_t doxmPayloadLen = 0;
330 OIC_LOG(DEBUG, TAG, "IN MOTSelectOTMethod");
332 VERIFY_NON_NULL(TAG, targetDeviceInfo, ERROR);
333 VERIFY_NON_NULL(TAG, resultCallback, ERROR);
335 bool isValidOxmsel = false;
336 for(size_t i = 0; i < targetDeviceInfo->doxm->oxmLen; i++)
338 if(targetDeviceInfo->doxm->oxm[i] == oxmSelValue)
340 isValidOxmsel = true;
344 VERIFY_SUCCESS(TAG, isValidOxmsel, ERROR);
346 //Dulpicate doxm resource to update the 'oxmsel' property
347 postMomRes = DoxmToCBORPayload(targetDeviceInfo->doxm, &doxmPayload, &doxmPayloadLen, false);
348 VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
350 postMomRes = CBORPayloadToDoxm(doxmPayload, doxmPayloadLen, &doxm);
351 VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
352 VERIFY_NON_NULL(TAG, doxm, ERROR);
354 doxm->oxmSel = oxmSelValue;
356 //Send POST reuqest for update doxm
357 postMomRes = MOTSendPostDoxm(ctx, targetDeviceInfo, resultCallback, doxm);
358 VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
360 OIC_LOG(DEBUG, TAG, "OUT MOTSelectOTMethod");
363 OICFree(doxmPayload);
364 DeleteDoxmBinData(doxm);
369 * API to provision preconfigured PIN to resource server.
371 * @param[in] targetDeviceInfo Selected target device.
372 * @param[in] preconfPIN Preconfig PIN which is used while multiple owner authentication
373 * @param[in] preconfPINLen Byte length of preconfig PIN
374 * @param[in] resultCallback callback provided by API user, callback will be called when
375 * POST credential request recieves a response from resource server.
376 * @return OC_STACK_OK in case of success and other value otherwise.
378 OCStackResult MOTProvisionPreconfigPIN(void *ctx, const OCProvisionDev_t *targetDeviceInfo,
379 const char* preconfPIN, size_t preconfPINLen, OCProvisionResultCB resultCallback)
381 OCStackResult postCredRes = OC_STACK_INVALID_PARAM;
382 bool freeFlag = true;
383 OCSecurityPayload* secPayload = NULL;
384 MOTContext_t *motCtx = NULL;
385 OicSecCred_t* pinCred = NULL;
387 OIC_LOG(DEBUG, TAG, "IN MOTProvisionPreconfigPIN");
389 VERIFY_NON_NULL(TAG, targetDeviceInfo, ERROR);
390 VERIFY_NON_NULL(TAG, resultCallback, ERROR);
391 VERIFY_NON_NULL(TAG, preconfPIN, ERROR);
392 VERIFY_SUCCESS(TAG, (0 != preconfPINLen), ERROR);
393 VERIFY_SUCCESS(TAG, (0 != preconfPINLen && OXM_PRECONFIG_PIN_SIZE >= preconfPINLen), ERROR);
395 postCredRes = OC_STACK_NO_MEMORY;
396 //Generate PIN based credential
397 pinCred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
398 VERIFY_NON_NULL(TAG, pinCred, ERROR);
400 pinCred->privateData.data = (uint8_t*)OICMalloc(preconfPINLen + 1);
401 VERIFY_NON_NULL(TAG, pinCred->privateData.data, ERROR);
403 memcpy(pinCred->privateData.data, preconfPIN, preconfPINLen);
404 pinCred->privateData.data[preconfPINLen] = '\0';
405 pinCred->privateData.len = preconfPINLen;
406 pinCred->privateData.encoding = OIC_ENCODING_RAW;
407 pinCred->credType = PIN_PASSWORD;
408 OICStrcpy(pinCred->subject.id, sizeof(pinCred->subject.id), WILDCARD_SUBJECT_ID.id);
410 //Generate the security payload using updated doxm
411 secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
412 VERIFY_NON_NULL(TAG, secPayload, ERROR);
413 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
415 postCredRes = CredToCBORPayload(pinCred, &secPayload->securityData, &secPayload->payloadSize, false);
416 VERIFY_SUCCESS(TAG, (OC_STACK_OK == postCredRes), ERROR);
418 OIC_LOG(DEBUG, TAG, "Created Credential payload to register PIN credential:");
419 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
421 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
422 bool queryGenRes = PMGenerateQuery(true,
423 targetDeviceInfo->endpoint.addr,
424 targetDeviceInfo->securePort,
425 targetDeviceInfo->connType,
426 query, sizeof(query), OIC_RSRC_CRED_URI);
427 VERIFY_SUCCESS(TAG, (true == queryGenRes), ERROR);
428 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
430 //Create the MOT Context to handle the response message
431 motCtx = (MOTContext_t*)OICCalloc(1, sizeof(MOTContext_t));
432 VERIFY_NON_NULL(TAG, motCtx, ERROR);
433 motCtx->deviceInfo = targetDeviceInfo;
434 motCtx->resultCallback = resultCallback;
435 motCtx->numOfResults=1;
436 motCtx->hasError = false;
438 motCtx->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
439 VERIFY_NON_NULL(TAG, motCtx->resArr, ERROR);
442 OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
443 cbData.cb = &MOTUpdateSecurityResourceCB;
444 cbData.context = (void *)motCtx;
445 OIC_LOG(DEBUG, TAG, "Sending POST Preconfiged PIN credenatial request to resource server");
446 postCredRes = OCDoResource(NULL, OC_REST_POST, query,
447 &targetDeviceInfo->endpoint, (OCPayload*)secPayload,
448 targetDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
449 VERIFY_SUCCESS(TAG, (OC_STACK_OK == postCredRes), ERROR);
453 OIC_LOG(DEBUG, TAG, "OUT MOTProvisionPreconfigPIN");
458 //If POST request successfully sent, motCtx will be cleaned from response handler.
459 if(freeFlag && motCtx)
461 OICFree(motCtx->resArr);
466 OICFree(pinCred->privateData.data);
473 /**********************************************************************
475 **********************************************************************/
477 static OCStackResult StartMultipleOwnershipTransfer(OTMContext_t* motCtx,
478 OCProvisionDev_t* selectedDevice);
481 * Array to store the callbacks for each owner transfer method.
483 static OTMCallbackData_t g_MOTCbDatas[OIC_OXM_COUNT] = {
485 {.loadSecretCB = LoadSecretJustWorksCallback,
486 .createSecureSessionCB = CreateSecureSessionJustWorksCallback,
487 .createSelectOxmPayloadCB = NULL,
488 .createOwnerTransferPayloadCB = NULL},
491 {.loadSecretCB = InputPinCodeCallback,
492 .createSecureSessionCB = CreateSecureSessionRandomPinCallback,
493 .createSelectOxmPayloadCB = NULL,
494 .createOwnerTransferPayloadCB = NULL},
497 {.loadSecretCB = NULL,
498 .createSecureSessionCB = NULL,
499 .createSelectOxmPayloadCB = NULL,
500 .createOwnerTransferPayloadCB = NULL},
503 {.loadSecretCB = LoadPreconfPinCodeCallback,
504 .createSecureSessionCB = CreateSecureSessionPreconfPinCallback,
505 .createSelectOxmPayloadCB = NULL,
506 .createOwnerTransferPayloadCB = NULL},
509 static OTMContext_t* g_MotCtx = NULL;
511 static bool IsComplete(OTMContext_t* otmCtx)
513 for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
515 if(OC_STACK_CONTINUE == otmCtx->ctxResultArray[i].res)
525 * Function to save the result of multiple ownership transfer.
527 * @param[in,out] motCtx Context instance of multiple ownership transfer.
528 * @param[in] res result of multiple ownership transfer.
530 static void SetMOTResult(OTMContext_t* motCtx, const OCStackResult res)
532 OIC_LOG_V(DEBUG, TAG, "IN SetMOTResult : %d ", res);
534 VERIFY_NON_NULL(TAG, motCtx, ERROR);
536 if(motCtx->selectedDeviceInfo)
538 //Revert psk_info callback in case of random PIN OxM
539 if(OIC_RANDOM_DEVICE_PIN == motCtx->selectedDeviceInfo->doxm->oxmSel ||
540 OIC_PRECONFIG_PIN == motCtx->selectedDeviceInfo->doxm->oxmSel)
542 if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
544 OIC_LOG(WARNING, TAG, "Failed to revert the DTLS credential handler.");
546 OicUuid_t emptyUuid = { .id={0}};
547 SetUuidForPinBasedOxm(&emptyUuid);
550 for(size_t i = 0; i < motCtx->ctxResultArraySize; i++)
552 if(memcmp(motCtx->selectedDeviceInfo->doxm->deviceID.id,
553 motCtx->ctxResultArray[i].deviceId.id, UUID_LENGTH) == 0)
555 motCtx->ctxResultArray[i].res = res;
556 if(OC_STACK_OK != res)
558 motCtx->ctxHasError = true;
565 //If all request is completed, invoke the user callback.
566 if(IsComplete(motCtx))
568 motCtx->ctxResultCallback(motCtx->userCtx, motCtx->ctxResultArraySize,
569 motCtx->ctxResultArray, motCtx->ctxHasError);
571 OICFree(motCtx->ctxResultArray);
576 if(OC_STACK_OK != StartMultipleOwnershipTransfer(motCtx,
577 motCtx->selectedDeviceInfo->next))
579 OIC_LOG(ERROR, TAG, "Failed to StartMultipleOwnershipTransfer");
585 OIC_LOG(DEBUG, TAG, "OUT SetMOTResult");
589 * API to add preconfigured PIN to local SVR DB.
591 * @param[in] targetDeviceInfo Selected target device.
592 * @param[in] preconfPIN Preconfig PIN which is used while multiple owner authentication
593 * @param[in] preconfPINLen Byte length of preconfig PIN
594 * @param[in] resultCallback callback provided by API user, callback will be called when
595 * POST credential request recieves a response from resource server.
596 * @return OC_STACK_OK in case of success and other value otherwise.
598 OCStackResult MOTAddPreconfigPIN(const OCProvisionDev_t *targetDeviceInfo,
599 const char* preconfPIN, size_t preconfPINLen)
601 OCStackResult addCredRes = OC_STACK_INVALID_PARAM;
602 OicSecCred_t* pinCred = NULL;
603 bool freeFlag = true;
605 OIC_LOG(DEBUG, TAG, "IN MOTAddPreconfigPIN");
607 VERIFY_NON_NULL(TAG, targetDeviceInfo, ERROR);
608 VERIFY_NON_NULL(TAG, preconfPIN, ERROR);
609 VERIFY_SUCCESS(TAG, (0 != preconfPINLen), ERROR);
610 VERIFY_SUCCESS(TAG, (0 != preconfPINLen && OXM_PRECONFIG_PIN_SIZE >= preconfPINLen), ERROR);
612 OicSecCred_t* prevCred = GetCredResourceData(&targetDeviceInfo->doxm->deviceID);
615 OIC_LOG(INFO, TAG, "PIN/PW Credential already exist!");
619 addCredRes = OC_STACK_NO_MEMORY;
620 //Generate PIN based credential
621 pinCred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
622 VERIFY_NON_NULL(TAG, pinCred, ERROR);
624 pinCred->privateData.data = (uint8_t*)OICMalloc(preconfPINLen + 1);
625 VERIFY_NON_NULL(TAG, pinCred->privateData.data, ERROR);
627 memcpy(pinCred->privateData.data, preconfPIN, preconfPINLen);
628 pinCred->privateData.data[preconfPINLen] = '\0';
629 pinCred->privateData.len = preconfPINLen;
630 pinCred->privateData.encoding = OIC_ENCODING_RAW;
631 pinCred->credType = PIN_PASSWORD;
632 memcpy(pinCred->subject.id, targetDeviceInfo->doxm->deviceID.id, sizeof(pinCred->subject.id));
634 addCredRes = AddCredential(pinCred);
635 VERIFY_SUCCESS(TAG, (OC_STACK_OK == addCredRes), ERROR);
637 OIC_LOG(DEBUG, TAG, "OUT MOTAddPreconfigPIN");
644 OICFree(pinCred->privateData.data);
651 * Function to save the SubOwner PSK.
653 * @param[in] selectedDeviceInfo selected device information to performing provisioning.
654 * @return OC_STACK_OK on success
656 static OCStackResult SaveSubOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
658 OIC_LOG(DEBUG, TAG, "IN SaveSubOwnerPSK");
660 OCStackResult res = OC_STACK_ERROR;
662 CAEndpoint_t endpoint;
663 memset(&endpoint, 0x00, sizeof(CAEndpoint_t));
664 OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, selectedDeviceInfo->endpoint.addr);
665 endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
666 endpoint.port = selectedDeviceInfo->securePort;
667 endpoint.adapter = selectedDeviceInfo->endpoint.adapter;
669 OicUuid_t ownerDeviceID = {.id={0}};
670 if (OC_STACK_OK != GetDoxmDeviceID(&ownerDeviceID))
672 OIC_LOG(ERROR, TAG, "Error while retrieving SubOwner's device ID");
676 uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
677 OicSecKey_t ownerKey = {ownerPSK, OWNER_PSK_LENGTH_128};
679 //Generating SubOwnerPSK
680 CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint,
681 (uint8_t *)GetOxmString(selectedDeviceInfo->doxm->oxmSel),
682 strlen(GetOxmString(selectedDeviceInfo->doxm->oxmSel)),
683 ownerDeviceID.id, sizeof(ownerDeviceID.id),
684 selectedDeviceInfo->doxm->deviceID.id, sizeof(selectedDeviceInfo->doxm->deviceID.id),
685 ownerPSK, OWNER_PSK_LENGTH_128);
687 if (CA_STATUS_OK == pskRet)
689 OIC_LOG(INFO, TAG, "SubOwner PSK dump:");
690 OIC_LOG_BUFFER(INFO, TAG, ownerPSK, OWNER_PSK_LENGTH_128);
691 //Generating new credential for provisioning tool
692 OicSecCred_t *cred = GenerateCredential(&selectedDeviceInfo->doxm->deviceID,
693 SYMMETRIC_PAIR_WISE_KEY, NULL,
694 &ownerKey, &ownerDeviceID, &ownerDeviceID);
695 VERIFY_NON_NULL(TAG, cred, ERROR);
697 uint32_t outSize = 0;
698 size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((OWNER_PSK_LENGTH_128 + 1));
699 char* b64Buf = (uint8_t *)OICCalloc(1, b64BufSize);
700 VERIFY_NON_NULL(TAG, b64Buf, ERROR);
701 b64Encode(cred->privateData.data, cred->privateData.len, b64Buf, b64BufSize, &outSize);
703 OICFree( cred->privateData.data );
704 cred->privateData.data = (uint8_t *)OICCalloc(1, outSize + 1);
705 VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
707 strncpy(cred->privateData.data, b64Buf, outSize);
708 cred->privateData.data[outSize] = '\0';
709 cred->privateData.encoding = OIC_ENCODING_BASE64;
710 cred->privateData.len = outSize;
714 res = AddCredential(cred);
715 if(res != OC_STACK_OK)
717 DeleteCredList(cred);
723 OIC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
726 OIC_LOG(DEBUG, TAG, "OUT SaveSubOwnerPSK");
733 * Response handler for update subowner crendetial request.
735 * @param[in] ctx ctx value passed to callback from calling function.
736 * @param[in] UNUSED handle to an invocation
737 * @param[in] clientResponse Response from queries to remote servers.
738 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
739 * and OC_STACK_KEEP_TRANSACTION to keep it.
741 static OCStackApplicationResult SubOwnerCredentialHandler(void *ctx, OCDoHandle UNUSED,
742 OCClientResponse *clientResponse)
744 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
745 VERIFY_NON_NULL(TAG, ctx, WARNING);
747 OIC_LOG(DEBUG, TAG, "IN SubOwnerCredentialHandler");
749 OCStackResult res = OC_STACK_ERROR;
750 OTMContext_t* motCtx = (OTMContext_t*)ctx;
752 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
754 if(motCtx && motCtx->selectedDeviceInfo)
756 //Close the temporal secure session to verify the owner credential
757 CAEndpoint_t* endpoint = (CAEndpoint_t *)&motCtx->selectedDeviceInfo->endpoint;
758 endpoint->port = motCtx->selectedDeviceInfo->securePort;
759 CAResult_t caResult = CAcloseSslSession(endpoint);
760 if(CA_STATUS_OK != caResult)
762 OIC_LOG(ERROR, TAG, "Failed to close DTLS session");
763 SetMOTResult(motCtx, OC_STACK_ERROR);
764 return OC_STACK_DELETE_TRANSACTION;
767 // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 = 0xC037, /**< see RFC 5489 */
768 caResult = CASelectCipherSuite(0xC037, endpoint->adapter);
769 if(CA_STATUS_OK != caResult)
771 OIC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL");
772 SetMOTResult(motCtx, OC_STACK_ERROR);
773 return OC_STACK_DELETE_TRANSACTION;
776 res = PDMAddDevice(&motCtx->selectedDeviceInfo->doxm->deviceID);
777 if (OC_STACK_OK == res)
779 OIC_LOG_V(INFO, TAG, "Add device's UUID in PDM_DB");
783 OIC_LOG(ERROR, TAG, "MOT is complete but adding information to DB is failed.");
786 SetMOTResult(motCtx, res);
791 res = clientResponse->result;
792 OIC_LOG_V(ERROR, TAG, "SubOwnerCredentialHandler : Unexpected result %d", res);
793 SetMOTResult(motCtx, res);
796 OIC_LOG(DEBUG, TAG, "OUT SubOwnerCredentialHandler");
799 return OC_STACK_DELETE_TRANSACTION;
803 static OCStackResult PostSubOwnerCredential(OTMContext_t* motCtx)
805 OIC_LOG(DEBUG, TAG, "IN PostSubOwnerCredential");
807 if(!motCtx || !motCtx->selectedDeviceInfo)
809 OIC_LOG(ERROR, TAG, "Invalid parameters");
810 return OC_STACK_INVALID_PARAM;
813 OCProvisionDev_t* deviceInfo = motCtx->selectedDeviceInfo;
814 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
816 if(!PMGenerateQuery(true,
817 deviceInfo->endpoint.addr, deviceInfo->securePort,
818 deviceInfo->connType,
819 query, sizeof(query), OIC_RSRC_CRED_URI))
821 OIC_LOG(ERROR, TAG, "PostSubOwnerCredential : Failed to generate query");
822 return OC_STACK_ERROR;
824 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
825 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
828 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
829 return OC_STACK_NO_MEMORY;
832 //Generate sub-owner credential for new device
833 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
834 const OicSecCred_t* ownerCredential = GetCredResourceData(&(deviceInfo->doxm->deviceID));
837 OIC_LOG(ERROR, TAG, "Can not find SubOwnerPSK.");
838 return OC_STACK_NO_RESOURCE;
841 OicUuid_t ownerId = {.id={0}};
842 if(OC_STACK_OK == GetDoxmDeviceID(&ownerId))
844 OicSecCred_t newCredential;
845 memcpy(&newCredential, ownerCredential, sizeof(OicSecCred_t));
846 newCredential.next = NULL;
848 //Set subject ID as SubOwner's ID
849 memcpy(&(newCredential.subject), &ownerId, sizeof(OicUuid_t));
851 //Set eowner ID as SubOwner's ID
852 if(NULL == newCredential.eownerID)
854 newCredential.eownerID = OICCalloc(1, sizeof(OicUuid_t));
855 if(NULL == newCredential.eownerID)
857 return OC_STACK_NO_MEMORY;
860 memcpy(newCredential.eownerID->id, ownerId.id, sizeof(ownerId.id));
862 //Fill private data as empty string
863 newCredential.privateData.data = "";
864 newCredential.privateData.len = 0;
865 newCredential.privateData.encoding = ownerCredential->privateData.encoding;
867 newCredential.publicData.data = NULL;
868 newCredential.publicData.len = 0;
870 //Send owner credential to new device : POST /oic/sec/cred [ owner credential ]
871 if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData,
872 &secPayload->payloadSize, 0))
875 OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
876 return OC_STACK_ERROR;
878 OIC_LOG(DEBUG, TAG, "Cred Payload:");
879 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
881 OCCallbackData cbData;
882 cbData.cb = &SubOwnerCredentialHandler;
883 cbData.context = (void *)motCtx;
885 OCStackResult res = OCDoResource(NULL, OC_REST_POST, query,
886 &deviceInfo->endpoint, (OCPayload*)secPayload,
887 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
888 if (res != OC_STACK_OK)
890 OIC_LOG(ERROR, TAG, "OCStack resource error");
895 OIC_LOG(ERROR, TAG, "Failed to read DOXM device ID.");
896 return OC_STACK_NO_RESOURCE;
899 OIC_LOG(DEBUG, TAG, "OUT PostSubOwnerCredential");
906 * Function to handle the handshake result in MOT.
907 * This function will be invoked after DTLS handshake
908 * @param endPoint [IN] The remote endpoint.
909 * @param errorInfo [IN] Error information from the endpoint.
912 static void MOTDtlsHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
914 if(NULL != g_MotCtx && NULL != g_MotCtx->selectedDeviceInfo &&
915 NULL != endpoint && NULL != info)
917 OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",
918 endpoint->addr, endpoint->port, info->result);
920 OicSecDoxm_t* newDevDoxm = g_MotCtx->selectedDeviceInfo->doxm;
922 if(NULL != newDevDoxm)
924 OicUuid_t emptyUuid = {.id={0}};
926 //Make sure the address matches.
927 if(strncmp(g_MotCtx->selectedDeviceInfo->endpoint.addr,
929 sizeof(endpoint->addr)) == 0 &&
930 g_MotCtx->selectedDeviceInfo->securePort == endpoint->port)
932 OCStackResult res = OC_STACK_ERROR;
934 //If temporal secure sesstion established successfully
935 if(CA_STATUS_OK == info->result)
937 //Delete previous credential such as preconfigured-pin
938 RemoveCredential(&(g_MotCtx->selectedDeviceInfo->doxm->deviceID));
940 res = SaveSubOwnerPSK(g_MotCtx->selectedDeviceInfo);
941 if(OC_STACK_OK == res)
943 //POST sub owner credential to new device.
944 res = PostSubOwnerCredential(g_MotCtx);
945 if(OC_STACK_OK != res)
948 "Failed to send POST request for SubOwner Credential");
949 SetMOTResult(g_MotCtx, res);
954 OIC_LOG(ERROR, TAG, "Failed to save the SubOwner PSK.");
955 SetMOTResult(g_MotCtx, res);
958 //In case of authentication failure
959 else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)
961 //in case of error from wrong PIN, re-start the ownership transfer
962 if(OIC_RANDOM_DEVICE_PIN == newDevDoxm->oxmSel)
964 OIC_LOG(ERROR, TAG, "The PIN number may incorrect.");
966 g_MotCtx->attemptCnt++;
968 if(WRONG_PIN_MAX_ATTEMP > g_MotCtx->attemptCnt)
970 res = StartMultipleOwnershipTransfer(g_MotCtx, g_MotCtx->selectedDeviceInfo);
971 if(OC_STACK_OK != res)
973 SetMOTResult(g_MotCtx, res);
974 OIC_LOG(ERROR, TAG, "Failed to Re-StartOwnershipTransfer");
979 OIC_LOG(ERROR, TAG, "User has exceeded the number of authentication attempts.");
980 SetMOTResult(g_MotCtx, OC_STACK_AUTHENTICATION_FAILURE);
985 OIC_LOG(ERROR, TAG, "Failed to establish DTLS session.");
986 SetMOTResult(g_MotCtx, OC_STACK_AUTHENTICATION_FAILURE);
994 static OCStackResult StartMultipleOwnershipTransfer(OTMContext_t* motCtx,
995 OCProvisionDev_t* selectedDevice)
997 OIC_LOG(INFO, TAG, "IN StartMultipleOwnershipTransfer");
998 OCStackResult res = OC_STACK_INVALID_PARAM;
1000 VERIFY_NON_NULL(TAG, selectedDevice, ERROR);
1001 VERIFY_NON_NULL(TAG, selectedDevice->doxm, ERROR);
1003 motCtx->selectedDeviceInfo = selectedDevice;
1005 //Register DTLS event handler to catch the dtls event while handshake
1006 if(CA_STATUS_OK != CAregisterSslHandshakeCallback(MOTDtlsHandshakeCB))
1008 OIC_LOG(WARNING, TAG, "StartOwnershipTransfer : Failed to register DTLS handshake callback.");
1011 size_t oxmSel = (size_t)(selectedDevice->doxm->oxmSel);
1012 OIC_LOG_V(DEBUG, TAG, "Multiple Ownership Transfer method = %d", selectedDevice->doxm->oxmSel);
1014 if(OIC_PRECONFIG_PIN != oxmSel && OIC_RANDOM_DEVICE_PIN != oxmSel)
1016 OIC_LOG(ERROR, TAG, "Unsupported OxM");
1017 return OC_STACK_ERROR;
1020 if(OIC_RANDOM_DEVICE_PIN == selectedDevice->doxm->oxmSel)
1022 if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm))
1024 OIC_LOG(ERROR, TAG, "Failed to register DTLS credential handler for Random PIN OxM.");
1028 res = g_MOTCbDatas[oxmSel].loadSecretCB(motCtx);
1029 VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
1031 //Save the current context instance to use on the dtls handshake callback
1034 res = g_MOTCbDatas[oxmSel].createSecureSessionCB(motCtx);
1035 VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
1037 OIC_LOG(INFO, TAG, "OUT StartMultipleOwnershipTransfer");
1043 OCStackResult MOTDoOwnershipTransfer(void* ctx,
1044 OCProvisionDev_t *selectedDevicelist,
1045 OCProvisionResultCB resultCallback)
1047 OIC_LOG(DEBUG, TAG, "IN MOTDoOwnershipTransfer");
1048 OCStackResult res = OC_STACK_INVALID_PARAM;
1049 OTMContext_t* motCtx = NULL;
1050 OCProvisionDev_t* pCurDev = NULL;
1052 VERIFY_NON_NULL(TAG, selectedDevicelist, ERROR);
1053 VERIFY_NON_NULL(TAG, resultCallback, ERROR);
1055 res = OC_STACK_NO_MEMORY;
1056 motCtx = (OTMContext_t*)OICCalloc(1,sizeof(OTMContext_t));
1057 VERIFY_NON_NULL(TAG, motCtx, ERROR);
1059 motCtx->ctxResultCallback = resultCallback;
1060 motCtx->ctxHasError = false;
1061 motCtx->userCtx = ctx;
1062 motCtx->ctxResultArraySize = 0;
1063 LL_FOREACH(selectedDevicelist, pCurDev)
1065 motCtx->ctxResultArraySize++;
1068 motCtx->ctxResultArray =
1069 (OCProvisionResult_t*)OICCalloc(motCtx->ctxResultArraySize, sizeof(OCProvisionResult_t));
1070 VERIFY_NON_NULL(TAG, motCtx->ctxResultArray, ERROR);
1072 //Fill the device UUID for result array.
1076 LL_FOREACH(selectedDevicelist, pCurDev)
1078 //Checking duplication of Device ID.
1079 bool isDuplicate = true;
1080 res = PDMIsDuplicateDevice(&pCurDev->doxm->deviceID, &isDuplicate);
1081 VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
1085 bool isStale = false;
1086 res = PDMIsDeviceStale(&pCurDev->doxm->deviceID, &isStale);
1087 VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
1088 VERIFY_SUCCESS(TAG, isStale, ERROR);
1092 OIC_LOG(INFO, TAG, "Detected duplicated UUID in stale status, "\
1093 "this UUID will be removed from PDM");
1095 res = PDMDeleteDevice(&pCurDev->doxm->deviceID);
1096 VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
1100 memcpy(motCtx->ctxResultArray[devIdx].deviceId.id,
1101 pCurDev->doxm->deviceID.id,
1103 motCtx->ctxResultArray[devIdx].res = OC_STACK_CONTINUE;
1107 res = StartMultipleOwnershipTransfer(motCtx, selectedDevicelist);
1108 VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
1110 OIC_LOG(DEBUG, TAG, "OUT MOTDoOwnershipTransfer");
1113 if(OC_STACK_OK != res)
1117 OICFree(motCtx->ctxResultArray);