Merge branch 'master' into resource-manipulation
[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         {
201             return true;
202         }
203     }
204     return false;
205  }
206
207 /**
208  * Find ACLs containing context->subject.
209  * Search each ACL for requested resource.
210  * If resource found, check for context->permission.
211  * Set context->retVal to result from first ACL found which contains
212  * correct subject AND resource.
213  *
214  * @retval void
215  */
216 void ProcessAccessRequest(PEContext_t *context)
217 {
218     OC_LOG(INFO, TAG, PCF("Entering ProcessAccessRequest()"));
219     if(NULL != context)
220     {
221         const OicSecAcl_t *currentAcl = NULL;
222         OicSecAcl_t *savePtr = NULL;
223
224         // Start out assuming subject not found.
225         context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
226         do
227         {
228             OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): getting ACL..."));
229             currentAcl = GetACLResourceData(context->subject, &savePtr);
230             if(NULL != currentAcl)
231             {
232                 // Found the subject, so how about resource?
233                 OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
234                     found ACL matching subject."));
235                 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
236                 OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
237                     Searching for resource..."));
238                 if(IsResourceInAcl(context->resource, currentAcl))
239                 {
240                     OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
241                         found matching resource in ACL."));
242                     context->matchingAclFound = true;
243                     // Found the resource, so it's down to permission.
244                     context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
245                     if(IsPermissionAllowingRequest(currentAcl->permission, \
246                         context->permission))
247                     {
248                         context->retVal = ACCESS_GRANTED;
249                     }
250                 }
251             }
252             else
253             {
254                 OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
255                     no ACL found matching subject ."));
256             }
257         }
258         while((NULL != currentAcl) && (false == context->matchingAclFound));
259
260         if(IsAccessGranted(context->retVal))
261         {
262             OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
263                 Leaving ProcessAccessRequest(ACCESS_GRANTED)"));
264         }
265         else
266         {
267             OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
268                 Leaving ProcessAccessRequest(ACCESS_DENIED)"));
269         }
270     }
271     else
272     {
273         OC_LOG(INFO, TAG, PCF("ProcessAccessRequest(): \
274             Leaving ProcessAccessRequest(context is NULL)"));
275     }
276
277 }
278
279 /**
280  * Check whether a request should be allowed.
281  * @param   context     Pointer to (Initialized) Policy Engine context to use.
282  * @param   subjectId   Pointer to Id of the requesting entity.
283  * @param   resource    Pointer to URI of Resource being requested.
284  * @param   permission  Requested permission.
285  * @return  ACCESS_GRANTED if request should go through,
286  *          otherwise some flavor of ACCESS_DENIED
287  */
288 SRMAccessResponse_t CheckPermission(
289     PEContext_t     *context,
290     const OicUuid_t *subjectId,
291     const char      *resource,
292     const uint16_t  requestedPermission)
293 {
294     SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
295
296     VERIFY_NON_NULL(TAG, context, ERROR);
297     VERIFY_NON_NULL(TAG, subjectId, ERROR);
298     VERIFY_NON_NULL(TAG, resource, ERROR);
299
300     // Each state machine context can only be processing one request at a time.
301     // Therefore if the context is not in AWAITING_REQUEST state, return error.
302     // Otherwise, change to BUSY state and begin processing request.
303     if(AWAITING_REQUEST == context->state)
304     {
305         SetPolicyEngineState(context, BUSY);
306         CopyParamsToContext(context, subjectId, resource, requestedPermission);
307         // Before doing any processing, check if request coming
308         // from DevOwner and if so, always GRANT.
309         if(IsRequestFromDevOwner(context))
310         {
311             context->retVal = ACCESS_GRANTED;
312         }
313         else
314         {
315             ProcessAccessRequest(context);
316             // If matching ACL not found, and subject != wildcard, try wildcard.
317             if((false == context->matchingAclFound) && \
318                 (false == IsWildCardSubject(context->subject)))
319             {
320                 OICFree(context->subject);
321                 context->subject = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
322                 VERIFY_NON_NULL(TAG, context->subject, ERROR);
323                 memcpy(context->subject, &WILDCARD_SUBJECT_ID,
324                     sizeof(OicUuid_t));
325                 ProcessAccessRequest(context); // TODO anonymous subj can result
326                                                // in confusing err code return.
327             }
328         }
329     }
330     else
331     {
332         context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
333     }
334
335     // Capture retVal before resetting state for next request.
336     retVal = context->retVal;
337     SetPolicyEngineState(context, AWAITING_REQUEST);
338
339 exit:
340     return retVal;
341 }
342
343 /**
344  * Initialize the Policy Engine. Call this before calling CheckPermission().
345  * @param   context     Pointer to Policy Engine context to initialize.
346  * @return  OC_STACK_OK for Success, otherwise some error value
347  */
348 OCStackResult InitPolicyEngine(PEContext_t *context)
349 {
350     if(NULL != context)
351     {
352         SetPolicyEngineState(context, AWAITING_REQUEST);
353     }
354
355     return OC_STACK_OK;
356 }
357
358 /**
359  * De-Initialize the Policy Engine.  Call this before exiting to allow Policy
360  * Engine to do cleanup on context.
361  * @param   context     Pointer to Policy Engine context to de-initialize.
362  * @return  none
363  */
364 void DeInitPolicyEngine(PEContext_t *context)
365 {
366     if(NULL != context)
367     {
368         SetPolicyEngineState(context, STOPPED);
369     }
370
371     return;
372 }