Merge branch 'master' into resource-manipulation
[platform/upstream/iotivity.git] / resource / csdk / security / src / secureresourcemanager.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 "ocstack.h"
22 #include "logger.h"
23 #include "cainterface.h"
24 #include "secureresourcemanager.h"
25 #include "resourcemanager.h"
26 #include "credresource.h"
27 #include "policyengine.h"
28 #include <string.h>
29
30 #define TAG  PCF("SRM")
31
32 //Request Callback handler
33 static CARequestCallback gRequestHandler = NULL;
34 //Response Callback handler
35 static CAResponseCallback gResponseHandler = NULL;
36 //Error Callback handler
37 static CAErrorCallback gErrorHandler = NULL;
38 //Persistent Storage callback handler for open/read/write/close/unlink
39 static OCPersistentStorage *gPersistentStorageHandler =  NULL;
40
41 /**
42  * A single global Policy Engine context will suffice as long
43  * as SRM is single-threaded.
44  */
45 PEContext_t g_policyEngineContext;
46
47 /**
48  * @brief   Handle the request from the SRM.
49  * @param   endPoint       [IN] Endpoint object from which the response is received.
50  * @param   requestInfo    [IN] Information for the request.
51  * @return  NONE
52  */
53 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
54 {
55     OC_LOG(INFO, TAG, PCF("Received request from remote device"));
56
57     if (!endPoint || !requestInfo)
58     {
59         OC_LOG(ERROR, TAG, PCF("Invalid arguments"));
60         return;
61     }
62
63     // Copy the subjectID
64     OicUuid_t subjectId = {};
65     memcpy(subjectId.id, endPoint->identity.id, sizeof(subjectId.id));
66
67     //Check the URI has the query and skip it before checking the permission
68     char *uri = strstr(requestInfo->info.resourceUri, "?");
69     int position = 0;
70     if (uri)
71     {
72         position = uri - requestInfo->info.resourceUri;
73     }
74     if (position > MAX_URI_LENGTH)
75     {
76         OC_LOG(ERROR, TAG, PCF("URI length is too long"));
77         return;
78     }
79     SRMAccessResponse_t response = ACCESS_DENIED;
80     if (position > 0)
81     {
82         char newUri[MAX_URI_LENGTH + 1];
83         strncpy(newUri, requestInfo->info.resourceUri, (position));
84         newUri[position] = '\0';
85         //Skip query and pass the newUri.
86         response = CheckPermission(&g_policyEngineContext, &subjectId,
87                               newUri,
88                               GetPermissionFromCAMethod_t(requestInfo->method));
89     }
90     else
91     {
92         //Pass resourceUri if there is no query info.
93         response = CheckPermission(&g_policyEngineContext, &subjectId,
94                               requestInfo->info.resourceUri,
95                               GetPermissionFromCAMethod_t(requestInfo->method));
96     }
97     if (IsAccessGranted(response) && gRequestHandler)
98     {
99         return (gRequestHandler(endPoint, requestInfo));
100     }
101
102     // Form a 'access deny' or 'Error' response and send to peer
103     CAResponseInfo_t responseInfo = {};
104     memcpy(&responseInfo.info, &(requestInfo->info), sizeof(responseInfo.info));
105     responseInfo.info.payload = NULL;
106     if (!gRequestHandler)
107     {
108         responseInfo.result = CA_INTERNAL_SERVER_ERROR;
109     }
110     else
111     {
112         /*
113          * TODO Enhance this logic more to decide between
114          * CA_UNAUTHORIZED_REQ or CA_FORBIDDEN_REQ depending
115          * upon SRMAccessResponseReasonCode_t
116          */
117         responseInfo.result = CA_UNAUTHORIZED_REQ;
118     }
119
120     if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
121     {
122         OC_LOG(ERROR, TAG, PCF("Failed in sending response to a unauthorized request!"));
123     }
124 }
125
126 /**
127  * @brief   Handle the response from the SRM.
128  * @param   endPoint     [IN] The remote endpoint.
129  * @param   responseInfo [IN] Response information from the endpoint.
130  * @return  NONE
131  */
132 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
133 {
134     OC_LOG(INFO, TAG, PCF("Received response from remote device"));
135     if (gResponseHandler)
136     {
137         gResponseHandler(endPoint, responseInfo);
138     }
139 }
140
141
142 /**
143  * @brief   Handle the error from the SRM.
144  * @param   endPoint  [IN] The remote endpoint.
145  * @param   errorInfo [IN] Error information from the endpoint.
146  * @return  NONE
147  */
148 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
149 {
150     OC_LOG(INFO, TAG, PCF("Received error from remote device"));
151     if (gErrorHandler)
152     {
153         gErrorHandler(endPoint, errorInfo);
154     }
155 }
156
157
158 /**
159  * @brief   Register request and response callbacks.
160  *          Requests and responses are delivered in these callbacks.
161  * @param   reqHandler   [IN] Request handler callback ( for GET,PUT ..etc)
162  * @param   respHandler  [IN] Response handler callback.
163  * @return
164  *     OC_STACK_OK    - No errors; Success
165  *     OC_STACK_INVALID_PARAM - invalid parameter
166  */
167 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
168                                  CAResponseCallback respHandler,
169                                  CAErrorCallback errHandler)
170 {
171     OC_LOG(INFO, TAG, PCF("SRMRegisterHandler !!"));
172     if( !reqHandler || !respHandler || !errHandler)
173     {
174         OC_LOG(ERROR, TAG, PCF("Callback handlers are invalid"));
175         return OC_STACK_INVALID_PARAM;
176     }
177     gRequestHandler = reqHandler;
178     gResponseHandler = respHandler;
179     gErrorHandler = errHandler;
180
181
182 #if defined(__WITH_DTLS__)
183     CARegisterHandler(SRMRequestHandler, SRMResponseHandler, SRMErrorHandler);
184 #else
185     CARegisterHandler(reqHandler, respHandler, errHandler);
186 #endif /* __WITH_DTLS__ */
187     return OC_STACK_OK;
188 }
189
190 /**
191  * @brief   Register Persistent storage callback.
192  * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
193  * @return
194  *     OC_STACK_OK    - No errors; Success
195  *     OC_STACK_INVALID_PARAM - Invalid parameter
196  */
197 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
198 {
199     OC_LOG(INFO, TAG, PCF("SRMRegisterPersistentStorageHandler !!"));
200     if(!persistentStorageHandler)
201     {
202         OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
203         return OC_STACK_INVALID_PARAM;
204     }
205     gPersistentStorageHandler = persistentStorageHandler;
206     return OC_STACK_OK;
207 }
208
209 /**
210  * @brief   Get Persistent storage handler pointer.
211  * @return
212  *     The pointer to Persistent Storage callback handler
213  */
214
215 OCPersistentStorage* SRMGetPersistentStorageHandler()
216 {
217     OC_LOG(INFO, TAG, PCF("SRMGetPersistentStorageHandler !!"));
218     return gPersistentStorageHandler;
219 }
220
221
222 /**
223  * @brief   Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
224  * @retval  OC_STACK_OK for Success, otherwise some error value
225  */
226 OCStackResult SRMInitSecureResources()
227 {
228     // TODO: temporarily returning OC_STACK_OK every time until default
229     // behavior (for when SVR DB is missing) is settled.
230     InitSecureResources();
231
232 #if defined(__WITH_DTLS__)
233     CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
234 #endif // (__WITH_DTLS__)
235
236     return OC_STACK_OK;
237 }
238
239 /**
240  * @brief   Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
241  * @retval  none
242  */
243 void SRMDeInitSecureResources()
244 {
245     DestroySecureResources();
246 }
247
248 /**
249  * @brief   Initialize Policy Engine.
250  * @return  OC_STACK_OK for Success, otherwise some error value.
251  */
252 OCStackResult SRMInitPolicyEngine()
253 {
254     return InitPolicyEngine(&g_policyEngineContext);
255 }
256
257 /**
258  * @brief   Cleanup Policy Engine.
259  * @return  none
260  */
261 void SRMDeInitPolicyEngine()
262 {
263     return DeInitPolicyEngine(&g_policyEngineContext);
264 }