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