[IOT-1595] Change Policy Engine to us ACE Union behavior.
[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 "OIC_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->amsProcessing = false;
103     context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
104
105     if (context->amsMgrContext)
106     {
107         if (context->amsMgrContext->requestInfo)
108         {
109             FreeCARequestInfo(context->amsMgrContext->requestInfo);
110         }
111         OICFree(context->amsMgrContext->endpoint);
112         memset(context->amsMgrContext, 0, sizeof(AmsMgrContext_t));
113     }
114
115     // Set state.
116     context->state = state;
117 }
118
119 /**
120  * Compare the request's subject to DevOwner.
121  *
122  * @return true if context->subjectId == GetDoxmDevOwner(), else false.
123  */
124 static bool IsRequestFromDevOwner(PEContext_t *context)
125 {
126     bool retVal = false;
127
128     if(NULL == context)
129     {
130         return retVal;
131     }
132
133     /*
134     if(OC_STACK_OK == GetDoxmDevOwnerId(&ownerid))
135     {
136         retVal = UuidCmp(&context->subject, &ownerid);
137     }
138     */
139
140     // TODO: Added as workaround for CTT
141     OicSecDoxm_t* doxm = (OicSecDoxm_t*) GetDoxmResourceData();
142     if (doxm)
143     {
144         retVal = UuidCmp(&doxm->owner, &context->subject);
145     }
146     return retVal;
147 }
148
149
150 #ifdef _ENABLE_MULTIPLE_OWNER_
151 /**
152  * Compare the request's subject to SubOwner.
153  *
154  * @return true if context->subjectId exist subowner list, else false.
155  */
156 static bool IsRequestFromSubOwner(PEContext_t *context)
157 {
158     bool retVal = false;
159
160     if(NULL == context)
161     {
162         return retVal;
163     }
164
165     if(IsSubOwner(&context->subject))
166     {
167         retVal = true;
168     }
169
170     if(true == retVal)
171     {
172         OIC_LOG(INFO, TAG, "PE.IsRequestFromSubOwner(): returning true");
173     }
174     else
175     {
176         OIC_LOG(INFO, TAG, "PE.IsRequestFromSubOwner(): returning false");
177     }
178
179     return retVal;
180 }
181
182
183 /**
184  * Verify the SubOwner's request.
185  *
186  * @return true if request is valid, else false.
187  */
188 static bool IsValidRequestFromSubOwner(PEContext_t *context)
189 {
190     bool isValidRequest = false;
191
192     if(NULL == context)
193     {
194         return isValidRequest;
195     }
196
197     switch(context->resourceType)
198     {
199         case OIC_R_DOXM_TYPE:
200             //SubOwner has READ permission only for DOXM
201             if(PERMISSION_READ == context->permission)
202             {
203                 isValidRequest = true;
204             }
205             break;
206         case OIC_R_PSTAT_TYPE:
207             //SubOwner has full permsion for PSTAT
208             isValidRequest = true;
209             break;
210         case OIC_R_CRED_TYPE:
211             //SubOwner can only access the credential which is registered as the eowner.
212             isValidRequest = IsValidCredentialAccessForSubOwner(&context->subject, context->payload, context->payloadSize);
213             break;
214         case OIC_R_ACL_TYPE:
215             //SubOwner can only access the ACL which is registered as the eowner.
216             isValidRequest = IsValidAclAccessForSubOwner(&context->subject, context->payload, context->payloadSize);
217             break;
218         default:
219             //SubOwner has full permission for all resource except the security resource
220             isValidRequest = true;
221             break;
222     }
223
224     if(isValidRequest)
225     {
226         OIC_LOG(INFO, TAG, "PE.IsValidRequestFromSubOwner(): returning true");
227     }
228     else
229     {
230         OIC_LOG(INFO, TAG, "PE.IsValidRequestFromSubOwner(): returning false");
231     }
232
233     return isValidRequest;
234 }
235 #endif //_ENABLE_MULTIPLE_OWNER_
236
237
238 // TODO - remove these function placeholders as they are implemented
239 // in the resource entity handler code.
240 // Note that because many SVRs do not have a rowner, in those cases we
241 // just return "OC_STACK_ERROR" which results in a "false" return by
242 // IsRequestFromResourceOwner().
243 // As these SVRs are revised to have a rowner, these functions should be
244 // replaced (see pstatresource.c for example of GetPstatRownerId).
245
246 OCStackResult GetCrlRownerId(OicUuid_t *rowner)
247 {
248     OC_UNUSED(rowner);
249     rowner = NULL;
250     return OC_STACK_ERROR;
251 }
252
253 OCStackResult GetSaclRownerId(OicUuid_t *rowner)
254 {
255     OC_UNUSED(rowner);
256     rowner = NULL;
257     return OC_STACK_ERROR;
258 }
259
260 OCStackResult GetSvcRownerId(OicUuid_t *rowner)
261 {
262     OC_UNUSED(rowner);
263     rowner = NULL;
264     return OC_STACK_ERROR;
265 }
266
267 static GetSvrRownerId_t GetSvrRownerId[OIC_SEC_SVR_TYPE_COUNT] = {
268     GetAclRownerId,
269     GetAmaclRownerId,
270     GetCredRownerId,
271     GetCrlRownerId,
272     GetDoxmRownerId,
273     GetDpairingRownerId,
274     GetPconfRownerId,
275     GetPstatRownerId,
276     GetSaclRownerId,
277     GetSvcRownerId
278 };
279
280 /**
281  * Compare the request's subject to resource.ROwner.
282  *
283  * @return true if context->subjectId equals SVR rowner id, else return false
284  */
285 bool IsRequestFromResourceOwner(PEContext_t *context)
286 {
287     bool retVal = false;
288     OicUuid_t resourceOwner;
289
290     if(NULL == context)
291     {
292         return false;
293     }
294
295     if((OIC_R_ACL_TYPE <= context->resourceType) && \
296         (OIC_SEC_SVR_TYPE_COUNT > context->resourceType))
297     {
298         if(OC_STACK_OK == GetSvrRownerId[(int)context->resourceType](&resourceOwner))
299         {
300             retVal = UuidCmp(&context->subject, &resourceOwner);
301         }
302     }
303
304     if(true == retVal)
305     {
306         OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning true");
307     }
308     else
309     {
310         OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning false");
311     }
312
313     return retVal;
314 }
315
316 INLINE_API bool IsRequestSubjectEmpty(PEContext_t *context)
317 {
318     OicUuid_t emptySubject = {.id={0}};
319
320     if(NULL == context)
321     {
322         return false;
323     }
324
325     return (memcmp(&context->subject, &emptySubject, sizeof(OicUuid_t)) == 0) ?
326             true : false;
327 }
328
329 /**
330  * Bitwise check to see if 'permission' contains 'request'.
331  *
332  * @param permission is the allowed CRUDN permission.
333  * @param request is the CRUDN permission being requested.
334  *
335  * @return true if 'permission' bits include all 'request' bits.
336  */
337 INLINE_API bool IsPermissionAllowingRequest(const uint16_t permission,
338     const uint16_t request)
339 {
340     if (request == (request & permission))
341     {
342         return true;
343     }
344     else
345     {
346         return false;
347     }
348 }
349
350 /**
351  * Compare the passed subject to the wildcard (aka anonymous) subjectId.
352  *
353  * @return true if 'subject' is the wildcard, false if it is not.
354  */
355 INLINE_API bool IsWildCardSubject(OicUuid_t *subject)
356 {
357     if(NULL == subject)
358     {
359         return false;
360     }
361
362     // Because always comparing to string literal, use strcmp()
363     if(0 == memcmp(subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)))
364     {
365         return true;
366     }
367     else
368     {
369         return false;
370     }
371 }
372
373 /**
374  * Copy the subject, resource and permission into the context fields.
375  */
376 static void CopyParamsToContext(PEContext_t     *context,
377                                 const OicUuid_t *subjectId,
378                                 const char      *resource,
379                                 const uint16_t  requestedPermission)
380 {
381     size_t length = 0;
382
383     if (NULL == context || NULL == subjectId || NULL == resource)
384     {
385         return;
386     }
387
388     memcpy(&context->subject, subjectId, sizeof(OicUuid_t));
389
390     // Copy the resource string into context.
391     length = sizeof(context->resource) - 1;
392     strncpy(context->resource, resource, length);
393     context->resource[length] = '\0';
394
395
396     // Assign the permission field.
397     context->permission = requestedPermission;
398 }
399
400 /**
401  * Check whether 'resource' is getting accessed within the valid time period.
402  *
403  * @param acl is the ACL to check.
404  *
405  * @return true if access is within valid time period or if the period or recurrence is not present.
406  * false if period and recurrence present and the access is not within valid time period.
407  */
408 static bool IsAccessWithinValidTime(const OicSecAce_t *ace)
409 {
410 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
411     //lack of absolute time
412     if (NULL== ace || NULL == ace->validities)
413     {
414         return true;
415     }
416
417     //periods & recurrences rules are paired.
418     if (NULL == ace->validities->recurrences)
419     {
420         return false;
421     }
422
423     OicSecValidity_t* validity =  NULL;
424     LL_FOREACH(ace->validities, validity)
425     {
426         for(size_t i = 0; i < validity->recurrenceLen; i++)
427         {
428             if (IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(validity->period,
429                 validity->recurrences[i]))
430             {
431                 OIC_LOG(INFO, TAG, "Access request is in allowed time period");
432                 return true;
433             }
434         }
435     }
436     OIC_LOG(ERROR, TAG, "Access request is in invalid time period");
437     return false;
438
439 #else
440     return true;
441 #endif
442 }
443
444 /**
445  * Check whether 'resource' is in the passed ACE.
446  *
447  * @param resource is the resource being searched.
448  * @param ace is the ACE to check.
449  *
450  * @return true if 'resource' found, otherwise false.
451  */
452  static bool IsResourceInAce(const char *resource, const OicSecAce_t *ace)
453 {
454     if (NULL== ace || NULL == resource)
455     {
456         return false;
457     }
458
459     OicSecRsrc_t* rsrc = NULL;
460     LL_FOREACH(ace->resources, rsrc)
461     {
462          if (0 == strcmp(resource, rsrc->href) || // TODO null terms?
463              0 == strcmp(WILDCARD_RESOURCE_URI, rsrc->href))
464          {
465              return true;
466          }
467     }
468     return false;
469 }
470
471
472 /**
473  * Find ACLs containing context->subject.
474  * Search each ACL for requested resource.
475  * If resource found, check for context->permission and period validity.
476  * If the ACL is not found locally and AMACL for the resource is found
477  * then sends the request to AMS service for the ACL.
478  * Set context->retVal to result from first ACL found which contains
479  * correct subject AND resource.
480  */
481 static void ProcessAccessRequest(PEContext_t *context)
482 {
483     OIC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
484     if (NULL != context)
485     {
486         const OicSecAce_t *currentAce = NULL;
487         OicSecAce_t *savePtr = NULL;
488
489         // Start out assuming subject not found.
490         context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
491
492         // Loop through all ACLs with a matching Subject searching for the right
493         // ACL for this request.
494         do
495         {
496             OIC_LOG_V(DEBUG, TAG, "%s: getting ACE..." ,__func__);
497             currentAce = GetACLResourceData(&context->subject, &savePtr);
498
499             if (NULL != currentAce)
500             {
501                 // Found the subject, so how about resource?
502                 OIC_LOG_V(DEBUG, TAG, "%s:found ACE matching subject" ,__func__);
503
504                 // Subject was found, so err changes to Rsrc not found for now.
505                 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
506                 OIC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
507                 if (IsResourceInAce(context->resource, currentAce))
508                 {
509                     OIC_LOG_V(INFO, TAG, "%s:found matching resource in ACE" ,__func__);
510
511                     // Found the resource, so it's down to valid period & permission.
512                     context->retVal = ACCESS_DENIED_INVALID_PERIOD;
513                     if (IsAccessWithinValidTime(currentAce))
514                     {
515                         context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
516                         if (IsPermissionAllowingRequest(currentAce->permission, context->permission))
517                         {
518                             context->retVal = ACCESS_GRANTED;
519                         }
520                     }
521                 }
522             }
523             else
524             {
525                 OIC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
526             }
527         } while ((NULL != currentAce) && (ACCESS_GRANTED != context->retVal));
528
529         if (IsAccessGranted(context->retVal))
530         {
531             OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
532         }
533         else
534         {
535             OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
536         }
537     }
538     else
539     {
540         OIC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
541     }
542 }
543
544 SRMAccessResponse_t CheckPermission(PEContext_t     *context,
545                                     const OicUuid_t *subjectId,
546                                     const char      *resource,
547                                     const uint16_t  requestedPermission)
548 {
549     SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
550
551     VERIFY_NON_NULL(TAG, context, ERROR);
552     VERIFY_NON_NULL(TAG, subjectId, ERROR);
553     VERIFY_NON_NULL(TAG, resource, ERROR);
554
555     // Each state machine context can only be processing one request at a time.
556     // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
557     // state, return error. Otherwise, change to BUSY state and begin processing request.
558     if (AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
559     {
560         if (AWAITING_REQUEST == context->state)
561         {
562             SetPolicyEngineState(context, BUSY);
563             CopyParamsToContext(context, subjectId, resource, requestedPermission);
564         }
565
566         // Before doing any ACL processing, check if request a) coming
567         // from DevOwner AND b) the device is in Ready for OTM or Reset state
568         // (which in IoTivity is equivalent to isOp == false && owned == false)
569         // AND c) the request is for a SVR resource.
570         // If all 3 conditions are met, grant request.
571         bool isDeviceOwned = true; // default to value that will not grant access
572         if (OC_STACK_OK != GetDoxmIsOwned(&isDeviceOwned)) // if runtime error, don't grant
573         {
574             context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
575         }
576         // If we were able to get the value of doxm->isOwned, proceed with
577         // test for implicit access...
578         else if (IsRequestFromDevOwner(context) // if from DevOwner
579         && (GetPstatIsop() == false) // AND if pstat->isOp == false
580         && (isDeviceOwned == false) // AND if doxm->isOwned == false
581         && (context->resourceType != NOT_A_SVR_RESOURCE)) // AND if SVR type
582         {
583             context->retVal = ACCESS_GRANTED;
584         }
585 #ifdef _ENABLE_MULTIPLE_OWNER_
586         //Then check if request from SubOwner
587         else if(IsRequestFromSubOwner(context))
588         {
589             if(IsValidRequestFromSubOwner(context))
590             {
591                 context->retVal = ACCESS_GRANTED;
592             }
593         }
594 #endif //_ENABLE_MULTIPLE_OWNER_
595         // If not granted via DevOwner status and not a subowner,
596         // then check if request is for a SVR and coming from rowner
597         else if (IsRequestFromResourceOwner(context))
598         {
599             context->retVal = ACCESS_GRANTED;
600         }
601         // Else request is a "normal" request that must be tested against ACL
602         else
603         {
604             OicUuid_t saveSubject = {.id={0}};
605             bool isSubEmpty = IsRequestSubjectEmpty(context);
606
607             ProcessAccessRequest(context);
608
609             // If access not already granted, and requested subject != wildcard,
610             // try looking for a wildcard ACE that grants access.
611             if ((ACCESS_GRANTED != context->retVal) && \
612               (false == IsWildCardSubject(&context->subject)))
613             {
614                 //Saving subject for Amacl check
615                 memcpy(&saveSubject, &context->subject,sizeof(OicUuid_t));
616
617                 //Setting context subject to WILDCARD_SUBJECT_ID
618                 //TODO: change ProcessAccessRequest method signature to
619                 //ProcessAccessRequest(context, subject) so that context
620                 //subject is not tempered.
621                 memset(&context->subject, 0, sizeof(context->subject));
622                 memcpy(&context->subject, &WILDCARD_SUBJECT_ID,sizeof(OicUuid_t));
623                 ProcessAccessRequest(context); // TODO anonymous subj can result
624                                                // in confusing err code return.
625             }
626
627             //No local ACE found for the request so checking Amacl resource
628             if (ACCESS_GRANTED != context->retVal)
629             {
630                 //If subject is not empty then restore the original subject
631                 //else keep the subject to WILDCARD_SUBJECT_ID
632                 if(!isSubEmpty)
633                 {
634                     memcpy(&context->subject, &saveSubject, sizeof(OicUuid_t));
635                 }
636
637                 //FoundAmaclForRequest method checks for Amacl and fills up
638                 //context->amsMgrContext->amsDeviceId with the AMS deviceId
639                 //if Amacl was found for the requested resource.
640                 if(FoundAmaclForRequest(context))
641                 {
642                     ProcessAMSRequest(context);
643                 }
644             }
645         }
646     }
647     else
648     {
649         context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
650     }
651
652     // Capture retVal before resetting state for next request.
653     retVal = context->retVal;
654
655    if (!context->amsProcessing)
656     {
657         OIC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
658         SetPolicyEngineState(context, AWAITING_REQUEST);
659     }
660
661 exit:
662     return retVal;
663 }
664
665 OCStackResult InitPolicyEngine(PEContext_t *context)
666 {
667     if(NULL == context)
668     {
669         return OC_STACK_ERROR;
670     }
671
672     context->amsMgrContext = (AmsMgrContext_t *)OICCalloc(1, sizeof(AmsMgrContext_t));
673     if(NULL == context->amsMgrContext)
674     {
675         return OC_STACK_ERROR;
676     }
677
678     SetPolicyEngineState(context, AWAITING_REQUEST);
679     return OC_STACK_OK;
680 }
681
682 void DeInitPolicyEngine(PEContext_t *context)
683 {
684     if(NULL != context)
685     {
686         SetPolicyEngineState(context, STOPPED);
687         OICFree(context->amsMgrContext);
688     }
689     return;
690 }