[IOT-1446] Fix discovery failure issue
[platform/upstream/iotivity.git] / resource / csdk / security / src / policyengine.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 #include <string.h>
21
22 #include "utlist.h"
23 #include "oic_malloc.h"
24 #include "policyengine.h"
25 #include "amsmgr.h"
26 #include "resourcemanager.h"
27 #include "securevirtualresourcetypes.h"
28 #include "srmresourcestrings.h"
29 #include "logger.h"
30 #include "aclresource.h"
31 #include "srmutility.h"
32 #include "doxmresource.h"
33 #include "iotvticalendar.h"
34 #include "pstatresource.h"
35 #include "dpairingresource.h"
36 #include "pconfresource.h"
37 #include "amaclresource.h"
38 #include "credresource.h"
39
40 #define TAG "SRM-PE"
41
42 uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method)
43 {
44     uint16_t perm = 0;
45     switch (method)
46     {
47         case CA_GET:
48             perm = (uint16_t)PERMISSION_READ;
49             break;
50         case CA_POST: // For now we treat all PUT & POST as Write
51         case CA_PUT:  // because we don't know if resource exists yet.
52             perm = (uint16_t)PERMISSION_WRITE;
53             break;
54         case CA_DELETE:
55             perm = (uint16_t)PERMISSION_DELETE;
56             break;
57         default: // if not recognized, must assume requesting full control
58             perm = (uint16_t)PERMISSION_FULL_CONTROL;
59             break;
60     }
61     return perm;
62 }
63
64 /**
65  * Compares two OicUuid_t structs.
66  *
67  * @return true if the two OicUuid_t structs are equal, else false.
68  */
69 static bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
70 {
71     // TODO use VERIFY macros to check for null when they are merged.
72     if(NULL == firstId || NULL == secondId)
73     {
74         return false;
75     }
76     // Check empty uuid string
77     if('\0' == firstId->id[0] || '\0' == secondId->id[0])
78     {
79         return false;
80     }
81     for(int i = 0; i < UUID_LENGTH; i++)
82     {
83         if(firstId->id[i] != secondId->id[i])
84         {
85             return false;
86         }
87     }
88     return true;
89 }
90
91 void SetPolicyEngineState(PEContext_t *context, const PEState_t state)
92 {
93     if (NULL == context)
94     {
95         return;
96     }
97
98     // Clear stateful context variables.
99     memset(&context->subject, 0, sizeof(context->subject));
100     memset(&context->resource, 0, sizeof(context->resource));
101     context->permission = 0x0;
102     context->matchingAclFound = false;
103     context->amsProcessing = false;
104     context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
105
106     if (context->amsMgrContext)
107     {
108         if (context->amsMgrContext->requestInfo)
109         {
110             FreeCARequestInfo(context->amsMgrContext->requestInfo);
111         }
112         OICFree(context->amsMgrContext->endpoint);
113         memset(context->amsMgrContext, 0, sizeof(AmsMgrContext_t));
114     }
115
116     // Set state.
117     context->state = state;
118 }
119
120 /**
121  * Compare the request's subject to DevOwner.
122  *
123  * @return true if context->subjectId == GetDoxmDevOwner(), else false.
124  */
125 static bool IsRequestFromDevOwner(PEContext_t *context)
126 {
127     bool retVal = false;
128
129     if(NULL == context)
130     {
131         return retVal;
132     }
133
134     /*
135     if(OC_STACK_OK == GetDoxmDevOwnerId(&ownerid))
136     {
137         retVal = UuidCmp(&context->subject, &ownerid);
138     }
139     */
140
141     // TODO: Added as workaround for CTT
142     OicSecDoxm_t* doxm = (OicSecDoxm_t*) GetDoxmResourceData();
143     if (doxm)
144     {
145         retVal = UuidCmp(&doxm->owner, &context->subject);
146     }
147     return retVal;
148 }
149
150 // TODO - remove these function placeholders as they are implemented
151 // in the resource entity handler code.
152 // Note that because many SVRs do not have a rowner, in those cases we
153 // just return "OC_STACK_ERROR" which results in a "false" return by
154 // IsRequestFromResourceOwner().
155 // As these SVRs are revised to have a rowner, these functions should be
156 // replaced (see pstatresource.c for example of GetPstatRownerId).
157
158 OCStackResult GetCrlRownerId(OicUuid_t *rowner)
159 {
160     OC_UNUSED(rowner);
161     rowner = NULL;
162     return OC_STACK_ERROR;
163 }
164
165 OCStackResult GetSaclRownerId(OicUuid_t *rowner)
166 {
167     OC_UNUSED(rowner);
168     rowner = NULL;
169     return OC_STACK_ERROR;
170 }
171
172 OCStackResult GetSvcRownerId(OicUuid_t *rowner)
173 {
174     OC_UNUSED(rowner);
175     rowner = NULL;
176     return OC_STACK_ERROR;
177 }
178
179 static GetSvrRownerId_t GetSvrRownerId[OIC_SEC_SVR_TYPE_COUNT] = {
180     GetAclRownerId,
181     GetAmaclRownerId,
182     GetCredRownerId,
183     GetCrlRownerId,
184     GetDoxmRownerId,
185     GetDpairingRownerId,
186     GetPconfRownerId,
187     GetPstatRownerId,
188     GetSaclRownerId,
189     GetSvcRownerId
190 };
191
192 /**
193  * Compare the request's subject to resource.ROwner.
194  *
195  * @return true if context->subjectId equals SVR rowner id, else return false
196  */
197 bool IsRequestFromResourceOwner(PEContext_t *context)
198 {
199     bool retVal = false;
200     OicUuid_t resourceOwner;
201
202     if(NULL == context)
203     {
204         return false;
205     }
206
207     if((OIC_R_ACL_TYPE <= context->resourceType) && \
208         (OIC_SEC_SVR_TYPE_COUNT > context->resourceType))
209     {
210         if(OC_STACK_OK == GetSvrRownerId[(int)context->resourceType](&resourceOwner))
211         {
212             retVal = UuidCmp(&context->subject, &resourceOwner);
213         }
214     }
215
216     if(true == retVal)
217     {
218         OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning true");
219     }
220     else
221     {
222         OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning false");
223     }
224
225     return retVal;
226 }
227
228 INLINE_API bool IsRequestSubjectEmpty(PEContext_t *context)
229 {
230     OicUuid_t emptySubject = {.id={0}};
231
232     if(NULL == context)
233     {
234         return false;
235     }
236
237     return (memcmp(&context->subject, &emptySubject, sizeof(OicUuid_t)) == 0) ?
238             true : false;
239 }
240
241 /**
242  * Bitwise check to see if 'permission' contains 'request'.
243  *
244  * @param permission is the allowed CRUDN permission.
245  * @param request is the CRUDN permission being requested.
246  *
247  * @return true if 'permission' bits include all 'request' bits.
248  */
249 INLINE_API bool IsPermissionAllowingRequest(const uint16_t permission,
250     const uint16_t request)
251 {
252     if (request == (request & permission))
253     {
254         return true;
255     }
256     else
257     {
258         return false;
259     }
260 }
261
262 /**
263  * Compare the passed subject to the wildcard (aka anonymous) subjectId.
264  *
265  * @return true if 'subject' is the wildcard, false if it is not.
266  */
267 INLINE_API bool IsWildCardSubject(OicUuid_t *subject)
268 {
269     if(NULL == subject)
270     {
271         return false;
272     }
273
274     // Because always comparing to string literal, use strcmp()
275     if(0 == memcmp(subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)))
276     {
277         return true;
278     }
279     else
280     {
281         return false;
282     }
283 }
284
285 /**
286  * Copy the subject, resource and permission into the context fields.
287  */
288 static void CopyParamsToContext(PEContext_t     *context,
289                                 const OicUuid_t *subjectId,
290                                 const char      *resource,
291                                 const uint16_t  requestedPermission)
292 {
293     size_t length = 0;
294
295     if (NULL == context || NULL == subjectId || NULL == resource)
296     {
297         return;
298     }
299
300     memcpy(&context->subject, subjectId, sizeof(OicUuid_t));
301
302     // Copy the resource string into context.
303     length = sizeof(context->resource) - 1;
304     strncpy(context->resource, resource, length);
305     context->resource[length] = '\0';
306
307
308     // Assign the permission field.
309     context->permission = requestedPermission;
310 }
311
312 /**
313  * Check whether 'resource' is getting accessed within the valid time period.
314  *
315  * @param acl is the ACL to check.
316  *
317  * @return true if access is within valid time period or if the period or recurrence is not present.
318  * false if period and recurrence present and the access is not within valid time period.
319  */
320 static bool IsAccessWithinValidTime(const OicSecAce_t *ace)
321 {
322 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
323     //lack of absolute time
324     if (NULL== ace || NULL == ace->validities)
325     {
326         return true;
327     }
328
329     //periods & recurrences rules are paired.
330     if (NULL == ace->validities->recurrences)
331     {
332         return false;
333     }
334
335     OicSecValidity_t* validity =  NULL;
336     LL_FOREACH(ace->validities, validity)
337     {
338         for(size_t i = 0; i < validity->recurrenceLen; i++)
339         {
340             if (IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(validity->period,
341                 validity->recurrences[i]))
342             {
343                 OIC_LOG(INFO, TAG, "Access request is in allowed time period");
344                 return true;
345             }
346         }
347     }
348     OIC_LOG(ERROR, TAG, "Access request is in invalid time period");
349     return false;
350
351 #else
352     return true;
353 #endif
354 }
355
356 /**
357  * Check whether 'resource' is in the passed ACE.
358  *
359  * @param resource is the resource being searched.
360  * @param ace is the ACE to check.
361  *
362  * @return true if 'resource' found, otherwise false.
363  */
364  static bool IsResourceInAce(const char *resource, const OicSecAce_t *ace)
365 {
366     if (NULL== ace || NULL == resource)
367     {
368         return false;
369     }
370
371     OicSecRsrc_t* rsrc = NULL;
372     LL_FOREACH(ace->resources, rsrc)
373     {
374          if (0 == strcmp(resource, rsrc->href) || // TODO null terms?
375              0 == strcmp(WILDCARD_RESOURCE_URI, rsrc->href))
376          {
377              return true;
378          }
379     }
380     return false;
381 }
382
383
384 /**
385  * Find ACLs containing context->subject.
386  * Search each ACL for requested resource.
387  * If resource found, check for context->permission and period validity.
388  * If the ACL is not found locally and AMACL for the resource is found
389  * then sends the request to AMS service for the ACL.
390  * Set context->retVal to result from first ACL found which contains
391  * correct subject AND resource.
392  */
393 static void ProcessAccessRequest(PEContext_t *context)
394 {
395     OIC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
396     if (NULL != context)
397     {
398         const OicSecAce_t *currentAce = NULL;
399         OicSecAce_t *savePtr = NULL;
400
401         // Start out assuming subject not found.
402         context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
403
404         // Loop through all ACLs with a matching Subject searching for the right
405         // ACL for this request.
406         do
407         {
408             OIC_LOG_V(DEBUG, TAG, "%s: getting ACE..." ,__func__);
409             currentAce = GetACLResourceData(&context->subject, &savePtr);
410
411             if (NULL != currentAce)
412             {
413                 // Found the subject, so how about resource?
414                 OIC_LOG_V(DEBUG, TAG, "%s:found ACE matching subject" ,__func__);
415
416                 // Subject was found, so err changes to Rsrc not found for now.
417                 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
418                 OIC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
419                 if (IsResourceInAce(context->resource, currentAce))
420                 {
421                     OIC_LOG_V(INFO, TAG, "%s:found matching resource in ACE" ,__func__);
422                     context->matchingAclFound = true;
423
424                     // Found the resource, so it's down to valid period & permission.
425                     context->retVal = ACCESS_DENIED_INVALID_PERIOD;
426                     if (IsAccessWithinValidTime(currentAce))
427                     {
428                         context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
429                         if (IsPermissionAllowingRequest(currentAce->permission, context->permission))
430                         {
431                             context->retVal = ACCESS_GRANTED;
432                         }
433                     }
434                 }
435             }
436             else
437             {
438                 OIC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
439             }
440         } while ((NULL != currentAce) && (false == context->matchingAclFound));
441
442         if (IsAccessGranted(context->retVal))
443         {
444             OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
445         }
446         else
447         {
448             OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
449         }
450     }
451     else
452     {
453         OIC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
454     }
455 }
456
457 SRMAccessResponse_t CheckPermission(PEContext_t     *context,
458                                     const OicUuid_t *subjectId,
459                                     const char      *resource,
460                                     const uint16_t  requestedPermission)
461 {
462     SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
463
464     VERIFY_NON_NULL(TAG, context, ERROR);
465     VERIFY_NON_NULL(TAG, subjectId, ERROR);
466     VERIFY_NON_NULL(TAG, resource, ERROR);
467
468     // Each state machine context can only be processing one request at a time.
469     // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
470     // state, return error. Otherwise, change to BUSY state and begin processing request.
471     if (AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
472     {
473         if (AWAITING_REQUEST == context->state)
474         {
475             SetPolicyEngineState(context, BUSY);
476             CopyParamsToContext(context, subjectId, resource, requestedPermission);
477         }
478
479         // Before doing any ACL processing, check if request a) coming
480         // from DevOwner AND b) the device is in Ready for OTM or Reset state
481         // (which in IoTivity is equivalent to isOp == false && owned == false)
482         // AND c) the request is for a SVR resource.
483         // If all 3 conditions are met, grant request.
484         bool isDeviceOwned = true; // default to value that will not grant access
485         if (OC_STACK_OK != GetDoxmIsOwned(&isDeviceOwned)) // if runtime error, don't grant
486         {
487             context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
488         }
489         // If we were able to get the value of doxm->isOwned, proceed with
490         // test for implicit access...
491         else if (IsRequestFromDevOwner(context) // if from DevOwner
492         && (GetPstatIsop() == false) // AND if pstat->isOp == false
493         && (isDeviceOwned == false) // AND if doxm->isOwned == false
494         && (context->resourceType != NOT_A_SVR_RESOURCE)) // AND if SVR type
495         {
496             context->retVal = ACCESS_GRANTED;
497         }
498         // If not granted via DevOwner status,
499         // then check if request is for a SVR and coming from rowner
500         else if (IsRequestFromResourceOwner(context))
501         {
502             context->retVal = ACCESS_GRANTED;
503         }
504         // Else request is a "normal" request that must be tested against ACL
505         else
506         {
507             OicUuid_t saveSubject = {.id={0}};
508             bool isSubEmpty = IsRequestSubjectEmpty(context);
509
510             ProcessAccessRequest(context);
511
512             // If matching ACL not found, and subject != wildcard, try wildcard.
513             if ((false == context->matchingAclFound) && \
514               (false == IsWildCardSubject(&context->subject)))
515             {
516                 //Saving subject for Amacl check
517                 memcpy(&saveSubject, &context->subject,sizeof(OicUuid_t));
518
519                 //Setting context subject to WILDCARD_SUBJECT_ID
520                 //TODO: change ProcessAccessRequest method signature to
521                 //ProcessAccessRequest(context, subject) so that context
522                 //subject is not tempered.
523                 memset(&context->subject, 0, sizeof(context->subject));
524                 memcpy(&context->subject, &WILDCARD_SUBJECT_ID,sizeof(OicUuid_t));
525                 ProcessAccessRequest(context); // TODO anonymous subj can result
526                                                // in confusing err code return.
527             }
528
529             //No local ACE found for the request so checking Amacl resource
530             if (ACCESS_GRANTED != context->retVal)
531             {
532                 //If subject is not empty then restore the original subject
533                 //else keep the subject to WILDCARD_SUBJECT_ID
534                 if(!isSubEmpty)
535                 {
536                     memcpy(&context->subject, &saveSubject, sizeof(OicUuid_t));
537                 }
538
539                 //FoundAmaclForRequest method checks for Amacl and fills up
540                 //context->amsMgrContext->amsDeviceId with the AMS deviceId
541                 //if Amacl was found for the requested resource.
542                 if(FoundAmaclForRequest(context))
543                 {
544                     ProcessAMSRequest(context);
545                 }
546             }
547         }
548     }
549     else
550     {
551         context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
552     }
553
554     // Capture retVal before resetting state for next request.
555     retVal = context->retVal;
556
557    if (!context->amsProcessing)
558     {
559         OIC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
560         SetPolicyEngineState(context, AWAITING_REQUEST);
561     }
562
563 exit:
564     return retVal;
565 }
566
567 OCStackResult InitPolicyEngine(PEContext_t *context)
568 {
569     if(NULL == context)
570     {
571         return OC_STACK_ERROR;
572     }
573
574     context->amsMgrContext = (AmsMgrContext_t *)OICCalloc(1, sizeof(AmsMgrContext_t));
575     if(NULL == context->amsMgrContext)
576     {
577         return OC_STACK_ERROR;
578     }
579
580     SetPolicyEngineState(context, AWAITING_REQUEST);
581     return OC_STACK_OK;
582 }
583
584 void DeInitPolicyEngine(PEContext_t *context)
585 {
586     if(NULL != context)
587     {
588         SetPolicyEngineState(context, STOPPED);
589         OICFree(context->amsMgrContext);
590     }
591     return;
592 }