Imported Upstream version 1.0.0
[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     if(NULL == context)
88     {
89         return;
90     }
91
92     // Clear stateful context variables.
93     memset(&context->subject, 0, sizeof(context->subject));
94     memset(&context->resource, 0, sizeof(context->resource));
95     context->permission = 0x0;
96     context->matchingAclFound = false;
97     context->amsProcessing = false;
98     context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
99     memset(context->amsMgrContext, 0, sizeof(AmsMgrContext_t));
100
101     // Set state.
102     context->state = state;
103 }
104
105 /**
106  * @brief Compare the request's subject to DevOwner.
107  *
108  * @return true if context->subjectId == GetDoxmDevOwner(), else false
109  */
110 bool IsRequestFromDevOwner(PEContext_t *context)
111 {
112     bool retVal = false;
113     OicUuid_t owner;
114
115     if(NULL == context)
116     {
117         return OC_STACK_ERROR;
118     }
119
120     if(OC_STACK_OK == GetDoxmDevOwnerId(&owner))
121     {
122         retVal = UuidCmp(&context->subject, &owner);
123     }
124
125     return retVal;
126 }
127
128
129 inline static bool IsRequestSubjectEmpty(PEContext_t *context)
130 {
131     OicUuid_t emptySubject = {.id={}};
132
133     if(NULL == context)
134     {
135         return false;
136     }
137
138     return (memcmp(&context->subject, &emptySubject, sizeof(OicUuid_t)) == 0) ?
139             true : false;
140 }
141
142
143 /**
144  * Bitwise check to see if 'permission' contains 'request'.
145  * @param   permission  The allowed CRUDN permission.
146  * @param   request     The CRUDN permission being requested.
147  * @return true if 'permission' bits include all 'request' bits.
148  */
149 static inline bool IsPermissionAllowingRequest(const uint16_t permission,
150     const uint16_t request)
151 {
152     if(request == (request & permission))
153     {
154         return true;
155     }
156     else
157     {
158         return false;
159     }
160 }
161
162 /**
163  * Compare the passed subject to the wildcard (aka anonymous) subjectId.
164  * @return true if 'subject' is the wildcard, false if it is not.
165  */
166 static inline bool IsWildCardSubject(OicUuid_t *subject)
167 {
168     if(NULL == subject)
169     {
170         return false;
171     }
172
173     // Because always comparing to string literal, use strcmp()
174     if(0 == memcmp(subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)))
175     {
176         return true;
177     }
178     else
179     {
180         return false;
181     }
182 }
183
184 /**
185  * Copy the subject, resource and permission into the context fields.
186  */
187 void CopyParamsToContext(
188     PEContext_t     *context,
189     const OicUuid_t *subjectId,
190     const char      *resource,
191     const uint16_t  requestedPermission)
192 {
193     size_t length = 0;
194
195     if(NULL == context || NULL == subjectId || NULL == resource)
196     {
197         return;
198     }
199
200     memcpy(&context->subject, subjectId, sizeof(OicUuid_t));
201
202     // Copy the resource string into context.
203     length = strlen(resource) + 1;
204     if(0 < length)
205     {
206         strncpy(context->resource, resource, length);
207         context->resource[length - 1] = '\0';
208     }
209
210     // Assign the permission field.
211     context->permission = requestedPermission;
212 }
213
214
215 /**
216  * Check whether 'resource' is getting accessed within the valid time period.
217  * @param   acl         The ACL to check.
218  * @return
219  *      true if access is within valid time period or if the period or recurrence is not present.
220  *      false if period and recurrence present and the access is not within valid time period.
221  */
222 static bool IsAccessWithinValidTime(const OicSecAcl_t *acl)
223 {
224 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
225                      //lack of absolute time
226     if(NULL== acl || NULL == acl->periods || 0 == acl->prdRecrLen)
227     {
228         return true;
229     }
230
231     //periods & recurrences rules are paired.
232     if(NULL == acl->recurrences)
233     {
234         return false;
235     }
236
237     for(size_t i = 0; i < acl->prdRecrLen; i++)
238     {
239         if(IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(acl->periods[i],
240             acl->recurrences[i]))
241         {
242             OC_LOG(INFO, TAG, "Access request is in allowed time period");
243             return true;
244         }
245     }
246     OC_LOG(ERROR, TAG, "Access request is in invalid time period");
247     return false;
248
249 #else
250     return true;
251 #endif
252 }
253
254 /**
255  * Check whether 'resource' is in the passed ACL.
256  * @param   resource    The resource to search for.
257  * @param   acl         The ACL to check.
258  * @return true if 'resource' found, otherwise false.
259  */
260  bool IsResourceInAcl(const char *resource, const OicSecAcl_t *acl)
261 {
262     if(NULL== acl || NULL == resource)
263     {
264         return false;
265     }
266
267      for(size_t n = 0; n < acl->resourcesLen; n++)
268      {
269          if(0 == strcmp(resource, acl->resources[n]) || // TODO null terms?
270                  0 == strcmp(WILDCARD_RESOURCE_URI, acl->resources[n]))
271          {
272              return true;
273          }
274     }
275     return false;
276 }
277
278
279 /**
280  * Find ACLs containing context->subject.
281  * Search each ACL for requested resource.
282  * If resource found, check for context->permission and period validity.
283  * If the ACL is not found locally and AMACL for the resource is found
284  * then sends the request to AMS service for the ACL
285  * Set context->retVal to result from first ACL found which contains
286  * correct subject AND resource.
287  *
288  * @retval void
289  */
290 void ProcessAccessRequest(PEContext_t *context)
291 {
292     OC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
293     if(NULL != context)
294     {
295         const OicSecAcl_t *currentAcl = NULL;
296         OicSecAcl_t *savePtr = NULL;
297
298         // Start out assuming subject not found.
299         context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
300
301         // Loop through all ACLs with a matching Subject searching for the right
302         // ACL for this request.
303         do
304         {
305             OC_LOG_V(DEBUG, TAG, "%s: getting ACL..." ,__func__);
306             currentAcl = GetACLResourceData(&context->subject, &savePtr);
307
308             if(NULL != currentAcl)
309             {
310                 // Found the subject, so how about resource?
311                 OC_LOG_V(DEBUG, TAG, "%s:found ACL matching subject" ,__func__);
312
313                 // Subject was found, so err changes to Rsrc not found for now.
314                 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
315                 OC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
316                 if(IsResourceInAcl(context->resource, currentAcl))
317                 {
318                     OC_LOG_V(INFO, TAG, "%s:found matching resource in ACL" ,__func__);
319                     context->matchingAclFound = true;
320
321                     // Found the resource, so it's down to valid period & permission.
322                     context->retVal = ACCESS_DENIED_INVALID_PERIOD;
323                     if(IsAccessWithinValidTime(currentAcl))
324                     {
325                         context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
326                         if(IsPermissionAllowingRequest(currentAcl->permission, context->permission))
327                         {
328                             context->retVal = ACCESS_GRANTED;
329                         }
330                     }
331                 }
332             }
333             else
334             {
335                 OC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
336             }
337         }
338         while((NULL != currentAcl) && (false == context->matchingAclFound));
339
340         if(IsAccessGranted(context->retVal))
341         {
342             OC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
343         }
344         else
345         {
346             OC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
347         }
348     }
349     else
350     {
351         OC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
352     }
353 }
354
355 /**
356  * Check whether a request should be allowed.
357  * @param   context     Pointer to (Initialized) Policy Engine context to use.
358  * @param   subjectId   Pointer to Id of the requesting entity.
359  * @param   resource    Pointer to URI of Resource being requested.
360  * @param   permission  Requested permission.
361  * @return  ACCESS_GRANTED if request should go through,
362  *          otherwise some flavor of ACCESS_DENIED
363  */
364 SRMAccessResponse_t CheckPermission(
365     PEContext_t     *context,
366     const OicUuid_t *subjectId,
367     const char      *resource,
368     const uint16_t  requestedPermission)
369 {
370     SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
371
372     VERIFY_NON_NULL(TAG, context, ERROR);
373     VERIFY_NON_NULL(TAG, subjectId, ERROR);
374     VERIFY_NON_NULL(TAG, resource, ERROR);
375
376     // Each state machine context can only be processing one request at a time.
377     // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
378     // state, return error. Otherwise, change to BUSY state and begin processing request.
379     if(AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
380     {
381         if(AWAITING_REQUEST == context->state)
382         {
383             SetPolicyEngineState(context, BUSY);
384             CopyParamsToContext(context, subjectId, resource, requestedPermission);
385         }
386
387         // Before doing any processing, check if request coming
388         // from DevOwner and if so, always GRANT.
389         if(IsRequestFromDevOwner(context))
390         {
391             context->retVal = ACCESS_GRANTED;
392         }
393         else
394         {
395             OicUuid_t saveSubject = {.id={}};
396             bool isSubEmpty = IsRequestSubjectEmpty(context);
397
398             ProcessAccessRequest(context);
399
400             // If matching ACL not found, and subject != wildcard, try wildcard.
401             if((false == context->matchingAclFound) && \
402               (false == IsWildCardSubject(&context->subject)))
403             {
404                 //Saving subject for Amacl check
405                 memcpy(&saveSubject, &context->subject,sizeof(OicUuid_t));
406
407                 //Setting context subject to WILDCARD_SUBJECT_ID
408                 //TODO: change ProcessAccessRequest method signature to
409                 //ProcessAccessRequest(context, subject) so that context
410                 //subject is not tempered.
411                 memset(&context->subject, 0, sizeof(context->subject));
412                 memcpy(&context->subject, &WILDCARD_SUBJECT_ID,sizeof(OicUuid_t));
413                 ProcessAccessRequest(context); // TODO anonymous subj can result
414                                                // in confusing err code return.
415             }
416
417             //No local ACE found for the request so checking Amacl resource
418             if(ACCESS_GRANTED != context->retVal)
419             {
420                 //If subject is not empty then restore the original subject
421                 //else keep the subject to WILDCARD_SUBJECT_ID
422                 if(!isSubEmpty)
423                 {
424                     memcpy(&context->subject, &saveSubject, sizeof(OicUuid_t));
425                 }
426
427                 //FoundAmaclForRequest method checks for Amacl and fills up
428                 //context->amsMgrContext->amsDeviceId with the AMS deviceId
429                 //if Amacl was found for the requested resource.
430                 if(FoundAmaclForRequest(context))
431                 {
432                     ProcessAMSRequest(context);
433                 }
434             }
435         }
436     }
437     else
438     {
439         context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
440     }
441
442     // Capture retVal before resetting state for next request.
443     retVal = context->retVal;
444
445     //Change the state of PE to "AWAITING_AMS_RESPONSE", if waiting
446     //for response from AMS service else to "AWAITING_REQUEST"
447     if(ACCESS_WAITING_FOR_AMS == retVal)
448     {
449         OC_LOG(INFO, TAG, "Setting PE State to AWAITING_AMS_RESPONSE");
450         context->state = AWAITING_AMS_RESPONSE;
451     }
452     else if(!context->amsProcessing)
453     {
454         OC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
455         SetPolicyEngineState(context, AWAITING_REQUEST);
456     }
457
458 exit:
459     return retVal;
460 }
461
462 /**
463  * Initialize the Policy Engine. Call this before calling CheckPermission().
464  * @param   context     Pointer to Policy Engine context to initialize.
465  * @return  OC_STACK_OK for Success, otherwise some error value
466  */
467 OCStackResult InitPolicyEngine(PEContext_t *context)
468 {
469     if(NULL== context)
470     {
471         return OC_STACK_ERROR;
472     }
473
474     context->amsMgrContext = (AmsMgrContext_t *)OICMalloc(sizeof(AmsMgrContext_t));
475     SetPolicyEngineState(context, AWAITING_REQUEST);
476
477     return OC_STACK_OK;
478 }
479
480 /**
481  * De-Initialize the Policy Engine.  Call this before exiting to allow Policy
482  * Engine to do cleanup on context.
483  * @param   context     Pointer to Policy Engine context to de-initialize.
484  * @return  none
485  */
486 void DeInitPolicyEngine(PEContext_t *context)
487 {
488     if(NULL != context)
489     {
490         SetPolicyEngineState(context, STOPPED);
491         OICFree(context->amsMgrContext);
492     }
493     return;
494 }