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