Merge branch 'master' into notification-service
[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     OicUuid_t ownerid;
129
130     if(NULL == context)
131     {
132         return retVal;
133     }
134
135     if(OC_STACK_OK == GetDoxmDevOwnerId(&ownerid))
136     {
137         retVal = UuidCmp(&context->subject, &ownerid);
138     }
139
140     return retVal;
141 }
142
143 // TODO - remove these function placeholders as they are implemented
144 // in the resource entity handler code.
145 // Note that because many SVRs do not have a rowner, in those cases we
146 // just return "OC_STACK_ERROR" which results in a "false" return by
147 // IsRequestFromResourceOwner().
148 // As these SVRs are revised to have a rowner, these functions should be
149 // replaced (see pstatresource.c for example of GetPstatRownerId).
150
151 OCStackResult GetCrlRownerId(OicUuid_t *rowner)
152 {
153     rowner = NULL;
154     return OC_STACK_ERROR;
155 }
156
157 OCStackResult GetSaclRownerId(OicUuid_t *rowner)
158 {
159     rowner = NULL;
160     return OC_STACK_ERROR;
161 }
162
163 OCStackResult GetSvcRownerId(OicUuid_t *rowner)
164 {
165     rowner = NULL;
166     return OC_STACK_ERROR;
167 }
168
169 static GetSvrRownerId_t GetSvrRownerId[OIC_SEC_SVR_TYPE_COUNT] = {
170     GetAclRownerId,
171     GetAmaclRownerId,
172     GetCredRownerId,
173     GetCrlRownerId,
174     GetDoxmRownerId,
175     GetDpairingRownerId,
176     GetPconfRownerId,
177     GetPstatRownerId,
178     GetSaclRownerId,
179     GetSvcRownerId
180 };
181
182 /**
183  * Compare the request's subject to resource.ROwner.
184  *
185  * @return true if context->subjectId equals SVR rowner id, else return false
186  */
187 bool IsRequestFromResourceOwner(PEContext_t *context)
188 {
189     bool retVal = false;
190     OicUuid_t resourceOwner;
191
192     if(NULL == context)
193     {
194         return false;
195     }
196
197     if((OIC_R_ACL_TYPE <= context->resourceType) && \
198         (OIC_SEC_SVR_TYPE_COUNT > context->resourceType))
199     {
200         if(OC_STACK_OK == GetSvrRownerId[(int)context->resourceType](&resourceOwner))
201         {
202             retVal = UuidCmp(&context->subject, &resourceOwner);
203         }
204     }
205
206     if(true == retVal)
207     {
208         OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning true");
209     }
210     else
211     {
212         OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning false");
213     }
214
215     return retVal;
216 }
217
218 INLINE_API bool IsRequestSubjectEmpty(PEContext_t *context)
219 {
220     OicUuid_t emptySubject = {.id={0}};
221
222     if(NULL == context)
223     {
224         return false;
225     }
226
227     return (memcmp(&context->subject, &emptySubject, sizeof(OicUuid_t)) == 0) ?
228             true : false;
229 }
230
231 /**
232  * Bitwise check to see if 'permission' contains 'request'.
233  *
234  * @param permission is the allowed CRUDN permission.
235  * @param request is the CRUDN permission being requested.
236  *
237  * @return true if 'permission' bits include all 'request' bits.
238  */
239 INLINE_API bool IsPermissionAllowingRequest(const uint16_t permission,
240     const uint16_t request)
241 {
242     if (request == (request & permission))
243     {
244         return true;
245     }
246     else
247     {
248         return false;
249     }
250 }
251
252 /**
253  * Compare the passed subject to the wildcard (aka anonymous) subjectId.
254  *
255  * @return true if 'subject' is the wildcard, false if it is not.
256  */
257 INLINE_API bool IsWildCardSubject(OicUuid_t *subject)
258 {
259     if(NULL == subject)
260     {
261         return false;
262     }
263
264     // Because always comparing to string literal, use strcmp()
265     if(0 == memcmp(subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)))
266     {
267         return true;
268     }
269     else
270     {
271         return false;
272     }
273 }
274
275 /**
276  * Copy the subject, resource and permission into the context fields.
277  */
278 static void CopyParamsToContext(PEContext_t     *context,
279                                 const OicUuid_t *subjectId,
280                                 const char      *resource,
281                                 const uint16_t  requestedPermission)
282 {
283     size_t length = 0;
284
285     if (NULL == context || NULL == subjectId || NULL == resource)
286     {
287         return;
288     }
289
290     memcpy(&context->subject, subjectId, sizeof(OicUuid_t));
291
292     // Copy the resource string into context.
293     length = strlen(resource) + 1;
294     if (0 < length)
295     {
296         strncpy(context->resource, resource, length);
297         context->resource[length - 1] = '\0';
298     }
299
300     // Assign the permission field.
301     context->permission = requestedPermission;
302 }
303
304 /**
305  * Check whether 'resource' is getting accessed within the valid time period.
306  *
307  * @param acl is the ACL to check.
308  *
309  * @return true if access is within valid time period or if the period or recurrence is not present.
310  * false if period and recurrence present and the access is not within valid time period.
311  */
312 static bool IsAccessWithinValidTime(const OicSecAce_t *ace)
313 {
314 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
315     //lack of absolute time
316     if (NULL== ace || NULL == ace->validities)
317     {
318         return true;
319     }
320
321     //periods & recurrences rules are paired.
322     if (NULL == ace->validities->recurrences)
323     {
324         return false;
325     }
326
327     OicSecValidity_t* validity =  NULL;
328     LL_FOREACH(ace->validities, validity)
329     {
330         for(size_t i = 0; i < validity->recurrenceLen; i++)
331         {
332             if (IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(validity->period,
333                 validity->recurrences[i]))
334             {
335                 OIC_LOG(INFO, TAG, "Access request is in allowed time period");
336                 return true;
337             }
338         }
339     }
340     OIC_LOG(ERROR, TAG, "Access request is in invalid time period");
341     return false;
342
343 #else
344     return true;
345 #endif
346 }
347
348 /**
349  * Check whether 'resource' is in the passed ACE.
350  *
351  * @param resource is the resource being searched.
352  * @param ace is the ACE to check.
353  *
354  * @return true if 'resource' found, otherwise false.
355  */
356  static bool IsResourceInAce(const char *resource, const OicSecAce_t *ace)
357 {
358     if (NULL== ace || NULL == resource)
359     {
360         return false;
361     }
362
363     OicSecRsrc_t* rsrc = NULL;
364     LL_FOREACH(ace->resources, rsrc)
365     {
366          if (0 == strcmp(resource, rsrc->href) || // TODO null terms?
367              0 == strcmp(WILDCARD_RESOURCE_URI, rsrc->href))
368          {
369              return true;
370          }
371     }
372     return false;
373 }
374
375
376 /**
377  * Find ACLs containing context->subject.
378  * Search each ACL for requested resource.
379  * If resource found, check for context->permission and period validity.
380  * If the ACL is not found locally and AMACL for the resource is found
381  * then sends the request to AMS service for the ACL.
382  * Set context->retVal to result from first ACL found which contains
383  * correct subject AND resource.
384  */
385 static void ProcessAccessRequest(PEContext_t *context)
386 {
387     OIC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
388     if (NULL != context)
389     {
390         const OicSecAce_t *currentAce = NULL;
391         OicSecAce_t *savePtr = NULL;
392
393         // Start out assuming subject not found.
394         context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
395
396         // Loop through all ACLs with a matching Subject searching for the right
397         // ACL for this request.
398         do
399         {
400             OIC_LOG_V(DEBUG, TAG, "%s: getting ACE..." ,__func__);
401             currentAce = GetACLResourceData(&context->subject, &savePtr);
402
403             if (NULL != currentAce)
404             {
405                 // Found the subject, so how about resource?
406                 OIC_LOG_V(DEBUG, TAG, "%s:found ACE matching subject" ,__func__);
407
408                 // Subject was found, so err changes to Rsrc not found for now.
409                 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
410                 OIC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
411                 if (IsResourceInAce(context->resource, currentAce))
412                 {
413                     OIC_LOG_V(INFO, TAG, "%s:found matching resource in ACE" ,__func__);
414                     context->matchingAclFound = true;
415
416                     // Found the resource, so it's down to valid period & permission.
417                     context->retVal = ACCESS_DENIED_INVALID_PERIOD;
418                     if (IsAccessWithinValidTime(currentAce))
419                     {
420                         context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
421                         if (IsPermissionAllowingRequest(currentAce->permission, context->permission))
422                         {
423                             context->retVal = ACCESS_GRANTED;
424                         }
425                     }
426                 }
427             }
428             else
429             {
430                 OIC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
431             }
432         } while ((NULL != currentAce) && (false == context->matchingAclFound));
433
434         if (IsAccessGranted(context->retVal))
435         {
436             OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
437         }
438         else
439         {
440             OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
441         }
442     }
443     else
444     {
445         OIC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
446     }
447 }
448
449 SRMAccessResponse_t CheckPermission(PEContext_t     *context,
450                                     const OicUuid_t *subjectId,
451                                     const char      *resource,
452                                     const uint16_t  requestedPermission)
453 {
454     SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
455
456     VERIFY_NON_NULL(TAG, context, ERROR);
457     VERIFY_NON_NULL(TAG, subjectId, ERROR);
458     VERIFY_NON_NULL(TAG, resource, ERROR);
459
460     // Each state machine context can only be processing one request at a time.
461     // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
462     // state, return error. Otherwise, change to BUSY state and begin processing request.
463     if (AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
464     {
465         if (AWAITING_REQUEST == context->state)
466         {
467             SetPolicyEngineState(context, BUSY);
468             CopyParamsToContext(context, subjectId, resource, requestedPermission);
469         }
470
471         // Before doing any processing, check if request coming
472         // from DevOwner and if so, always GRANT.
473         if (IsRequestFromDevOwner(context))
474         {
475             context->retVal = ACCESS_GRANTED;
476         }
477         // Then check if request is for a SVR and coming from rowner
478         else if (IsRequestFromResourceOwner(context))
479         {
480             context->retVal = ACCESS_GRANTED;
481         }
482         // Else request is a "normal" request that must be tested against ACL
483         else
484         {
485             OicUuid_t saveSubject = {.id={0}};
486             bool isSubEmpty = IsRequestSubjectEmpty(context);
487
488             ProcessAccessRequest(context);
489
490             // If matching ACL not found, and subject != wildcard, try wildcard.
491             if ((false == context->matchingAclFound) && \
492               (false == IsWildCardSubject(&context->subject)))
493             {
494                 //Saving subject for Amacl check
495                 memcpy(&saveSubject, &context->subject,sizeof(OicUuid_t));
496
497                 //Setting context subject to WILDCARD_SUBJECT_ID
498                 //TODO: change ProcessAccessRequest method signature to
499                 //ProcessAccessRequest(context, subject) so that context
500                 //subject is not tempered.
501                 memset(&context->subject, 0, sizeof(context->subject));
502                 memcpy(&context->subject, &WILDCARD_SUBJECT_ID,sizeof(OicUuid_t));
503                 ProcessAccessRequest(context); // TODO anonymous subj can result
504                                                // in confusing err code return.
505             }
506
507             //No local ACE found for the request so checking Amacl resource
508             if (ACCESS_GRANTED != context->retVal)
509             {
510                 //If subject is not empty then restore the original subject
511                 //else keep the subject to WILDCARD_SUBJECT_ID
512                 if(!isSubEmpty)
513                 {
514                     memcpy(&context->subject, &saveSubject, sizeof(OicUuid_t));
515                 }
516
517                 //FoundAmaclForRequest method checks for Amacl and fills up
518                 //context->amsMgrContext->amsDeviceId with the AMS deviceId
519                 //if Amacl was found for the requested resource.
520                 if(FoundAmaclForRequest(context))
521                 {
522                     ProcessAMSRequest(context);
523                 }
524             }
525         }
526     }
527     else
528     {
529         context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
530     }
531
532     // Capture retVal before resetting state for next request.
533     retVal = context->retVal;
534
535    if (!context->amsProcessing)
536     {
537         OIC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
538         SetPolicyEngineState(context, AWAITING_REQUEST);
539     }
540
541 exit:
542     return retVal;
543 }
544
545 OCStackResult InitPolicyEngine(PEContext_t *context)
546 {
547     if(NULL == context)
548     {
549         return OC_STACK_ERROR;
550     }
551
552     context->amsMgrContext = (AmsMgrContext_t *)OICCalloc(1, sizeof(AmsMgrContext_t));
553     if(NULL == context->amsMgrContext)
554     {
555         return OC_STACK_ERROR;
556     }
557
558     SetPolicyEngineState(context, AWAITING_REQUEST);
559     return OC_STACK_OK;
560 }
561
562 void DeInitPolicyEngine(PEContext_t *context)
563 {
564     if(NULL != context)
565     {
566         SetPolicyEngineState(context, STOPPED);
567         OICFree(context->amsMgrContext);
568     }
569     return;
570 }