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