1 //******************************************************************
3 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
24 #include "cainterface.h"
25 #include "resourcemanager.h"
26 #include "credresource.h"
27 #include "policyengine.h"
28 #include "srmutility.h"
30 #include "oic_string.h"
31 #include "oic_malloc.h"
32 #include "securevirtualresourcetypes.h"
33 #include "secureresourcemanager.h"
34 #include "srmresourcestrings.h"
39 #include "crlresource.h"
40 #endif // __WITH_X509__
42 //Request Callback handler
43 static CARequestCallback gRequestHandler = NULL;
44 //Response Callback handler
45 static CAResponseCallback gResponseHandler = NULL;
46 //Error Callback handler
47 static CAErrorCallback gErrorHandler = NULL;
48 //Persistent Storage callback handler for open/read/write/close/unlink
49 static OCPersistentStorage *gPersistentStorageHandler = NULL;
50 //Provisioning response callback
51 static SPResponseCallback gSPResponseHandler = NULL;
54 * A single global Policy Engine context will suffice as long
55 * as SRM is single-threaded.
57 PEContext_t g_policyEngineContext;
60 * @brief function to register provisoning API's response callback.
61 * @param respHandler response handler callback.
63 void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler)
65 gSPResponseHandler = respHandler;
69 static void SRMSendUnAuthorizedAccessresponse(PEContext_t *context)
71 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
74 NULL == context->amsMgrContext->requestInfo)
76 OIC_LOG_V(ERROR, TAG, "%s : NULL Parameter(s)",__func__);
80 memcpy(&responseInfo.info, &(context->amsMgrContext->requestInfo->info),
81 sizeof(responseInfo.info));
82 responseInfo.info.payload = NULL;
83 responseInfo.result = CA_UNAUTHORIZED_REQ;
85 if (CA_STATUS_OK == CASendResponse(context->amsMgrContext->endpoint, &responseInfo))
87 OIC_LOG(DEBUG, TAG, "Succeed in sending response to a unauthorized request!");
91 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
96 void SRMSendResponse(SRMAccessResponse_t responseVal)
98 OIC_LOG(DEBUG, TAG, "Sending response to remote device");
100 if (IsAccessGranted(responseVal) && gRequestHandler)
102 OIC_LOG_V(INFO, TAG, "%s : Access granted. Passing Request to RI layer", __func__);
103 if (!g_policyEngineContext.amsMgrContext->endpoint ||
104 !g_policyEngineContext.amsMgrContext->requestInfo)
106 OIC_LOG_V(ERROR, TAG, "%s : Invalid arguments", __func__);
107 SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
110 gRequestHandler(g_policyEngineContext.amsMgrContext->endpoint,
111 g_policyEngineContext.amsMgrContext->requestInfo);
115 OIC_LOG_V(INFO, TAG, "%s : ACCESS_DENIED.", __func__);
116 SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
120 //Resetting PE state to AWAITING_REQUEST
121 SetPolicyEngineState(&g_policyEngineContext, AWAITING_REQUEST);
126 * @brief Handle the request from the SRM.
127 * @param endPoint [IN] Endpoint object from which the response is received.
128 * @param requestInfo [IN] Information for the request.
131 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
133 OIC_LOG(DEBUG, TAG, "Received request from remote device");
135 if (!endPoint || !requestInfo)
137 OIC_LOG(ERROR, TAG, "Invalid arguments");
141 // Copy the subjectID
142 OicUuid_t subjectId = {.id = {0}};
143 memcpy(subjectId.id, requestInfo->info.identity.id, sizeof(subjectId.id));
145 //Check the URI has the query and skip it before checking the permission
146 char *uri = strstr(requestInfo->info.resourceUri, "?");
150 //Skip query and pass the resource uri
151 position = uri - requestInfo->info.resourceUri;
155 position = strlen(requestInfo->info.resourceUri);
157 if (MAX_URI_LENGTH < position || 0 > position)
159 OIC_LOG(ERROR, TAG, "Incorrect URI length");
162 SRMAccessResponse_t response = ACCESS_DENIED;
163 char newUri[MAX_URI_LENGTH + 1];
164 OICStrcpyPartial(newUri, MAX_URI_LENGTH + 1, requestInfo->info.resourceUri, position);
166 //New request are only processed if the policy engine state is AWAITING_REQUEST.
167 if(AWAITING_REQUEST == g_policyEngineContext.state)
169 OIC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method, %d",
170 requestInfo->info.resourceUri, requestInfo->method);
171 response = CheckPermission(&g_policyEngineContext, &subjectId, newUri,
172 GetPermissionFromCAMethod_t(requestInfo->method));
176 OIC_LOG_V(INFO, TAG, "PE state %d. Ignoring request with uri, %s for method, %d",
177 g_policyEngineContext.state, requestInfo->info.resourceUri, requestInfo->method);
180 if (IsAccessGranted(response) && gRequestHandler)
182 return (gRequestHandler(endPoint, requestInfo));
185 // Form a 'Error', 'slow response' or 'access deny' response and send to peer
186 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
187 memcpy(&responseInfo.info, &(requestInfo->info), sizeof(responseInfo.info));
188 responseInfo.info.payload = NULL;
190 VERIFY_NON_NULL(TAG, gRequestHandler, ERROR);
192 if(ACCESS_WAITING_FOR_AMS == response)
194 OIC_LOG(INFO, TAG, "Sending slow response");
196 UpdateAmsMgrContext(&g_policyEngineContext, endPoint, requestInfo);
197 responseInfo.result = CA_EMPTY;
198 responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
203 * TODO Enhance this logic more to decide between
204 * CA_UNAUTHORIZED_REQ or CA_FORBIDDEN_REQ depending
205 * upon SRMAccessResponseReasonCode_t
207 OIC_LOG(INFO, TAG, "Sending for regular response");
208 responseInfo.result = CA_UNAUTHORIZED_REQ;
211 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
213 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
217 responseInfo.result = CA_INTERNAL_SERVER_ERROR;
218 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
220 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
225 * @brief Handle the response from the SRM.
226 * @param endPoint [IN] The remote endpoint.
227 * @param responseInfo [IN] Response information from the endpoint.
230 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
232 OIC_LOG(DEBUG, TAG, "Received response from remote device");
234 // isProvResponse flag is to check whether response is catered by provisioning APIs or not.
235 // When token sent by CA response matches with token generated by provisioning request,
236 // gSPResponseHandler returns true and response is not sent to RI layer. In case
237 // gSPResponseHandler is null and isProvResponse is false response then the response is for
239 bool isProvResponse = false;
241 if (gSPResponseHandler)
243 isProvResponse = gSPResponseHandler(endPoint, responseInfo);
245 if (!isProvResponse && gResponseHandler)
247 gResponseHandler(endPoint, responseInfo);
253 * @brief Handle the error from the SRM.
254 * @param endPoint [IN] The remote endpoint.
255 * @param errorInfo [IN] Error information from the endpoint.
258 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
260 OIC_LOG_V(INFO, TAG, "Received error from remote device with result, %d for request uri, %s",
261 errorInfo->result, errorInfo->info.resourceUri);
264 gErrorHandler(endPoint, errorInfo);
270 * @brief Register request and response callbacks.
271 * Requests and responses are delivered in these callbacks.
272 * @param reqHandler [IN] Request handler callback ( for GET,PUT ..etc)
273 * @param respHandler [IN] Response handler callback.
275 * OC_STACK_OK - No errors; Success
276 * OC_STACK_INVALID_PARAM - invalid parameter
278 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
279 CAResponseCallback respHandler,
280 CAErrorCallback errHandler)
282 OIC_LOG(DEBUG, TAG, "SRMRegisterHandler !!");
283 if( !reqHandler || !respHandler || !errHandler)
285 OIC_LOG(ERROR, TAG, "Callback handlers are invalid");
286 return OC_STACK_INVALID_PARAM;
288 gRequestHandler = reqHandler;
289 gResponseHandler = respHandler;
290 gErrorHandler = errHandler;
293 #if defined(__WITH_DTLS__)
294 CARegisterHandler(SRMRequestHandler, SRMResponseHandler, SRMErrorHandler);
296 CARegisterHandler(reqHandler, respHandler, errHandler);
297 #endif /* __WITH_DTLS__ */
302 * @brief Register Persistent storage callback.
303 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
305 * OC_STACK_OK - No errors; Success
306 * OC_STACK_INVALID_PARAM - Invalid parameter
308 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
310 OIC_LOG(DEBUG, TAG, "SRMRegisterPersistentStorageHandler !!");
311 if(!persistentStorageHandler)
313 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
314 return OC_STACK_INVALID_PARAM;
316 gPersistentStorageHandler = persistentStorageHandler;
321 * @brief Get Persistent storage handler pointer.
323 * The pointer to Persistent Storage callback handler
326 OCPersistentStorage* SRMGetPersistentStorageHandler()
328 return gPersistentStorageHandler;
333 * @brief Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
334 * @retval OC_STACK_OK for Success, otherwise some error value
336 OCStackResult SRMInitSecureResources()
338 // TODO: temporarily returning OC_STACK_OK every time until default
339 // behavior (for when SVR DB is missing) is settled.
340 InitSecureResources();
341 OCStackResult ret = OC_STACK_OK;
342 #if defined(__WITH_DTLS__)
343 if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
345 OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
346 ret = OC_STACK_ERROR;
349 #endif // (__WITH_DTLS__)
350 #if defined(__WITH_X509__)
351 CARegisterDTLSX509CredentialsHandler(GetDtlsX509Credentials);
352 CARegisterDTLSCrlHandler(GetDerCrl);
353 #endif // (__WITH_X509__)
359 * @brief Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
362 void SRMDeInitSecureResources()
364 DestroySecureResources();
368 * @brief Initialize Policy Engine.
369 * @return OC_STACK_OK for Success, otherwise some error value.
371 OCStackResult SRMInitPolicyEngine()
373 return InitPolicyEngine(&g_policyEngineContext);
377 * @brief Cleanup Policy Engine.
380 void SRMDeInitPolicyEngine()
382 return DeInitPolicyEngine(&g_policyEngineContext);
386 * @brief Check the security resource URI.
387 * @param uri [IN] Pointers to security resource URI.
388 * @return true if the URI is one of security resources, otherwise false.
390 bool SRMIsSecurityResourceURI(const char* uri)
397 const char *rsrcs[] = {
406 OIC_RSRC_DPAIRING_URI,
409 // Remove query from Uri for resource string comparison
410 size_t uriLen = strlen(uri);
411 char *query = strchr (uri, '?');
414 uriLen = query - uri;
417 for (size_t i = 0; i < sizeof(rsrcs)/sizeof(rsrcs[0]); i++)
419 size_t svrLen = strlen(rsrcs[i]);
421 if ((uriLen == svrLen) &&
422 (strncmp(uri, rsrcs[i], svrLen) == 0))