Merging security-M3 to master
[platform/upstream/iotivity.git] / resource / csdk / security / src / secureresourcemanager.c
1 //******************************************************************
2 //
3 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
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
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
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.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 #include "ocstack.h"
22 #include "logger.h"
23 #include "cainterface.h"
24 #include "secureresourcemanager.h"
25 #include "resourcemanager.h"
26 #include "credresource.h"
27 #include "policyengine.h"
28 #include <string.h>
29
30 #define TAG  PCF("SRM")
31
32 //Request Callback handler
33 static CARequestCallback gRequestHandler = NULL;
34 //Response Callback handler
35 static CAResponseCallback gResponseHandler = NULL;
36 //Error Callback handler
37 static CAErrorCallback gErrorHandler = NULL;
38 //Persistent Storage callback handler for open/read/write/close/unlink
39 static OCPersistentStorage *gPersistentStorageHandler =  NULL;
40
41 /**
42  * A single global Policy Engine context will suffice as long
43  * as SRM is single-threaded.
44  */
45 PEContext_t g_policyEngineContext;
46
47 /**
48  * @brief   Handle the request from the SRM.
49  * @param   endPoint       [IN] Endpoint object from which the response is received.
50  * @param   requestInfo    [IN] Information for the request.
51  * @return  NONE
52  */
53 void SRMRequestHandler(const CARemoteEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
54 {
55     OC_LOG(INFO, TAG, PCF("Received request from remote device"));
56
57     if (!endPoint || !requestInfo)
58     {
59         OC_LOG(ERROR, TAG, PCF("Invalid arguments"));
60         return;
61     }
62
63     // Copy the subjectID
64     OicUuid_t subjectId = {};
65     memcpy(subjectId.id, endPoint->identity.id, sizeof(subjectId.id));
66
67     //Check the URI has the query and skip it before checking the permission
68     char *uri = strstr(endPoint->resourceUri, "?");
69     int position = 0;
70     if (uri)
71     {
72         position = uri - endPoint->resourceUri;
73     }
74     if (position > MAX_URI_LENGTH)
75     {
76         OC_LOG(ERROR, TAG, PCF("URI length is too long"));
77         return;
78     }
79     SRMAccessResponse_t response = ACCESS_DENIED;
80     if (position > 0)
81     {
82         char newUri[MAX_URI_LENGTH + 1];
83         strncpy(newUri, endPoint->resourceUri, (position));
84         newUri[position] = '\0';
85         //Skip query and pass the newUri.
86         response = CheckPermission(&g_policyEngineContext, &subjectId, newUri,
87                 GetPermissionFromCAMethod_t(requestInfo->method));
88
89     }
90     else
91     {
92         //Pass endPoint->resourceUri if there is no query info.
93         response = CheckPermission(&g_policyEngineContext, &subjectId, endPoint->resourceUri,
94                 GetPermissionFromCAMethod_t(requestInfo->method));
95     }
96     if (IsAccessGranted(response) && gRequestHandler)
97     {
98         return (gRequestHandler(endPoint, requestInfo));
99     }
100
101     // Form a 'access deny' or 'Error' response and send to peer
102     CAResponseInfo_t responseInfo = {};
103     memcpy(&responseInfo.info, &(requestInfo->info), sizeof(responseInfo.info));
104     responseInfo.info.payload = NULL;
105     if (!gRequestHandler)
106     {
107         responseInfo.result = CA_INTERNAL_SERVER_ERROR;
108     }
109     else
110     {
111         /*
112          * TODO Enhance this logic more to decide between
113          * CA_UNAUTHORIZED_REQ or CA_FORBIDDEN_REQ depending
114          * upon SRMAccessResponseReasonCode_t
115          */
116         responseInfo.result = CA_UNAUTHORIZED_REQ;
117     }
118
119     if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
120     {
121         OC_LOG(ERROR, TAG, PCF("Failed in sending response to a unauthorized request!"));
122     }
123 }
124
125 /**
126  * @brief   Handle the response from the SRM.
127  * @param   endPoint     [IN] The remote endpoint.
128  * @param   responseInfo [IN] Response information from the endpoint.
129  * @return  NONE
130  */
131 void SRMResponseHandler(const CARemoteEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
132 {
133     OC_LOG(INFO, TAG, PCF("Received response from remote device"));
134     if (gResponseHandler)
135     {
136         gResponseHandler(endPoint, responseInfo);
137     }
138 }
139
140
141 /**
142  * @brief   Handle the error from the SRM.
143  * @param   endPoint  [IN] The remote endpoint.
144  * @param   errorInfo [IN] Error information from the endpoint.
145  * @return  NONE
146  */
147 void SRMErrorHandler(const CARemoteEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
148 {
149     OC_LOG(INFO, TAG, PCF("Received error from remote device"));
150     if (gErrorHandler)
151     {
152         gErrorHandler(endPoint, errorInfo);
153     }
154 }
155
156
157 /**
158  * @brief   Register request and response callbacks.
159  *          Requests and responses are delivered in these callbacks.
160  * @param   reqHandler   [IN] Request handler callback ( for GET,PUT ..etc)
161  * @param   respHandler  [IN] Response handler callback.
162  * @return
163  *     OC_STACK_OK    - No errors; Success
164  *     OC_STACK_INVALID_PARAM - invalid parameter
165  */
166 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
167                                  CAResponseCallback respHandler,
168                                  CAErrorCallback errHandler)
169 {
170     OC_LOG(INFO, TAG, PCF("SRMRegisterHandler !!"));
171     if( !reqHandler || !respHandler || !errHandler)
172     {
173         OC_LOG(ERROR, TAG, PCF("Callback handlers are invalid"));
174         return OC_STACK_INVALID_PARAM;
175     }
176     gRequestHandler = reqHandler;
177     gResponseHandler = respHandler;
178     gErrorHandler = errHandler;
179
180
181 #if defined(__WITH_DTLS__)
182     CARegisterHandler(SRMRequestHandler, SRMResponseHandler, SRMErrorHandler);
183 #else
184     CARegisterHandler(reqHandler, respHandler, errHandler);
185 #endif /* __WITH_DTLS__ */
186     return OC_STACK_OK;
187 }
188
189 /**
190  * @brief   Register Persistent storage callback.
191  * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
192  * @return
193  *     OC_STACK_OK    - No errors; Success
194  *     OC_STACK_INVALID_PARAM - Invalid parameter
195  */
196 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
197 {
198     OC_LOG(INFO, TAG, PCF("SRMRegisterPersistentStorageHandler !!"));
199     if(!persistentStorageHandler)
200     {
201         OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
202         return OC_STACK_INVALID_PARAM;
203     }
204     gPersistentStorageHandler = persistentStorageHandler;
205     return OC_STACK_OK;
206 }
207
208 /**
209  * @brief   Get Persistent storage handler pointer.
210  * @return
211  *     The pointer to Persistent Storage callback handler
212  */
213
214 OCPersistentStorage* SRMGetPersistentStorageHandler()
215 {
216     OC_LOG(INFO, TAG, PCF("SRMGetPersistentStorageHandler !!"));
217     return gPersistentStorageHandler;
218 }
219
220
221 /**
222  * @brief   Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
223  * @retval  OC_STACK_OK for Success, otherwise some error value
224  */
225 OCStackResult SRMInitSecureResources()
226 {
227     // TODO: temporarily returning OC_STACK_OK every time until default
228     // behavior (for when SVR DB is missing) is settled.
229     InitSecureResources();
230
231 #if defined(__WITH_DTLS__)
232     CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
233 #endif // (__WITH_DTLS__)
234
235     return OC_STACK_OK;
236 }
237
238 /**
239  * @brief   Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
240  * @retval  none
241  */
242 void SRMDeInitSecureResources()
243 {
244     DestroySecureResources();
245 }
246
247 /**
248  * @brief   Initialize Policy Engine.
249  * @return  OC_STACK_OK for Success, otherwise some error value.
250  */
251 OCStackResult SRMInitPolicyEngine()
252 {
253     return InitPolicyEngine(&g_policyEngineContext);
254 }
255
256 /**
257  * @brief   Cleanup Policy Engine.
258  * @return  none
259  */
260 void SRMDeInitPolicyEngine()
261 {
262     return DeInitPolicyEngine(&g_policyEngineContext);
263 }