Change registerParametricMethod/regiterNonPrametricMethod to expose
[platform/core/security/ode.git] / server / external-encryption.cpp
1 /*
2  *  Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *  Licensed under the Apache License, Version 2.0 (the "License");
5  *  you may not use this file except in compliance with the License.
6  *  You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License
15  */
16 #include <fstream>
17 #include <sstream>
18
19 #include <signal.h>
20 #include <unistd.h>
21 #include <sys/mount.h>
22
23 #include <vconf.h>
24 #include <tzplatform_config.h>
25
26 #include <klay/file-user.h>
27 #include <klay/filesystem.h>
28 #include <klay/audit/logger.h>
29
30 #include "launchpad.h"
31 #include "app-bundle.h"
32 #include "engine/ecryptfs-engine.h"
33 #include "key-manager/key-manager.h"
34 #include <klay/dbus/variant.h>
35 #include <klay/dbus/connection.h>
36
37 #include "rmi/external-encryption.h"
38 #include "progress-bar.h"
39 #include "progress-vconf-backend.h"
40
41 #define EXTERNAL_STORAGE_PATH   "/opt/media/SDCardA1"
42 #define DEFAULT_USER "owner"
43 #define EXTERNAL_STATE_VCONF_KEY VCONFKEY_SDE_CRYPTO_STATE
44 #define EXTERNAL_OPTION_ONLY_NEW_FILE_VCONF_KEY VCONFKEY_SDE_ENCRYPT_NEWFILE
45 #define EXTERNAL_OPTION_EXCEPT_FOR_MEDIA_FILE_VCONF_KEY VCONFKEY_SDE_EXCLUDE_MEDIAFILE
46
47 namespace ode {
48
49 namespace {
50
51 VConfBackend vconfBackend(VCONFKEY_SDE_ENCRYPT_PROGRESS);
52 ProgressBar progressBar(std::bind(&VConfBackend::update, &vconfBackend, std::placeholders::_1));
53
54 EcryptfsEngine engine(EXTERNAL_STORAGE_PATH, EXTERNAL_STORAGE_PATH, progressBar);
55
56 void killDependedApplications()
57 {
58         for (pid_t pid : runtime::FileUser::getList(EXTERNAL_STORAGE_PATH, true)) {
59                 INFO("Close process - " + std::to_string(pid));
60                 ::kill(pid, SIGKILL);
61         }
62 }
63
64 void externalCallback(dbus::Variant parameters)
65 {
66         int intparams[6];
67         char* strparams[7];
68
69         parameters.get("(issssssisibii)",
70                 &intparams[0], // block type: 0 - scsi, 1 : mmc
71                 &strparams[0], // devnode
72                 &strparams[1], // syspath
73                 &strparams[2], // usage
74                 &strparams[3], // fs type
75                 &strparams[4], // fs version
76                 &strparams[5], // fs uuid enc
77                 &intparams[1], // readonly: 0 - rw, 1 - ro
78                 &strparams[6], // mount point
79                 &intparams[2], // state: 0 - unmount, 1 - mount
80                 &intparams[3], // primary: 0 - flase, 1 - true
81                 &intparams[4], // flags: 1 - unmounted 2 - broken filesystem 4 - no filesystem 8 - not supported 16 - readonly
82                 &intparams[5]); // strage id
83
84         if(intparams[2] == 0) {
85                 INFO("Unmounted");
86         } else {
87                 INFO("Mounted");
88                 char *value = ::vconf_get_str(EXTERNAL_STATE_VCONF_KEY);
89                 if (value != NULL) {
90                         std::string valueStr(value);
91                         free(value);
92                         if (valueStr == "encrypted") {
93                                 try {
94                                         INFO("Launch SD card password popup");
95                                         AppBundle bundle;
96                                         bundle.add("viewtype", "SD_CARD_PASSWORD");
97
98                                         Launchpad launchpad(::tzplatform_getuid(TZ_SYS_DEFAULT_USER));
99                                         launchpad.launch("org.tizen.ode", bundle);
100                                 } catch (runtime::Exception &e) {
101                                         ERROR("Failed to launch SD card password popup");
102                                 }
103                         }
104                 }
105         }
106 }
107
108 void externalAddEventReceiver()
109 {
110         dbus::Connection &systemDBus = dbus::Connection::getSystem();
111
112         systemDBus.subscribeSignal("",
113                                                                 "/Org/Tizen/System/Storage/Block/Manager",
114                                                                 "org.tizen.system.storage.BlockManager",
115                                                                 "DeviceChanged",
116                                                                 externalCallback);
117 }
118
119 unsigned int getOptions()
120 {
121         unsigned int result = 0;
122         int value;
123
124         value = 0;
125         ::vconf_get_bool(EXTERNAL_OPTION_EXCEPT_FOR_MEDIA_FILE_VCONF_KEY, &value);
126         if (value) {
127                 result |= ExternalEncryption::Option::OnlyNewFile;
128         }
129
130         value = 0;
131         ::vconf_get_bool(EXTERNAL_OPTION_ONLY_NEW_FILE_VCONF_KEY, &value);
132         if (value) {
133                 result |= ExternalEncryption::Option::ExceptForMediaFile;
134         }
135
136         return result;
137 }
138
139 void setOptions(unsigned int options)
140 {
141         bool value;
142
143         if (options & ExternalEncryption::Option::OnlyNewFile) {
144                 value = true;
145         } else {
146                 value = false;
147         }
148         ::vconf_set_bool(EXTERNAL_OPTION_EXCEPT_FOR_MEDIA_FILE_VCONF_KEY, value);
149
150         if (options & ExternalEncryption::Option::ExceptForMediaFile) {
151                 value = true;
152         } else {
153                 value = false;
154         }
155         ::vconf_set_bool(EXTERNAL_OPTION_ONLY_NEW_FILE_VCONF_KEY, value);
156 }
157
158 } // namsepace
159
160 ExternalEncryption::ExternalEncryption(ODEControlContext &ctx) :
161         context(ctx)
162 {
163         context.expose(this, "", (int)(ExternalEncryption::mount)(std::string));
164         context.expose(this, "", (int)(ExternalEncryption::umount)());
165         context.expose(this, "", (int)(ExternalEncryption::encrypt)(std::string, unsigned int));
166         context.expose(this, "", (int)(ExternalEncryption::decrypt)(std::string));
167         context.expose(this, "", (int)(ExternalEncryption::isPasswordInitialized)());
168         context.expose(this, "", (int)(ExternalEncryption::initPassword)(std::string));
169         context.expose(this, "", (int)(ExternalEncryption::cleanPassword)(std::string));
170         context.expose(this, "", (int)(ExternalEncryption::changePassword)(std::string, std::string));
171         context.expose(this, "", (int)(ExternalEncryption::verifyPassword)(std::string));
172         context.expose(this, "", (int)(ExternalEncryption::getState)());
173         context.expose(this, "", (unsigned int)(ExternalEncryption::getSupportedOptions)());
174
175         externalAddEventReceiver();
176 }
177
178 ExternalEncryption::~ExternalEncryption()
179 {
180 }
181
182 int ExternalEncryption::mount(const std::string &password)
183 {
184         if (getState() != State::Encrypted) {
185                 return -1;
186         }
187
188         KeyManager::data data(password.begin(), password.end());
189         KeyManager keyManager(engine.getKeyMeta());
190
191         if (!keyManager.verifyPassword(data)) {
192                 return -2;
193         }
194
195         engine.mount(keyManager.getMasterKey(data), getOptions());
196         return 0;
197 }
198
199 int ExternalEncryption::umount()
200 {
201         if (getState() != State::Encrypted) {
202                 return -1;
203         }
204
205         INFO("Close all applications using external storage...");
206         killDependedApplications();
207         INFO("Umount external storage...");
208         engine.umount();
209
210         return 0;
211 }
212
213 int ExternalEncryption::encrypt(const std::string &password, unsigned int options)
214 {
215         if (getState() != State::Unencrypted) {
216                 return -1;
217         }
218
219         KeyManager::data pwData(password.begin(), password.end());
220         KeyManager keyManager(engine.getKeyMeta());
221
222         if (!keyManager.verifyPassword(pwData)) {
223                 return -2;
224         }
225
226         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
227         auto encryptWorker = [MasterKey, options, this]() {
228                 try {
229                         INFO("Close all applications using external storage...");
230                         killDependedApplications();
231                         INFO("Encryption started...");
232                         ::vconf_set_str(EXTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
233                         engine.encrypt(MasterKey, options);
234                         setOptions(options & getSupportedOptions());
235                         INFO("Sync disk...");
236                         sync();
237                         INFO("Encryption completed");
238                         ::vconf_set_str(EXTERNAL_STATE_VCONF_KEY, "encrypted");
239                 } catch (runtime::Exception &e) {
240                         ERROR("Encryption failed - " + std::string(e.what()));
241                 }
242         };
243
244         std::thread asyncWork(encryptWorker);
245         asyncWork.detach();
246
247         return 0;
248 }
249
250 int ExternalEncryption::decrypt(const std::string &password)
251 {
252         if (getState() != State::Encrypted) {
253                 return -1;
254         }
255
256         KeyManager::data pwData(password.begin(), password.end());
257         KeyManager keyManager(engine.getKeyMeta());
258
259         if (!keyManager.verifyPassword(pwData)) {
260                 return -2;
261         }
262
263         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
264         auto decryptWorker = [MasterKey, this]() {
265                 try {
266                         INFO("Close all applications using external storage...");
267                         killDependedApplications();
268                         INFO("Umount external storage...");
269                         while (1) {
270                                 try {
271                                         engine.umount();
272                                         break;
273                                 } catch (runtime::Exception &e) {
274                                         killDependedApplications();
275                                 }
276                         }
277
278                         INFO("Decryption started...");
279                         ::vconf_set_str(EXTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
280                         engine.decrypt(MasterKey, getOptions());
281                         INFO("Sync disk...");
282                         sync();
283                         INFO("Decryption completed");
284                         ::vconf_set_str(EXTERNAL_STATE_VCONF_KEY, "unencrypted");
285                 } catch (runtime::Exception &e) {
286                         ERROR("Decryption failed - " + std::string(e.what()));
287                 }
288         };
289
290         std::thread asyncWork(decryptWorker);
291         asyncWork.detach();
292
293         return 0;
294 }
295
296 int ExternalEncryption::isPasswordInitialized()
297 {
298         if (engine.isKeyMetaSet()) {
299                 return 1;
300         }
301         return 0;
302 }
303
304 int ExternalEncryption::initPassword(const std::string& password)
305 {
306         KeyManager::data pwData(password.begin(), password.end());
307         KeyManager keyManager;
308
309         keyManager.initPassword(pwData);
310         engine.setKeyMeta(keyManager.serialize());
311         return 0;
312 }
313
314 int ExternalEncryption::cleanPassword(const std::string& password)
315 {
316         KeyManager::data pwData(password.begin(), password.end());
317         KeyManager keyManager(engine.getKeyMeta());
318
319         if (!keyManager.verifyPassword(pwData)) {
320                 return -2;
321         }
322
323         engine.clearKeyMeta();
324         return 0;
325 }
326
327 int ExternalEncryption::changePassword(const std::string &oldPassword,
328                                                                            const std::string &newPassword)
329 {
330         KeyManager::data oldPwData(oldPassword.begin(), oldPassword.end());
331         KeyManager::data newPwData(newPassword.begin(), newPassword.end());
332         KeyManager keyManager(engine.getKeyMeta());
333
334         if (!keyManager.verifyPassword(oldPwData)) {
335                 return -2;
336         }
337
338         keyManager.changePassword(oldPwData, newPwData);
339         engine.setKeyMeta(keyManager.serialize());
340
341         return 0;
342 }
343
344 int ExternalEncryption::verifyPassword(const std::string& password)
345 {
346         KeyManager::data pwData(password.begin(), password.end());
347         KeyManager keyManager(engine.getKeyMeta());
348
349         if (keyManager.verifyPassword(pwData)) {
350                 return 1;
351         }
352         return 0;
353 }
354
355 int ExternalEncryption::getState()
356 {
357         char *value = ::vconf_get_str(EXTERNAL_STATE_VCONF_KEY);
358         if (value == NULL) {
359                 throw runtime::Exception("Failed to get vconf value");
360         }
361
362         std::string valueStr(value);
363         free(value);
364
365         if (valueStr == "encrypted") {
366                 return State::Encrypted;
367         } else if (valueStr == "unencrypted") {
368                 return State::Unencrypted;
369         } else {
370                 return State::Corrupted;
371         }
372
373         return 0;
374 }
375
376 unsigned int ExternalEncryption::getSupportedOptions()
377 {
378         return engine.getSupportedOptions();
379 }
380
381 } // namespace ode