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