Merge "Merge branch 'master' into cloud-interface" into cloud-interface
[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 "RemoteEnrolleeResource.h"
27 #include "logger.h"
28 #include "ESException.h"
29 #include "oic_malloc.h"
30 #include "oic_string.h"
31
32 namespace OIC
33 {
34     namespace Service
35     {
36         #define MAX_PERMISSION_LENGTH (5)
37         #define CREATE (1)
38         #define READ (2)
39         #define UPDATE (4)
40         #define DELETE (8)
41         #define NOTIFY (16)
42         #define DASH '-'
43
44         //TODO : Currently discovery timeout for owned and unowned devices is fixed as 5
45         // The value should be accepted from the application as a parameter during ocplatform
46         // config call
47 #define ES_SEC_DISCOVERY_TIMEOUT 5
48
49         EnrolleeSecurity::EnrolleeSecurity(
50         std::shared_ptr< RemoteEnrolleeResource > remoteEnrolleeResource,
51         std::string secDbPath)
52         {
53             m_enrolleeSecState = EnrolleeSecState::ES_SEC_UNKNOWN;
54             m_remoteEnrolleeResource = remoteEnrolleeResource;
55         }
56
57         ESResult EnrolleeSecurity::registerCallbackHandler(EnrolleeSecStatusCb enrolleeSecStatusCb,
58                 SecurityPinCb securityPinCb, SecProvisioningDbPathCb secProvisioningDbPathCb)
59
60         {
61             m_enrolleeSecStatusCb = enrolleeSecStatusCb;
62             m_securityPinCb = securityPinCb;
63             m_secProvisioningDbPathCb = secProvisioningDbPathCb;
64
65             return ES_ERROR;
66         }
67
68         std::shared_ptr< OC::OCSecureResource > EnrolleeSecurity::getEnrollee(DeviceList_t &list)
69         {
70             for (unsigned int i = 0; i < list.size(); i++)
71             {
72                 OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Device %d ID %s ", i + 1,
73                         list[i]->getDeviceID().c_str());
74                 OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "From IP :%s", list[i]->getDevAddr().c_str());
75
76                 //Always return the first element of the unOwned devices. This is considering that Mediator is
77                 // always connected with only one Enrollee for which ownership transfer is being performed.
78                 // Incase of multiple Enrollee devices connected to the Mediator via any OnBoarding method (SoftAp
79                 // for example), the Enrollee devices will be provisioned in the first come first serve basis in the order
80                 // returned by the security layer.
81                 return list[i];
82             }
83         }
84
85         void EnrolleeSecurity::convertUUIDToString(OicUuid_t uuid, std::string& uuidString)
86         {
87             char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*) 0)->id)) + 1] =
88             { 0, };
89             uint32_t outLen = 0;
90             B64Result b64Ret = B64_OK;
91             std::ostringstream deviceId("");
92
93             b64Ret = b64Encode(uuid.id, sizeof(uuid.id),
94                     base64Buff, sizeof(base64Buff), &outLen);
95
96             if (B64_OK == b64Ret)
97             {
98                 deviceId << base64Buff;
99             }
100             uuidString =  deviceId.str();
101         }
102
103         void EnrolleeSecurity::ownershipTransferCb(OC::PMResultList_t *result, int hasError)
104         {
105             if (hasError)
106             {
107                 OIC_LOG(ERROR, ENROLEE_SECURITY_TAG,"Error!!! in OwnershipTransfer");
108
109                 std::shared_ptr< SecProvisioningResult > securityProvisioningStatus = nullptr;
110                 std::string uuid;
111                 convertUUIDToString(result->at(0).deviceId, uuid);
112                 securityProvisioningStatus = std::make_shared< SecProvisioningResult >(uuid,
113                         ES_ERROR);
114
115                 m_enrolleeSecStatusCb(securityProvisioningStatus);
116                 return;
117             }
118             else
119             {
120                 OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "ownershipTransferCb : Received provisioning results: ");
121                 for (unsigned int i = 0; i < result->size(); i++)
122                 {
123                     OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Result is = %d for device",result->at(i).res);
124                     std::string uuid;
125                     convertUUIDToString(result->at(0).deviceId, uuid);
126
127                     OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "UUID : %s",uuid.c_str());
128                     std::shared_ptr< SecProvisioningResult > securityProvisioningStatus = nullptr;
129                     securityProvisioningStatus = std::make_shared< SecProvisioningResult >(uuid,
130                             ES_OK);
131
132                     m_enrolleeSecStatusCb(securityProvisioningStatus);
133                     return;
134                 }
135
136                 delete result;
137             }
138         }
139
140         EasySetupState EnrolleeSecurity::performOwnershipTransfer()
141         {
142             EasySetupState ownershipStatus = DEVICE_NOT_OWNED;
143
144             OC::DeviceList_t pUnownedDevList, pOwnedDevList;
145
146             pOwnedDevList.clear();
147             pUnownedDevList.clear();
148
149             OCStackResult result;
150
151             //Developer note : Always test the mediator and enrollee applications on different devices. Running
152             // Mediator and Enrollee in same device will result in returning the same device as already owned.
153             /*result = OCSecure::discoverOwnedDevices(ES_SEC_DISCOVERY_TIMEOUT,
154                     pOwnedDevList);
155             if (result != OC_STACK_OK)
156             {
157                 OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "Owned Discovery failed.");
158                 ownershipStatus = DEVICE_NOT_OWNED;
159                 //Throw exception
160                 throw ESPlatformException(result);
161                 return ownershipStatus;
162             }
163             else if (pOwnedDevList.size())
164             {
165                 OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Found owned devices. Count =%d",
166                         pOwnedDevList.size());
167                 std::shared_ptr< OC::OCSecureResource > ownedDevice = getEnrollee(pOwnedDevList);
168                 if (ownedDevice)
169                 {
170                     ownershipStatus = DEVICE_OWNED;
171                     return ownershipStatus;
172                 }
173             }
174             else
175             {
176                 OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "No owned devices found.");
177                 ownershipStatus = DEVICE_NOT_OWNED;
178             }*/
179
180             result = OCSecure::discoverUnownedDevices(ES_SEC_DISCOVERY_TIMEOUT, pUnownedDevList);
181             if (result != OC_STACK_OK)
182             {
183                 OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "UnOwned Discovery failed.");
184                 ownershipStatus = DEVICE_NOT_OWNED;
185                 //Throw exception
186                 throw ESPlatformException(result);
187                 return ownershipStatus;
188             }
189             else if (pUnownedDevList.size())
190             {
191                 OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Found Unowned devices. Count =%d",
192                         pUnownedDevList.size());
193
194                 m_unownedDevice = getEnrollee(pUnownedDevList);
195                 if (m_unownedDevice)
196                 {
197                     OTMCallbackData_t justWorksCBData;
198                     justWorksCBData.loadSecretCB = LoadSecretJustWorksCallback;
199                     justWorksCBData.createSecureSessionCB = CreateSecureSessionJustWorksCallback;
200                     justWorksCBData.createSelectOxmPayloadCB = CreateJustWorksSelectOxmPayload;
201                     justWorksCBData.createOwnerTransferPayloadCB =
202                             CreateJustWorksOwnerTransferPayload;
203                     OCSecure::setOwnerTransferCallbackData(OIC_JUST_WORKS, &justWorksCBData, NULL);
204
205                     OIC_LOG_V(DEBUG, ENROLEE_SECURITY_TAG, "Transfering ownership for : %s ",
206                             m_unownedDevice->getDeviceID().c_str());
207
208                     OC::ResultCallBack ownershipTransferCb = std::bind(
209                             &EnrolleeSecurity::ownershipTransferCb, this, std::placeholders::_1,
210                             std::placeholders::_2);
211
212                     if (m_unownedDevice->doOwnershipTransfer(ownershipTransferCb) != OC_STACK_OK)
213                     {
214                         OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "OwnershipTransferCallback is failed");
215                         ownershipStatus = DEVICE_NOT_OWNED;
216                         return ownershipStatus;
217                     }
218                     ownershipStatus = DEVICE_NOT_OWNED;
219                 }
220             }
221             else
222             {
223                 OIC_LOG(ERROR, ENROLEE_SECURITY_TAG, "No unSecure devices found.");
224                 ownershipStatus = DEVICE_NOT_OWNED;
225
226                 return ownershipStatus;
227             }
228
229             return ownershipStatus;
230         }
231     }
232 }