Remove wrapping '(' and ')' in OC_LOG arguments to resolve Tizen Build error.
[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
21 #include "oic_malloc.h"
22 #include "policyengine.h"
23 #include "amsmgr.h"
24 #include "resourcemanager.h"
25 #include "securevirtualresourcetypes.h"
26 #include "srmresourcestrings.h"
27 #include "logger.h"
28 #include "aclresource.h"
29 #include "srmutility.h"
30 #include "doxmresource.h"
31 #include "iotvticalendar.h"
32 #include <string.h>
33
34 #define TAG "SRM-PE"
35
36 /**
37  * Return the uint16_t CRUDN permission corresponding to passed CAMethod_t.
38  */
39 uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method)
40 {
41     uint16_t perm = 0;
42     switch(method)
43     {
44         case CA_GET:
45             perm = (uint16_t)PERMISSION_READ;
46             break;
47         case CA_POST: // For now we treat all PUT & POST as Write
48         case CA_PUT:  // because we don't know if resource exists yet.
49             perm = (uint16_t)PERMISSION_WRITE;
50             break;
51         case CA_DELETE:
52             perm = (uint16_t)PERMISSION_DELETE;
53             break;
54         default: // if not recognized, must assume requesting full control
55             perm = (uint16_t)PERMISSION_FULL_CONTROL;
56             break;
57     }
58     return perm;
59 }
60
61 /**
62  * @brief Compares two OicUuid_t structs.
63  * @return true if the two OicUuid_t structs are equal, else false.
64  */
65 bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
66 {
67     // TODO use VERIFY macros to check for null when they are merged.
68     if(NULL == firstId || NULL == secondId)
69     {
70         return false;
71     }
72     for(int i = 0; i < UUID_LENGTH; i++)
73     {
74         if(firstId->id[i] != secondId->id[i])
75         {
76             return false;
77         }
78     }
79     return true;
80 }
81
82 /**
83  * Set the state and clear other stateful context vars.
84  */
85 void SetPolicyEngineState(PEContext_t *context, const PEState_t state)
86 {
87     // Clear stateful context variables.
88     memset(&context->subject, 0, sizeof(context->subject));
89     memset(&context->resource, 0, sizeof(context->resource));
90     context->permission = 0x0;
91     context->matchingAclFound = false;
92     context->amsProcessing = false;
93     context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
94     memset(context->amsMgrContext, 0, sizeof(AmsMgrContext_t));
95
96     // Set state.
97     context->state = state;
98 }
99
100 /**
101  * @brief Compare the request's subject to DevOwner.
102  *
103  * @return true if context->subjectId == GetDoxmDevOwner(), else false
104  */
105 bool IsRequestFromDevOwner(PEContext_t *context)
106 {
107     bool retVal = false;
108     OicUuid_t owner;
109
110     if(OC_STACK_OK == GetDoxmDevOwnerId(&owner))
111     {
112         retVal = UuidCmp(&context->subject, &owner);
113     }
114
115     return retVal;
116 }
117
118
119 inline static bool IsRequestSubjectEmpty(PEContext_t *context)
120 {
121     OicUuid_t emptySubject = {.id={}};
122     return (memcmp(&context->subject, &emptySubject, sizeof(OicUuid_t)) == 0) ?
123             true : false;
124 }
125
126
127 /**
128  * Bitwise check to see if 'permission' contains 'request'.
129  * @param   permission  The allowed CRUDN permission.
130  * @param   request     The CRUDN permission being requested.
131  * @return true if 'permission' bits include all 'request' bits.
132  */
133 static inline bool IsPermissionAllowingRequest(const uint16_t permission,
134     const uint16_t request)
135 {
136     if(request == (request & permission))
137     {
138         return true;
139     }
140     else
141     {
142         return false;
143     }
144 }
145
146 /**
147  * Compare the passed subject to the wildcard (aka anonymous) subjectId.
148  * @return true if 'subject' is the wildcard, false if it is not.
149  */
150 static inline bool IsWildCardSubject(OicUuid_t *subject)
151 {
152     // Because always comparing to string literal, use strcmp()
153     if(0 == memcmp(subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)))
154     {
155         return true;
156     }
157     else
158     {
159         return false;
160     }
161 }
162
163 /**
164  * Copy the subject, resource and permission into the context fields.
165  */
166 void CopyParamsToContext(
167     PEContext_t     *context,
168     const OicUuid_t *subjectId,
169     const char      *resource,
170     const uint16_t  requestedPermission)
171 {
172     size_t length = 0;
173
174      memcpy(&context->subject, subjectId, sizeof(OicUuid_t));
175
176     // Copy the resource string into context.
177     length = strlen(resource) + 1;
178     if(0 < length)
179     {
180         strncpy(context->resource, resource, length);
181         context->resource[length - 1] = '\0';
182     }
183
184     // Assign the permission field.
185     context->permission = requestedPermission;
186 }
187
188
189 /**
190  * Check whether 'resource' is getting accessed within the valid time period.
191  * @param   acl         The ACL to check.
192  * @return
193  *      true if access is within valid time period or if the period or recurrence is not present.
194  *      false if period and recurrence present and the access is not within valid time period.
195  */
196 static bool IsAccessWithinValidTime(const OicSecAcl_t *acl)
197 {
198 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
199                      //lack of absolute time
200     if(NULL== acl || NULL == acl->periods || 0 == acl->prdRecrLen)
201     {
202         return true;
203     }
204
205     for(size_t i = 0; i < acl->prdRecrLen; i++)
206     {
207         if(IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(acl->periods[i],
208             acl->recurrences[i]))
209         {
210             OC_LOG(INFO, TAG, "Access request is in allowed time period");
211             return true;
212         }
213     }
214     OC_LOG(INFO, TAG, "Access request is in invalid time period");
215     return false;
216
217 #else
218     return true;
219 #endif
220 }
221
222 /**
223  * Check whether 'resource' is in the passed ACL.
224  * @param   resource    The resource to search for.
225  * @param   acl         The ACL to check.
226  * @return true if 'resource' found, otherwise false.
227  */
228  bool IsResourceInAcl(const char *resource, const OicSecAcl_t *acl)
229 {
230      for(size_t n = 0; n < acl->resourcesLen; n++)
231      {
232          if(0 == strcmp(resource, acl->resources[n]) || // TODO null terms?
233                  0 == strcmp(WILDCARD_RESOURCE_URI, acl->resources[n]))
234          {
235              return true;
236          }
237     }
238     return false;
239 }
240
241
242 /**
243  * Find ACLs containing context->subject.
244  * Search each ACL for requested resource.
245  * If resource found, check for context->permission and period validity.
246  * If the ACL is not found locally and AMACL for the resource is found
247  * then sends the request to AMS service for the ACL
248  * Set context->retVal to result from first ACL found which contains
249  * correct subject AND resource.
250  *
251  * @retval void
252  */
253 void ProcessAccessRequest(PEContext_t *context)
254 {
255     OC_LOG(INFO, TAG, "Entering ProcessAccessRequest()");
256     if(NULL != context)
257     {
258         const OicSecAcl_t *currentAcl = NULL;
259         OicSecAcl_t *savePtr = NULL;
260
261         // Start out assuming subject not found.
262         context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
263
264         // Loop through all ACLs with a matching Subject searching for the right
265         // ACL for this request.
266         do
267         {
268             OC_LOG_V(INFO, TAG, "%s: getting ACL..." ,__func__);
269             currentAcl = GetACLResourceData(&context->subject, &savePtr);
270
271             if(NULL != currentAcl)
272             {
273                 // Found the subject, so how about resource?
274                 OC_LOG_V(INFO, TAG, "%s:found ACL matching subject" ,__func__);
275
276                 // Subject was found, so err changes to Rsrc not found for now.
277                 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
278                 OC_LOG_V(INFO, TAG, "%s:Searching for resource..." ,__func__);
279                 if(IsResourceInAcl(context->resource, currentAcl))
280                 {
281                     OC_LOG_V(INFO, TAG, "%s:found matching resource in ACL" ,__func__);
282                     context->matchingAclFound = true;
283
284                     // Found the resource, so it's down to valid period & permission.
285                     context->retVal = ACCESS_DENIED_INVALID_PERIOD;
286                     if(IsAccessWithinValidTime(currentAcl))
287                     {
288                         context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
289                         if(IsPermissionAllowingRequest(currentAcl->permission, context->permission))
290                         {
291                             context->retVal = ACCESS_GRANTED;
292                         }
293                     }
294                 }
295             }
296             else
297             {
298                 OC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
299             }
300         }
301         while((NULL != currentAcl) && (false == context->matchingAclFound));
302
303         if(IsAccessGranted(context->retVal))
304         {
305             OC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
306         }
307         else
308         {
309             OC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
310         }
311     }
312     else
313     {
314         OC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
315     }
316 }
317
318 /**
319  * Check whether a request should be allowed.
320  * @param   context     Pointer to (Initialized) Policy Engine context to use.
321  * @param   subjectId   Pointer to Id of the requesting entity.
322  * @param   resource    Pointer to URI of Resource being requested.
323  * @param   permission  Requested permission.
324  * @return  ACCESS_GRANTED if request should go through,
325  *          otherwise some flavor of ACCESS_DENIED
326  */
327 SRMAccessResponse_t CheckPermission(
328     PEContext_t     *context,
329     const OicUuid_t *subjectId,
330     const char      *resource,
331     const uint16_t  requestedPermission)
332 {
333     SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
334
335     VERIFY_NON_NULL(TAG, context, ERROR);
336     VERIFY_NON_NULL(TAG, subjectId, ERROR);
337     VERIFY_NON_NULL(TAG, resource, ERROR);
338
339     // Each state machine context can only be processing one request at a time.
340     // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
341     // state, return error. Otherwise, change to BUSY state and begin processing request.
342     if(AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
343     {
344         if(AWAITING_REQUEST == context->state)
345         {
346             SetPolicyEngineState(context, BUSY);
347             CopyParamsToContext(context, subjectId, resource, requestedPermission);
348         }
349
350         // Before doing any processing, check if request coming
351         // from DevOwner and if so, always GRANT.
352         if(IsRequestFromDevOwner(context))
353         {
354             context->retVal = ACCESS_GRANTED;
355         }
356         else
357         {
358             OicUuid_t saveSubject = {.id={}};
359             bool isSubEmpty = IsRequestSubjectEmpty(context);
360
361             ProcessAccessRequest(context);
362
363             // If matching ACL not found, and subject != wildcard, try wildcard.
364             if((false == context->matchingAclFound) && \
365               (false == IsWildCardSubject(&context->subject)))
366             {
367                 //Saving subject for Amacl check
368                 memcpy(&saveSubject, &context->subject,sizeof(OicUuid_t));
369
370                 //Setting context subject to WILDCARD_SUBJECT_ID
371                 //TODO: change ProcessAccessRequest method signature to
372                 //ProcessAccessRequest(context, subject) so that context
373                 //subject is not tempered.
374                 memset(&context->subject, 0, sizeof(context->subject));
375                 memcpy(&context->subject, &WILDCARD_SUBJECT_ID,sizeof(OicUuid_t));
376                 ProcessAccessRequest(context); // TODO anonymous subj can result
377                                                // in confusing err code return.
378             }
379
380             //No local ACE found for the request so checking Amacl resource
381             if(ACCESS_GRANTED != context->retVal)
382             {
383                 //If subject is not empty then restore the original subject
384                 //else keep the subject to WILDCARD_SUBJECT_ID
385                 if(!isSubEmpty)
386                 {
387                     memcpy(&context->subject, &saveSubject, sizeof(OicUuid_t));
388                 }
389
390                 //FoundAmaclForRequest method checks for Amacl and fills up
391                 //context->amsMgrContext->amsDeviceId with the AMS deviceId
392                 //if Amacl was found for the requested resource.
393                 if(FoundAmaclForRequest(context))
394                 {
395                     ProcessAMSRequest(context);
396                 }
397             }
398         }
399     }
400     else
401     {
402         context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
403     }
404
405     // Capture retVal before resetting state for next request.
406     retVal = context->retVal;
407
408     //Change the state of PE to "AWAITING_AMS_RESPONSE", if waiting
409     //for response from AMS service else to "AWAITING_REQUEST"
410     if(ACCESS_WAITING_FOR_AMS == retVal)
411     {
412         OC_LOG(INFO, TAG, "Setting PE State to AWAITING_AMS_RESPONSE");
413         context->state = AWAITING_AMS_RESPONSE;
414     }
415     else if(!context->amsProcessing)
416     {
417         OC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
418         SetPolicyEngineState(context, AWAITING_REQUEST);
419     }
420
421 exit:
422     return retVal;
423 }
424
425 /**
426  * Initialize the Policy Engine. Call this before calling CheckPermission().
427  * @param   context     Pointer to Policy Engine context to initialize.
428  * @return  OC_STACK_OK for Success, otherwise some error value
429  */
430 OCStackResult InitPolicyEngine(PEContext_t *context)
431 {
432     context->amsMgrContext = (AmsMgrContext_t *)OICMalloc(sizeof(AmsMgrContext_t));
433     if(NULL != context)
434     {
435         SetPolicyEngineState(context, AWAITING_REQUEST);
436     }
437
438     return OC_STACK_OK;
439 }
440
441 /**
442  * De-Initialize the Policy Engine.  Call this before exiting to allow Policy
443  * Engine to do cleanup on context.
444  * @param   context     Pointer to Policy Engine context to de-initialize.
445  * @return  none
446  */
447 void DeInitPolicyEngine(PEContext_t *context)
448 {
449     if(NULL != context)
450     {
451         SetPolicyEngineState(context, STOPPED);
452     }
453     OICFree(context->amsMgrContext);
454     return;
455 }