resource: check for valid pointers
[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     for(size_t i = 0; i < acl->prdRecrLen; i++)
232     {
233         if(IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(acl->periods[i],
234             acl->recurrences[i]))
235         {
236             OC_LOG(INFO, TAG, "Access request is in allowed time period");
237             return true;
238         }
239     }
240     OC_LOG(ERROR, TAG, "Access request is in invalid time period");
241     return false;
242
243 #else
244     return true;
245 #endif
246 }
247
248 /**
249  * Check whether 'resource' is in the passed ACL.
250  * @param   resource    The resource to search for.
251  * @param   acl         The ACL to check.
252  * @return true if 'resource' found, otherwise false.
253  */
254  bool IsResourceInAcl(const char *resource, const OicSecAcl_t *acl)
255 {
256     if(NULL== acl || NULL == resource)
257     {
258         return false;
259     }
260
261      for(size_t n = 0; n < acl->resourcesLen; n++)
262      {
263          if(0 == strcmp(resource, acl->resources[n]) || // TODO null terms?
264                  0 == strcmp(WILDCARD_RESOURCE_URI, acl->resources[n]))
265          {
266              return true;
267          }
268     }
269     return false;
270 }
271
272
273 /**
274  * Find ACLs containing context->subject.
275  * Search each ACL for requested resource.
276  * If resource found, check for context->permission and period validity.
277  * If the ACL is not found locally and AMACL for the resource is found
278  * then sends the request to AMS service for the ACL
279  * Set context->retVal to result from first ACL found which contains
280  * correct subject AND resource.
281  *
282  * @retval void
283  */
284 void ProcessAccessRequest(PEContext_t *context)
285 {
286     OC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
287     if(NULL != context)
288     {
289         const OicSecAcl_t *currentAcl = NULL;
290         OicSecAcl_t *savePtr = NULL;
291
292         // Start out assuming subject not found.
293         context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
294
295         // Loop through all ACLs with a matching Subject searching for the right
296         // ACL for this request.
297         do
298         {
299             OC_LOG_V(DEBUG, TAG, "%s: getting ACL..." ,__func__);
300             currentAcl = GetACLResourceData(&context->subject, &savePtr);
301
302             if(NULL != currentAcl)
303             {
304                 // Found the subject, so how about resource?
305                 OC_LOG_V(DEBUG, TAG, "%s:found ACL matching subject" ,__func__);
306
307                 // Subject was found, so err changes to Rsrc not found for now.
308                 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
309                 OC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
310                 if(IsResourceInAcl(context->resource, currentAcl))
311                 {
312                     OC_LOG_V(INFO, TAG, "%s:found matching resource in ACL" ,__func__);
313                     context->matchingAclFound = true;
314
315                     // Found the resource, so it's down to valid period & permission.
316                     context->retVal = ACCESS_DENIED_INVALID_PERIOD;
317                     if(IsAccessWithinValidTime(currentAcl))
318                     {
319                         context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
320                         if(IsPermissionAllowingRequest(currentAcl->permission, context->permission))
321                         {
322                             context->retVal = ACCESS_GRANTED;
323                         }
324                     }
325                 }
326             }
327             else
328             {
329                 OC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
330             }
331         }
332         while((NULL != currentAcl) && (false == context->matchingAclFound));
333
334         if(IsAccessGranted(context->retVal))
335         {
336             OC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
337         }
338         else
339         {
340             OC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
341         }
342     }
343     else
344     {
345         OC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
346     }
347 }
348
349 /**
350  * Check whether a request should be allowed.
351  * @param   context     Pointer to (Initialized) Policy Engine context to use.
352  * @param   subjectId   Pointer to Id of the requesting entity.
353  * @param   resource    Pointer to URI of Resource being requested.
354  * @param   permission  Requested permission.
355  * @return  ACCESS_GRANTED if request should go through,
356  *          otherwise some flavor of ACCESS_DENIED
357  */
358 SRMAccessResponse_t CheckPermission(
359     PEContext_t     *context,
360     const OicUuid_t *subjectId,
361     const char      *resource,
362     const uint16_t  requestedPermission)
363 {
364     SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
365
366     VERIFY_NON_NULL(TAG, context, ERROR);
367     VERIFY_NON_NULL(TAG, subjectId, ERROR);
368     VERIFY_NON_NULL(TAG, resource, ERROR);
369
370     // Each state machine context can only be processing one request at a time.
371     // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
372     // state, return error. Otherwise, change to BUSY state and begin processing request.
373     if(AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
374     {
375         if(AWAITING_REQUEST == context->state)
376         {
377             SetPolicyEngineState(context, BUSY);
378             CopyParamsToContext(context, subjectId, resource, requestedPermission);
379         }
380
381         // Before doing any processing, check if request coming
382         // from DevOwner and if so, always GRANT.
383         if(IsRequestFromDevOwner(context))
384         {
385             context->retVal = ACCESS_GRANTED;
386         }
387         else
388         {
389             OicUuid_t saveSubject = {.id={}};
390             bool isSubEmpty = IsRequestSubjectEmpty(context);
391
392             ProcessAccessRequest(context);
393
394             // If matching ACL not found, and subject != wildcard, try wildcard.
395             if((false == context->matchingAclFound) && \
396               (false == IsWildCardSubject(&context->subject)))
397             {
398                 //Saving subject for Amacl check
399                 memcpy(&saveSubject, &context->subject,sizeof(OicUuid_t));
400
401                 //Setting context subject to WILDCARD_SUBJECT_ID
402                 //TODO: change ProcessAccessRequest method signature to
403                 //ProcessAccessRequest(context, subject) so that context
404                 //subject is not tempered.
405                 memset(&context->subject, 0, sizeof(context->subject));
406                 memcpy(&context->subject, &WILDCARD_SUBJECT_ID,sizeof(OicUuid_t));
407                 ProcessAccessRequest(context); // TODO anonymous subj can result
408                                                // in confusing err code return.
409             }
410
411             //No local ACE found for the request so checking Amacl resource
412             if(ACCESS_GRANTED != context->retVal)
413             {
414                 //If subject is not empty then restore the original subject
415                 //else keep the subject to WILDCARD_SUBJECT_ID
416                 if(!isSubEmpty)
417                 {
418                     memcpy(&context->subject, &saveSubject, sizeof(OicUuid_t));
419                 }
420
421                 //FoundAmaclForRequest method checks for Amacl and fills up
422                 //context->amsMgrContext->amsDeviceId with the AMS deviceId
423                 //if Amacl was found for the requested resource.
424                 if(FoundAmaclForRequest(context))
425                 {
426                     ProcessAMSRequest(context);
427                 }
428             }
429         }
430     }
431     else
432     {
433         context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
434     }
435
436     // Capture retVal before resetting state for next request.
437     retVal = context->retVal;
438
439     //Change the state of PE to "AWAITING_AMS_RESPONSE", if waiting
440     //for response from AMS service else to "AWAITING_REQUEST"
441     if(ACCESS_WAITING_FOR_AMS == retVal)
442     {
443         OC_LOG(INFO, TAG, "Setting PE State to AWAITING_AMS_RESPONSE");
444         context->state = AWAITING_AMS_RESPONSE;
445     }
446     else if(!context->amsProcessing)
447     {
448         OC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
449         SetPolicyEngineState(context, AWAITING_REQUEST);
450     }
451
452 exit:
453     return retVal;
454 }
455
456 /**
457  * Initialize the Policy Engine. Call this before calling CheckPermission().
458  * @param   context     Pointer to Policy Engine context to initialize.
459  * @return  OC_STACK_OK for Success, otherwise some error value
460  */
461 OCStackResult InitPolicyEngine(PEContext_t *context)
462 {
463     if(NULL== context)
464     {
465         return OC_STACK_ERROR;
466     }
467
468     context->amsMgrContext = (AmsMgrContext_t *)OICMalloc(sizeof(AmsMgrContext_t));
469     SetPolicyEngineState(context, AWAITING_REQUEST);
470
471     return OC_STACK_OK;
472 }
473
474 /**
475  * De-Initialize the Policy Engine.  Call this before exiting to allow Policy
476  * Engine to do cleanup on context.
477  * @param   context     Pointer to Policy Engine context to de-initialize.
478  * @return  none
479  */
480 void DeInitPolicyEngine(PEContext_t *context)
481 {
482     if(NULL != context)
483     {
484         SetPolicyEngineState(context, STOPPED);
485         OICFree(context->amsMgrContext);
486     }
487     return;
488 }