Update security-provisioning logic
[platform/upstream/iotivity.git] / service / easy-setup / mediator / richsdk / src / EnrolleeSecurity.cpp
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 #include "base64.h"
22
23 #include "EnrolleeSecurity.h"
24 #include "oxmjustworks.h"
25 #include "oxmrandompin.h"
26 #include "EnrolleeResource.h"
27 #include "logger.h"
28 #include "ESException.h"
29 #include "oic_malloc.h"
30 #include "provisioningdatabasemanager.h"
31 #include "oic_string.h"
32 #include "utlist.h"
33
34 namespace OIC
35 {
36     namespace Service
37     {
38         #define MAX_PERMISSION_LENGTH (5)
39         #define CREATE (1)
40         #define READ (2)
41         #define UPDATE (4)
42         #define DELETE (8)
43         #define NOTIFY (16)
44         #define DASH '-'
45         #define DISCOVERY_TIMEOUT (10)
46
47         //TODO : Currently discovery timeout for owned and unowned devices is fixed as 5
48         // The value should be accepted from the application as a parameter during ocplatform
49         // config call
50         #define ES_SEC_DISCOVERY_TIMEOUT 5
51
52         EnrolleeSecurity::EnrolleeSecurity(
53             std::shared_ptr< OC::OCResource > resource,
54             const std::string secDbPath)
55         {
56             (void) secDbPath;
57             m_ocResource = resource;
58         }
59
60         void EnrolleeSecurity::registerCallbackHandler(
61             const SecurityProvStatusCb securityProvStatusCb,
62             const SecurityPinCb securityPinCb,
63             const SecProvisioningDbPathCb secProvisioningDbPathCb)
64         {
65             m_securityProvStatusCb = securityProvStatusCb;
66             m_securityPinCb = securityPinCb;
67             m_secProvisioningDbPathCb = secProvisioningDbPathCb;
68         }
69
70         std::shared_ptr< OC::OCSecureResource > EnrolleeSecurity::findEnrolleeSecurityResource(
71             DeviceList_t &list)
72         {
73             for (unsigned int i = 0; i < list.size(); i++)
74             {
75                 if(m_ocResource->sid() == list[i]->getDeviceID().c_str())
76                 {
77                     OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Device %d ID %s ", i + 1,
78                             list[i]->getDeviceID().c_str());
79                     OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "From IP :%s",
80                                                             list[i]->getDevAddr().c_str());
81                     return list[i];
82                 }
83             }
84             OIC_LOG(ERROR, ENROLEE_SECURITY_TAG,"Error!!! DeviceList_t is NULL");
85             return NULL;
86         }
87
88         void EnrolleeSecurity::convertUUIDToString(const uint8_t uuid[UUID_SIZE],
89                                                               std::string& uuidString)
90         {
91             char uuidArray[UUID_STRING_SIZE] = {'\0',};
92             int ret = snprintf(uuidArray, UUID_STRING_SIZE,
93                     "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
94                     uuid[0], uuid[1], uuid[2], uuid[3],
95                     uuid[4], uuid[5], uuid[6], uuid[7],
96                     uuid[8], uuid[9], uuid[10], uuid[11],
97                     uuid[12], uuid[13], uuid[14], uuid[15]
98                     );
99
100             if (ret != UUID_STRING_SIZE - 1)
101             {
102                 return;
103             }
104
105             uuidString = uuidArray;
106         }
107
108         void EnrolleeSecurity::convertStringToUUID(OicUuid_t& uuid,
109                                                               const std::string uuidString)
110         {
111             size_t outBufSize = B64DECODE_OUT_SAFESIZE((uuidString.length() + 1));
112             uint8_t* outKey = (uint8_t*)OICCalloc(1, outBufSize);
113             uint32_t outKeySize = 0;
114             if(NULL == outKey)
115             {
116                 OIC_LOG (ERROR, ENROLEE_SECURITY_TAG, "Failed to memoray allocation.");
117                 throw ESBadRequestException ("Failed to memoray allocation.");
118             }
119
120             if(B64_OK == b64Decode((char*)uuidString.c_str(),
121                                     uuidString.length(),
122                                     outKey,
123                                     outBufSize,
124                                     &outKeySize))
125             {
126                 memcpy(uuid.id, outKey, outKeySize);
127             }
128             else
129             {
130                 OIC_LOG (ERROR, ENROLEE_SECURITY_TAG, "Failed to base64 decoding.");
131                 throw ESBadRequestException ("Failed to base64 decoding.");
132             }
133
134             OICFree(outKey);
135         }
136
137         void EnrolleeSecurity::ownershipTransferCb(OC::PMResultList_t *result, int hasError)
138         {
139             if (hasError)
140             {
141                 OIC_LOG(ERROR, ENROLEE_SECURITY_TAG,"Error!!! in OwnershipTransfer");
142
143                 std::string uuid;
144                 convertUUIDToString(result->at(0).deviceId.id, uuid);
145                 std::shared_ptr< SecProvisioningStatus > securityProvisioningStatus =
146                         std::make_shared< SecProvisioningStatus >(uuid, ES_ERROR);
147                 m_securityProvStatusCb(securityProvisioningStatus);
148                 return;
149             }
150             else
151             {
152                 OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "ownershipTransferCb : Received provisioning results: ");
153                 for (unsigned int i = 0; i < result->size(); i++)
154                 {
155                     OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Result is = %d for device",result->at(i).res);
156                     std::string uuid;
157                     convertUUIDToString(result->at(0).deviceId.id, uuid);
158
159                     OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "UUID : %s",uuid.c_str());
160                     std::shared_ptr< SecProvisioningStatus > securityProvisioningStatus =
161                             std::make_shared< SecProvisioningStatus >(uuid, ES_OK);
162                     m_securityProvStatusCb(securityProvisioningStatus);
163                     return;
164                 }
165
166                 delete result;
167             }
168         }
169
170         void EnrolleeSecurity::provisionOwnership()
171         {
172             OC::DeviceList_t pUnownedDevList, pOwnedDevList;
173
174             pOwnedDevList.clear();
175             pUnownedDevList.clear();
176
177             OCStackResult result = OC_STACK_ERROR;
178
179             result = OCSecure::discoverOwnedDevices(ES_SEC_DISCOVERY_TIMEOUT,
180                     pOwnedDevList);
181             if (result != OC_STACK_OK)
182             {
183                 OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "Owned Discovery failed.");
184                 //Throw exception
185                 throw ESPlatformException(result);
186             }
187             else if (pOwnedDevList.size())
188             {
189                 OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Found owned devices. Count =%d",
190                         pOwnedDevList.size());
191                 std::shared_ptr< OC::OCSecureResource > ownedDevice = findEnrolleeSecurityResource(pOwnedDevList);
192
193                 if (ownedDevice)
194                 {
195                     std::shared_ptr< SecProvisioningStatus > securityProvisioningStatus =
196                             std::make_shared< SecProvisioningStatus >(ownedDevice->getDeviceID(), ES_OK);
197                     m_securityProvStatusCb(securityProvisioningStatus);
198                     return;
199                 }
200             }
201
202             result = OCSecure::discoverUnownedDevices(ES_SEC_DISCOVERY_TIMEOUT, pUnownedDevList);
203             if (result != OC_STACK_OK)
204             {
205                 OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "UnOwned Discovery failed.");
206                 //Throw exception
207                 throw ESPlatformException(result);
208             }
209             else if (pUnownedDevList.size())
210             {
211                 OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Found Unowned devices. Count =%d",
212                         pUnownedDevList.size());
213
214                 m_unownedDevice = findEnrolleeSecurityResource(pUnownedDevList);
215                 if (m_unownedDevice)
216                 {
217                     if(isOwnedDeviceRegisteredInSVRDB())
218                     {
219                         OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG,
220                             "Found Unowned device's DevID at DB of ownedDevices list");
221
222                         OC::ResultCallBack removeDeviceWithUuidCB = std::bind(
223                                 &EnrolleeSecurity::removeDeviceWithUuidCB,
224                                 this, std::placeholders::_1, std::placeholders::_2);
225
226                         OCSecure::removeDeviceWithUuid(DISCOVERY_TIMEOUT,
227                                                        m_ocResource->sid(),
228                                                        removeDeviceWithUuidCB);
229                     }
230                     else
231                     {
232                         performOwnershipTransfer();
233                     }
234                 }
235                 else
236                 {
237                     OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "No matched unowned devices found.");
238                     throw ESException("No matched unowned devices found.");
239                 }
240             }
241             else
242             {
243                 OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "No unowned devices found.");
244                 throw ESException("No unowned devices found.");
245             }
246         }
247
248         void EnrolleeSecurity::performOwnershipTransfer()
249         {
250             OCStackResult result = OC_STACK_ERROR;
251
252             OTMCallbackData_t justWorksCBData;
253             justWorksCBData.loadSecretCB = LoadSecretJustWorksCallback;
254             justWorksCBData.createSecureSessionCB = CreateSecureSessionJustWorksCallback;
255             justWorksCBData.createSelectOxmPayloadCB = CreateJustWorksSelectOxmPayload;
256             justWorksCBData.createOwnerTransferPayloadCB =
257                     CreateJustWorksOwnerTransferPayload;
258             OCSecure::setOwnerTransferCallbackData(OIC_JUST_WORKS, &justWorksCBData, NULL);
259
260             OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Transfering ownership for : %s ",
261                     m_unownedDevice->getDeviceID().c_str());
262
263             OC::ResultCallBack ownershipTransferCb = std::bind(
264                     &EnrolleeSecurity::ownershipTransferCb, this, std::placeholders::_1,
265                     std::placeholders::_2);
266
267             result = m_unownedDevice->doOwnershipTransfer(ownershipTransferCb);
268             if (result != OC_STACK_OK)
269             {
270                 OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "doOwnershipTransfer is failed");
271                 throw ESPlatformException(result);
272             }
273         }
274
275         void EnrolleeSecurity::removeDeviceWithUuidCB(OC::PMResultList_t *result, int hasError)
276         {
277             if (hasError)
278             {
279                OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Error in removeDeviceWithUuid operation!");
280                throw ESException("removeDeviceWithUuid Error");
281             }
282
283             else
284             {
285                OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Received provisioning results: ");
286
287                for (unsigned int i = 0; i < result->size(); i++)
288                {
289                     std::string uuid;
290                     convertUUIDToString(result->at(i).deviceId.id, uuid);
291
292                     OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG,
293                         "Result is = %d for device %s",  result->at(i).res, uuid.c_str());
294                }
295                performOwnershipTransfer();
296             }
297         }
298
299         bool EnrolleeSecurity::isOwnedDeviceRegisteredInSVRDB()
300         {
301             OCStackResult res = OC_STACK_ERROR;
302
303             OCUuidList_t *uuidList = NULL;
304             size_t numOfDevices = 0;
305
306             res = PDMGetOwnedDevices(&uuidList, &numOfDevices);
307             if (OC_STACK_OK != res)
308             {
309                 OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "Error while getting info from DB");
310                 return false;
311             }
312
313             OCUuidList_t *pUuidList = uuidList;
314
315             while (pUuidList)
316             {
317                 std::string uuid;
318                 convertUUIDToString(pUuidList->dev.id, uuid);
319                 OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG,
320                     "m_ocResource->sid(): %s, cur DB UUID %s",
321                     m_ocResource->sid().c_str(), uuid.c_str());
322                 if(m_ocResource->sid() == uuid.c_str())
323                 {
324                     return true;
325                 }
326                 pUuidList = pUuidList->next;
327             }
328             return false;
329         }
330
331         ESResult EnrolleeSecurity::provisionACLForCloudServer(std::string cloudUuid)
332         {
333             ESResult res = ESResult::ES_ERROR;
334
335             OicUuid_t uuid;
336             convertStringToUUID(uuid, cloudUuid);
337
338             // Need to discover Owned device in a given network, again
339             OC::DeviceList_t pOwnedDevList;
340             std::shared_ptr< OC::OCSecureResource > ownedDevice = NULL;
341
342             pOwnedDevList.clear();
343
344             OCStackResult result;
345
346             result = OCSecure::discoverOwnedDevices(ES_SEC_DISCOVERY_TIMEOUT,
347                     pOwnedDevList);
348             if (result != OC_STACK_OK)
349             {
350                 OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "Owned Discovery failed.");
351                 //Throw exception
352                 throw ESPlatformException(result);
353             }
354             else if (pOwnedDevList.size())
355             {
356                 OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Found owned devices. Count =%d",
357                         pOwnedDevList.size());
358                 ownedDevice = findEnrolleeSecurityResource(pOwnedDevList);
359
360                 if (!ownedDevice)
361                 {
362                     OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Not found owned devices.");
363                     return res;
364                 }
365             }
366             else
367             {
368                 OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Not found owned devices.");
369                 return res;
370             }
371
372             // Create Acl for Cloud Server to be provisioned to Enrollee
373             OicSecAcl_t* acl = createAcl(uuid);
374             if(!acl)
375             {
376                 OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "createAcl error return");
377                 return res;
378             }
379
380             OC::ResultCallBack aclProvisioningCb = std::bind(
381                             &EnrolleeSecurity::ACLProvisioningCb, this, std::placeholders::_1,
382                             std::placeholders::_2);
383             // ACL provisioning to Enrollee
384             OCStackResult rst = ownedDevice->provisionACL(acl, aclProvisioningCb);
385             if(OC_STACK_OK != rst)
386             {
387                 OIC_LOG_V(ERROR, ENROLEE_SECURITY_TAG, "OCProvisionACL API error: %d", rst);
388                 return res;
389             }
390
391             std::unique_lock<std::mutex> lck(m_mtx);
392             m_cond.wait_for(lck, std::chrono::seconds(ES_SEC_DISCOVERY_TIMEOUT));
393
394             if(aclResult)
395             {
396                 res = ESResult::ES_OK;
397             }
398
399             return res;
400         }
401
402         std::string EnrolleeSecurity::getUUID() const
403         {
404             return m_ocResource->sid();
405         };
406
407         OicSecAcl_t* EnrolleeSecurity::createAcl(const OicUuid_t cloudUuid)
408         {
409             // allocate memory for |acl| struct
410             OicSecAcl_t* acl = (OicSecAcl_t*) OICCalloc(1, sizeof(OicSecAcl_t));
411             if(!acl)
412             {
413                 OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "createAcl: OICCalloc error return");
414                 return NULL;  // not need to 'goto' |ERROR| before allocating |acl|
415             }
416             OicSecAce_t* ace = (OicSecAce_t*) OICCalloc(1, sizeof(OicSecAce_t));
417             if(!ace)
418             {
419                 OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG,  "createAcl: OICCalloc error return");
420                 return NULL;  // not need to 'goto' |ERROR| before allocating |acl|
421             }
422             LL_APPEND(acl->aces, ace);
423
424             memcpy(&ace->subjectuuid, &cloudUuid, UUID_LENGTH);
425
426             OicSecRsrc_t* rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
427             if(!rsrc)
428             {
429                 OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "createAcl: OICCalloc error return");
430                 OCDeleteACLList(acl);
431                 return NULL;
432             }
433
434             char href[] = "*";
435             size_t len = strlen(href)+1;  // '1' for null termination
436             rsrc->href = (char*) OICCalloc(len, sizeof(char));
437             if(!rsrc->href)
438             {
439                 OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG,  "createAcl: OICCalloc error return");
440                 OCDeleteACLList(acl);
441                 return NULL;
442             }
443             OICStrcpy(rsrc->href, len, href);
444
445             size_t arrLen = 1;
446             rsrc->typeLen = arrLen;
447             rsrc->types = (char**)OICCalloc(arrLen, sizeof(char*));
448             rsrc->interfaces = (char**)OICCalloc(arrLen, sizeof(char*));
449             rsrc->types[0] = OICStrdup("rt");   // ignore
450             rsrc->interfaces[0] = OICStrdup("if");  // ignore
451
452             LL_APPEND(ace->resources, rsrc);
453
454             ace->permission = 31;   // R/W/U/D
455
456             return acl;
457         }
458
459         void EnrolleeSecurity::ACLProvisioningCb(PMResultList_t *result, int hasError)
460         {
461             if (hasError)
462             {
463                OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Error in provisioning operation!");
464                aclResult = false;
465             }
466             else
467             {
468                OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Received provisioning results: ");
469
470                std::string devUuid;
471                for (unsigned int i = 0; i < result->size(); i++)
472                {
473                    convertUUIDToString(result->at(i).deviceId.id, devUuid);
474                    OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Result is = %d  for device %s",
475                                                            result->at(i).res, devUuid.c_str());
476                }
477                delete result;
478                aclResult = true;
479             }
480             m_cond.notify_all();
481         }
482     }
483 }