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"
29 #include "oic_string.h"
30 #include "oic_malloc.h"
31 #include "securevirtualresourcetypes.h"
32 #include "secureresourcemanager.h"
33 #include "srmresourcestrings.h"
34 #include "ocresourcehandler.h"
36 #if defined( __WITH_TLS__) || defined(__WITH_DTLS__)
37 #include "pkix_interface.h"
38 #endif //__WITH_TLS__ or __WITH_DTLS__
41 //Request Callback handler
42 static CARequestCallback gRequestHandler = NULL;
43 //Response Callback handler
44 static CAResponseCallback gResponseHandler = NULL;
45 //Error Callback handler
46 static CAErrorCallback gErrorHandler = NULL;
47 //Provisioning response callback
48 static SPResponseCallback gSPResponseHandler = NULL;
51 * A single global Request context will suffice as long
52 * as SRM is single-threaded.
54 SRMRequestContext_t g_requestContext;
57 * Function to register provisoning API's response callback.
58 * @param respHandler response handler callback.
60 void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler)
62 gSPResponseHandler = respHandler;
65 void SetRequestedResourceType(SRMRequestContext_t *context)
67 context->resourceType = GetSvrTypeFromUri(context->resourceUri);
70 // Send the response (context->responseInfo) to the requester
71 // (context->endPoint).
72 static void SRMSendResponse(SRMRequestContext_t *context)
75 && NULL != context->requestInfo
76 && NULL != context->endPoint)
79 if (CA_STATUS_OK == CASendResponse(context->endPoint,
80 &(context->responseInfo)))
82 OIC_LOG_V(DEBUG, TAG, "SRM response sent.");
83 context->responseSent = true;
87 OIC_LOG_V(ERROR, TAG, "SRM response failed.");
92 OIC_LOG_V(ERROR, TAG, "%s : NULL Parameter(s)",__func__);
98 // Based on the context->responseVal, either call the entity handler for the
99 // request (which must send the response), or send an ACCESS_DENIED response.
100 void SRMGenerateResponse(SRMRequestContext_t *context)
102 OIC_LOG_V(INFO, TAG, "%s : entering function.", __func__);
104 // If Access Granted, validate parameters and then pass request
105 // on to resource endpoint.
106 if (IsAccessGranted(context->responseVal))
108 if(NULL != gRequestHandler
109 && NULL != context->endPoint
110 && NULL != context->requestInfo)
112 OIC_LOG_V(INFO, TAG, "%s : Access granted, passing req to endpoint.",
114 gRequestHandler(context->endPoint, context->requestInfo);
115 context->responseSent = true; // SRM counts on the endpoint to send
118 else // error condition; log relevant msg then send DENIED response
120 OIC_LOG_V(ERROR, TAG, "%s : Null values in context.", __func__);
121 context->responseVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
122 context->responseInfo.result = CA_INTERNAL_SERVER_ERROR;
123 SRMSendResponse(context);
126 else // Access Denied
128 OIC_LOG_V(INFO, TAG, "%s : Access Denied; sending CA_UNAUTHORIZED_REQ.",
130 // TODO: in future version, differentiate between types of DENIED.
131 // See JIRA issue 1796 (https://jira.iotivity.org/browse/IOT-1796)
132 context->responseInfo.result = CA_UNAUTHORIZED_REQ;
133 SRMSendResponse(context);
138 // Set the value of context->resourceUri, based on the context->requestInfo.
139 void SetResourceUriAndType(SRMRequestContext_t *context)
141 char *uri = strstr(context->requestInfo->info.resourceUri, "?");
146 //Skip query and pass the resource uri
147 position = uri - context->requestInfo->info.resourceUri;
151 position = strlen(context->requestInfo->info.resourceUri);
153 if (MAX_URI_LENGTH < position || 0 > position)
155 OIC_LOG_V(ERROR, TAG, "Incorrect URI length.");
158 OICStrcpyPartial(context->resourceUri, MAX_URI_LENGTH + 1,
159 context->requestInfo->info.resourceUri, position);
161 // Set the resource type.
162 context->resourceType = GetSvrTypeFromUri(context->resourceUri);
167 // Check if this request is asking to access a "sec" = true resource
168 // over an unsecure channel. This type of request is forbidden with
169 // the exception of a few SVRs (see Security Specification).
170 void CheckRequestForSecResourceOverUnsecureChannel(SRMRequestContext_t *context)
172 // if request is over unsecure channel, check resource type
173 if(false == context->secureChannel)
175 OCResource *resPtr = FindResourceByUri(context->resourceUri);
178 // All vertical secure resources and SVR resources other than
179 // DOXM & PSTAT should reject requests over unsecure channel.
180 if ((((resPtr->resourceProperties) & OC_SECURE)
181 && (context->resourceType == NOT_A_SVR_RESOURCE))
182 || ((context->resourceType < OIC_SEC_SVR_TYPE_COUNT)
183 && (context->resourceType != OIC_R_DOXM_TYPE)
184 && (context->resourceType != OIC_R_PSTAT_TYPE)))
186 // Reject all the requests over coap for secure resource.
187 context->responseVal = ACCESS_DENIED_SEC_RESOURCE_OVER_UNSECURE_CHANNEL;
188 context->responseInfo.result = CA_FORBIDDEN_REQ;
189 SRMSendResponse(context);
197 void ClearRequestContext(SRMRequestContext_t *context)
202 OIC_LOG(ERROR, TAG, "Null context.");
206 // Clear context variables.
207 context->endPoint = NULL;
208 context->resourceType = OIC_RESOURCE_TYPE_ERROR;
209 memset(&context->resourceUri, 0, sizeof(context->resourceUri));
210 context->requestedPermission = PERMISSION_ERROR;
211 memset(&context->responseInfo, 0, sizeof(context->responseInfo));
212 context->responseSent = false;
213 context->responseVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
214 context->requestInfo = NULL;
215 context->secureChannel = false;
216 context->slowResponseSent = false;
217 context->subjectIdType = SUBJECT_ID_TYPE_ERROR;
218 memset(&context->subjectUuid, 0, sizeof(context->subjectUuid));
219 #ifdef MULTIPLE_OWNER
220 memset(&context->payload, 0, context->payloadSize); // TODO Samsung reviewer: please confirm
221 context->payloadSize = 0; // TODO Samsung reviewer: please confirm
222 #endif //MULTIPLE_OWNER
228 // Returns true iff Request arrived over secure channel
229 bool isRequestOverSecureChannel(SRMRequestContext_t *context)
231 OicUuid_t nullSubjectId = {.id = {0}};
233 // if flag set, return true
234 if(context->endPoint->flags & CA_SECURE)
238 // a null subject ID indicates CoAP, so if non-null, also return true
239 else if(memcmp(context->requestInfo->info.identity.id,
240 nullSubjectId.id, sizeof(context->requestInfo->info.identity.id)) != 0)
249 * Entry point into SRM, called by lower layer to determine whether an incoming
250 * request should be GRANTED or DENIED.
252 * @param endPoint object from which the response is received.
253 * @param requestInfo contains information for the request.
255 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
257 OIC_LOG(DEBUG, TAG, "Received request from remote device");
259 SRMRequestContext_t *ctx = &g_requestContext; // Always use our single ctx for now.
261 ClearRequestContext(ctx);
263 if (!endPoint || !requestInfo)
265 OIC_LOG(ERROR, TAG, "Invalid endPoint or requestInfo; can't process.");
269 ctx->endPoint = endPoint;
270 ctx->requestInfo = requestInfo;
271 ctx->requestedPermission = GetPermissionFromCAMethod_t(requestInfo->method);
273 // Copy the subjectID.
274 memcpy(ctx->subjectUuid.id,
275 requestInfo->info.identity.id, sizeof(ctx->subjectUuid.id));
276 ctx->subjectIdType = SUBJECT_ID_TYPE_UUID; // only supported type for now
278 // Set secure channel boolean.
279 ctx->secureChannel = isRequestOverSecureChannel(ctx);
281 // Set resource URI and type.
282 SetResourceUriAndType(ctx);
284 // Initialize responseInfo.
285 memcpy(&(ctx->responseInfo.info), &(requestInfo->info),
286 sizeof(ctx->responseInfo.info));
287 ctx->responseInfo.info.payload = NULL;
288 ctx->responseInfo.result = CA_INTERNAL_SERVER_ERROR;
289 ctx->responseInfo.info.dataType = CA_RESPONSE_DATA;
291 // Before consulting ACL, check if this is a forbidden request type.
292 CheckRequestForSecResourceOverUnsecureChannel(ctx);
294 // If DENIED response wasn't sent already, then it's time to check ACL.
295 if(false == ctx->responseSent)
297 #ifdef MULTIPLE_OWNER // TODO Samsung: please verify that these two calls belong
298 // here inside this conditional statement.
299 // In case of ACL and CRED, The payload required to verify the payload.
300 // Payload information will be used for subowner's permission verification.
301 ctx->payload = (uint8_t*)requestInfo->info.payload;
302 ctx->payloadSize = requestInfo->info.payloadSize;
303 #endif //MULTIPLE_OWNER
305 OIC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method %d",
306 ctx->requestInfo->info.resourceUri, ctx->requestInfo->method);
307 CheckPermission(ctx);
308 OIC_LOG_V(DEBUG, TAG, "Request for permission %d received responseVal %d.",
309 ctx->requestedPermission, ctx->responseVal);
311 // Now that we have determined the correct response and set responseVal,
312 // we generate and send the response to the requester.
313 SRMGenerateResponse(ctx);
317 if(false == ctx->responseSent)
319 OIC_LOG(ERROR, TAG, "Exiting SRM without responding to requester!");
326 * Handle the response from the SRM.
328 * @param endPoint points to the remote endpoint.
329 * @param responseInfo contains response information from the endpoint.
331 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
333 OIC_LOG(DEBUG, TAG, "Received response from remote device");
335 // isProvResponse flag is to check whether response is catered by provisioning APIs or not.
336 // When token sent by CA response matches with token generated by provisioning request,
337 // gSPResponseHandler returns true and response is not sent to RI layer. In case
338 // gSPResponseHandler is null and isProvResponse is false response then the response is for
340 bool isProvResponse = false;
342 if (gSPResponseHandler)
344 isProvResponse = gSPResponseHandler(endPoint, responseInfo);
346 if (!isProvResponse && gResponseHandler)
348 gResponseHandler(endPoint, responseInfo);
353 * Handle the error from the SRM.
355 * @param endPoint is the remote endpoint.
356 * @param errorInfo contains error information from the endpoint.
358 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
360 OIC_LOG_V(INFO, TAG, "Received error from remote device with result, %d for request uri, %s",
361 errorInfo->result, errorInfo->info.resourceUri);
364 gErrorHandler(endPoint, errorInfo);
368 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
369 CAResponseCallback respHandler, CAErrorCallback errHandler)
371 OIC_LOG(DEBUG, TAG, "SRMRegisterHandler !!");
372 if( !reqHandler || !respHandler || !errHandler)
374 OIC_LOG(ERROR, TAG, "Callback handlers are invalid");
375 return OC_STACK_INVALID_PARAM;
377 gRequestHandler = reqHandler;
378 gResponseHandler = respHandler;
379 gErrorHandler = errHandler;
382 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
383 CARegisterHandler(SRMRequestHandler, SRMResponseHandler, SRMErrorHandler);
385 CARegisterHandler(reqHandler, respHandler, errHandler);
386 #endif /* __WITH_DTLS__ */
390 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
392 OIC_LOG(DEBUG, TAG, "SRMRegisterPersistentStorageHandler !!");
393 return OCRegisterPersistentStorageHandler(persistentStorageHandler);
396 OCPersistentStorage* SRMGetPersistentStorageHandler()
398 return OCGetPersistentStorageHandler();
401 OCStackResult SRMInitSecureResources()
403 // TODO: temporarily returning OC_STACK_OK every time until default
404 // behavior (for when SVR DB is missing) is settled.
405 InitSecureResources();
406 OCStackResult ret = OC_STACK_OK;
407 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
408 if (CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
410 OIC_LOG(ERROR, TAG, "Failed to revert TLS credential handler.");
411 ret = OC_STACK_ERROR;
413 CAregisterPkixInfoHandler(GetPkixInfo);
414 CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
415 #endif // __WITH_DTLS__ or __WITH_TLS__
419 void SRMDeInitSecureResources()
421 DestroySecureResources();
424 bool SRMIsSecurityResourceURI(const char* uri)
431 const char *rsrcs[] = {
440 OIC_RSRC_DPAIRING_URI,
442 OC_RSRVD_PROV_CRL_URL
445 // Remove query from Uri for resource string comparison
446 size_t uriLen = strlen(uri);
447 char *query = strchr (uri, '?');
450 uriLen = query - uri;
453 for (size_t i = 0; i < sizeof(rsrcs)/sizeof(rsrcs[0]); i++)
455 size_t svrLen = strlen(rsrcs[i]);
457 if ((uriLen == svrLen) &&
458 (strncmp(uri, rsrcs[i], svrLen) == 0))
468 * Get the Secure Virtual Resource (SVR) type from the URI.
469 * @param uri [IN] Pointer to URI in question.
470 * @return The OicSecSvrType_t of the URI passed (note: if not a Secure Virtual
471 Resource, e.g. /a/light, will return "NOT_A_SVR_TYPE" enum value)
473 static const char URI_QUERY_CHAR = '?';
474 OicSecSvrType_t GetSvrTypeFromUri(const char* uri)
478 return NOT_A_SVR_RESOURCE;
481 // Remove query from Uri for resource string comparison
482 size_t uriLen = strlen(uri);
483 char *query = strchr (uri, URI_QUERY_CHAR);
486 uriLen = query - uri;
491 svrLen = strlen(OIC_RSRC_ACL_URI);
494 if(0 == strncmp(uri, OIC_RSRC_ACL_URI, svrLen))
496 return OIC_R_ACL_TYPE;
500 svrLen = strlen(OIC_RSRC_AMACL_URI);
503 if(0 == strncmp(uri, OIC_RSRC_AMACL_URI, svrLen))
505 return OIC_R_AMACL_TYPE;
509 svrLen = strlen(OIC_RSRC_CRED_URI);
512 if(0 == strncmp(uri, OIC_RSRC_CRED_URI, svrLen))
514 return OIC_R_CRED_TYPE;
518 svrLen = strlen(OIC_RSRC_CRL_URI);
521 if(0 == strncmp(uri, OIC_RSRC_CRL_URI, svrLen))
523 return OIC_R_CRL_TYPE;
527 svrLen = strlen(OIC_RSRC_DOXM_URI);
530 if(0 == strncmp(uri, OIC_RSRC_DOXM_URI, svrLen))
532 return OIC_R_DOXM_TYPE;
536 svrLen = strlen(OIC_RSRC_DPAIRING_URI);
539 if(0 == strncmp(uri, OIC_RSRC_DPAIRING_URI, svrLen))
541 return OIC_R_DPAIRING_TYPE;
545 svrLen = strlen(OIC_RSRC_PCONF_URI);
548 if(0 == strncmp(uri, OIC_RSRC_PCONF_URI, svrLen))
550 return OIC_R_PCONF_TYPE;
554 svrLen = strlen(OIC_RSRC_PSTAT_URI);
557 if(0 == strncmp(uri, OIC_RSRC_PSTAT_URI, svrLen))
559 return OIC_R_PSTAT_TYPE;
563 svrLen = strlen(OIC_RSRC_SVC_URI);
566 if(0 == strncmp(uri, OIC_RSRC_SVC_URI, svrLen))
568 return OIC_R_SVC_TYPE;
572 svrLen = strlen(OIC_RSRC_SACL_URI);
575 if(0 == strncmp(uri, OIC_RSRC_SACL_URI, svrLen))
577 return OIC_R_SACL_TYPE;
581 return NOT_A_SVR_RESOURCE;