[IOT-1831] Fix requested permission
[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 #include <assert.h>
22
23 #include "utlist.h"
24 #include "oic_malloc.h"
25 #include "policyengine.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 "OIC_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: // Treat all POST as Write (Update) because
51                       // we don't know if resource exists yet.
52                       // This will be addressed in IoTivity impl of OCF 1.0
53             perm = (uint16_t)PERMISSION_WRITE;
54             break;
55         case CA_PUT: // Per convention, OIC/OCF uses PUT only for Create,
56                      // never for Update.
57             perm = (uint16_t)PERMISSION_CREATE;
58             break;
59         case CA_DELETE:
60             perm = (uint16_t)PERMISSION_DELETE;
61             break;
62         default: // if not recognized, must assume requesting full control
63             perm = (uint16_t)PERMISSION_FULL_CONTROL;
64             break;
65     }
66
67     OIC_LOG_V(INFO, TAG, "%s: CA method %d requires permission %#x",
68         __func__, method, (uint32_t)perm);
69     return perm;
70 }
71
72 /**
73  * Compares two OicUuid_t structs.
74  *
75  * @return true if the two OicUuid_t structs are equal, else false.
76  */
77 static bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
78 {
79     // TODO use VERIFY macros to check for null when they are merged.
80     if(NULL == firstId || NULL == secondId)
81     {
82         return false;
83     }
84     // Check empty uuid string
85     if('\0' == firstId->id[0] || '\0' == secondId->id[0])
86     {
87         return false;
88     }
89     for(int i = 0; i < UUID_LENGTH; i++)
90     {
91         if(firstId->id[i] != secondId->id[i])
92         {
93             return false;
94         }
95     }
96     return true;
97 }
98
99 /**
100  * Compare the request's subject to DevOwner.
101  *
102  * @return true if context->subjectId == GetDoxmDevOwner(), else false.
103  */
104 static bool IsRequestFromDevOwner(SRMRequestContext_t *context)
105 {
106     bool retVal = false;
107
108     if(NULL == context)
109     {
110         return retVal;
111     }
112
113     OicSecDoxm_t* doxm = (OicSecDoxm_t*) GetDoxmResourceData();
114     if (doxm)
115     {
116         retVal = UuidCmp(&doxm->owner, &context->subjectUuid);
117         OIC_LOG_V(DEBUG, TAG, "%s: request was %sreceived from device owner",
118             __func__, retVal ? "" : "NOT ");
119     }
120
121 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
122     //Ownership Transfer sessions are allowed to bypass SVR ACEs, while this
123     //Device is not owned yet.
124     if (!retVal && (NULL != context->endPoint))
125     {
126         uint32_t allAttributes;
127         if (CAGetSecureEndpointAttributes(context->endPoint, &allAttributes) &&
128             (allAttributes & CA_SECURE_ENDPOINT_ATTRIBUTE_ADMINISTRATOR))
129         {
130             retVal = true;
131         }
132
133         OIC_LOG_V(DEBUG, TAG, "%s: request was %sreceived from Ownership Transfer session",
134             __func__, retVal ? "" : "NOT ");
135     }
136 #endif
137
138     return retVal;
139 }
140
141 #ifdef MULTIPLE_OWNER
142 /**
143  * Compare the request's subject to SubOwner.
144  *
145  * @return true if context->subjectId exist subowner list, else false.
146  */
147 static bool IsRequestFromSubOwner(SRMRequestContext_t *context)
148 {
149     bool retVal = false;
150
151     if (NULL != context)
152     {
153         retVal = IsSubOwner(&context->subjectUuid);
154     }
155
156     OIC_LOG_V(INFO, TAG, "%s: returning %s", __func__, retVal ? "true" : "false");
157     return retVal;
158 }
159
160 /**
161  * Verify the SubOwner's request.
162  *
163  * @return true if request is valid, else false.
164  */
165 static bool IsValidRequestFromSubOwner(SRMRequestContext_t *context)
166 {
167     bool isValidRequest = false;
168
169     if(NULL == context)
170     {
171         return isValidRequest;
172     }
173
174     switch(context->resourceType)
175     {
176         case OIC_R_DOXM_TYPE:
177             //SubOwner has READ permission only for DOXM
178             if(PERMISSION_READ == context->requestedPermission)
179             {
180                 isValidRequest = true;
181             }
182             break;
183         case OIC_R_PSTAT_TYPE:
184             //SubOwner has full permsion for PSTAT
185             isValidRequest = true;
186             break;
187         case OIC_R_CRED_TYPE:
188             //SubOwner can only access the credential which is registered as the eowner.
189             isValidRequest = IsValidCredentialAccessForSubOwner(&context->subjectUuid,
190              context->payload, context->payloadSize);
191             break;
192         case OIC_R_ACL_TYPE:
193             //SubOwner can only access the ACL which is registered as the eowner.
194             isValidRequest = IsValidAclAccessForSubOwner(&context->subjectUuid,
195                 context->payload, context->payloadSize);
196             break;
197         default:
198             //SubOwner has full permission for all resource except the security resource
199             isValidRequest = true;
200             break;
201     }
202
203     OIC_LOG_V(INFO, TAG, "%s: returning %s", __func__, isValidRequest ? "true" : "false");
204     return isValidRequest;
205 }
206 #endif //MULTIPLE_OWNER
207
208 // TODO - remove these function placeholders as they are implemented
209 // in the resource entity handler code.
210 // Note that because many SVRs do not have a rowner, in those cases we
211 // just return "OC_STACK_ERROR" which results in a "false" return by
212 // IsRequestFromResourceOwner().
213 // As these SVRs are revised to have a rowner, these functions should be
214 // replaced (see pstatresource.c for example of GetPstatRownerId).
215
216 OCStackResult GetCrlRownerId(OicUuid_t *rowner)
217 {
218     OC_UNUSED(rowner);
219     rowner = NULL;
220     return OC_STACK_ERROR;
221 }
222
223 OCStackResult GetSaclRownerId(OicUuid_t *rowner)
224 {
225     OC_UNUSED(rowner);
226     rowner = NULL;
227     return OC_STACK_ERROR;
228 }
229
230 OCStackResult GetSvcRownerId(OicUuid_t *rowner)
231 {
232     OC_UNUSED(rowner);
233     rowner = NULL;
234     return OC_STACK_ERROR;
235 }
236
237 static GetSvrRownerId_t GetSvrRownerId[OIC_SEC_SVR_TYPE_COUNT + 1] = {
238     NULL,
239     GetAclRownerId,
240     GetAmaclRownerId,
241     GetCredRownerId,
242     GetCrlRownerId,
243     GetDoxmRownerId,
244     GetDpairingRownerId,
245     GetPconfRownerId,
246     GetPstatRownerId,
247     GetSaclRownerId,
248     GetSvcRownerId
249 };
250
251 /**
252  * Compare the request's subject to resource.ROwner.
253  *
254  * @return true if context->subjectId equals SVR rowner id, else return false
255  */
256 bool IsRequestFromResourceOwner(SRMRequestContext_t *context)
257 {
258     bool retVal = false;
259     OicUuid_t resourceOwner;
260
261     if(NULL == context)
262     {
263         return false;
264     }
265
266     if((OIC_R_ACL_TYPE <= context->resourceType) && \
267         (OIC_SEC_SVR_TYPE_COUNT > context->resourceType))
268     {
269         if(OC_STACK_OK == GetSvrRownerId[(int)context->resourceType](&resourceOwner))
270         {
271             retVal = UuidCmp(&context->subjectUuid, &resourceOwner);
272         }
273     }
274
275     OIC_LOG_V(INFO, TAG, "%s: returning %s", __func__, retVal ? "true" : "false");
276     return retVal;
277 }
278
279 /**
280  * Bitwise check to see if 'permission' contains 'request'.
281  *
282  * @param permission is the allowed CRUDN permission.
283  * @param request is the CRUDN permission being requested.
284  *
285  * @return true if 'permission' bits include all 'request' bits.
286  */
287 INLINE_API bool IsPermissionAllowingRequest(const uint16_t permission,
288     const uint16_t request)
289 {
290     bool allowed = (request == (request & permission));
291
292     OIC_LOG_V(INFO, TAG, "%s: ACE allows permission %#x, "
293         "requested permission %#x -> allowed = %u", __func__,
294         (uint32_t)permission, (uint32_t)request, (uint32_t)allowed);
295
296     return allowed;
297 }
298
299 /**
300  * Compare the passed subject to the wildcard (aka anonymous) subjectId.
301  *
302  * @return true if 'subject' is the wildcard, false if it is not.
303  */
304 INLINE_API bool IsWildCardSubject(OicUuid_t *subject)
305 {
306     if(NULL == subject)
307     {
308         return false;
309     }
310
311     // Because always comparing to string literal, use strcmp()
312     if(0 == memcmp(subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)))
313     {
314         return true;
315     }
316     else
317     {
318         return false;
319     }
320 }
321
322 /**
323  * Check whether 'resource' is getting accessed within the valid time period.
324  *
325  * @param acl is the ACL to check.
326  *
327  * @return true if access is within valid time period or if the period or recurrence is not present.
328  * false if period and recurrence present and the access is not within valid time period.
329  */
330 static bool IsAccessWithinValidTime(const OicSecAce_t *ace)
331 {
332 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
333     //lack of absolute time
334     if (NULL== ace || NULL == ace->validities)
335     {
336         return true;
337     }
338
339     //periods & recurrences rules are paired.
340     if (NULL == ace->validities->recurrences)
341     {
342         return false;
343     }
344
345     OicSecValidity_t* validity =  NULL;
346     LL_FOREACH(ace->validities, validity)
347     {
348         for(size_t i = 0; i < validity->recurrenceLen; i++)
349         {
350             if (IOTVTICAL_VALID_ACCESS == IsRequestWithinValidTime(validity->period,
351                 validity->recurrences[i]))
352             {
353                 OIC_LOG(INFO, TAG, "Access request is in allowed time period");
354                 return true;
355             }
356         }
357     }
358     OIC_LOG(ERROR, TAG, "Access request is in invalid time period");
359     return false;
360
361 #else
362     return true;
363 #endif
364 }
365
366 /**
367  * Check whether 'resource' is in the passed ACE.
368  *
369  * @param resource is the resource being searched.
370  * @param ace is the ACE to check.
371  *
372  * @return true if 'resource' found, otherwise false.
373  */
374 static bool IsResourceInAce(const char *resource, const OicSecAce_t *ace)
375 {
376     if (NULL== ace || NULL == resource)
377     {
378         return false;
379     }
380
381     OicSecRsrc_t* rsrc = NULL;
382     LL_FOREACH(ace->resources, rsrc)
383     {
384          if (0 == strcmp(resource, rsrc->href) || // TODO null terms?
385              0 == strcmp(WILDCARD_RESOURCE_URI, rsrc->href))
386          {
387              return true;
388          }
389     }
390     return false;
391 }
392
393
394 /**
395  * Find ACLs containing context->subject.
396  * Search each ACL for requested resource.
397  * If resource found, check for context->permission and period validity.
398  * If the ACL is not found locally and AMACL for the resource is found
399  * then sends the request to AMS service for the ACL.
400  * Set context->retVal to result from first ACL found which contains
401  * correct subject AND resource.
402  */
403 static void ProcessAccessRequest(SRMRequestContext_t *context)
404 {
405     OIC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest().");
406
407     if (NULL != context)
408     {
409         const OicSecAce_t *currentAce = NULL;
410         OicSecAce_t *aceSavePtr = NULL;
411
412         OIC_LOG_V(DEBUG, TAG, "Entering ProcessAccessRequest(%s)",
413             context->resourceUri);
414
415         // Start out assuming subject not found.
416         context->responseVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
417
418         // Loop through all ACLs with a matching Subject searching for the right
419         // ACL for this request.
420         do
421         {
422             OIC_LOG_V(DEBUG, TAG, "%s: getting ACE..." ,__func__);
423             currentAce = GetACLResourceData(&context->subjectUuid, &aceSavePtr);
424
425             if (NULL != currentAce)
426             {
427                 // Found the subject, so how about resource?
428                 OIC_LOG_V(DEBUG, TAG, "%s:found ACE matching subject" ,__func__);
429
430                 // Subject was found, so err changes to Rsrc not found for now.
431                 context->responseVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
432                 OIC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
433                 if (IsResourceInAce(context->resourceUri, currentAce))
434                 {
435                     OIC_LOG_V(INFO, TAG, "%s:found matching resource in ACE" ,__func__);
436
437                     // Found the resource, so it's down to valid period & permission.
438                     context->responseVal = ACCESS_DENIED_INVALID_PERIOD;
439                     if (IsAccessWithinValidTime(currentAce))
440                     {
441                         context->responseVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
442                         if (IsPermissionAllowingRequest(currentAce->permission,
443                             context->requestedPermission))
444                         {
445                             context->responseVal = ACCESS_GRANTED;
446                         }
447                     }
448                 }
449             }
450             else
451             {
452                 OIC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",
453                     __func__, context->resourceUri);
454             }
455         } while ((NULL != currentAce)
456             && (false == IsAccessGranted(context->responseVal)));
457
458         if (IsAccessGranted(context->responseVal))
459         {
460             OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
461         }
462         else
463         {
464             OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
465         }
466     }
467     else
468     {
469         OIC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
470     }
471
472     return;
473 }
474
475 void CheckPermission(SRMRequestContext_t *context)
476 {
477     assert(NULL != context);
478     assert(context->requestedPermission != 0);
479     assert((context->requestedPermission & ~PERMISSION_FULL_CONTROL) == 0);
480
481     // Before doing any ACL processing, check if request is a) coming
482     // from DevOwner AND b) the device is in Ready for OTM or Reset state
483     // (which in IoTivity is equivalent to isOp == false && owned == false)
484     // AND c) the request is for a SVR resource.
485     // If all 3 conditions are met, grant request.
486     // TODO_IoTivity_1.3: use pstat.dos instead of these two checks.
487     bool isDeviceOwned = true; // default to value that will NOT grant access
488     if (OC_STACK_OK != GetDoxmIsOwned(&isDeviceOwned)) // if runtime error, don't grant
489     {
490         OIC_LOG_V(ERROR, TAG, "GetDoxmIsOwned() call failed.");
491         context->responseVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
492     }
493     // If we were able to get the value of doxm->isOwned, proceed with
494     // test for implicit access.
495     else if (IsRequestFromDevOwner(context) &&  // if from DevOwner
496             !GetPstatIsop() &&                  // AND if pstat->isOp == false
497             !isDeviceOwned &&                   // AND if doxm->isOwned == false
498             (NOT_A_SVR_RESOURCE != context->resourceType)) // AND if is SVR type
499     {
500         OIC_LOG(INFO, TAG, "CheckPermission: granting access to device owner");
501         context->responseVal = ACCESS_GRANTED;
502     }
503     // If not granted via DevOwner status and not a subowner,
504     // then check if request is for a SVR and coming from rowner
505     else if (IsRequestFromResourceOwner(context))
506     {
507         OIC_LOG(INFO, TAG, "CheckPermission: granting access to resource owner");
508         context->responseVal = ACCESS_GRANTED;
509     }
510 #ifdef MULTIPLE_OWNER // TODO Samsung reviewer: per above comment, should this
511                       // go above IsRequestFromResourceOwner() call, or here?
512     // Then check if request from SubOwner.
513     else if (IsRequestFromSubOwner(context))
514     {
515         if (IsValidRequestFromSubOwner(context))
516         {
517             OIC_LOG(INFO, TAG, "CheckPermission: granting access to device sub-owner");
518             context->responseVal = ACCESS_GRANTED;
519         }
520     }
521 #endif //MULTIPLE_OWNER
522     // Else request is a "normal" request that must be tested against ACL.
523     else
524     {
525         OicUuid_t saveSubjectUuid = {.id={0}};
526         // bool isSubEmpty = IsRequestSubjectEmpty(context);
527
528         ProcessAccessRequest(context);
529
530         // TODO_IoTivity_1.3: ensure check order results in Union permissions
531         // If access not already granted, and requested subject != wildcard,
532         // try looking for a wildcard ACE that grants access.
533         // See JIRA ticket 1795 (https://jira.iotivity.org/browse/IOT-1795)
534         if (ACCESS_GRANTED != context->responseVal &&
535             !IsWildCardSubject(&context->subjectUuid))
536         {
537             // Save subject to restore context after wildcard subject check.
538             memcpy(&saveSubjectUuid, &context->subjectUuid,
539                 sizeof(context->subjectUuid));
540
541             // Set context->subjectUuid to WILDCARD_SUBJECT_ID.
542             memset(&context->subjectUuid, 0, sizeof(context->subjectUuid));
543             memcpy(&context->subjectUuid,
544                 &WILDCARD_SUBJECT_ID, sizeof(context->subjectUuid));
545             ProcessAccessRequest(context);
546
547             // Restore subjectUuid.
548             memcpy(&context->subjectUuid,
549                 &saveSubjectUuid, sizeof(context->subjectUuid));
550         }
551     }
552
553     return;
554 }