Clean compilar warnings
[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 #include <string.h>
21
22 #include "utlist.h"
23 #include "oic_malloc.h"
24 #include "policyengine.h"
25 #include "amsmgr.h"
26 #include "resourcemanager.h"
27 #include "securevirtualresourcetypes.h"
28 #include "srmresourcestrings.h"
29 #include "logger.h"
30 #include "aclresource.h"
31 #include "srmutility.h"
32 #include "doxmresource.h"
33 #include "iotvticalendar.h"
34 #include "pstatresource.h"
35 #include "dpairingresource.h"
36 #include "pconfresource.h"
37 #include "amaclresource.h"
38 #include "credresource.h"
39
40 #define TAG "SRM-PE"
41
42 uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method)
43 {
44     uint16_t perm = 0;
45     switch (method)
46     {
47         case CA_GET:
48             perm = (uint16_t)PERMISSION_READ;
49             break;
50         case CA_POST: // For now we treat all PUT & POST as Write
51         case CA_PUT:  // because we don't know if resource exists yet.
52             perm = (uint16_t)PERMISSION_WRITE;
53             break;
54         case CA_DELETE:
55             perm = (uint16_t)PERMISSION_DELETE;
56             break;
57         default: // if not recognized, must assume requesting full control
58             perm = (uint16_t)PERMISSION_FULL_CONTROL;
59             break;
60     }
61     return perm;
62 }
63
64 /**
65  * Compares two OicUuid_t structs.
66  *
67  * @return true if the two OicUuid_t structs are equal, else false.
68  */
69 static bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
70 {
71     // TODO use VERIFY macros to check for null when they are merged.
72     if(NULL == firstId || NULL == secondId)
73     {
74         return false;
75     }
76     // Check empty uuid string
77     if('\0' == firstId->id[0] || '\0' == secondId->id[0])
78     {
79         return false;
80     }
81     for(int i = 0; i < UUID_LENGTH; i++)
82     {
83         if(firstId->id[i] != secondId->id[i])
84         {
85             return false;
86         }
87     }
88     return true;
89 }
90
91 void SetPolicyEngineState(PEContext_t *context, const PEState_t state)
92 {
93     if (NULL == context)
94     {
95         return;
96     }
97
98     // Clear stateful context variables.
99     memset(&context->subject, 0, sizeof(context->subject));
100     memset(&context->resource, 0, sizeof(context->resource));
101     context->permission = 0x0;
102     context->matchingAclFound = false;
103     context->amsProcessing = false;
104     context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
105
106     if (context->amsMgrContext)
107     {
108         if (context->amsMgrContext->requestInfo)
109         {
110             FreeCARequestInfo(context->amsMgrContext->requestInfo);
111         }
112         OICFree(context->amsMgrContext->endpoint);
113         memset(context->amsMgrContext, 0, sizeof(AmsMgrContext_t));
114     }
115
116     // Set state.
117     context->state = state;
118 }
119
120 /**
121  * Compare the request's subject to DevOwner.
122  *
123  * @return true if context->subjectId == GetDoxmDevOwner(), else false.
124  */
125 static bool IsRequestFromDevOwner(PEContext_t *context)
126 {
127     bool retVal = false;
128
129     if(NULL == context)
130     {
131         return retVal;
132     }
133
134     /*
135     if(OC_STACK_OK == GetDoxmDevOwnerId(&ownerid))
136     {
137         retVal = UuidCmp(&context->subject, &ownerid);
138     }
139     */
140
141     // TODO: Added as workaround for CTT
142     OicSecDoxm_t* doxm = (OicSecDoxm_t*) GetDoxmResourceData();
143     if (doxm)
144     {
145         retVal = UuidCmp(&doxm->owner, &context->subject);
146     }
147     return retVal;
148 }
149
150 // TODO - remove these function placeholders as they are implemented
151 // in the resource entity handler code.
152 // Note that because many SVRs do not have a rowner, in those cases we
153 // just return "OC_STACK_ERROR" which results in a "false" return by
154 // IsRequestFromResourceOwner().
155 // As these SVRs are revised to have a rowner, these functions should be
156 // replaced (see pstatresource.c for example of GetPstatRownerId).
157
158 OCStackResult GetCrlRownerId(OicUuid_t *rowner)
159 {
160     OC_UNUSED(rowner);
161     rowner = NULL;
162     return OC_STACK_ERROR;
163 }
164
165 OCStackResult GetSaclRownerId(OicUuid_t *rowner)
166 {
167     OC_UNUSED(rowner);
168     rowner = NULL;
169     return OC_STACK_ERROR;
170 }
171
172 OCStackResult GetSvcRownerId(OicUuid_t *rowner)
173 {
174     OC_UNUSED(rowner);
175     rowner = NULL;
176     return OC_STACK_ERROR;
177 }
178
179 static GetSvrRownerId_t GetSvrRownerId[OIC_SEC_SVR_TYPE_COUNT] = {
180     GetAclRownerId,
181     GetAmaclRownerId,
182     GetCredRownerId,
183     GetCrlRownerId,
184     GetDoxmRownerId,
185     GetDpairingRownerId,
186     GetPconfRownerId,
187     GetPstatRownerId,
188     GetSaclRownerId,
189     GetSvcRownerId
190 };
191
192 /**
193  * Compare the request's subject to resource.ROwner.
194  *
195  * @return true if context->subjectId equals SVR rowner id, else return false
196  */
197 bool IsRequestFromResourceOwner(PEContext_t *context)
198 {
199     bool retVal = false;
200     OicUuid_t resourceOwner;
201
202     if(NULL == context)
203     {
204         return false;
205     }
206
207     if((OIC_R_ACL_TYPE <= context->resourceType) && \
208         (OIC_SEC_SVR_TYPE_COUNT > context->resourceType))
209     {
210         if(OC_STACK_OK == GetSvrRownerId[(int)context->resourceType](&resourceOwner))
211         {
212             retVal = UuidCmp(&context->subject, &resourceOwner);
213         }
214     }
215
216     if(true == retVal)
217     {
218         OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning true");
219     }
220     else
221     {
222         OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning false");
223     }
224
225     return retVal;
226 }
227
228 INLINE_API bool IsRequestSubjectEmpty(PEContext_t *context)
229 {
230     OicUuid_t emptySubject = {.id={0}};
231
232     if(NULL == context)
233     {
234         return false;
235     }
236
237     return (memcmp(&context->subject, &emptySubject, sizeof(OicUuid_t)) == 0) ?
238             true : false;
239 }
240
241 /**
242  * Bitwise check to see if 'permission' contains 'request'.
243  *
244  * @param permission is the allowed CRUDN permission.
245  * @param request is the CRUDN permission being requested.
246  *
247  * @return true if 'permission' bits include all 'request' bits.
248  */
249 INLINE_API bool IsPermissionAllowingRequest(const uint16_t permission,
250     const uint16_t request)
251 {
252     if (request == (request & permission))
253     {
254         return true;
255     }
256     else
257     {
258         return false;
259     }
260 }
261
262 /**
263  * Compare the passed subject to the wildcard (aka anonymous) subjectId.
264  *
265  * @return true if 'subject' is the wildcard, false if it is not.
266  */
267 INLINE_API bool IsWildCardSubject(OicUuid_t *subject)
268 {
269     if(NULL == subject)
270     {
271         return false;
272     }
273
274     // Because always comparing to string literal, use strcmp()
275     if(0 == memcmp(subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)))
276     {
277         return true;
278     }
279     else
280     {
281         return false;
282     }
283 }
284
285 /**
286  * Copy the subject, resource and permission into the context fields.
287  */
288 static void CopyParamsToContext(PEContext_t     *context,
289                                 const OicUuid_t *subjectId,
290                                 const char      *resource,
291                                 const uint16_t  requestedPermission)
292 {
293     size_t length = 0;
294
295     if (NULL == context || NULL == subjectId || NULL == resource)
296     {
297         return;
298     }
299
300     memcpy(&context->subject, subjectId, sizeof(OicUuid_t));
301
302     // Copy the resource string into context.
303     length = strlen(resource) + 1;
304     if (0 < length)
305     {
306         strncpy(context->resource, resource, length);
307         context->resource[length - 1] = '\0';
308     }
309
310     // Assign the permission field.
311     context->permission = requestedPermission;
312 }
313
314 /**
315  * Check whether 'resource' is getting accessed within the valid time period.
316  *
317  * @param acl is the ACL to check.
318  *
319  * @return true if access is within valid time period or if the period or recurrence is not present.
320  * false if period and recurrence present and the access is not within valid time period.
321  */
322 static bool IsAccessWithinValidTime(const OicSecAce_t *ace)
323 {
324 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
325     //lack of absolute time
326     if (NULL== ace || NULL == ace->validities)
327     {
328         return true;
329     }
330
331     //periods & recurrences rules are paired.
332     if (NULL == ace->validities->recurrences)
333     {
334         return false;
335     }
336
337     OicSecValidity_t* validity =  NULL;
338     LL_FOREACH(ace->validities, validity)
339     {
340         for(size_t i = 0; i < validity->recurrenceLen; i++)
341         {
342             if (IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(validity->period,
343                 validity->recurrences[i]))
344             {
345                 OIC_LOG(INFO, TAG, "Access request is in allowed time period");
346                 return true;
347             }
348         }
349     }
350     OIC_LOG(ERROR, TAG, "Access request is in invalid time period");
351     return false;
352
353 #else
354     return true;
355 #endif
356 }
357
358 /**
359  * Check whether 'resource' is in the passed ACE.
360  *
361  * @param resource is the resource being searched.
362  * @param ace is the ACE to check.
363  *
364  * @return true if 'resource' found, otherwise false.
365  */
366  static bool IsResourceInAce(const char *resource, const OicSecAce_t *ace)
367 {
368     if (NULL== ace || NULL == resource)
369     {
370         return false;
371     }
372
373     OicSecRsrc_t* rsrc = NULL;
374     LL_FOREACH(ace->resources, rsrc)
375     {
376          if (0 == strcmp(resource, rsrc->href) || // TODO null terms?
377              0 == strcmp(WILDCARD_RESOURCE_URI, rsrc->href))
378          {
379              return true;
380          }
381     }
382     return false;
383 }
384
385
386 /**
387  * Find ACLs containing context->subject.
388  * Search each ACL for requested resource.
389  * If resource found, check for context->permission and period validity.
390  * If the ACL is not found locally and AMACL for the resource is found
391  * then sends the request to AMS service for the ACL.
392  * Set context->retVal to result from first ACL found which contains
393  * correct subject AND resource.
394  */
395 static void ProcessAccessRequest(PEContext_t *context)
396 {
397     OIC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
398     if (NULL != context)
399     {
400         const OicSecAce_t *currentAce = NULL;
401         OicSecAce_t *savePtr = NULL;
402
403         // Start out assuming subject not found.
404         context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
405
406         // Loop through all ACLs with a matching Subject searching for the right
407         // ACL for this request.
408         do
409         {
410             OIC_LOG_V(DEBUG, TAG, "%s: getting ACE..." ,__func__);
411             currentAce = GetACLResourceData(&context->subject, &savePtr);
412
413             if (NULL != currentAce)
414             {
415                 // Found the subject, so how about resource?
416                 OIC_LOG_V(DEBUG, TAG, "%s:found ACE matching subject" ,__func__);
417
418                 // Subject was found, so err changes to Rsrc not found for now.
419                 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
420                 OIC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
421                 if (IsResourceInAce(context->resource, currentAce))
422                 {
423                     OIC_LOG_V(INFO, TAG, "%s:found matching resource in ACE" ,__func__);
424                     context->matchingAclFound = true;
425
426                     // Found the resource, so it's down to valid period & permission.
427                     context->retVal = ACCESS_DENIED_INVALID_PERIOD;
428                     if (IsAccessWithinValidTime(currentAce))
429                     {
430                         context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
431                         if (IsPermissionAllowingRequest(currentAce->permission, context->permission))
432                         {
433                             context->retVal = ACCESS_GRANTED;
434                         }
435                     }
436                 }
437             }
438             else
439             {
440                 OIC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
441             }
442         } while ((NULL != currentAce) && (false == context->matchingAclFound));
443
444         if (IsAccessGranted(context->retVal))
445         {
446             OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
447         }
448         else
449         {
450             OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
451         }
452     }
453     else
454     {
455         OIC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
456     }
457 }
458
459 SRMAccessResponse_t CheckPermission(PEContext_t     *context,
460                                     const OicUuid_t *subjectId,
461                                     const char      *resource,
462                                     const uint16_t  requestedPermission)
463 {
464     SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
465
466     VERIFY_NON_NULL(TAG, context, ERROR);
467     VERIFY_NON_NULL(TAG, subjectId, ERROR);
468     VERIFY_NON_NULL(TAG, resource, ERROR);
469
470     // Each state machine context can only be processing one request at a time.
471     // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
472     // state, return error. Otherwise, change to BUSY state and begin processing request.
473     if (AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
474     {
475         if (AWAITING_REQUEST == context->state)
476         {
477             SetPolicyEngineState(context, BUSY);
478             CopyParamsToContext(context, subjectId, resource, requestedPermission);
479         }
480
481         // Before doing any processing, check if request coming
482         // from DevOwner and if so, always GRANT.
483         if (IsRequestFromDevOwner(context))
484         {
485             context->retVal = ACCESS_GRANTED;
486         }
487         // Then check if request is for a SVR and coming from rowner
488         else if (IsRequestFromResourceOwner(context))
489         {
490             context->retVal = ACCESS_GRANTED;
491         }
492         // Else request is a "normal" request that must be tested against ACL
493         else
494         {
495             OicUuid_t saveSubject = {.id={0}};
496             bool isSubEmpty = IsRequestSubjectEmpty(context);
497
498             ProcessAccessRequest(context);
499
500             // If matching ACL not found, and subject != wildcard, try wildcard.
501             if ((false == context->matchingAclFound) && \
502               (false == IsWildCardSubject(&context->subject)))
503             {
504                 //Saving subject for Amacl check
505                 memcpy(&saveSubject, &context->subject,sizeof(OicUuid_t));
506
507                 //Setting context subject to WILDCARD_SUBJECT_ID
508                 //TODO: change ProcessAccessRequest method signature to
509                 //ProcessAccessRequest(context, subject) so that context
510                 //subject is not tempered.
511                 memset(&context->subject, 0, sizeof(context->subject));
512                 memcpy(&context->subject, &WILDCARD_SUBJECT_ID,sizeof(OicUuid_t));
513                 ProcessAccessRequest(context); // TODO anonymous subj can result
514                                                // in confusing err code return.
515             }
516
517             //No local ACE found for the request so checking Amacl resource
518             if (ACCESS_GRANTED != context->retVal)
519             {
520                 //If subject is not empty then restore the original subject
521                 //else keep the subject to WILDCARD_SUBJECT_ID
522                 if(!isSubEmpty)
523                 {
524                     memcpy(&context->subject, &saveSubject, sizeof(OicUuid_t));
525                 }
526
527                 //FoundAmaclForRequest method checks for Amacl and fills up
528                 //context->amsMgrContext->amsDeviceId with the AMS deviceId
529                 //if Amacl was found for the requested resource.
530                 if(FoundAmaclForRequest(context))
531                 {
532                     ProcessAMSRequest(context);
533                 }
534             }
535         }
536     }
537     else
538     {
539         context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
540     }
541
542     // Capture retVal before resetting state for next request.
543     retVal = context->retVal;
544
545    if (!context->amsProcessing)
546     {
547         OIC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
548         SetPolicyEngineState(context, AWAITING_REQUEST);
549     }
550
551 exit:
552     return retVal;
553 }
554
555 OCStackResult InitPolicyEngine(PEContext_t *context)
556 {
557     if(NULL == context)
558     {
559         return OC_STACK_ERROR;
560     }
561
562     context->amsMgrContext = (AmsMgrContext_t *)OICCalloc(1, sizeof(AmsMgrContext_t));
563     if(NULL == context->amsMgrContext)
564     {
565         return OC_STACK_ERROR;
566     }
567
568     SetPolicyEngineState(context, AWAITING_REQUEST);
569     return OC_STACK_OK;
570 }
571
572 void DeInitPolicyEngine(PEContext_t *context)
573 {
574     if(NULL != context)
575     {
576         SetPolicyEngineState(context, STOPPED);
577         OICFree(context->amsMgrContext);
578     }
579     return;
580 }