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"
35 #include "ocresourcehandler.h"
37 #if defined( __WITH_TLS__) || defined(__WITH_DTLS__)
38 #include "pkix_interface.h"
39 #endif //__WITH_TLS__ or __WITH_DTLS__
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 //Provisioning response callback
49 static SPResponseCallback gSPResponseHandler = NULL;
52 * A single global Policy Engine context will suffice as long
53 * as SRM is single-threaded.
55 PEContext_t g_policyEngineContext;
58 * Function to register provisoning API's response callback.
59 * @param respHandler response handler callback.
61 void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler)
63 gSPResponseHandler = respHandler;
66 void SetResourceRequestType(PEContext_t *context, const char *resourceUri)
68 context->resourceType = GetSvrTypeFromUri(resourceUri);
71 static void SRMSendUnAuthorizedAccessresponse(PEContext_t *context)
73 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
75 if (NULL == context ||
76 NULL == context->amsMgrContext->requestInfo)
78 OIC_LOG_V(ERROR, TAG, "%s : NULL Parameter(s)",__func__);
82 memcpy(&responseInfo.info, &(context->amsMgrContext->requestInfo->info),
83 sizeof(responseInfo.info));
84 responseInfo.info.payload = NULL;
85 responseInfo.result = CA_UNAUTHORIZED_REQ;
86 responseInfo.info.dataType = CA_RESPONSE_DATA;
88 if (CA_STATUS_OK == CASendResponse(context->amsMgrContext->endpoint, &responseInfo))
90 OIC_LOG(DEBUG, TAG, "Succeed in sending response to a unauthorized request!");
94 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
98 void SRMSendResponse(SRMAccessResponse_t responseVal)
100 OIC_LOG(DEBUG, TAG, "Sending response to remote device");
102 if (IsAccessGranted(responseVal) && gRequestHandler)
104 OIC_LOG_V(INFO, TAG, "%s : Access granted. Passing Request to RI layer", __func__);
105 if (!g_policyEngineContext.amsMgrContext->endpoint ||
106 !g_policyEngineContext.amsMgrContext->requestInfo)
108 OIC_LOG_V(ERROR, TAG, "%s : Invalid arguments", __func__);
109 SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
112 gRequestHandler(g_policyEngineContext.amsMgrContext->endpoint,
113 g_policyEngineContext.amsMgrContext->requestInfo);
117 OIC_LOG_V(INFO, TAG, "%s : ACCESS_DENIED.", __func__);
118 SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
122 //Resetting PE state to AWAITING_REQUEST
123 SetPolicyEngineState(&g_policyEngineContext, AWAITING_REQUEST);
127 * Handle the request from the SRM.
129 * @param endPoint object from which the response is received.
130 * @param requestInfo contains information for the request.
132 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
134 OIC_LOG(DEBUG, TAG, "Received request from remote device");
136 bool isRequestOverSecureChannel = false;
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));
146 if (endPoint->flags & CA_SECURE)
148 OIC_LOG(INFO, TAG, "request over secure channel");
149 isRequestOverSecureChannel = true;
152 //Check the URI has the query and skip it before checking the permission
153 if (NULL == requestInfo->info.resourceUri)
155 OIC_LOG(ERROR, TAG, "Invalid resourceUri");
159 char *uri = strstr(requestInfo->info.resourceUri, "?");
163 //Skip query and pass the resource uri
164 position = uri - requestInfo->info.resourceUri;
168 position = strlen(requestInfo->info.resourceUri);
170 if (MAX_URI_LENGTH < position || 0 > position)
172 OIC_LOG(ERROR, TAG, "Incorrect URI length");
175 SRMAccessResponse_t response = ACCESS_DENIED;
176 char newUri[MAX_URI_LENGTH + 1];
177 OICStrcpyPartial(newUri, MAX_URI_LENGTH + 1, requestInfo->info.resourceUri, position);
179 SetResourceRequestType(&g_policyEngineContext, newUri);
181 // Form a 'Error', 'slow response' or 'access deny' response and send to peer
182 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
183 memcpy(&responseInfo.info, &(requestInfo->info), sizeof(responseInfo.info));
184 responseInfo.info.payload = NULL;
185 responseInfo.info.dataType = CA_RESPONSE_DATA;
187 OCResource *resPtr = FindResourceByUri(newUri);
190 // All vertical secure resources and SVR resources other than DOXM & PSTAT should reject request
192 if ((((resPtr->resourceProperties) & OC_SECURE)
193 && (g_policyEngineContext.resourceType == NOT_A_SVR_RESOURCE))
194 || ((g_policyEngineContext.resourceType < OIC_SEC_SVR_TYPE_COUNT)
195 && (g_policyEngineContext.resourceType != OIC_R_DOXM_TYPE)
196 && (g_policyEngineContext.resourceType != OIC_R_PSTAT_TYPE)))
198 // if resource is secure and request is over insecure channel
199 if (!isRequestOverSecureChannel)
201 // Reject all the requests over coap for secure resource.
202 responseInfo.result = CA_FORBIDDEN_REQ;
203 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
205 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
211 #ifdef MULTIPLE_OWNER
213 * In case of ACL and CRED, The payload required to verify the payload.
214 * Payload information will be used for subowner's permission verification.
216 g_policyEngineContext.payload = (uint8_t*)requestInfo->info.payload;
217 g_policyEngineContext.payloadSize = requestInfo->info.payloadSize;
218 #endif //MULTIPLE_OWNER
220 //New request are only processed if the policy engine state is AWAITING_REQUEST.
221 if (AWAITING_REQUEST == g_policyEngineContext.state)
223 OIC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method, %d",
224 requestInfo->info.resourceUri, requestInfo->method);
225 response = CheckPermission(&g_policyEngineContext, &subjectId, newUri,
226 GetPermissionFromCAMethod_t(requestInfo->method));
230 OIC_LOG_V(INFO, TAG, "PE state %d. Ignoring request with uri, %s for method, %d",
231 g_policyEngineContext.state, requestInfo->info.resourceUri, requestInfo->method);
234 if (IsAccessGranted(response) && gRequestHandler)
236 gRequestHandler(endPoint, requestInfo);
240 VERIFY_NON_NULL(TAG, gRequestHandler, ERROR);
242 if (ACCESS_WAITING_FOR_AMS == response)
244 OIC_LOG(INFO, TAG, "Sending slow response");
246 UpdateAmsMgrContext(&g_policyEngineContext, endPoint, requestInfo);
247 responseInfo.result = CA_EMPTY;
248 responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
253 * TODO Enhance this logic more to decide between
254 * CA_UNAUTHORIZED_REQ or CA_FORBIDDEN_REQ depending
255 * upon SRMAccessResponseReasonCode_t
257 OIC_LOG(INFO, TAG, "Sending for regular response");
258 responseInfo.result = CA_UNAUTHORIZED_REQ;
261 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
263 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
267 responseInfo.result = CA_INTERNAL_SERVER_ERROR;
268 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
270 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
275 * Handle the response from the SRM.
277 * @param endPoint points to the remote endpoint.
278 * @param responseInfo contains response information from the endpoint.
280 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
282 OIC_LOG(DEBUG, TAG, "Received response from remote device");
284 // isProvResponse flag is to check whether response is catered by provisioning APIs or not.
285 // When token sent by CA response matches with token generated by provisioning request,
286 // gSPResponseHandler returns true and response is not sent to RI layer. In case
287 // gSPResponseHandler is null and isProvResponse is false response then the response is for
289 bool isProvResponse = false;
291 if (gSPResponseHandler)
293 isProvResponse = gSPResponseHandler(endPoint, responseInfo);
295 if (!isProvResponse && gResponseHandler)
297 gResponseHandler(endPoint, responseInfo);
302 * Handle the error from the SRM.
304 * @param endPoint is the remote endpoint.
305 * @param errorInfo contains error information from the endpoint.
307 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
309 OIC_LOG_V(INFO, TAG, "Received error from remote device with result, %d for request uri, %s",
310 errorInfo->result, errorInfo->info.resourceUri);
313 gErrorHandler(endPoint, errorInfo);
317 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
318 CAResponseCallback respHandler,
319 CAErrorCallback errHandler)
321 OIC_LOG(DEBUG, TAG, "SRMRegisterHandler !!");
322 if( !reqHandler || !respHandler || !errHandler)
324 OIC_LOG(ERROR, TAG, "Callback handlers are invalid");
325 return OC_STACK_INVALID_PARAM;
327 gRequestHandler = reqHandler;
328 gResponseHandler = respHandler;
329 gErrorHandler = errHandler;
332 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
333 CARegisterHandler(SRMRequestHandler, SRMResponseHandler, SRMErrorHandler);
335 CARegisterHandler(reqHandler, respHandler, errHandler);
336 #endif /* __WITH_DTLS__ */
340 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
342 OIC_LOG(DEBUG, TAG, "SRMRegisterPersistentStorageHandler !!");
343 return OCRegisterPersistentStorageHandler(persistentStorageHandler);
346 OCPersistentStorage* SRMGetPersistentStorageHandler()
348 return OCGetPersistentStorageHandler();
351 OCStackResult SRMInitSecureResources()
353 // TODO: temporarily returning OC_STACK_OK every time until default
354 // behavior (for when SVR DB is missing) is settled.
355 InitSecureResources();
356 OCStackResult ret = OC_STACK_OK;
357 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
358 if (CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
360 OIC_LOG(ERROR, TAG, "Failed to revert TLS credential handler.");
361 ret = OC_STACK_ERROR;
363 CAregisterPkixInfoHandler(GetPkixInfo);
364 CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
365 #endif // __WITH_DTLS__ or __WITH_TLS__
369 void SRMDeInitSecureResources()
371 DestroySecureResources();
374 OCStackResult SRMInitPolicyEngine()
376 return InitPolicyEngine(&g_policyEngineContext);
379 void SRMDeInitPolicyEngine()
381 DeInitPolicyEngine(&g_policyEngineContext);
384 bool SRMIsSecurityResourceURI(const char* uri)
391 const char *rsrcs[] = {
400 OIC_RSRC_DPAIRING_URI,
402 OC_RSRVD_PROV_CRL_URL
405 // Remove query from Uri for resource string comparison
406 size_t uriLen = strlen(uri);
407 char *query = strchr (uri, '?');
410 uriLen = query - uri;
413 for (size_t i = 0; i < sizeof(rsrcs)/sizeof(rsrcs[0]); i++)
415 size_t svrLen = strlen(rsrcs[i]);
417 if ((uriLen == svrLen) &&
418 (strncmp(uri, rsrcs[i], svrLen) == 0))
428 * Get the Secure Virtual Resource (SVR) type from the URI.
429 * @param uri [IN] Pointer to URI in question.
430 * @return The OicSecSvrType_t of the URI passed (note: if not a Secure Virtual
431 Resource, e.g. /a/light, will return "NOT_A_SVR_TYPE" enum value)
433 static const char URI_QUERY_CHAR = '?';
434 OicSecSvrType_t GetSvrTypeFromUri(const char* uri)
438 return NOT_A_SVR_RESOURCE;
441 // Remove query from Uri for resource string comparison
442 size_t uriLen = strlen(uri);
443 char *query = strchr (uri, URI_QUERY_CHAR);
446 uriLen = query - uri;
451 svrLen = strlen(OIC_RSRC_ACL_URI);
454 if(0 == strncmp(uri, OIC_RSRC_ACL_URI, svrLen))
456 return OIC_R_ACL_TYPE;
460 svrLen = strlen(OIC_RSRC_AMACL_URI);
463 if(0 == strncmp(uri, OIC_RSRC_AMACL_URI, svrLen))
465 return OIC_R_AMACL_TYPE;
469 svrLen = strlen(OIC_RSRC_CRED_URI);
472 if(0 == strncmp(uri, OIC_RSRC_CRED_URI, svrLen))
474 return OIC_R_CRED_TYPE;
478 svrLen = strlen(OIC_RSRC_CRL_URI);
481 if(0 == strncmp(uri, OIC_RSRC_CRL_URI, svrLen))
483 return OIC_R_CRL_TYPE;
487 svrLen = strlen(OIC_RSRC_DOXM_URI);
490 if(0 == strncmp(uri, OIC_RSRC_DOXM_URI, svrLen))
492 return OIC_R_DOXM_TYPE;
496 svrLen = strlen(OIC_RSRC_DPAIRING_URI);
499 if(0 == strncmp(uri, OIC_RSRC_DPAIRING_URI, svrLen))
501 return OIC_R_DPAIRING_TYPE;
505 svrLen = strlen(OIC_RSRC_PCONF_URI);
508 if(0 == strncmp(uri, OIC_RSRC_PCONF_URI, svrLen))
510 return OIC_R_PCONF_TYPE;
514 svrLen = strlen(OIC_RSRC_PSTAT_URI);
517 if(0 == strncmp(uri, OIC_RSRC_PSTAT_URI, svrLen))
519 return OIC_R_PSTAT_TYPE;
523 svrLen = strlen(OIC_RSRC_SVC_URI);
526 if(0 == strncmp(uri, OIC_RSRC_SVC_URI, svrLen))
528 return OIC_R_SVC_TYPE;
532 svrLen = strlen(OIC_RSRC_SACL_URI);
535 if(0 == strncmp(uri, OIC_RSRC_SACL_URI, svrLen))
537 return OIC_R_SACL_TYPE;
541 return NOT_A_SVR_RESOURCE;