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