CA retrieve PKIX resource from SRM using callbacks
[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 "oic_string.h"
29 #include <string.h>
30
31 #ifdef __WITH_X509__
32 #include "crlresource.h"
33 #endif // __WITH_X509__
34
35 #define TAG  PCF("SRM")
36
37 //Request Callback handler
38 static CARequestCallback gRequestHandler = NULL;
39 //Response Callback handler
40 static CAResponseCallback gResponseHandler = NULL;
41 //Error Callback handler
42 static CAErrorCallback gErrorHandler = NULL;
43 //Persistent Storage callback handler for open/read/write/close/unlink
44 static OCPersistentStorage *gPersistentStorageHandler =  NULL;
45 //Provisioning response callback
46 static SPResponseCallback gSPResponseHandler = NULL;
47
48 /**
49  * A single global Policy Engine context will suffice as long
50  * as SRM is single-threaded.
51  */
52 PEContext_t g_policyEngineContext;
53
54 /**
55  * @brief function to register provisoning API's response callback.
56  * @param respHandler response handler callback.
57  */
58 void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler)
59 {
60     gSPResponseHandler = respHandler;
61 }
62 /**
63  * @brief   Handle the request from the SRM.
64  * @param   endPoint       [IN] Endpoint object from which the response is received.
65  * @param   requestInfo    [IN] Information for the request.
66  * @return  NONE
67  */
68 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
69 {
70     OC_LOG(INFO, TAG, PCF("Received request from remote device"));
71
72     if (!endPoint || !requestInfo)
73     {
74         OC_LOG(ERROR, TAG, PCF("Invalid arguments"));
75         return;
76     }
77
78     // Copy the subjectID
79     OicUuid_t subjectId = {.id = {0}};
80     memcpy(subjectId.id, requestInfo->info.identity.id, sizeof(subjectId.id));
81
82     //Check the URI has the query and skip it before checking the permission
83     char *uri = strstr(requestInfo->info.resourceUri, "?");
84     int position = 0;
85     if (uri)
86     {
87         position = uri - requestInfo->info.resourceUri;
88     }
89     if (position > MAX_URI_LENGTH)
90     {
91         OC_LOG(ERROR, TAG, PCF("URI length is too long"));
92         return;
93     }
94     SRMAccessResponse_t response = ACCESS_DENIED;
95     if (position > 0)
96     {
97         char newUri[MAX_URI_LENGTH + 1];
98         OICStrcpyPartial(newUri, MAX_URI_LENGTH + 1, requestInfo->info.resourceUri, position);
99         //Skip query and pass the newUri.
100         response = CheckPermission(&g_policyEngineContext, &subjectId,
101                               newUri,
102                               GetPermissionFromCAMethod_t(requestInfo->method));
103     }
104     else
105     {
106         //Pass resourceUri if there is no query info.
107         response = CheckPermission(&g_policyEngineContext, &subjectId,
108                               requestInfo->info.resourceUri,
109                               GetPermissionFromCAMethod_t(requestInfo->method));
110     }
111     if (IsAccessGranted(response) && gRequestHandler)
112     {
113         return (gRequestHandler(endPoint, requestInfo));
114     }
115
116     // Form a 'access deny' or 'Error' response and send to peer
117     CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
118     memcpy(&responseInfo.info, &(requestInfo->info), sizeof(responseInfo.info));
119     responseInfo.info.payload = NULL;
120     if (!gRequestHandler)
121     {
122         responseInfo.result = CA_INTERNAL_SERVER_ERROR;
123     }
124     else
125     {
126         /*
127          * TODO Enhance this logic more to decide between
128          * CA_UNAUTHORIZED_REQ or CA_FORBIDDEN_REQ depending
129          * upon SRMAccessResponseReasonCode_t
130          */
131         responseInfo.result = CA_UNAUTHORIZED_REQ;
132     }
133
134     if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
135     {
136         OC_LOG(ERROR, TAG, PCF("Failed in sending response to a unauthorized request!"));
137     }
138 }
139
140 /**
141  * @brief   Handle the response from the SRM.
142  * @param   endPoint     [IN] The remote endpoint.
143  * @param   responseInfo [IN] Response information from the endpoint.
144  * @return  NONE
145  */
146 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
147 {
148     OC_LOG(INFO, TAG, PCF("Received response from remote device"));
149
150     // isProvResponse flag is to check whether response is catered by provisioning APIs or not.
151     // When token sent by CA response matches with token generated by provisioning request,
152     // gSPResponseHandler returns true and response is not sent to RI layer. In case
153     // gSPResponseHandler is null and isProvResponse is false response then the response is for
154     // RI layer.
155     bool isProvResponse = false;
156
157     if (gSPResponseHandler)
158     {
159         isProvResponse = gSPResponseHandler(endPoint, responseInfo);
160     }
161     if (!isProvResponse && gResponseHandler)
162     {
163         gResponseHandler(endPoint, responseInfo);
164     }
165 }
166
167
168 /**
169  * @brief   Handle the error from the SRM.
170  * @param   endPoint  [IN] The remote endpoint.
171  * @param   errorInfo [IN] Error information from the endpoint.
172  * @return  NONE
173  */
174 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
175 {
176     OC_LOG(INFO, TAG, PCF("Received error from remote device"));
177     if (gErrorHandler)
178     {
179         gErrorHandler(endPoint, errorInfo);
180     }
181 }
182
183
184 /**
185  * @brief   Register request and response callbacks.
186  *          Requests and responses are delivered in these callbacks.
187  * @param   reqHandler   [IN] Request handler callback ( for GET,PUT ..etc)
188  * @param   respHandler  [IN] Response handler callback.
189  * @return
190  *     OC_STACK_OK    - No errors; Success
191  *     OC_STACK_INVALID_PARAM - invalid parameter
192  */
193 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
194                                  CAResponseCallback respHandler,
195                                  CAErrorCallback errHandler)
196 {
197     OC_LOG(INFO, TAG, PCF("SRMRegisterHandler !!"));
198     if( !reqHandler || !respHandler || !errHandler)
199     {
200         OC_LOG(ERROR, TAG, PCF("Callback handlers are invalid"));
201         return OC_STACK_INVALID_PARAM;
202     }
203     gRequestHandler = reqHandler;
204     gResponseHandler = respHandler;
205     gErrorHandler = errHandler;
206
207
208 #if defined(__WITH_DTLS__)
209     CARegisterHandler(SRMRequestHandler, SRMResponseHandler, SRMErrorHandler);
210 #else
211     CARegisterHandler(reqHandler, respHandler, errHandler);
212 #endif /* __WITH_DTLS__ */
213     return OC_STACK_OK;
214 }
215
216 /**
217  * @brief   Register Persistent storage callback.
218  * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
219  * @return
220  *     OC_STACK_OK    - No errors; Success
221  *     OC_STACK_INVALID_PARAM - Invalid parameter
222  */
223 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
224 {
225     OC_LOG(INFO, TAG, PCF("SRMRegisterPersistentStorageHandler !!"));
226     if(!persistentStorageHandler)
227     {
228         OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
229         return OC_STACK_INVALID_PARAM;
230     }
231     gPersistentStorageHandler = persistentStorageHandler;
232     return OC_STACK_OK;
233 }
234
235 /**
236  * @brief   Get Persistent storage handler pointer.
237  * @return
238  *     The pointer to Persistent Storage callback handler
239  */
240
241 OCPersistentStorage* SRMGetPersistentStorageHandler()
242 {
243     return gPersistentStorageHandler;
244 }
245
246
247 /**
248  * @brief   Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
249  * @retval  OC_STACK_OK for Success, otherwise some error value
250  */
251 OCStackResult SRMInitSecureResources()
252 {
253     // TODO: temporarily returning OC_STACK_OK every time until default
254     // behavior (for when SVR DB is missing) is settled.
255     InitSecureResources();
256
257 #if defined(__WITH_DTLS__)
258     CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
259 #endif // (__WITH_DTLS__)
260 #if defined(__WITH_X509__)
261     CARegisterDTLSX509CredentialsHandler(GetDtlsX509Credentials);
262     CARegisterDTLSCrlHandler(GetDerCrl);
263 #endif // (__WITH_X509__)
264
265     return OC_STACK_OK;
266 }
267
268 /**
269  * @brief   Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
270  * @retval  none
271  */
272 void SRMDeInitSecureResources()
273 {
274     DestroySecureResources();
275 }
276
277 /**
278  * @brief   Initialize Policy Engine.
279  * @return  OC_STACK_OK for Success, otherwise some error value.
280  */
281 OCStackResult SRMInitPolicyEngine()
282 {
283     return InitPolicyEngine(&g_policyEngineContext);
284 }
285
286 /**
287  * @brief   Cleanup Policy Engine.
288  * @return  none
289  */
290 void SRMDeInitPolicyEngine()
291 {
292     return DeInitPolicyEngine(&g_policyEngineContext);
293 }