Imported Upstream version 1.0.1
[platform/upstream/iotivity.git] / resource / csdk / security / src / amsmgr.c
1 //******************************************************************
2 //
3 // Copyright 2015 Intel Mobile Communications GmbH 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 "oic_malloc.h"
22 #include "amsmgr.h"
23 #include "resourcemanager.h"
24 #include "securevirtualresourcetypes.h"
25 #include "srmresourcestrings.h"
26 #include "logger.h"
27 #include "ocrandom.h"
28 #include "aclresource.h"
29 #include "amaclresource.h"
30 #include "srmutility.h"
31 #include "base64.h"
32 #include "secureresourcemanager.h"
33 #include "doxmresource.h"
34 #include "policyengine.h"
35 #include "oic_string.h"
36 #include "caremotehandler.h"
37 #include <string.h>
38
39 #define TAG "SRM-AMSMGR"
40
41
42  //Callback for AMS service multicast discovery request.
43 static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle handle,
44                          OCClientResponse * clientResponse);
45
46 //Callback for unicast secured port discovery request.
47 static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandle handle,
48                          OCClientResponse * clientResponse);
49
50 //Callback for unicast ACL request
51 static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handle,
52     OCClientResponse * clientResponse);
53
54
55 OCStackResult DiscoverAmsService(PEContext_t *context)
56 {
57     OC_LOG(INFO, TAG, "IN DiscoverAmsService");
58
59     OCStackResult ret = OC_STACK_ERROR;
60     const char DOXM_DEVICEID_QUERY_FMT[] = "%s?%s=%s";
61     char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {};
62     OCCallbackData cbData = {.context=NULL};
63     char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
64     uint32_t outLen = 0;
65     B64Result b64Ret;
66
67     VERIFY_NON_NULL(TAG, context, ERROR);
68     b64Ret = b64Encode(context->amsMgrContext->amsDeviceId.id,
69           sizeof(context->amsMgrContext->amsDeviceId.id), base64Buff, sizeof(base64Buff), &outLen);
70     VERIFY_SUCCESS(TAG, B64_OK == b64Ret, ERROR);
71     snprintf(uri, sizeof(uri), DOXM_DEVICEID_QUERY_FMT, OIC_RSRC_DOXM_URI,
72                                        OIC_JSON_DEVICE_ID_NAME, base64Buff);
73
74     cbData.cb = &AmsMgrDiscoveryCallback;
75     cbData.context = (void*)context;
76
77     /* TODO
78      * If no good response was received for this discovery request,
79      * PE would be blocked forever waiting for AMS service to respond with the ACE.
80      * Need logic to reset the PE state and send ACCESS_DENIED response,
81      * when discovery response from AMS service is not received within certain time.
82      */
83     OC_LOG_V(INFO, TAG,"AMS Manager Sending Multicast Discovery with URI = %s", uri);
84     ret = OCDoResource(NULL, OC_REST_DISCOVER, uri, NULL, NULL,
85                        CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
86
87 exit:
88     OC_LOG(INFO, TAG, "Leaving DiscoverAmsService");
89     return ret;
90 }
91
92
93 static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle handle,
94                          OCClientResponse * clientResponse)
95 {
96     OC_LOG_V(INFO, TAG, "%s Begin", __func__ );
97
98     if (!ctx ||
99         !clientResponse ||
100         !clientResponse->payload||
101         (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)||
102         (OC_STACK_OK != clientResponse->result))
103     {
104         OC_LOG_V(ERROR, TAG, "%s Invalid Response ", __func__);
105         return OC_STACK_KEEP_TRANSACTION;
106     }
107
108     (void)handle;
109     PEContext_t *context = (PEContext_t *) ctx;
110     if (context->state != AWAITING_AMS_RESPONSE)
111     {
112         OC_LOG_V(ERROR, TAG, "%s Invalid PE State ", __func__);
113         return OC_STACK_DELETE_TRANSACTION;
114     }
115
116     OicSecDoxm_t *doxm = NULL;
117     OC_LOG_V(INFO, TAG, "Doxm DeviceId Discovery response = %s\n",
118           ((OCSecurityPayload*)clientResponse->payload)->securityData);
119     doxm = JSONToDoxmBin(((OCSecurityPayload*)clientResponse->payload)->securityData);
120
121     //As doxm is NULL amsmgr can't test if response from trusted AMS service
122     //so keep the transaction.
123     if(NULL == doxm)
124     {
125         OC_LOG_V(ERROR, TAG, "%s : Unable to convert JSON to Binary",__func__);
126         return OC_STACK_KEEP_TRANSACTION;
127     }
128
129     OicUuid_t deviceId = {.id={}};
130     memcpy(&deviceId, &doxm->deviceID, sizeof(deviceId));
131     OICFree(doxm);
132
133     /* TODO : By assuming that the first response received is the actual
134      * AMS service, a 'bad device' can cause DoS attack.
135      */
136     if (memcmp(&context->amsMgrContext->amsDeviceId, &deviceId,
137             sizeof(context->amsMgrContext->amsDeviceId)) == 0)
138     {
139         OC_LOG(INFO, TAG, "AMS Manager Sending unicast discovery to get secured port info");
140         //Sending Unicast discovery to get secure port information
141         if(OC_STACK_OK == SendUnicastSecurePortDiscovery(context, &clientResponse->devAddr,
142                 clientResponse->connType))
143         {
144             context->retVal = ACCESS_WAITING_FOR_AMS;
145             return OC_STACK_DELETE_TRANSACTION;
146         }
147     }
148     context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
149     SRMSendResponse(context->retVal);
150     return OC_STACK_DELETE_TRANSACTION;
151 }
152
153
154 OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,OCDevAddr *devAddr,
155                                       OCConnectivityType connType)
156 {
157     OC_LOG(INFO, TAG, "IN SendUnicastSecurePortDiscovery");
158
159     const char RES_DOXM_QUERY_FMT[] = "%s?%s=%s";
160     OCCallbackData cbData = {.context=NULL};
161     char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {};
162     snprintf(uri, sizeof(uri), RES_DOXM_QUERY_FMT, OC_RSRVD_WELL_KNOWN_URI,
163             OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DOXM);
164
165     cbData.cb = &SecurePortDiscoveryCallback;
166     cbData.context = context;
167
168     OC_LOG_V(INFO, TAG, "AMS Manager Sending Unicast Discovery with URI = %s", uri);
169
170     return  OCDoResource(NULL, OC_REST_DISCOVER, uri, devAddr, NULL,
171                          connType, OC_LOW_QOS, &cbData, NULL, 0);
172 }
173
174 static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandle handle,
175                          OCClientResponse * clientResponse)
176 {
177     OC_LOG(INFO, TAG, "In SecurePortDiscoveryCallback");
178
179     if (!ctx ||
180         !clientResponse ||
181         !clientResponse->payload||
182         (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)||
183         (OC_STACK_OK != clientResponse->result))
184         {
185             OC_LOG_V(ERROR, TAG, "%s Invalid Response ", __func__);
186             SRMSendResponse(ACCESS_DENIED_AMS_SERVICE_ERROR);
187             return OC_STACK_DELETE_TRANSACTION;
188         }
189
190     PEContext_t *context = (PEContext_t *) ctx;
191     (void)handle;
192     if (context->state != AWAITING_AMS_RESPONSE)
193     {
194         OC_LOG_V(ERROR, TAG, "%s Invalid PE State ", __func__);
195         context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
196         SRMSendResponse(context->retVal);
197         return OC_STACK_DELETE_TRANSACTION;
198     }
199     OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
200
201     //Verifying if the ID of the sender is an AMS service that this device trusts.
202     if(resPayload &&
203        memcmp(context->amsMgrContext->amsDeviceId.id,
204             ((OCDiscoveryPayload*)clientResponse->payload)->sid,
205             // resPayload->sid,
206                     sizeof(context->amsMgrContext->amsDeviceId.id)) != 0)
207     {
208         context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
209         SRMSendResponse(context->retVal);
210         return OC_STACK_DELETE_TRANSACTION;
211     }
212
213     if (resPayload && resPayload->secure)
214     {
215         if(OC_STACK_OK == SendAclReq(context, &clientResponse->devAddr, clientResponse->connType,
216                 resPayload->port))
217         {
218             return OC_STACK_DELETE_TRANSACTION;
219         }
220     }
221     OC_LOG(INFO, TAG, "Can not find secure port information");
222     context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
223     SRMSendResponse(context->retVal);
224     return OC_STACK_DELETE_TRANSACTION;
225 }
226
227
228 OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivityType connType,
229         uint16_t securedPort)
230 {
231     OCStackResult ret = OC_STACK_ERROR;
232     const char GET_ACE_QUERY_FMT[] = "%s?%s=%s;%s=%s";
233     char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
234     uint32_t outLen = 0;
235     char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {};
236     OCCallbackData cbData = {.context=NULL};
237     OCDevAddr destAddr = {.adapter = OC_ADAPTER_IP};
238     B64Result b64Ret;
239
240     VERIFY_NON_NULL(TAG, context, ERROR);
241     VERIFY_NON_NULL(TAG, devAddr, ERROR);
242
243     b64Ret = b64Encode(context->subject.id, sizeof(context->subject.id),
244                        base64Buff, sizeof(base64Buff), &outLen);
245     VERIFY_SUCCESS(TAG, B64_OK == b64Ret, ERROR);
246
247     snprintf(uri, sizeof(uri), GET_ACE_QUERY_FMT, OIC_RSRC_ACL_URI,
248                                     OIC_JSON_SUBJECT_NAME, base64Buff,
249                                     OIC_JSON_RESOURCES_NAME, context->resource);
250
251     cbData.cb = &AmsMgrAclReqCallback;
252     cbData.context = context;
253
254     destAddr = *devAddr;
255     //update port info
256     destAddr.flags = (OCTransportFlags)(destAddr.flags | OC_FLAG_SECURE);
257     destAddr.port = securedPort;
258
259     OC_LOG_V(INFO, TAG, "AMS Manager Sending Unicast ACL request with URI = %s", uri);
260     ret = OCDoResource(NULL, OC_REST_GET, uri, &destAddr, NULL,
261             connType, OC_LOW_QOS, &cbData, NULL, 0);
262
263 exit:
264     OC_LOG_V(INFO, TAG, "%s returns %d ", __func__, ret);
265     return ret;
266 }
267
268
269 static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handle,
270     OCClientResponse * clientResponse)
271 {
272     OC_LOG_V(INFO, TAG, "%s Begin", __func__ );
273
274     (void)handle;
275     PEContext_t *context = (PEContext_t *) ctx;
276     SRMAccessResponse_t rsps;
277
278     if (!ctx ||
279         !clientResponse ||
280         !clientResponse->payload||
281         (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type) ||
282         (clientResponse->result != OC_STACK_OK))
283     {
284         SRMSendResponse(ACCESS_DENIED_AMS_SERVICE_ERROR);
285         goto exit;
286     }
287
288     if (context->state != AWAITING_AMS_RESPONSE)
289     {
290         OC_LOG_V(ERROR, TAG, "%s Invalid State ", __func__);
291         context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
292         SRMSendResponse(context->retVal);
293         return OC_STACK_DELETE_TRANSACTION;
294     }
295
296     // Verify before installing ACL if the ID of the sender of this ACL is an AMS
297     //service that this device trusts.
298     rsps = ACCESS_DENIED;
299     if((UUID_LENGTH == clientResponse->identity.id_length) &&
300         memcmp(context->amsMgrContext->amsDeviceId.id, clientResponse->identity.id,
301                        sizeof(context->amsMgrContext->amsDeviceId.id)) == 0)
302     {
303         OCStackResult ret =
304                 InstallNewACL(((OCSecurityPayload*)clientResponse->payload)->securityData);
305         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
306
307         OC_LOG_V(INFO, TAG, "%s : Calling checkPermission", __func__);
308         rsps = CheckPermission(context, &context->subject, context->resource, context->permission);
309         VERIFY_SUCCESS(TAG, (true == IsAccessGranted(rsps)), ERROR);
310
311         OC_LOG_V(INFO, TAG, "%sAccess granted, Calling SRMCallCARequestHandler", __func__);
312         context->retVal = ACCESS_GRANTED;
313         SRMSendResponse(context->retVal);
314         return OC_STACK_DELETE_TRANSACTION;
315     }
316
317 exit:
318     context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
319     SRMSendResponse(context->retVal);
320     FreeCARequestInfo(context->amsMgrContext->requestInfo);
321     OICFree(context->amsMgrContext->endpoint);
322     return OC_STACK_DELETE_TRANSACTION;
323 }
324
325
326 OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endpoint,
327                         const CARequestInfo_t *requestInfo)
328 {
329     OCStackResult ret = OC_STACK_ERROR;
330
331     //The AmsMgr context endpoint and requestInfo will be free from ,
332     //AmsMgrAclReqCallback function
333     if(context->amsMgrContext->endpoint)
334     {
335         OICFree(context->amsMgrContext->endpoint);
336         context->amsMgrContext->endpoint = NULL;
337     }
338     context->amsMgrContext->endpoint = (CAEndpoint_t *)OICCalloc(1, sizeof(CAEndpoint_t ));
339     VERIFY_NON_NULL(TAG, context->amsMgrContext->endpoint, ERROR);
340     *context->amsMgrContext->endpoint = *endpoint;
341
342     if(context->amsMgrContext->requestInfo)
343     {
344         FreeCARequestInfo(context->amsMgrContext->requestInfo);
345         context->amsMgrContext->requestInfo = NULL;
346     }
347     context->amsMgrContext->requestInfo = CACloneRequestInfo(requestInfo);
348     VERIFY_NON_NULL(TAG, context->amsMgrContext->requestInfo, ERROR);
349     ret = OC_STACK_OK;
350 exit:
351     return ret;
352 }
353
354 void FreeCARequestInfo(CARequestInfo_t *requestInfo)
355 {
356     OICFree(requestInfo->info.token);
357     OICFree(requestInfo->info.options);
358     OICFree(requestInfo->info.payload);
359     OICFree(requestInfo->info.resourceUri);
360     OICFree(requestInfo);
361 }
362
363
364 //This method checks for Amacl resource. If Amacl is found then it fills up
365 //context->amsMgrContext->amsDeviceId with amsID of the Amacl else leaves it empty.
366 bool FoundAmaclForRequest(PEContext_t *context)
367 {
368     OC_LOG_V(INFO, TAG, "%s:no ACL found. Searching for AMACL",__func__);
369
370     bool ret = false;
371     VERIFY_NON_NULL(TAG, context, ERROR);
372     memset(&context->amsMgrContext->amsDeviceId, 0, sizeof(context->amsMgrContext->amsDeviceId));
373
374     //Call amacl resource function to get the AMS service deviceID for the resource
375     if(OC_STACK_OK == AmaclGetAmsDeviceId(context->resource, &context->amsMgrContext->amsDeviceId))
376     {
377         OC_LOG_V(INFO, TAG, "%s:AMACL found for the requested resource %s",
378                 __func__, context->resource);
379         ret = true;
380     }
381     else
382     {
383         OC_LOG_V(INFO, TAG, "%s:AMACL found for the requested resource %s",
384                 __func__, context->resource);
385         ret = false;
386     }
387
388  exit:
389      return ret;
390 }
391
392
393 void ProcessAMSRequest(PEContext_t *context)
394 {
395     OicUuid_t  emptyUuid = {.id={}};
396     OC_LOG_V(INFO, TAG, "Entering %s", __func__);
397     if(NULL != context)
398     {
399         if((false == context->matchingAclFound) && (false == context->amsProcessing))
400         {
401             context->amsProcessing = true;
402
403             //Checking if context AMS deviceId is empty
404             if(memcmp(&context->amsMgrContext->amsDeviceId, &emptyUuid, sizeof(OicUuid_t)) != 0 )
405             {
406                 if(OC_STACK_OK == DiscoverAmsService(context))
407                 {
408                     context->retVal = ACCESS_WAITING_FOR_AMS;
409                 }
410                 else
411                 {
412                     context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
413                 }
414             }
415         }
416     }
417     else
418     {
419         OC_LOG_V(INFO, TAG, "Leaving %s(context is NULL)", __func__);
420     }
421
422     if(ACCESS_WAITING_FOR_AMS == context->retVal )
423     {
424         OC_LOG_V(INFO, TAG, "Leaving %s(WAITING_FOR_AMS)", __func__);
425     }
426 }