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;
59 static void SRMSendUnAuthorizedAccessresponse(PEContext_t *context)
61 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
63 if (NULL == context ||
64 NULL == context->amsMgrContext->requestInfo)
66 OIC_LOG_V(ERROR, TAG, "%s : NULL Parameter(s)",__func__);
70 memcpy(&responseInfo.info, &(context->amsMgrContext->requestInfo->info),
71 sizeof(responseInfo.info));
72 responseInfo.info.payload = NULL;
73 responseInfo.result = CA_UNAUTHORIZED_REQ;
75 if (CA_STATUS_OK == CASendResponse(context->amsMgrContext->endpoint, &responseInfo))
77 OIC_LOG(DEBUG, TAG, "Succeed in sending response to a unauthorized request!");
81 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
85 void SRMSendResponse(SRMAccessResponse_t responseVal)
87 OIC_LOG(DEBUG, TAG, "Sending response to remote device");
89 if (IsAccessGranted(responseVal) && gRequestHandler)
91 OIC_LOG_V(INFO, TAG, "%s : Access granted. Passing Request to RI layer", __func__);
92 if (!g_policyEngineContext.amsMgrContext->endpoint ||
93 !g_policyEngineContext.amsMgrContext->requestInfo)
95 OIC_LOG_V(ERROR, TAG, "%s : Invalid arguments", __func__);
96 SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
99 gRequestHandler(g_policyEngineContext.amsMgrContext->endpoint,
100 g_policyEngineContext.amsMgrContext->requestInfo);
104 OIC_LOG_V(INFO, TAG, "%s : ACCESS_DENIED.", __func__);
105 SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
109 //Resetting PE state to AWAITING_REQUEST
110 SetPolicyEngineState(&g_policyEngineContext, AWAITING_REQUEST);
114 * Handle the request from the SRM.
116 * @param endPoint object from which the response is received.
117 * @param requestInfo contains information for the request.
119 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
121 OIC_LOG(DEBUG, TAG, "Received request from remote device");
123 if (!endPoint || !requestInfo)
125 OIC_LOG(ERROR, TAG, "Invalid arguments");
129 // Copy the subjectID
130 OicUuid_t subjectId = {.id = {0}};
131 memcpy(subjectId.id, requestInfo->info.identity.id, sizeof(subjectId.id));
133 //Check the URI has the query and skip it before checking the permission
134 char *uri = strstr(requestInfo->info.resourceUri, "?");
138 //Skip query and pass the resource uri
139 position = uri - requestInfo->info.resourceUri;
143 position = strlen(requestInfo->info.resourceUri);
145 if (MAX_URI_LENGTH < position || 0 > position)
147 OIC_LOG(ERROR, TAG, "Incorrect URI length");
150 SRMAccessResponse_t response = ACCESS_DENIED;
151 char newUri[MAX_URI_LENGTH + 1];
152 OICStrcpyPartial(newUri, MAX_URI_LENGTH + 1, requestInfo->info.resourceUri, position);
154 //New request are only processed if the policy engine state is AWAITING_REQUEST.
155 if (AWAITING_REQUEST == g_policyEngineContext.state)
157 OIC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method, %d",
158 requestInfo->info.resourceUri, requestInfo->method);
159 response = CheckPermission(&g_policyEngineContext, &subjectId, newUri,
160 GetPermissionFromCAMethod_t(requestInfo->method));
164 OIC_LOG_V(INFO, TAG, "PE state %d. Ignoring request with uri, %s for method, %d",
165 g_policyEngineContext.state, requestInfo->info.resourceUri, requestInfo->method);
168 if (IsAccessGranted(response) && gRequestHandler)
170 return (gRequestHandler(endPoint, requestInfo));
173 // Form a 'Error', 'slow response' or 'access deny' response and send to peer
174 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
175 memcpy(&responseInfo.info, &(requestInfo->info), sizeof(responseInfo.info));
176 responseInfo.info.payload = NULL;
178 VERIFY_NON_NULL(TAG, gRequestHandler, ERROR);
180 if (ACCESS_WAITING_FOR_AMS == response)
182 OIC_LOG(INFO, TAG, "Sending slow response");
184 UpdateAmsMgrContext(&g_policyEngineContext, endPoint, requestInfo);
185 responseInfo.result = CA_EMPTY;
186 responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
191 * TODO Enhance this logic more to decide between
192 * CA_UNAUTHORIZED_REQ or CA_FORBIDDEN_REQ depending
193 * upon SRMAccessResponseReasonCode_t
195 OIC_LOG(INFO, TAG, "Sending for regular response");
196 responseInfo.result = CA_UNAUTHORIZED_REQ;
199 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
201 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
205 responseInfo.result = CA_INTERNAL_SERVER_ERROR;
206 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
208 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
213 * Handle the response from the SRM.
215 * @param endPoint points to the remote endpoint.
216 * @param responseInfo contains response information from the endpoint.
218 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
220 OIC_LOG(DEBUG, TAG, "Received response from remote device");
222 // isProvResponse flag is to check whether response is catered by provisioning APIs or not.
223 // When token sent by CA response matches with token generated by provisioning request,
224 // gSPResponseHandler returns true and response is not sent to RI layer. In case
225 // gSPResponseHandler is null and isProvResponse is false response then the response is for
227 bool isProvResponse = false;
229 if (gSPResponseHandler)
231 isProvResponse = gSPResponseHandler(endPoint, responseInfo);
233 if (!isProvResponse && gResponseHandler)
235 gResponseHandler(endPoint, responseInfo);
240 * Handle the error from the SRM.
242 * @param endPoint is the remote endpoint.
243 * @param errorInfo contains error information from the endpoint.
245 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
247 OIC_LOG_V(INFO, TAG, "Received error from remote device with result, %d for request uri, %s",
248 errorInfo->result, errorInfo->info.resourceUri);
251 gErrorHandler(endPoint, errorInfo);
255 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
256 CAResponseCallback respHandler,
257 CAErrorCallback errHandler)
259 OIC_LOG(DEBUG, TAG, "SRMRegisterHandler !!");
260 if( !reqHandler || !respHandler || !errHandler)
262 OIC_LOG(ERROR, TAG, "Callback handlers are invalid");
263 return OC_STACK_INVALID_PARAM;
265 gRequestHandler = reqHandler;
266 gResponseHandler = respHandler;
267 gErrorHandler = errHandler;
270 #if defined(__WITH_DTLS__)
271 CARegisterHandler(SRMRequestHandler, SRMResponseHandler, SRMErrorHandler);
273 CARegisterHandler(reqHandler, respHandler, errHandler);
274 #endif /* __WITH_DTLS__ */
278 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
280 OIC_LOG(DEBUG, TAG, "SRMRegisterPersistentStorageHandler !!");
281 if(!persistentStorageHandler)
283 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
284 return OC_STACK_INVALID_PARAM;
286 gPersistentStorageHandler = persistentStorageHandler;
290 OCPersistentStorage* SRMGetPersistentStorageHandler()
292 return gPersistentStorageHandler;
295 OCStackResult SRMInitSecureResources()
297 // TODO: temporarily returning OC_STACK_OK every time until default
298 // behavior (for when SVR DB is missing) is settled.
299 InitSecureResources();
300 OCStackResult ret = OC_STACK_OK;
301 #if defined(__WITH_DTLS__)
302 if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
304 OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
305 ret = OC_STACK_ERROR;
308 #endif // (__WITH_DTLS__)
309 #if defined(__WITH_X509__)
310 CARegisterDTLSX509CredentialsHandler(GetDtlsX509Credentials);
311 CARegisterDTLSCrlHandler(GetDerCrl);
312 #endif // (__WITH_X509__)
317 void SRMDeInitSecureResources()
319 DestroySecureResources();
322 OCStackResult SRMInitPolicyEngine()
324 return InitPolicyEngine(&g_policyEngineContext);
327 void SRMDeInitPolicyEngine()
329 return DeInitPolicyEngine(&g_policyEngineContext);
332 bool SRMIsSecurityResourceURI(const char* uri)
339 const char *rsrcs[] = {
348 OIC_RSRC_DPAIRING_URI,
351 // Remove query from Uri for resource string comparison
352 size_t uriLen = strlen(uri);
353 char *query = strchr (uri, '?');
356 uriLen = query - uri;
359 for (size_t i = 0; i < sizeof(rsrcs)/sizeof(rsrcs[0]); i++)
361 size_t svrLen = strlen(rsrcs[i]);
363 if ((uriLen == svrLen) &&
364 (strncmp(uri, rsrcs[i], svrLen) == 0))