Add PIN based OxM for security provisioning
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / src / ownershiptransfermanager.c
1 /* *****************************************************************
2  *
3  * Copyright 2015 Samsung Electronics 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 // Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
22 // causes header files to expose definitions
23 // corresponding to the POSIX.1b, Real-time extensions
24 // (IEEE Std 1003.1b-1993) specification
25 //
26 // For this specific file, see use of clock_gettime,
27 // Refer to http://pubs.opengroup.org/stage7tc1/functions/clock_gettime.html
28 // and to http://man7.org/linux/man-pages/man2/clock_gettime.2.html
29 #ifndef _POSIX_C_SOURCE
30 #define _POSIX_C_SOURCE 200809L
31 #endif
32
33 #include <time.h>
34 #include <unistd.h>
35 #include <sys/time.h>
36 #include <stdbool.h>
37 #include <string.h>
38
39 #include "logger.h"
40 #include "oic_malloc.h"
41 #include "oic_string.h"
42 #include "cacommon.h"
43 #include "cainterface.h"
44 #include "base64.h"
45 #include "cJSON.h"
46
47 #include "srmresourcestrings.h"
48 #include "doxmresource.h"
49 #include "pstatresource.h"
50 #include "credresource.h"
51 #include "aclresource.h"
52 #include "ownershiptransfermanager.h"
53 #include "securevirtualresourcetypes.h"
54 #include "oxmjustworks.h"
55 #include "pmtypes.h"
56 #include "pmutility.h"
57 #include "srmutility.h"
58
59 // TODO: Not yet supported.
60 //#include "oxmrandompin.h"
61
62 #define DEFAULT_CONTEXT_VALUE 0x99
63 #define DEFAULT_SECURE_PORT 5684
64
65 #define TAG "OTM"
66
67 OCProvisionResultCB g_resultCallback;
68 OCProvisionResult_t* g_resultArray = NULL;
69 size_t g_resultArraySize = 0;
70 bool g_hasError = false;
71
72 /**
73  * Possible states of ownership transfer manager module.
74  */
75 typedef enum
76 {
77     SP_NO_MASK                = (0       ),
78     SP_DISCOVERY_STARTED      = (0x1 << 1),
79     SP_DISCOVERY_ERROR        = (0x1 << 2),
80     SP_DISCOVERY_DONE         = (0x1 << 3),
81     SP_UP_OWN_TR_METH_STARTED = (0x1 << 4),
82     SP_UP_OWN_TR_METH_ERROR   = (0x1 << 5),
83     SP_UP_OWN_TR_METH_DONE    = (0x1 << 6),
84     SP_LIST_METHODS_STARTED   = (0x1 << 7),
85     SP_LIST_METHODS_ERROR     = (0x1 << 8),
86     SP_LIST_METHODS_DONE      = (0x1 << 9),
87     SP_UPDATE_OP_MODE_STARTED = (0x1 << 10),
88     SP_UPDATE_OP_MODE_ERROR   = (0x1 << 11),
89     SP_UPDATE_OP_MODE_DONE    = (0x1 << 12),
90     SP_UPDATE_OWNER_STARTED   = (0x1 << 13),
91     SP_UPDATE_OWNER_ERROR     = (0x1 << 14),
92     SP_UPDATE_OWNER_DONE      = (0x1 << 15)
93 } OTMStates;
94
95
96
97 /**
98  * Array to store the callbacks for each owner transfer method.
99  */
100 OTMCallbackData_t g_OTMDatas[OIC_OXM_COUNT];
101
102 /**
103  * Variable for storing provisioning tool's provisioning capabilities
104  * Must be in decreasing order of preference. More prefered method should
105  * have lower array index.
106  */
107 static OicSecDpom_t gProvisioningToolCapability[] = { SINGLE_SERVICE_CLIENT_DRIVEN };
108
109 /**
110  * Number of supported provisioning methods
111  * current version supports only one.
112  */
113 static size_t gNumOfProvisioningMethodsPT = 1;
114
115 /**
116  * Function to getting string of ownership transfer method
117  */
118 static const char* GetOxmString(OicSecOxm_t oxmType)
119 {
120     switch(oxmType)
121     {
122         case OIC_JUST_WORKS:
123             return OXM_JUST_WORKS;
124         case OIC_MODE_SWITCH:
125             return OXM_MODE_SWITCH;
126         case OIC_RANDOM_DEVICE_PIN:
127             return OXM_RANDOM_DEVICE_PIN;
128         case OIC_PRE_PROVISIONED_DEVICE_PIN:
129             return OXM_PRE_PROVISIONED_DEVICE_PIN;
130         case OIC_PRE_PROVISION_STRONG_CREDENTIAL:
131             return OXM_PRE_PROVISIONED_STRONG_CREDENTIAL;
132         default:
133             return NULL;
134     }
135 }
136
137 /**
138  * Function to select appropriate  provisioning method.
139  *
140  * @param[in] supportedMethods   Array of supported methods
141  * @param[in] numberOfMethods   number of supported methods
142  * @param[out]  selectedMethod         Selected methods
143  * @return  SP_SUCCESS on success
144  */
145 static OCStackResult SelectProvisioningMethod(const OicSecOxm_t *supportedMethods,
146                                                             size_t numberOfMethods,
147                                                             OicSecOxm_t *selectedMethod)
148 {
149     OC_LOG(DEBUG, TAG, "IN SelectProvisioningMethod");
150
151     if(numberOfMethods == 0 || !supportedMethods)
152     {
153         OC_LOG(WARNING, TAG, "Could not find a supported OxM.");
154         return OC_STACK_ERROR;
155     }
156
157     *selectedMethod  = supportedMethods[0];
158     for(size_t i = 0; i < numberOfMethods; i++)
159     {
160         if(*selectedMethod < supportedMethods[i])
161         {
162             *selectedMethod =  supportedMethods[i];
163         }
164     }
165
166     return OC_STACK_OK;
167 }
168
169 /**
170  * Function to select operation mode.This function will return most secure common operation mode.
171  *
172  * @param[in] selectedDeviceInfo   selected device information to performing provisioning.
173  * @param[out]   selectedMode   selected operation mode
174  * @return  SP_SUCCESS on success
175  */
176 static void SelectOperationMode(const OCProvisionDev_t *selectedDeviceInfo,
177                                 OicSecDpom_t *selectedMode)
178 {
179     OC_LOG(DEBUG, TAG, "IN SelectOperationMode");
180
181     size_t i = 0;
182     size_t j = 0;
183
184     while (i < gNumOfProvisioningMethodsPT && j < selectedDeviceInfo->pstat->smLen)
185     {
186         if (gProvisioningToolCapability[i] < selectedDeviceInfo->pstat->sm[j])
187         {
188             i++;
189         }
190         else if (selectedDeviceInfo->pstat->sm[j] < gProvisioningToolCapability[i])
191         {
192             j++;
193         }
194         else /* if gProvisioningToolCapability[i] == deviceSupportedMethods[j] */
195         {
196             *selectedMode = gProvisioningToolCapability[j];
197             break;
198         }
199     }
200     OC_LOG(DEBUG, TAG, "OUT SelectOperationMode");
201 }
202
203 /**
204  * Function to update owner transfer mode
205  *
206  * @param[in]  otmCtx  Context value of ownership transfer.
207  * @return  OC_STACK_OK on success
208  */
209 static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx);
210
211 /**
212  * Function to send request to resource to get its pstat resource information.
213  *
214  * @param[in]  otmCtx  Context value of ownership transfer.
215  * @return  OC_STACK_OK on success
216  */
217 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx);
218
219
220 /**
221  * Function to send ownerShip info. This function would update Owned as true and
222  * owner as UUID for provisioning tool
223  *
224  * @param[in]  otmCtx  Context value of ownership transfer.
225  * @return  OC_STACK_OK on success
226  */
227 static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx);
228
229 /**
230  * Function to update the operation mode. As per the spec. Operation mode in client driven
231  * single service provisioning it will be updated to 0x3
232  *
233  * @param[in]  otmCtx  Context value of ownership transfer.
234  * @param[in] selectedOperationMode selected operation mode
235  * @return  OC_STACK_OK on success
236  */
237 static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx,
238                                     OicSecDpom_t selectedOperationMode);
239
240 /**
241  * Function to start ownership transfer.
242  * This function will send the first request for provisioning,
243  * The next request message is sent from the response handler for this request.
244  *
245  * @param[in] ctx   context value passed to callback from calling function.
246  * @param[in] selectedDevice   selected device information to performing provisioning.
247  * @return  OC_STACK_OK on success
248  */
249 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice);
250
251 /*
252  * Function to finalize provisioning.
253  * This function will send default ACL and commit hash.
254  *
255  * @param[in] otmCtx   Context value of ownership transfer.
256  * @return  OC_STACK_OK on success
257  */
258 static OCStackResult FinalizeProvisioning(OTMContext_t* otmCtx);
259
260
261 static bool IsComplete()
262 {
263     for(size_t i = 0; i < g_resultArraySize; i++)
264     {
265         if(OC_STACK_CONTINUE == g_resultArray[i].res)
266         {
267             return false;
268         }
269     }
270
271     return true;
272 }
273
274 /**
275  * Function to save the result of provisioning.
276  *
277  * @param[in,out] otmCtx   Context value of ownership transfer.
278  * @param[in] res   result of provisioning
279  */
280 static void SetResult(OTMContext_t* otmCtx, const OCStackResult res)
281 {
282     OC_LOG(DEBUG, TAG, "IN SetResult");
283
284     if(!otmCtx)
285     {
286         OC_LOG(WARNING, TAG, "OTMContext is NULL");
287         return;
288     }
289
290     if(otmCtx->selectedDeviceInfo)
291     {
292         for(size_t i = 0; i < g_resultArraySize; i++)
293         {
294             if(memcmp(otmCtx->selectedDeviceInfo->doxm->deviceID.id,
295                       g_resultArray[i].deviceId.id, UUID_LENGTH) == 0)
296             {
297                 g_resultArray[i].res = res;
298                 if(OC_STACK_OK != res)
299                 {
300                     g_hasError = true;
301                 }
302             }
303         }
304
305         //If all request is completed, invoke the user callback.
306         if(IsComplete())
307         {
308             g_resultCallback(otmCtx->userCtx, g_resultArraySize, g_resultArray, g_hasError);
309         }
310         else
311         {
312             if(OC_STACK_OK != StartOwnershipTransfer(otmCtx->userCtx,
313                                                      otmCtx->selectedDeviceInfo->next))
314             {
315                 OC_LOG(ERROR, TAG, "Failed to StartOwnershipTransfer");
316             }
317         }
318     }
319
320     OC_LOG(DEBUG, TAG, "OUT SetResult");
321
322     OICFree(otmCtx);
323 }
324
325
326 /**
327  * Function to save ownerPSK at provisioning tool end.
328  *
329  * @param[in] selectedDeviceInfo   selected device information to performing provisioning.
330  * @return  OC_STACK_OK on success
331  */
332 static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
333 {
334     OC_LOG(DEBUG, TAG, "IN SaveOwnerPSK");
335
336     OCStackResult res = OC_STACK_ERROR;
337
338     CAEndpoint_t endpoint;
339     memset(&endpoint, 0x00, sizeof(CAEndpoint_t));
340     OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, selectedDeviceInfo->endpoint.addr);
341     endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
342     endpoint.port = selectedDeviceInfo->securePort;
343
344     OicUuid_t ptDeviceID = {.id={0}};
345     if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID))
346     {
347         OC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
348         return res;
349     }
350
351     uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
352
353     //Generating OwnerPSK
354     CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint,
355             (uint8_t *)GetOxmString(selectedDeviceInfo->doxm->oxmSel),
356             strlen(GetOxmString(selectedDeviceInfo->doxm->oxmSel)), ptDeviceID.id,
357             sizeof(ptDeviceID.id), selectedDeviceInfo->doxm->deviceID.id,
358             sizeof(selectedDeviceInfo->doxm->deviceID.id), ownerPSK,
359             OWNER_PSK_LENGTH_128);
360
361     if (CA_STATUS_OK == pskRet)
362     {
363         OC_LOG(INFO, TAG,"ownerPSK dump:\n");
364         OC_LOG_BUFFER(INFO, TAG,ownerPSK, OWNER_PSK_LENGTH_128);
365         //Generating new credential for provisioning tool
366         size_t ownLen = 1;
367         uint32_t outLen = 0;
368
369         char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(ownerPSK)) + 1] = {};
370         B64Result b64Ret = b64Encode(ownerPSK, sizeof(ownerPSK), base64Buff, sizeof(base64Buff),
371                 &outLen);
372         VERIFY_SUCCESS(TAG, B64_OK == b64Ret, ERROR);
373
374         OicSecCred_t *cred = GenerateCredential(&selectedDeviceInfo->doxm->deviceID,
375                 SYMMETRIC_PAIR_WISE_KEY, NULL,
376                 base64Buff, ownLen, &ptDeviceID);
377         VERIFY_NON_NULL(TAG, cred, ERROR);
378
379         res = AddCredential(cred);
380         if(res != OC_STACK_OK)
381         {
382             DeleteCredList(cred);
383             return res;
384         }
385     }
386     else
387     {
388         OC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
389     }
390
391     OC_LOG(DEBUG, TAG, "OUT SaveOwnerPSK");
392 exit:
393     return res;
394 }
395
396 /**
397  * Callback handler for OwnerShipTransferModeHandler API.
398  *
399  * @param[in] ctx             ctx value passed to callback from calling function.
400  * @param[in] UNUSED          handle to an invocation
401  * @param[in] clientResponse  Response from queries to remote servers.
402  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
403  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
404  */
405 static OCStackApplicationResult OwnerTransferModeHandler(void *ctx, OCDoHandle UNUSED,
406         OCClientResponse *clientResponse)
407 {
408     OC_LOG(DEBUG, TAG, "IN OwnerTransferModeHandler");
409
410     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
411     VERIFY_NON_NULL(TAG, ctx, WARNING);
412
413     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
414
415     if(clientResponse->result == OC_STACK_OK)
416     {
417         OC_LOG(INFO, TAG, "OwnerTransferModeHandler : response result = OC_STACK_OK");
418         //Send request : GET /oic/sec/pstat
419         OCStackResult res = GetProvisioningStatusResource(otmCtx);
420         if(OC_STACK_OK != res)
421         {
422             OC_LOG(WARNING, TAG, "Failed to get pstat information");
423             SetResult(otmCtx, res);
424         }
425     }
426     else
427     {
428         OC_LOG_V(WARNING, TAG, "OwnerTransferModeHandler : Client response is incorrect : %d",
429         clientResponse->result);
430         SetResult(otmCtx, clientResponse->result);
431     }
432
433     OC_LOG(DEBUG, TAG, "OUT OwnerTransferModeHandler");
434
435 exit:
436     return  OC_STACK_DELETE_TRANSACTION;
437 }
438
439 /**
440  * Callback handler for ProvisioningStatusResouceHandler API.
441  *
442  * @param[in] ctx             ctx value passed to callback from calling function.
443  * @param[in] UNUSED          handle to an invocation
444  * @param[in] clientResponse  Response from queries to remote servers.
445  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
446  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
447  */
448 static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
449         OCClientResponse *clientResponse)
450 {
451     OC_LOG(DEBUG, TAG, "IN ListMethodsHandler");
452
453     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
454     VERIFY_NON_NULL(TAG, ctx, WARNING);
455
456     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
457
458     if  (OC_STACK_OK == clientResponse->result)
459     {
460         if  (NULL == clientResponse->payload)
461         {
462             OC_LOG(INFO, TAG, "Skiping Null payload");
463             SetResult(otmCtx, OC_STACK_ERROR);
464             return OC_STACK_DELETE_TRANSACTION;
465         }
466
467         if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
468         {
469             OC_LOG(INFO, TAG, "Unknown payload type");
470             SetResult(otmCtx, OC_STACK_ERROR);
471             return OC_STACK_DELETE_TRANSACTION;
472         }
473
474         OicSecPstat_t* pstat = JSONToPstatBin(
475                 ((OCSecurityPayload*)clientResponse->payload)->securityData);
476         if(NULL == pstat)
477         {
478             OC_LOG(ERROR, TAG, "Error while converting json to pstat bin");
479             SetResult(otmCtx, OC_STACK_ERROR);
480             return OC_STACK_DELETE_TRANSACTION;
481         }
482         otmCtx->selectedDeviceInfo->pstat = pstat;
483
484         //Select operation mode (Currently supported SINGLE_SERVICE_CLIENT_DRIVEN only)
485         OicSecDpom_t selectedOperationMode;
486         SelectOperationMode(otmCtx->selectedDeviceInfo, &selectedOperationMode);
487
488         //Send request : PUT /oic/sec/pstat [{"OM":"0x11", .. }]
489         OCStackResult res = PutUpdateOperationMode(otmCtx, selectedOperationMode);
490         if (OC_STACK_OK != res)
491         {
492             OC_LOG(ERROR, TAG, "Error while updating operation mode.");
493             SetResult(otmCtx, res);
494         }
495     }
496     else
497     {
498         OC_LOG_V(WARNING, TAG, "ListMethodsHandler : Client response is incorrect : %d",
499             clientResponse->result);
500         SetResult(otmCtx, clientResponse->result);
501     }
502
503     OC_LOG(DEBUG, TAG, "OUT ListMethodsHandler");
504 exit:
505     return  OC_STACK_DELETE_TRANSACTION;
506 }
507
508 /**
509  * Callback handler for OwnershipInformationHandler API.
510  *
511  * @param[in] ctx             ctx value passed to callback from calling function.
512  * @param[in] UNUSED          handle to an invocation
513  * @param[in] clientResponse  Response from queries to remote servers.
514  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
515  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
516  */
517 static OCStackApplicationResult OwnershipInformationHandler(void *ctx,
518                                 OCDoHandle UNUSED, OCClientResponse *clientResponse)
519 {
520     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
521     VERIFY_NON_NULL(TAG, ctx, WARNING);
522
523     OC_LOG(DEBUG, TAG, "IN OwnershipInformationHandler");
524
525     OCStackResult res = OC_STACK_OK;
526     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
527     if  (OC_STACK_OK == clientResponse->result)
528     {
529         if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
530         {
531             res = RemoveCredential(&otmCtx->tempCredId);
532             if(OC_STACK_RESOURCE_DELETED != res)
533             {
534                 OC_LOG_V(ERROR, TAG, "Failed to remove temporal PSK : %d", res);
535                 return OC_STACK_DELETE_TRANSACTION;
536             }
537         }
538
539         res = SaveOwnerPSK(otmCtx->selectedDeviceInfo);
540         if(OC_STACK_OK != res)
541         {
542             OC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to owner PSK generation");
543             SetResult(otmCtx, res);
544             return OC_STACK_DELETE_TRANSACTION;
545         }
546
547         CAEndpoint_t* endpoint = (CAEndpoint_t *)&otmCtx->selectedDeviceInfo->endpoint;
548         endpoint->port = otmCtx->selectedDeviceInfo->securePort;
549         CAResult_t closeRes = CACloseDtlsSession(endpoint);
550         if(CA_STATUS_OK != closeRes)
551         {
552             OC_LOG(ERROR, TAG, "Failed to close DTLS session");
553             SetResult(otmCtx, closeRes);
554             return OC_STACK_DELETE_TRANSACTION;
555         }
556
557         OC_LOG(INFO, TAG, "Ownership transfer was successfully completed.");
558         OC_LOG(INFO, TAG, "Start defualt ACL & commit-hash provisioning.");
559
560         res = FinalizeProvisioning(otmCtx);
561         if(OC_STACK_OK != res)
562         {
563             SetResult(otmCtx, res);
564         }
565     }
566     else
567     {
568         res = clientResponse->result;
569     }
570
571     OC_LOG(DEBUG, TAG, "OUT OwnershipInformationHandler");
572
573 exit:
574     return  OC_STACK_DELETE_TRANSACTION;
575 }
576
577 /**
578  * Response handler for update operation mode.
579  *
580  * @param[in] ctx             ctx value passed to callback from calling function.
581  * @param[in] UNUSED          handle to an invocation
582  * @param[in] clientResponse  Response from queries to remote servers.
583  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
584  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
585  */
586 static OCStackApplicationResult OperationModeUpdateHandler(void *ctx,
587                                 OCDoHandle UNUSED, OCClientResponse *clientResponse)
588 {
589     OC_LOG(DEBUG, TAG, "IN OperationModeUpdateHandler");
590
591     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
592     VERIFY_NON_NULL(TAG, ctx, WARNING);
593
594     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
595     if  (OC_STACK_OK == clientResponse->result)
596     {
597         OCStackResult res = OC_STACK_ERROR;
598         OicSecOxm_t selOxm = otmCtx->selectedDeviceInfo->doxm->oxmSel;
599         //DTLS Handshake
600         //Load secret for temporal secure session.
601         if(g_OTMDatas[selOxm].loadSecretCB)
602         {
603             res = g_OTMDatas[selOxm].loadSecretCB(otmCtx);
604             if(OC_STACK_OK != res)
605             {
606                 OC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to load secret");
607                 SetResult(otmCtx, res);
608                 return  OC_STACK_DELETE_TRANSACTION;
609             }
610         }
611
612         //Try DTLS handshake to generate secure session
613         if(g_OTMDatas[selOxm].createSecureSessionCB)
614         {
615             res = g_OTMDatas[selOxm].createSecureSessionCB(otmCtx);
616             if(OC_STACK_OK != res)
617             {
618                 OC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to create DTLS session");
619                 SetResult(otmCtx, res);
620                 return OC_STACK_DELETE_TRANSACTION;
621             }
622         }
623
624         //Send request : PUT /oic/sec/doxm [{"Owned":"True", .. , "Owner":"PT's UUID"}]
625         res = PutOwnershipInformation(otmCtx);
626         if(OC_STACK_OK != res)
627         {
628             OC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to send owner information");
629             SetResult(otmCtx, res);
630         }
631     }
632     else
633     {
634         OC_LOG(ERROR, TAG, "Error while update operation mode");
635         SetResult(otmCtx, clientResponse->result);
636     }
637
638     OC_LOG(DEBUG, TAG, "OUT OperationModeUpdateHandler");
639
640 exit:
641     return  OC_STACK_DELETE_TRANSACTION;
642 }
643
644
645 static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx)
646 {
647     OC_LOG(DEBUG, TAG, "IN PutOwnerTransferModeToResource");
648
649     if(!otmCtx || !otmCtx->selectedDeviceInfo)
650     {
651         OC_LOG(ERROR, TAG, "Invailed parameters");
652         return OC_STACK_INVALID_PARAM;
653     }
654
655     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
656     OicSecOxm_t selectedOxm = deviceInfo->doxm->oxmSel;
657     char query[MAX_QUERY_LENGTH] = {};
658     sprintf(query, "%s%s:%d%s", COAP_PREFIX,
659                                 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
660                                 OIC_RSRC_DOXM_URI);
661     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
662     if(!secPayload)
663     {
664         OC_LOG(ERROR, TAG, "Failed to memory allocation");
665         return OC_STACK_NO_MEMORY;
666     }
667     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
668     secPayload->securityData = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx);
669     if (NULL == secPayload->securityData)
670     {
671         OICFree(secPayload);
672         OC_LOG(ERROR, TAG, "Error while converting bin to json");
673         return OC_STACK_ERROR;
674     }
675     OC_LOG_V(DEBUG, TAG, "Payload : %s", secPayload->securityData);
676
677     OCCallbackData cbData;
678     cbData.cb = &OwnerTransferModeHandler;
679     cbData.context = (void *)otmCtx;
680     cbData.cd = NULL;
681
682     // TODO: 6th argument need to be changed, if we have to use CT_FLAG_SECURE
683     OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query,
684                                      &deviceInfo->endpoint, (OCPayload*)secPayload,
685                                      CT_ADAPTER_IP, OC_LOW_QOS, &cbData, NULL, 0);
686     if (res != OC_STACK_OK)
687     {
688         OC_LOG(ERROR, TAG, "OCStack resource error");
689     }
690
691     OC_LOG(DEBUG, TAG, "OUT PutOwnerTransferModeToResource");
692
693     return res;
694 }
695
696 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
697 {
698     OC_LOG(DEBUG, TAG, "IN GetProvisioningStatusResource");
699
700     if(!otmCtx || !otmCtx->selectedDeviceInfo)
701     {
702         OC_LOG(ERROR, TAG, "Invailed parameters");
703         return OC_STACK_INVALID_PARAM;
704     }
705
706     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
707     char query[MAX_QUERY_LENGTH] = {};
708     sprintf(query, "%s%s:%d%s", COAP_PREFIX,
709                                 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
710                                 OIC_RSRC_PSTAT_URI);
711     OCCallbackData cbData;
712     cbData.cb = &ListMethodsHandler;
713     cbData.context = (void *)otmCtx;
714     cbData.cd = NULL;
715
716     // TODO: 6th argument need to be changed, if we have to use CT_FLAG_SECURE
717     OCStackResult res = OCDoResource(NULL, OC_REST_GET, query, NULL, NULL,
718                                      CT_ADAPTER_IP, OC_LOW_QOS, &cbData, NULL, 0);
719     if (res != OC_STACK_OK)
720     {
721         OC_LOG(ERROR, TAG, "OCStack resource error");
722     }
723
724     OC_LOG(DEBUG, TAG, "OUT GetProvisioningStatusResource");
725
726     return res;
727 }
728
729
730 static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx)
731 {
732     OC_LOG(DEBUG, TAG, "IN PutOwnershipInformation");
733
734     if(!otmCtx || !otmCtx->selectedDeviceInfo)
735     {
736         OC_LOG(ERROR, TAG, "Invailed parameters");
737         return OC_STACK_INVALID_PARAM;
738     }
739
740     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
741     char query[MAX_QUERY_LENGTH] = {};
742     sprintf(query, "%s%s:%d%s", COAPS_PREFIX,
743                                 deviceInfo->endpoint.addr, deviceInfo->securePort,
744                                 OIC_RSRC_DOXM_URI);
745     //OwnershipInformationHandler
746     OicSecOxm_t selOxm = deviceInfo->doxm->oxmSel;
747     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
748     if(!secPayload)
749     {
750         OC_LOG(ERROR, TAG, "Failed to memory allocation");
751         return OC_STACK_NO_MEMORY;
752     }
753     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
754     secPayload->securityData = g_OTMDatas[selOxm].createOwnerTransferPayloadCB(otmCtx);
755     if (NULL == secPayload->securityData)
756     {
757         OICFree(secPayload);
758         OC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
759         return OC_STACK_INVALID_PARAM;
760     }
761
762     OCCallbackData cbData;
763     cbData.cb = &OwnershipInformationHandler;
764     cbData.context = (void *)otmCtx;
765     cbData.cd = NULL;
766     // TODO: 6th argument need to be changed, if we have to use CT_FLAG_SECURE
767     OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
768                                      CT_ADAPTER_IP, OC_LOW_QOS, &cbData, NULL, 0);
769     if (res != OC_STACK_OK)
770     {
771         OC_LOG(ERROR, TAG, "OCStack resource error");
772     }
773
774     OC_LOG(DEBUG, TAG, "OUT PutOwnershipInformation");
775
776     return res;
777 }
778
779 static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx,
780                                     OicSecDpom_t selectedOperationMode)
781 {
782     OC_LOG(DEBUG, TAG, "IN PutUpdateOperationMode");
783
784     if(!otmCtx || !otmCtx->selectedDeviceInfo)
785     {
786         return OC_STACK_INVALID_PARAM;
787     }
788
789     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
790     char query[MAX_QUERY_LENGTH] = {};
791     sprintf(query, "%s%s:%d%s", COAP_PREFIX,
792                                 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
793                                 OIC_RSRC_PSTAT_URI);
794     deviceInfo->pstat->om = selectedOperationMode;
795
796     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
797     if(!secPayload)
798     {
799         OC_LOG(ERROR, TAG, "Failed to memory allocation");
800         return OC_STACK_NO_MEMORY;
801     }
802     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
803     secPayload->securityData = BinToPstatJSON(deviceInfo->pstat);
804     if (NULL == secPayload->securityData)
805     {
806         OICFree(secPayload);
807         OC_LOG(ERROR, TAG, "Error while converting pstat bin to json");
808         return OC_STACK_INVALID_PARAM;
809     }
810
811     OCCallbackData cbData;
812     cbData.cb = &OperationModeUpdateHandler;
813     cbData.context = (void *)otmCtx;
814     cbData.cd = NULL;
815
816     OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
817                                      CT_ADAPTER_IP, OC_LOW_QOS, &cbData, NULL, 0);
818     if (res != OC_STACK_OK)
819     {
820         OC_LOG(ERROR, TAG, "OCStack resource error");
821     }
822
823     OC_LOG(DEBUG, TAG, "OUT PutUpdateOperationMode");
824
825     return res;
826 }
827
828 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice)
829 {
830     OC_LOG(INFO, TAG, "IN StartOwnershipTransfer");
831     OTMContext_t* otmCtx = (OTMContext_t*)OICMalloc(sizeof(OTMContext_t));
832     if(!otmCtx)
833     {
834         OC_LOG(ERROR, TAG, "Failed to create OTM Context");
835         return OC_STACK_NO_MEMORY;
836     }
837     otmCtx->userCtx = ctx;
838     otmCtx->selectedDeviceInfo = selectedDevice;
839
840     //Set to the lowest level OxM, and then find more higher level OxM.
841     OCStackResult res = SelectProvisioningMethod(selectedDevice->doxm->oxm,
842                                                  selectedDevice->doxm->oxmLen,
843                                                  &selectedDevice->doxm->oxmSel);
844     if(OC_STACK_OK != res)
845     {
846         OC_LOG(ERROR, TAG, "Failed to select the provisioning method");
847         SetResult(otmCtx, res);
848         return res;
849     }
850     OC_LOG_V(DEBUG, TAG, "Selected provisoning method = %d", selectedDevice->doxm->oxmSel);
851
852     //Send Req: PUT /oic/sec/doxm [{..."OxmSel" :g_OTMDatas[Index of Selected OxM].OXMString,...}]
853     res = PutOwnerTransferModeToResource(otmCtx);
854     if(OC_STACK_OK != res)
855     {
856         OC_LOG(WARNING, TAG, "Failed to select the provisioning method");
857         SetResult(otmCtx, res);
858         return res;
859     }
860
861     OC_LOG(INFO, TAG, "OUT StartOwnershipTransfer");
862
863     return res;
864
865 }
866
867 OCStackResult OTMSetOwnershipTransferCallbackData(OicSecOxm_t oxmType, OTMCallbackData_t* data)
868 {
869     OC_LOG(DEBUG, TAG, "IN OTMSetOwnerTransferCallbackData");
870
871     if(!data)
872     {
873         OC_LOG(ERROR, TAG, "OTMSetOwnershipTransferCallbackData : Invalid parameters");
874         return OC_STACK_INVALID_PARAM;
875     }
876     if(oxmType >= OIC_OXM_COUNT)
877     {
878         OC_LOG(INFO, TAG, "Unknow ownership transfer method");
879         return OC_STACK_INVALID_PARAM;
880     }
881
882     g_OTMDatas[oxmType].loadSecretCB= data->loadSecretCB;
883     g_OTMDatas[oxmType].createSecureSessionCB = data->createSecureSessionCB;
884     g_OTMDatas[oxmType].createSelectOxmPayloadCB = data->createSelectOxmPayloadCB;
885     g_OTMDatas[oxmType].createOwnerTransferPayloadCB = data->createOwnerTransferPayloadCB;
886
887     OC_LOG(DEBUG, TAG, "OUT OTMSetOwnerTransferCallbackData");
888
889     return OC_STACK_OK;
890 }
891
892 /**
893  * NOTE : Unowned discovery should be done before performing OTMDoOwnershipTransfer
894  */
895 OCStackResult OTMDoOwnershipTransfer(void* ctx,
896                                      OCProvisionDev_t *selectedDevicelist,
897                                      OCProvisionResultCB resultCallback)
898 {
899     OC_LOG(DEBUG, TAG, "IN OTMDoOwnershipTransfer");
900
901     if (NULL == selectedDevicelist || NULL == resultCallback )
902     {
903         return OC_STACK_INVALID_PARAM;
904     }
905
906     g_resultCallback = resultCallback;
907     g_hasError = false;
908
909     OCProvisionDev_t* pCurDev = selectedDevicelist;
910
911     //Counting number of selected devices.
912     g_resultArraySize = 0;
913     while(NULL != pCurDev)
914     {
915         g_resultArraySize++;
916         pCurDev = pCurDev->next;
917     }
918
919     if(g_resultArray)
920     {
921         OICFree(g_resultArray);
922     }
923     g_resultArray =
924         (OCProvisionResult_t*)OICMalloc(sizeof(OCProvisionResult_t) * g_resultArraySize);
925     if(NULL == g_resultArray)
926     {
927         OC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Failed to memory allocation");
928         return OC_STACK_NO_MEMORY;
929     }
930
931     pCurDev = selectedDevicelist;
932     //Fill the device UUID for result array.
933     for(size_t devIdx = 0; devIdx < g_resultArraySize; devIdx++)
934     {
935         memcpy(g_resultArray[devIdx].deviceId.id,
936                pCurDev->doxm->deviceID.id,
937                UUID_LENGTH);
938         g_resultArray[devIdx].res = OC_STACK_CONTINUE;
939         pCurDev = pCurDev->next;
940     }
941
942     StartOwnershipTransfer(ctx, selectedDevicelist);
943
944     OC_LOG(DEBUG, TAG, "OUT OTMDoOwnershipTransfer");
945
946     return (g_hasError ? OC_STACK_ERROR : OC_STACK_OK);
947 }
948
949 /**
950  * Callback handler of SRPFinalizeProvisioning.
951  *
952  * @param[in] ctx             ctx value passed to callback from calling function.
953  * @param[in] UNUSED          handle to an invocation
954  * @param[in] clientResponse  Response from queries to remote servers.
955  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
956  *          and OC_STACK_KEEP_TRANSACTION to keep it.
957  */
958 static OCStackApplicationResult FinalizeProvisioningCB(void *ctx, OCDoHandle UNUSED,
959         OCClientResponse *clientResponse)
960 {
961     OC_LOG_V(INFO, TAG, "IN FinalizeProvisioningCB.");
962
963     VERIFY_NON_NULL(TAG, clientResponse, ERROR);
964     VERIFY_NON_NULL(TAG, ctx, ERROR);
965
966     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
967
968     if(OC_STACK_OK == clientResponse->result)
969     {
970         SetResult(otmCtx, OC_STACK_OK);
971     }
972 exit:
973     return OC_STACK_DELETE_TRANSACTION;
974 }
975
976 /**
977  * Callback handler of default ACL provisioning.
978  *
979  * @param[in] ctx             ctx value passed to callback from calling function.
980  * @param[in] UNUSED          handle to an invocation
981  * @param[in] clientResponse  Response from queries to remote servers.
982  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
983  *          and OC_STACK_KEEP_TRANSACTION to keep it.
984  */
985 static OCStackApplicationResult ProvisionDefaultACLCB(void *ctx, OCDoHandle UNUSED,
986         OCClientResponse *clientResponse)
987 {
988     OC_LOG_V(INFO, TAG, "IN ProvisionDefaultACLCB.");
989
990     VERIFY_NON_NULL(TAG, clientResponse, ERROR);
991     VERIFY_NON_NULL(TAG, ctx, ERROR);
992
993     OTMContext_t* otmCtx = (OTMContext_t*) ctx;
994
995     if (OC_STACK_RESOURCE_CREATED == clientResponse->result)
996     {
997         OC_LOG_V(INFO, TAG, "Staring commit hash task.");
998         // TODO hash currently have fixed value 0.
999         uint16_t aclHash = 0;
1000         otmCtx->selectedDeviceInfo->pstat->commitHash = aclHash;
1001         otmCtx->selectedDeviceInfo->pstat->tm = NORMAL;
1002         OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1003         if(!secPayload)
1004         {
1005             OC_LOG(ERROR, TAG, "Failed to memory allocation");
1006             return OC_STACK_NO_MEMORY;
1007         }
1008         secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1009         secPayload->securityData = BinToPstatJSON(otmCtx->selectedDeviceInfo->pstat);
1010         if (NULL == secPayload->securityData)
1011         {
1012             OICFree(secPayload);
1013             SetResult(otmCtx, OC_STACK_INVALID_JSON);
1014             return OC_STACK_DELETE_TRANSACTION;
1015         }
1016         OC_LOG_V(INFO, TAG, "Created payload for commit hash: %s",secPayload->securityData);
1017
1018         char uri[MAX_QUERY_LENGTH] = { 0 };
1019         size_t uriLen = sizeof(uri);
1020
1021         snprintf(uri, uriLen - 1, COAPS_QUERY, otmCtx->selectedDeviceInfo->endpoint.addr,
1022                 otmCtx->selectedDeviceInfo->securePort, OIC_RSRC_PSTAT_URI);
1023         uri[uriLen - 1] = '\0';
1024         OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1025         cbData.cb = &FinalizeProvisioningCB;
1026         cbData.context = (void*)otmCtx; // forward context to SRPFinalizeProvisioningCB
1027         cbData.cd = NULL;
1028
1029         // TODO change value of CT_ADAPTER_IP with val from discovery
1030         OCStackResult ret = OCDoResource(NULL, OC_REST_PUT, uri, 0, (OCPayload*)secPayload,
1031                 CT_ADAPTER_IP, OC_HIGH_QOS, &cbData, NULL, 0);
1032         OC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1033         if (ret != OC_STACK_OK)
1034         {
1035             OC_LOG(ERROR, TAG, "OCStack resource error");
1036             SetResult(otmCtx, ret);
1037         }
1038     }
1039     else
1040     {
1041         OC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
1042                             clientResponse->result);
1043         SetResult(otmCtx, clientResponse->result);
1044     }
1045 exit:
1046     return OC_STACK_DELETE_TRANSACTION;
1047 }
1048
1049
1050 OCStackResult FinalizeProvisioning(OTMContext_t* otmCtx)
1051 {
1052     OC_LOG(INFO, TAG, "IN FinalizeProvisioning");
1053
1054     if(!otmCtx)
1055     {
1056         OC_LOG(ERROR, TAG, "OTMContext is NULL");
1057         return OC_STACK_INVALID_PARAM;
1058     }
1059     if(!otmCtx->selectedDeviceInfo)
1060     {
1061         OC_LOG(ERROR, TAG, "Can't find device information in OTMContext");
1062         OICFree(otmCtx);
1063         return OC_STACK_INVALID_PARAM;
1064     }
1065     // Provision Default ACL to device
1066     OicSecAcl_t defaultAcl =
1067     { {.id={0}},
1068         1,
1069         NULL,
1070         0x001F,
1071         0,
1072         NULL,
1073         NULL,
1074         1,
1075         NULL,
1076         NULL,
1077     };
1078
1079     OicUuid_t provTooldeviceID = {.id={0}};
1080     if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
1081     {
1082         OC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
1083         SetResult(otmCtx, OC_STACK_ERROR);
1084         return OC_STACK_ERROR;
1085     }
1086     OC_LOG(INFO, TAG, "Retieved deviceID");
1087     memcpy(defaultAcl.subject.id, provTooldeviceID.id, sizeof(defaultAcl.subject.id));
1088     char *wildCardResource = "*";
1089     defaultAcl.resources = &wildCardResource;
1090
1091     defaultAcl.owners = (OicUuid_t *) OICCalloc(1, UUID_LENGTH);
1092     if(!defaultAcl.owners)
1093     {
1094         OC_LOG(ERROR, TAG, "Failed to memory allocation for default ACL");
1095         SetResult(otmCtx, OC_STACK_NO_MEMORY);
1096         return OC_STACK_NO_MEMORY;
1097     }
1098     memcpy(defaultAcl.owners->id, provTooldeviceID.id, UUID_LENGTH);
1099     OC_LOG(INFO, TAG, "Provisioning default ACL");
1100
1101     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1102     if(!secPayload)
1103     {
1104         OC_LOG(ERROR, TAG, "Failed to memory allocation");
1105         return OC_STACK_NO_MEMORY;
1106     }
1107     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1108     secPayload->securityData = BinToAclJSON(&defaultAcl);
1109     OICFree(defaultAcl.owners);
1110     if(!secPayload->securityData)
1111     {
1112         OICFree(secPayload);
1113         OC_LOG(INFO, TAG, "FinalizeProvisioning : Failed to BinToAclJSON");
1114         SetResult(otmCtx, OC_STACK_ERROR);
1115         return OC_STACK_ERROR;
1116     }
1117     OC_LOG_V(INFO, TAG, "Provisioning default ACL : %s",secPayload->securityData);
1118
1119     char uri[MAX_QUERY_LENGTH] = { 0 };
1120
1121     size_t uriLen = sizeof(uri);
1122     snprintf(uri, uriLen - 1, COAPS_QUERY, otmCtx->selectedDeviceInfo->endpoint.addr,
1123             otmCtx->selectedDeviceInfo->securePort, OIC_RSRC_ACL_URI);
1124     uri[uriLen - 1] = '\0';
1125     OC_LOG_V(INFO, TAG, "Request URI for Provisioning default ACL : %s",uri);
1126
1127     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
1128     cbData.cb = &ProvisionDefaultACLCB;
1129     cbData.context = (void *)otmCtx;
1130     cbData.cd = NULL;
1131
1132     OCStackResult ret = OCDoResource(NULL, OC_REST_POST, uri,
1133             &otmCtx->selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
1134             CT_ADAPTER_IP, OC_HIGH_QOS, &cbData, NULL, 0);
1135     if (OC_STACK_OK != ret)
1136     {
1137         SetResult(otmCtx, ret);
1138         return ret;
1139     }
1140
1141     OC_LOG(INFO, TAG, "OUT FinalizeProvisioning");
1142
1143     return ret;
1144
1145 }
1146