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