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