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