Imported Upstream version 0.9.2
[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
21 #include "oic_malloc.h"
22 #include "policyengine.h"
23 #include "resourcemanager.h"
24 #include "securevirtualresourcetypes.h"
25 #include "srmresourcestrings.h"
26 #include "logger.h"
27 #include "aclresource.h"
28 #include "srmutility.h"
29 #include "doxmresource.h"
30 #include <string.h>
31
32 #define TAG PCF("SRM-PE")
33
34 /**
35  * Return the uint16_t CRUDN permission corresponding to passed CAMethod_t.
36  */
37 uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method)
38 {
39     uint16_t perm = 0;
40     switch(method)
41     {
42         case CA_GET:
43             perm = (uint16_t)PERMISSION_READ;
44             break;
45         case CA_POST: // For now we treat all PUT & POST as Write
46         case CA_PUT:  // because we don't know if resource exists yet.
47             perm = (uint16_t)PERMISSION_WRITE;
48             break;
49         case CA_DELETE:
50             perm = (uint16_t)PERMISSION_DELETE;
51             break;
52         default: // if not recognized, must assume requesting full control
53             perm = (uint16_t)PERMISSION_FULL_CONTROL;
54             break;
55     }
56     return perm;
57 }
58
59 /**
60  * @brief Compares two OicUuid_t structs.
61  * @return true if the two OicUuid_t structs are equal, else false.
62  */
63 bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
64 {
65     // TODO use VERIFY macros to check for null when they are merged.
66     if(NULL == firstId || NULL == secondId)
67     {
68         return false;
69     }
70     for(int i = 0; i < UUID_LENGTH; i++)
71     {
72         if(firstId->id[i] != secondId->id[i])
73         {
74             return false;
75         }
76     }
77     return true;
78 }
79
80
81 /**
82  * Set the state and clear other stateful context vars.
83  */
84 void SetPolicyEngineState(PEContext_t *context, const PEState_t state)
85 {
86     // Clear stateful context variables.
87     OICFree(context->subject);
88     context->subject = NULL;
89     OICFree(context->resource);
90     context->resource = NULL;
91     context->permission = 0x0;
92     context->matchingAclFound = false;
93     context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
94
95     // Set state.
96     context->state = state;
97 }
98
99 /**
100  * @brief Compare the request's subject to DevOwner.
101  *
102  * @return true if context->subjectId == GetDoxmDevOwner(), else false
103  */
104 bool IsRequestFromDevOwner(PEContext_t *context)
105 {
106     bool retVal = false;
107     OicUuid_t owner;
108
109     if(OC_STACK_OK == GetDoxmDevOwnerId(&owner))
110     {
111         retVal = UuidCmp(context->subject, &owner);
112     }
113
114     return retVal;
115 }
116
117 /**
118  * Bitwise check to see if 'permission' contains 'request'.
119  * @param   permission  The allowed CRUDN permission.
120  * @param   request     The CRUDN permission being requested.
121  * @return true if 'permission' bits include all 'request' bits.
122  */
123 static inline bool IsPermissionAllowingRequest(const uint16_t permission,
124     const uint16_t request)
125 {
126     if(request == (request & permission))
127     {
128         return true;
129     }
130     else
131     {
132         return false;
133     }
134 }
135
136 /**
137  * Compare the passed subject to the wildcard (aka anonymous) subjectId.
138  * @return true if 'subject' is the wildcard, false if it is not.
139  */
140 static inline bool IsWildCardSubject(OicUuid_t *subject)
141 {
142     // Because always comparing to string literal, use strcmp()
143     if(0 == memcmp(subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)))
144     {
145         return true;
146     }
147     else
148     {
149         return false;
150     }
151 }
152
153 /**
154  * Copy the subject, resource and permission into the context fields.
155  */
156 void CopyParamsToContext(
157     PEContext_t     *context,
158     const OicUuid_t *subjectId,
159     const char      *resource,
160     const uint16_t  requestedPermission)
161 {
162     size_t length = 0;
163
164     // Free any existing subject.
165     OICFree(context->subject);
166     // Copy the subjectId into context.
167     context->subject = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
168     VERIFY_NON_NULL(TAG, context->subject, ERROR);
169     memcpy(context->subject, subjectId, sizeof(OicUuid_t));
170
171     // Copy the resource string into context.
172     length = strlen(resource) + 1;
173     if(0 < length)
174     {
175         OICFree(context->resource);
176         context->resource = (char*)OICMalloc(length);
177         VERIFY_NON_NULL(TAG, context->resource, ERROR);
178         strncpy(context->resource, resource, length);
179         context->resource[length - 1] = '\0';
180     }
181
182     // Assign the permission field.
183     context->permission = requestedPermission;
184
185 exit:
186     return;
187 }
188
189 /**
190  * Check whether 'resource' is in the passed ACL.
191  * @param   resource    The resource to search for.
192  * @param   acl         The ACL to check.
193  * @return true if 'resource' found, otherwise false.
194  */
195  bool IsResourceInAcl(const char *resource, const OicSecAcl_t *acl)
196  {
197     for(size_t n = 0; n < acl->resourcesLen; n++)
198     {
199         if(0 == strcmp(resource, acl->resources[n]) || // TODO null terms?
200          0 == strcmp(WILDCARD_RESOURCE_URI, acl->resources[n]))
201         {
202             return true;
203         }
204     }
205     return false;
206  }
207
208 /**
209  * Find ACLs containing context->subject.
210  * Search each ACL for requested resource.
211  * If resource found, check for context->permission.
212  * Set context->retVal to result from first ACL found which contains
213  * correct subject AND resource.
214  *
215  * @retval void
216  */
217 void ProcessAccessRequest(PEContext_t *context)
218 {
219     OC_LOG(INFO, TAG, PCF("Entering ProcessAccessRequest()"));
220     if(NULL != context)
221     {
222         const OicSecAcl_t *currentAcl = NULL;
223         OicSecAcl_t *savePtr = NULL;
224
225         // Start out assuming subject not found.
226         context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
227         do
228         {
229             OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): getting ACL..."));
230             currentAcl = GetACLResourceData(context->subject, &savePtr);
231             if(NULL != currentAcl)
232             {
233                 // Found the subject, so how about resource?
234                 OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
235                     found ACL matching subject."));
236                 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
237                 OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
238                     Searching for resource..."));
239                 if(IsResourceInAcl(context->resource, currentAcl))
240                 {
241                     OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
242                         found matching resource in ACL."));
243                     context->matchingAclFound = true;
244                     // Found the resource, so it's down to permission.
245                     context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
246                     if(IsPermissionAllowingRequest(currentAcl->permission, \
247                         context->permission))
248                     {
249                         context->retVal = ACCESS_GRANTED;
250                     }
251                 }
252             }
253             else
254             {
255                 OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
256                     no ACL found matching subject ."));
257             }
258         }
259         while((NULL != currentAcl) && (false == context->matchingAclFound));
260
261         if(IsAccessGranted(context->retVal))
262         {
263             OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
264                 Leaving ProcessAccessRequest(ACCESS_GRANTED)"));
265         }
266         else
267         {
268             OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
269                 Leaving ProcessAccessRequest(ACCESS_DENIED)"));
270         }
271     }
272     else
273     {
274         OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
275             Leaving ProcessAccessRequest(context is NULL)"));
276     }
277
278 }
279
280 /**
281  * Check whether a request should be allowed.
282  * @param   context     Pointer to (Initialized) Policy Engine context to use.
283  * @param   subjectId   Pointer to Id of the requesting entity.
284  * @param   resource    Pointer to URI of Resource being requested.
285  * @param   permission  Requested permission.
286  * @return  ACCESS_GRANTED if request should go through,
287  *          otherwise some flavor of ACCESS_DENIED
288  */
289 SRMAccessResponse_t CheckPermission(
290     PEContext_t     *context,
291     const OicUuid_t *subjectId,
292     const char      *resource,
293     const uint16_t  requestedPermission)
294 {
295     SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
296
297     VERIFY_NON_NULL(TAG, context, ERROR);
298     VERIFY_NON_NULL(TAG, subjectId, ERROR);
299     VERIFY_NON_NULL(TAG, resource, ERROR);
300
301     // Each state machine context can only be processing one request at a time.
302     // Therefore if the context is not in AWAITING_REQUEST state, return error.
303     // Otherwise, change to BUSY state and begin processing request.
304     if(AWAITING_REQUEST == context->state)
305     {
306         SetPolicyEngineState(context, BUSY);
307         CopyParamsToContext(context, subjectId, resource, requestedPermission);
308         // Before doing any processing, check if request coming
309         // from DevOwner and if so, always GRANT.
310         if(IsRequestFromDevOwner(context))
311         {
312             context->retVal = ACCESS_GRANTED;
313         }
314         else
315         {
316             ProcessAccessRequest(context);
317             // If matching ACL not found, and subject != wildcard, try wildcard.
318             if((false == context->matchingAclFound) && \
319                 (false == IsWildCardSubject(context->subject)))
320             {
321                 OICFree(context->subject);
322                 context->subject = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
323                 VERIFY_NON_NULL(TAG, context->subject, ERROR);
324                 memcpy(context->subject, &WILDCARD_SUBJECT_ID,
325                     sizeof(OicUuid_t));
326                 ProcessAccessRequest(context); // TODO anonymous subj can result
327                                                // in confusing err code return.
328             }
329         }
330     }
331     else
332     {
333         context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
334     }
335
336     // Capture retVal before resetting state for next request.
337     retVal = context->retVal;
338     SetPolicyEngineState(context, AWAITING_REQUEST);
339
340 exit:
341     return retVal;
342 }
343
344 /**
345  * Initialize the Policy Engine. Call this before calling CheckPermission().
346  * @param   context     Pointer to Policy Engine context to initialize.
347  * @return  OC_STACK_OK for Success, otherwise some error value
348  */
349 OCStackResult InitPolicyEngine(PEContext_t *context)
350 {
351     if(NULL != context)
352     {
353         SetPolicyEngineState(context, AWAITING_REQUEST);
354     }
355
356     return OC_STACK_OK;
357 }
358
359 /**
360  * De-Initialize the Policy Engine.  Call this before exiting to allow Policy
361  * Engine to do cleanup on context.
362  * @param   context     Pointer to Policy Engine context to de-initialize.
363  * @return  none
364  */
365 void DeInitPolicyEngine(PEContext_t *context)
366 {
367     if(NULL != context)
368     {
369         SetPolicyEngineState(context, STOPPED);
370     }
371
372     return;
373 }