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