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