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