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 //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;
88 responseInfo.info.dataType = CA_RESPONSE_DATA;
90 if (CA_STATUS_OK == CASendResponse(context->amsMgrContext->endpoint, &responseInfo))
92 OIC_LOG(DEBUG, TAG, "Succeed in sending response to a unauthorized request!");
96 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
100 void SRMSendResponse(SRMAccessResponse_t responseVal)
102 OIC_LOG(DEBUG, TAG, "Sending response to remote device");
104 if (IsAccessGranted(responseVal) && gRequestHandler)
106 OIC_LOG_V(INFO, TAG, "%s : Access granted. Passing Request to RI layer", __func__);
107 if (!g_policyEngineContext.amsMgrContext->endpoint ||
108 !g_policyEngineContext.amsMgrContext->requestInfo)
110 OIC_LOG_V(ERROR, TAG, "%s : Invalid arguments", __func__);
111 SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
114 gRequestHandler(g_policyEngineContext.amsMgrContext->endpoint,
115 g_policyEngineContext.amsMgrContext->requestInfo);
119 OIC_LOG_V(INFO, TAG, "%s : ACCESS_DENIED.", __func__);
120 SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
124 //Resetting PE state to AWAITING_REQUEST
125 SetPolicyEngineState(&g_policyEngineContext, AWAITING_REQUEST);
129 * Handle the request from the SRM.
131 * @param endPoint object from which the response is received.
132 * @param requestInfo contains information for the request.
134 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
136 OIC_LOG(DEBUG, TAG, "Received request from remote device");
138 bool isRequestOverSecureChannel = false;
139 if (!endPoint || !requestInfo)
141 OIC_LOG(ERROR, TAG, "Invalid arguments");
145 // Copy the subjectID
146 OicUuid_t subjectId = {.id = {0}};
147 memcpy(subjectId.id, requestInfo->info.identity.id, sizeof(subjectId.id));
148 if (endPoint->flags & CA_SECURE)
150 OIC_LOG(INFO, TAG, "request over secure channel");
151 isRequestOverSecureChannel = true;
154 //Check the URI has the query and skip it before checking the permission
155 char *uri = strstr(requestInfo->info.resourceUri, "?");
159 //Skip query and pass the resource uri
160 position = uri - requestInfo->info.resourceUri;
164 position = strlen(requestInfo->info.resourceUri);
166 if (MAX_URI_LENGTH < position || 0 > position)
168 OIC_LOG(ERROR, TAG, "Incorrect URI length");
171 SRMAccessResponse_t response = ACCESS_DENIED;
172 char newUri[MAX_URI_LENGTH + 1];
173 OICStrcpyPartial(newUri, MAX_URI_LENGTH + 1, requestInfo->info.resourceUri, position);
175 SetResourceRequestType(&g_policyEngineContext, newUri);
177 // Form a 'Error', 'slow response' or 'access deny' response and send to peer
178 CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
179 memcpy(&responseInfo.info, &(requestInfo->info), sizeof(responseInfo.info));
180 responseInfo.info.payload = NULL;
181 responseInfo.info.dataType = CA_RESPONSE_DATA;
183 OCResource *resPtr = FindResourceByUri(newUri);
186 // All vertical secure resources and SVR resources other than DOXM & PSTAT should reject request
188 if ((((resPtr->resourceProperties) & OC_SECURE)
189 && (g_policyEngineContext.resourceType == NOT_A_SVR_RESOURCE))
190 || ((g_policyEngineContext.resourceType < OIC_SEC_SVR_TYPE_COUNT)
191 && (g_policyEngineContext.resourceType != OIC_R_DOXM_TYPE)
192 && (g_policyEngineContext.resourceType != OIC_R_PSTAT_TYPE)))
194 // if resource is secure and request is over insecure channel
195 if (!isRequestOverSecureChannel)
197 // Reject all the requests over coap for secure resource.
198 responseInfo.result = CA_FORBIDDEN_REQ;
199 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
201 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
207 #ifdef MULTIPLE_OWNER
209 * In case of ACL and CRED, The payload required to verify the payload.
210 * Payload information will be used for subowner's permission verification.
212 g_policyEngineContext.payload = (uint8_t*)requestInfo->info.payload;
213 g_policyEngineContext.payloadSize = requestInfo->info.payloadSize;
214 #endif //MULTIPLE_OWNER
216 //New request are only processed if the policy engine state is AWAITING_REQUEST.
217 if (AWAITING_REQUEST == g_policyEngineContext.state)
219 OIC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method, %d",
220 requestInfo->info.resourceUri, requestInfo->method);
221 response = CheckPermission(&g_policyEngineContext, &subjectId, newUri,
222 GetPermissionFromCAMethod_t(requestInfo->method));
226 OIC_LOG_V(INFO, TAG, "PE state %d. Ignoring request with uri, %s for method, %d",
227 g_policyEngineContext.state, requestInfo->info.resourceUri, requestInfo->method);
230 if (IsAccessGranted(response) && gRequestHandler)
232 gRequestHandler(endPoint, requestInfo);
236 VERIFY_NON_NULL(TAG, gRequestHandler, ERROR);
238 if (ACCESS_WAITING_FOR_AMS == response)
240 OIC_LOG(INFO, TAG, "Sending slow response");
242 UpdateAmsMgrContext(&g_policyEngineContext, endPoint, requestInfo);
243 responseInfo.result = CA_EMPTY;
244 responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
249 * TODO Enhance this logic more to decide between
250 * CA_UNAUTHORIZED_REQ or CA_FORBIDDEN_REQ depending
251 * upon SRMAccessResponseReasonCode_t
253 OIC_LOG(INFO, TAG, "Sending for regular response");
254 responseInfo.result = CA_UNAUTHORIZED_REQ;
257 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
259 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
263 responseInfo.result = CA_INTERNAL_SERVER_ERROR;
264 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
266 OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
271 * Handle the response from the SRM.
273 * @param endPoint points to the remote endpoint.
274 * @param responseInfo contains response information from the endpoint.
276 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
278 OIC_LOG(DEBUG, TAG, "Received response from remote device");
280 // isProvResponse flag is to check whether response is catered by provisioning APIs or not.
281 // When token sent by CA response matches with token generated by provisioning request,
282 // gSPResponseHandler returns true and response is not sent to RI layer. In case
283 // gSPResponseHandler is null and isProvResponse is false response then the response is for
285 bool isProvResponse = false;
287 if (gSPResponseHandler)
289 isProvResponse = gSPResponseHandler(endPoint, responseInfo);
291 if (!isProvResponse && gResponseHandler)
293 gResponseHandler(endPoint, responseInfo);
298 * Handle the error from the SRM.
300 * @param endPoint is the remote endpoint.
301 * @param errorInfo contains error information from the endpoint.
303 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
305 OIC_LOG_V(INFO, TAG, "Received error from remote device with result, %d for request uri, %s",
306 errorInfo->result, errorInfo->info.resourceUri);
309 gErrorHandler(endPoint, errorInfo);
313 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
314 CAResponseCallback respHandler,
315 CAErrorCallback errHandler)
317 OIC_LOG(DEBUG, TAG, "SRMRegisterHandler !!");
318 if( !reqHandler || !respHandler || !errHandler)
320 OIC_LOG(ERROR, TAG, "Callback handlers are invalid");
321 return OC_STACK_INVALID_PARAM;
323 gRequestHandler = reqHandler;
324 gResponseHandler = respHandler;
325 gErrorHandler = errHandler;
328 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
329 CARegisterHandler(SRMRequestHandler, SRMResponseHandler, SRMErrorHandler);
331 CARegisterHandler(reqHandler, respHandler, errHandler);
332 #endif /* __WITH_DTLS__ */
336 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
338 OIC_LOG(DEBUG, TAG, "SRMRegisterPersistentStorageHandler !!");
339 if(!persistentStorageHandler)
341 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
342 return OC_STACK_INVALID_PARAM;
344 gPersistentStorageHandler = persistentStorageHandler;
348 OCPersistentStorage* SRMGetPersistentStorageHandler()
350 return gPersistentStorageHandler;
353 OCStackResult SRMInitSecureResources()
355 // TODO: temporarily returning OC_STACK_OK every time until default
356 // behavior (for when SVR DB is missing) is settled.
357 InitSecureResources();
358 OCStackResult ret = OC_STACK_OK;
359 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
360 if (CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
362 OIC_LOG(ERROR, TAG, "Failed to revert TLS credential handler.");
363 ret = OC_STACK_ERROR;
365 CAregisterPkixInfoHandler(GetPkixInfo);
366 CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
367 #endif // __WITH_DTLS__ or __WITH_TLS__
371 void SRMDeInitSecureResources()
373 DestroySecureResources();
376 OCStackResult SRMInitPolicyEngine()
378 return InitPolicyEngine(&g_policyEngineContext);
381 void SRMDeInitPolicyEngine()
383 DeInitPolicyEngine(&g_policyEngineContext);
386 bool SRMIsSecurityResourceURI(const char* uri)
393 const char *rsrcs[] = {
402 OIC_RSRC_DPAIRING_URI,
404 OC_RSRVD_PROV_CRL_URL
407 // Remove query from Uri for resource string comparison
408 size_t uriLen = strlen(uri);
409 char *query = strchr (uri, '?');
412 uriLen = query - uri;
415 for (size_t i = 0; i < sizeof(rsrcs)/sizeof(rsrcs[0]); i++)
417 size_t svrLen = strlen(rsrcs[i]);
419 if ((uriLen == svrLen) &&
420 (strncmp(uri, rsrcs[i], svrLen) == 0))
430 * Get the Secure Virtual Resource (SVR) type from the URI.
431 * @param uri [IN] Pointer to URI in question.
432 * @return The OicSecSvrType_t of the URI passed (note: if not a Secure Virtual
433 Resource, e.g. /a/light, will return "NOT_A_SVR_TYPE" enum value)
435 static const char URI_QUERY_CHAR = '?';
436 OicSecSvrType_t GetSvrTypeFromUri(const char* uri)
440 return NOT_A_SVR_RESOURCE;
443 // Remove query from Uri for resource string comparison
444 size_t uriLen = strlen(uri);
445 char *query = strchr (uri, URI_QUERY_CHAR);
448 uriLen = query - uri;
453 svrLen = strlen(OIC_RSRC_ACL_URI);
456 if(0 == strncmp(uri, OIC_RSRC_ACL_URI, svrLen))
458 return OIC_R_ACL_TYPE;
462 svrLen = strlen(OIC_RSRC_AMACL_URI);
465 if(0 == strncmp(uri, OIC_RSRC_AMACL_URI, svrLen))
467 return OIC_R_AMACL_TYPE;
471 svrLen = strlen(OIC_RSRC_CRED_URI);
474 if(0 == strncmp(uri, OIC_RSRC_CRED_URI, svrLen))
476 return OIC_R_CRED_TYPE;
480 svrLen = strlen(OIC_RSRC_CRL_URI);
483 if(0 == strncmp(uri, OIC_RSRC_CRL_URI, svrLen))
485 return OIC_R_CRL_TYPE;
489 svrLen = strlen(OIC_RSRC_DOXM_URI);
492 if(0 == strncmp(uri, OIC_RSRC_DOXM_URI, svrLen))
494 return OIC_R_DOXM_TYPE;
498 svrLen = strlen(OIC_RSRC_DPAIRING_URI);
501 if(0 == strncmp(uri, OIC_RSRC_DPAIRING_URI, svrLen))
503 return OIC_R_DPAIRING_TYPE;
507 svrLen = strlen(OIC_RSRC_PCONF_URI);
510 if(0 == strncmp(uri, OIC_RSRC_PCONF_URI, svrLen))
512 return OIC_R_PCONF_TYPE;
516 svrLen = strlen(OIC_RSRC_PSTAT_URI);
519 if(0 == strncmp(uri, OIC_RSRC_PSTAT_URI, svrLen))
521 return OIC_R_PSTAT_TYPE;
525 svrLen = strlen(OIC_RSRC_SVC_URI);
528 if(0 == strncmp(uri, OIC_RSRC_SVC_URI, svrLen))
530 return OIC_R_SVC_TYPE;
534 svrLen = strlen(OIC_RSRC_SACL_URI);
537 if(0 == strncmp(uri, OIC_RSRC_SACL_URI, svrLen))
539 return OIC_R_SACL_TYPE;
543 return NOT_A_SVR_RESOURCE;