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"
36 #include "pkix_interface.h"
41 #include "crlresource.h"
42 #endif // __WITH_X509__
44 //Request Callback handler
45 static CARequestCallback gRequestHandler = NULL;
46 //Response Callback handler
47 static CAResponseCallback gResponseHandler = NULL;
48 //Error Callback handler
49 static CAErrorCallback gErrorHandler = NULL;
50 //Persistent Storage callback handler for open/read/write/close/unlink
51 static OCPersistentStorage *gPersistentStorageHandler = NULL;
52 //Provisioning response callback
53 static SPResponseCallback gSPResponseHandler = NULL;
56 * A single global Policy Engine context will suffice as long
57 * as SRM is single-threaded.
59 PEContext_t g_policyEngineContext;
62 * Function to register provisoning API's response callback.
63 * @param respHandler response handler callback.
65 void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler)
67 gSPResponseHandler = respHandler;
70 void SetResourceRequestType(PEContext_t *context, const char *resourceUri)
72 context->resourceType = GetSvrTypeFromUri(resourceUri);
75 static void SRMSendUnAuthorizedAccessresponse(PEContext_t *context)
77 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
79 if (NULL == context ||
80 NULL == context->amsMgrContext->requestInfo)
82 OIC_LOG_V(ERROR, TAG, "%s : NULL Parameter(s)",__func__);
86 memcpy(&responseInfo.info, &(context->amsMgrContext->requestInfo->info),
87 sizeof(responseInfo.info));
88 responseInfo.info.payload = NULL;
89 responseInfo.result = CA_UNAUTHORIZED_REQ;
90 responseInfo.info.dataType = CA_RESPONSE_DATA;
92 if (CA_STATUS_OK == CASendResponse(context->amsMgrContext->endpoint, &responseInfo))
94 OIC_LOG(DEBUG, TAG, "Succeed in sending response to a unauthorized request!");
98 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
102 void SRMSendResponse(SRMAccessResponse_t responseVal)
104 OIC_LOG(DEBUG, TAG, "Sending response to remote device");
106 if (IsAccessGranted(responseVal) && gRequestHandler)
108 OIC_LOG_V(INFO, TAG, "%s : Access granted. Passing Request to RI layer", __func__);
109 if (!g_policyEngineContext.amsMgrContext->endpoint ||
110 !g_policyEngineContext.amsMgrContext->requestInfo)
112 OIC_LOG_V(ERROR, TAG, "%s : Invalid arguments", __func__);
113 SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
116 gRequestHandler(g_policyEngineContext.amsMgrContext->endpoint,
117 g_policyEngineContext.amsMgrContext->requestInfo);
121 OIC_LOG_V(INFO, TAG, "%s : ACCESS_DENIED.", __func__);
122 SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
126 //Resetting PE state to AWAITING_REQUEST
127 SetPolicyEngineState(&g_policyEngineContext, AWAITING_REQUEST);
131 * Handle the request from the SRM.
133 * @param endPoint object from which the response is received.
134 * @param requestInfo contains information for the request.
136 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
138 OIC_LOG(DEBUG, TAG, "Received request from remote device");
140 if (!endPoint || !requestInfo)
142 OIC_LOG(ERROR, TAG, "Invalid arguments");
146 // Copy the subjectID
147 OicUuid_t subjectId = {.id = {0}};
148 memcpy(subjectId.id, requestInfo->info.identity.id, sizeof(subjectId.id));
150 //Check the URI has the query and skip it before checking the permission
151 char *uri = strstr(requestInfo->info.resourceUri, "?");
155 //Skip query and pass the resource uri
156 position = uri - requestInfo->info.resourceUri;
160 position = strlen(requestInfo->info.resourceUri);
162 if (MAX_URI_LENGTH < position || 0 > position)
164 OIC_LOG(ERROR, TAG, "Incorrect URI length");
167 SRMAccessResponse_t response = ACCESS_DENIED;
168 char newUri[MAX_URI_LENGTH + 1];
169 OICStrcpyPartial(newUri, MAX_URI_LENGTH + 1, requestInfo->info.resourceUri, position);
171 SetResourceRequestType(&g_policyEngineContext, newUri);
173 //New request are only processed if the policy engine state is AWAITING_REQUEST.
174 if (AWAITING_REQUEST == g_policyEngineContext.state)
176 OIC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method, %d",
177 requestInfo->info.resourceUri, requestInfo->method);
178 response = CheckPermission(&g_policyEngineContext, &subjectId, newUri,
179 GetPermissionFromCAMethod_t(requestInfo->method));
183 OIC_LOG_V(INFO, TAG, "PE state %d. Ignoring request with uri, %s for method, %d",
184 g_policyEngineContext.state, requestInfo->info.resourceUri, requestInfo->method);
187 if (IsAccessGranted(response) && gRequestHandler)
189 gRequestHandler(endPoint, requestInfo);
193 // Form a 'Error', 'slow response' or 'access deny' response and send to peer
194 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
195 memcpy(&responseInfo.info, &(requestInfo->info), sizeof(responseInfo.info));
196 responseInfo.info.payload = NULL;
197 responseInfo.info.dataType = CA_RESPONSE_DATA;
199 VERIFY_NON_NULL(TAG, gRequestHandler, ERROR);
201 if (ACCESS_WAITING_FOR_AMS == response)
203 OIC_LOG(INFO, TAG, "Sending slow response");
205 UpdateAmsMgrContext(&g_policyEngineContext, endPoint, requestInfo);
206 responseInfo.result = CA_EMPTY;
207 responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
212 * TODO Enhance this logic more to decide between
213 * CA_UNAUTHORIZED_REQ or CA_FORBIDDEN_REQ depending
214 * upon SRMAccessResponseReasonCode_t
216 OIC_LOG(INFO, TAG, "Sending for regular response");
217 responseInfo.result = CA_UNAUTHORIZED_REQ;
220 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
222 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
226 responseInfo.result = CA_INTERNAL_SERVER_ERROR;
227 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
229 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
234 * Handle the response from the SRM.
236 * @param endPoint points to the remote endpoint.
237 * @param responseInfo contains response information from the endpoint.
239 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
241 OIC_LOG(DEBUG, TAG, "Received response from remote device");
243 // isProvResponse flag is to check whether response is catered by provisioning APIs or not.
244 // When token sent by CA response matches with token generated by provisioning request,
245 // gSPResponseHandler returns true and response is not sent to RI layer. In case
246 // gSPResponseHandler is null and isProvResponse is false response then the response is for
248 bool isProvResponse = false;
250 if (gSPResponseHandler)
252 isProvResponse = gSPResponseHandler(endPoint, responseInfo);
254 if (!isProvResponse && gResponseHandler)
256 gResponseHandler(endPoint, responseInfo);
261 * Handle the error from the SRM.
263 * @param endPoint is the remote endpoint.
264 * @param errorInfo contains error information from the endpoint.
266 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
268 OIC_LOG_V(INFO, TAG, "Received error from remote device with result, %d for request uri, %s",
269 errorInfo->result, errorInfo->info.resourceUri);
272 gErrorHandler(endPoint, errorInfo);
276 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
277 CAResponseCallback respHandler,
278 CAErrorCallback errHandler)
280 OIC_LOG(DEBUG, TAG, "SRMRegisterHandler !!");
281 if( !reqHandler || !respHandler || !errHandler)
283 OIC_LOG(ERROR, TAG, "Callback handlers are invalid");
284 return OC_STACK_INVALID_PARAM;
286 gRequestHandler = reqHandler;
287 gResponseHandler = respHandler;
288 gErrorHandler = errHandler;
291 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
292 CARegisterHandler(SRMRequestHandler, SRMResponseHandler, SRMErrorHandler);
294 CARegisterHandler(reqHandler, respHandler, errHandler);
295 #endif /* __WITH_DTLS__ */
299 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
301 OIC_LOG(DEBUG, TAG, "SRMRegisterPersistentStorageHandler !!");
302 if(!persistentStorageHandler)
304 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
305 return OC_STACK_INVALID_PARAM;
307 gPersistentStorageHandler = persistentStorageHandler;
311 OCPersistentStorage* SRMGetPersistentStorageHandler()
313 return gPersistentStorageHandler;
316 OCStackResult SRMInitSecureResources()
318 // TODO: temporarily returning OC_STACK_OK every time until default
319 // behavior (for when SVR DB is missing) is settled.
320 InitSecureResources();
321 OCStackResult ret = OC_STACK_OK;
322 #if defined(__WITH_DTLS__)
323 if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
325 OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
326 ret = OC_STACK_ERROR;
330 if (CA_STATUS_OK != CAregisterTlsCredentialsHandler(GetDtlsPskCredentials))
332 OIC_LOG(ERROR, TAG, "Failed to revert TLS credential handler.");
333 ret = OC_STACK_ERROR;
335 CAregisterPkixInfoHandler(GetPkixInfo);
336 CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
338 #if defined(__WITH_X509__)
339 CARegisterDTLSX509CredentialsHandler(GetDtlsX509Credentials);
340 CARegisterDTLSCrlHandler(GetDerCrl);
341 #endif // (__WITH_X509__)
346 void SRMDeInitSecureResources()
348 DestroySecureResources();
351 OCStackResult SRMInitPolicyEngine()
353 return InitPolicyEngine(&g_policyEngineContext);
356 void SRMDeInitPolicyEngine()
358 DeInitPolicyEngine(&g_policyEngineContext);
361 bool SRMIsSecurityResourceURI(const char* uri)
368 const char *rsrcs[] = {
377 OIC_RSRC_DPAIRING_URI,
379 OC_RSRVD_PROV_CRL_URL
382 // Remove query from Uri for resource string comparison
383 size_t uriLen = strlen(uri);
384 char *query = strchr (uri, '?');
387 uriLen = query - uri;
390 for (size_t i = 0; i < sizeof(rsrcs)/sizeof(rsrcs[0]); i++)
392 size_t svrLen = strlen(rsrcs[i]);
394 if ((uriLen == svrLen) &&
395 (strncmp(uri, rsrcs[i], svrLen) == 0))
405 * Get the Secure Virtual Resource (SVR) type from the URI.
406 * @param uri [IN] Pointer to URI in question.
407 * @return The OicSecSvrType_t of the URI passed (note: if not a Secure Virtual
408 Resource, e.g. /a/light, will return "NOT_A_SVR_TYPE" enum value)
410 static const char URI_QUERY_CHAR = '?';
411 OicSecSvrType_t GetSvrTypeFromUri(const char* uri)
415 return NOT_A_SVR_RESOURCE;
418 // Remove query from Uri for resource string comparison
419 size_t uriLen = strlen(uri);
420 char *query = strchr (uri, URI_QUERY_CHAR);
423 uriLen = query - uri;
428 svrLen = strlen(OIC_RSRC_ACL_URI);
431 if(0 == strncmp(uri, OIC_RSRC_ACL_URI, svrLen))
433 return OIC_R_ACL_TYPE;
437 svrLen = strlen(OIC_RSRC_AMACL_URI);
440 if(0 == strncmp(uri, OIC_RSRC_AMACL_URI, svrLen))
442 return OIC_R_AMACL_TYPE;
446 svrLen = strlen(OIC_RSRC_CRED_URI);
449 if(0 == strncmp(uri, OIC_RSRC_CRED_URI, svrLen))
451 return OIC_R_CRED_TYPE;
455 svrLen = strlen(OIC_RSRC_CRL_URI);
458 if(0 == strncmp(uri, OIC_RSRC_CRL_URI, svrLen))
460 return OIC_R_CRL_TYPE;
464 svrLen = strlen(OIC_RSRC_DOXM_URI);
467 if(0 == strncmp(uri, OIC_RSRC_DOXM_URI, svrLen))
469 return OIC_R_DOXM_TYPE;
473 svrLen = strlen(OIC_RSRC_DPAIRING_URI);
476 if(0 == strncmp(uri, OIC_RSRC_DPAIRING_URI, svrLen))
478 return OIC_R_DPAIRING_TYPE;
482 svrLen = strlen(OIC_RSRC_PCONF_URI);
485 if(0 == strncmp(uri, OIC_RSRC_PCONF_URI, svrLen))
487 return OIC_R_PCONF_TYPE;
491 svrLen = strlen(OIC_RSRC_PSTAT_URI);
494 if(0 == strncmp(uri, OIC_RSRC_PSTAT_URI, svrLen))
496 return OIC_R_PSTAT_TYPE;
500 svrLen = strlen(OIC_RSRC_SVC_URI);
503 if(0 == strncmp(uri, OIC_RSRC_SVC_URI, svrLen))
505 return OIC_R_SVC_TYPE;
509 svrLen = strlen(OIC_RSRC_SACL_URI);
512 if(0 == strncmp(uri, OIC_RSRC_SACL_URI, svrLen))
514 return OIC_R_SACL_TYPE;
518 return NOT_A_SVR_RESOURCE;