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