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 * Function to register provisoning API's response callback.
61 * @param respHandler response handler callback.
63 void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler)
65 gSPResponseHandler = respHandler;
68 void SetResourceRequestType(PEContext_t *context, const char *resourceUri)
70 context->resourceType = GetSvrTypeFromUri(resourceUri);
73 static void SRMSendUnAuthorizedAccessresponse(PEContext_t *context)
75 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
77 if (NULL == context ||
78 NULL == context->amsMgrContext->requestInfo)
80 OIC_LOG_V(ERROR, TAG, "%s : NULL Parameter(s)",__func__);
84 memcpy(&responseInfo.info, &(context->amsMgrContext->requestInfo->info),
85 sizeof(responseInfo.info));
86 responseInfo.info.payload = NULL;
87 responseInfo.result = CA_UNAUTHORIZED_REQ;
89 if (CA_STATUS_OK == CASendResponse(context->amsMgrContext->endpoint, &responseInfo))
91 OIC_LOG(DEBUG, TAG, "Succeed in sending response to a unauthorized request!");
95 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
99 void SRMSendResponse(SRMAccessResponse_t responseVal)
101 OIC_LOG(DEBUG, TAG, "Sending response to remote device");
103 if (IsAccessGranted(responseVal) && gRequestHandler)
105 OIC_LOG_V(INFO, TAG, "%s : Access granted. Passing Request to RI layer", __func__);
106 if (!g_policyEngineContext.amsMgrContext->endpoint ||
107 !g_policyEngineContext.amsMgrContext->requestInfo)
109 OIC_LOG_V(ERROR, TAG, "%s : Invalid arguments", __func__);
110 SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
113 gRequestHandler(g_policyEngineContext.amsMgrContext->endpoint,
114 g_policyEngineContext.amsMgrContext->requestInfo);
118 OIC_LOG_V(INFO, TAG, "%s : ACCESS_DENIED.", __func__);
119 SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
123 //Resetting PE state to AWAITING_REQUEST
124 SetPolicyEngineState(&g_policyEngineContext, AWAITING_REQUEST);
128 * Handle the request from the SRM.
130 * @param endPoint object from which the response is received.
131 * @param requestInfo contains information for the request.
133 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
135 OIC_LOG(DEBUG, TAG, "Received request from remote device");
137 if (!endPoint || !requestInfo)
139 OIC_LOG(ERROR, TAG, "Invalid arguments");
143 // Copy the subjectID
144 OicUuid_t subjectId = {.id = {0}};
145 memcpy(subjectId.id, requestInfo->info.identity.id, sizeof(subjectId.id));
147 //Check the URI has the query and skip it before checking the permission
148 char *uri = strstr(requestInfo->info.resourceUri, "?");
152 //Skip query and pass the resource uri
153 position = uri - requestInfo->info.resourceUri;
157 position = strlen(requestInfo->info.resourceUri);
159 if (MAX_URI_LENGTH < position || 0 > position)
161 OIC_LOG(ERROR, TAG, "Incorrect URI length");
164 SRMAccessResponse_t response = ACCESS_DENIED;
165 char newUri[MAX_URI_LENGTH + 1];
166 OICStrcpyPartial(newUri, MAX_URI_LENGTH + 1, requestInfo->info.resourceUri, position);
168 SetResourceRequestType(&g_policyEngineContext, newUri);
170 //New request are only processed if the policy engine state is AWAITING_REQUEST.
171 if (AWAITING_REQUEST == g_policyEngineContext.state)
173 OIC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method, %d",
174 requestInfo->info.resourceUri, requestInfo->method);
175 response = CheckPermission(&g_policyEngineContext, &subjectId, newUri,
176 GetPermissionFromCAMethod_t(requestInfo->method));
180 OIC_LOG_V(INFO, TAG, "PE state %d. Ignoring request with uri, %s for method, %d",
181 g_policyEngineContext.state, requestInfo->info.resourceUri, requestInfo->method);
184 if (IsAccessGranted(response) && gRequestHandler)
186 return (gRequestHandler(endPoint, requestInfo));
189 // Form a 'Error', 'slow response' or 'access deny' response and send to peer
190 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
191 memcpy(&responseInfo.info, &(requestInfo->info), sizeof(responseInfo.info));
192 responseInfo.info.payload = NULL;
194 VERIFY_NON_NULL(TAG, gRequestHandler, ERROR);
196 if (ACCESS_WAITING_FOR_AMS == response)
198 OIC_LOG(INFO, TAG, "Sending slow response");
200 UpdateAmsMgrContext(&g_policyEngineContext, endPoint, requestInfo);
201 responseInfo.result = CA_EMPTY;
202 responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
207 * TODO Enhance this logic more to decide between
208 * CA_UNAUTHORIZED_REQ or CA_FORBIDDEN_REQ depending
209 * upon SRMAccessResponseReasonCode_t
211 OIC_LOG(INFO, TAG, "Sending for regular response");
212 responseInfo.result = CA_UNAUTHORIZED_REQ;
215 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
217 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
221 responseInfo.result = CA_INTERNAL_SERVER_ERROR;
222 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
224 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
229 * Handle the response from the SRM.
231 * @param endPoint points to the remote endpoint.
232 * @param responseInfo contains response information from the endpoint.
234 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
236 OIC_LOG(DEBUG, TAG, "Received response from remote device");
238 // isProvResponse flag is to check whether response is catered by provisioning APIs or not.
239 // When token sent by CA response matches with token generated by provisioning request,
240 // gSPResponseHandler returns true and response is not sent to RI layer. In case
241 // gSPResponseHandler is null and isProvResponse is false response then the response is for
243 bool isProvResponse = false;
245 if (gSPResponseHandler)
247 isProvResponse = gSPResponseHandler(endPoint, responseInfo);
249 if (!isProvResponse && gResponseHandler)
251 gResponseHandler(endPoint, responseInfo);
256 * Handle the error from the SRM.
258 * @param endPoint is the remote endpoint.
259 * @param errorInfo contains error information from the endpoint.
261 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
263 OIC_LOG_V(INFO, TAG, "Received error from remote device with result, %d for request uri, %s",
264 errorInfo->result, errorInfo->info.resourceUri);
267 gErrorHandler(endPoint, errorInfo);
271 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
272 CAResponseCallback respHandler,
273 CAErrorCallback errHandler)
275 OIC_LOG(DEBUG, TAG, "SRMRegisterHandler !!");
276 if( !reqHandler || !respHandler || !errHandler)
278 OIC_LOG(ERROR, TAG, "Callback handlers are invalid");
279 return OC_STACK_INVALID_PARAM;
281 gRequestHandler = reqHandler;
282 gResponseHandler = respHandler;
283 gErrorHandler = errHandler;
286 #if defined(__WITH_DTLS__)
287 CARegisterHandler(SRMRequestHandler, SRMResponseHandler, SRMErrorHandler);
289 CARegisterHandler(reqHandler, respHandler, errHandler);
290 #endif /* __WITH_DTLS__ */
294 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
296 OIC_LOG(DEBUG, TAG, "SRMRegisterPersistentStorageHandler !!");
297 if(!persistentStorageHandler)
299 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
300 return OC_STACK_INVALID_PARAM;
302 gPersistentStorageHandler = persistentStorageHandler;
306 OCPersistentStorage* SRMGetPersistentStorageHandler()
308 return gPersistentStorageHandler;
311 OCStackResult SRMInitSecureResources()
313 // TODO: temporarily returning OC_STACK_OK every time until default
314 // behavior (for when SVR DB is missing) is settled.
315 InitSecureResources();
316 OCStackResult ret = OC_STACK_OK;
317 #if defined(__WITH_DTLS__)
318 if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
320 OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
321 ret = OC_STACK_ERROR;
324 #endif // (__WITH_DTLS__)
325 #if defined(__WITH_X509__)
326 CARegisterDTLSX509CredentialsHandler(GetDtlsX509Credentials);
327 CARegisterDTLSCrlHandler(GetDerCrl);
328 #endif // (__WITH_X509__)
333 void SRMDeInitSecureResources()
335 DestroySecureResources();
338 OCStackResult SRMInitPolicyEngine()
340 return InitPolicyEngine(&g_policyEngineContext);
343 void SRMDeInitPolicyEngine()
345 return DeInitPolicyEngine(&g_policyEngineContext);
348 bool SRMIsSecurityResourceURI(const char* uri)
355 const char *rsrcs[] = {
364 OIC_RSRC_DPAIRING_URI,
368 // Remove query from Uri for resource string comparison
369 size_t uriLen = strlen(uri);
370 char *query = strchr (uri, '?');
373 uriLen = query - uri;
376 for (size_t i = 0; i < sizeof(rsrcs)/sizeof(rsrcs[0]); i++)
378 size_t svrLen = strlen(rsrcs[i]);
380 if ((uriLen == svrLen) &&
381 (strncmp(uri, rsrcs[i], svrLen) == 0))
391 * Get the Secure Virtual Resource (SVR) type from the URI.
392 * @param uri [IN] Pointer to URI in question.
393 * @return The OicSecSvrType_t of the URI passed (note: if not a Secure Virtual
394 Resource, e.g. /a/light, will return "NOT_A_SVR_TYPE" enum value)
396 static const char URI_QUERY_CHAR = '?';
397 OicSecSvrType_t GetSvrTypeFromUri(const char* uri)
401 return NOT_A_SVR_RESOURCE;
404 // Remove query from Uri for resource string comparison
405 size_t uriLen = strlen(uri);
406 char *query = strchr (uri, URI_QUERY_CHAR);
409 uriLen = query - uri;
414 svrLen = strlen(OIC_RSRC_ACL_URI);
417 if(0 == strncmp(uri, OIC_RSRC_ACL_URI, svrLen))
419 return OIC_R_ACL_TYPE;
423 svrLen = strlen(OIC_RSRC_AMACL_URI);
426 if(0 == strncmp(uri, OIC_RSRC_AMACL_URI, svrLen))
428 return OIC_R_AMACL_TYPE;
432 svrLen = strlen(OIC_RSRC_CRED_URI);
435 if(0 == strncmp(uri, OIC_RSRC_CRED_URI, svrLen))
437 return OIC_R_CRED_TYPE;
441 svrLen = strlen(OIC_RSRC_CRL_URI);
444 if(0 == strncmp(uri, OIC_RSRC_CRL_URI, svrLen))
446 return OIC_R_CRL_TYPE;
450 svrLen = strlen(OIC_RSRC_DOXM_URI);
453 if(0 == strncmp(uri, OIC_RSRC_DOXM_URI, svrLen))
455 return OIC_R_DOXM_TYPE;
459 svrLen = strlen(OIC_RSRC_DPAIRING_URI);
462 if(0 == strncmp(uri, OIC_RSRC_DPAIRING_URI, svrLen))
464 return OIC_R_DPAIRING_TYPE;
468 svrLen = strlen(OIC_RSRC_PCONF_URI);
471 if(0 == strncmp(uri, OIC_RSRC_PCONF_URI, svrLen))
473 return OIC_R_PCONF_TYPE;
477 svrLen = strlen(OIC_RSRC_PSTAT_URI);
480 if(0 == strncmp(uri, OIC_RSRC_PSTAT_URI, svrLen))
482 return OIC_R_PSTAT_TYPE;
486 svrLen = strlen(OIC_RSRC_SVC_URI);
489 if(0 == strncmp(uri, OIC_RSRC_SVC_URI, svrLen))
491 return OIC_R_SVC_TYPE;
495 svrLen = strlen(OIC_RSRC_SACL_URI);
498 if(0 == strncmp(uri, OIC_RSRC_SACL_URI, svrLen))
500 return OIC_R_SACL_TYPE;
504 return NOT_A_SVR_RESOURCE;