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