Change to allow duplicated mount/umount API calls for lockscreen
[platform/core/security/ode.git] / server / internal-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 <set>
17
18 #include <signal.h>
19 #include <unistd.h>
20 #include <sys/mount.h>
21 #include <sys/reboot.h>
22
23 #include <vconf.h>
24 #include <tzplatform_config.h>
25 #include <klay/process.h>
26 #include <klay/file-user.h>
27 #include <klay/filesystem.h>
28 #include <klay/dbus/connection.h>
29 #include <klay/audit/logger.h>
30
31 #include "vconf.h"
32 #include "progress-bar.h"
33 #include "engine/encryption/dmcrypt-engine.h"
34 #include "key-manager/key-manager.h"
35
36 #include "rmi/internal-encryption.h"
37
38 #define INTERNAL_ENGINE DMCryptEngine
39 #define INTERNAL_DEV    "/dev/mmcblk0p25"
40 #define INTERNAL_PATH   "/opt/usr"
41 #define INTERNAL_STATE_VCONF_KEY                                        VCONFKEY_ODE_CRYPTO_STATE
42 #define INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY      VCONFKEY_ODE_FAST_ENCRYPTION
43
44 #define PRIVILEGE_PLATFORM "http://tizen.org/privilege/internal/default/platform"
45
46 const std::string PROG_FACTORY_RESET = "/usr/bin/dbus-send";
47 const std::vector<std::string> wipeCommand = {
48     PROG_FACTORY_RESET,
49     "--system",
50     "--type=signal",
51     "--print-reply",
52     "--dest=com.samsung.factoryreset",
53     "/com/samsung/factoryreset",
54     "com.samsung.factoryreset.start.setting"
55 };
56
57 namespace ode {
58
59 namespace {
60
61 std::unique_ptr<INTERNAL_ENGINE> engine;
62
63 void stopSystemdUserSessions() {
64         std::vector<std::string> userSessionServices;
65         dbus::Connection& systemDBus = dbus::Connection::getSystem();
66         dbus::VariantIterator iter;
67
68         systemDBus.methodcall("org.freedesktop.systemd1",
69                                                         "/org/freedesktop/systemd1",
70                                                         "org.freedesktop.systemd1.Manager",
71                                                         "ListUnits",
72                                                         -1, "(a(ssssssouso))", "")
73                                                                 .get("(a(ssssssouso))", &iter);
74
75         while (1) {
76                 unsigned int dataUint;
77                 char *dataStr[9];
78                 int ret;
79
80                 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
81                                                 dataStr + 3, dataStr + 4, dataStr + 5,
82                                                 dataStr + 6, &dataUint, dataStr + 7,
83                                                 dataStr + 8);
84
85                 if (!ret) {
86                         break;
87                 }
88
89                 std::string service(dataStr[0]);
90                 if (service.compare(0, 5, "user@") == 0) {
91                         userSessionServices.push_back(service);
92                 }
93         }
94
95         for (const std::string& service : userSessionServices) {
96                 INFO("Stop service - " + service);
97                 systemDBus.methodcall("org.freedesktop.systemd1",
98                                                                 "/org/freedesktop/systemd1",
99                                                                 "org.freedesktop.systemd1.Manager",
100                                                                 "StopUnit",
101                                                                 -1, "", "(ss)", service.c_str(), "flush");
102         }
103
104         sleep(1);
105 }
106
107 void stopDependedSystemdServices()
108 {
109         dbus::Connection& systemDBus = dbus::Connection::getSystem();
110         std::set<std::string> servicesToStop;
111
112         for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
113                 try {
114                         char *service;
115                         systemDBus.methodcall("org.freedesktop.systemd1",
116                                                                         "/org/freedesktop/systemd1",
117                                                                         "org.freedesktop.systemd1.Manager",
118                                                                         "GetUnitByPID",
119                                                                         -1, "(o)", "(u)", (unsigned int)pid)
120                                                                                 .get("(o)", &service);
121                         servicesToStop.insert(service);
122                 } catch (runtime::Exception &e) {
123                         INFO("Close process - " + std::to_string(pid));
124                         ::kill(pid, SIGKILL);
125                 }
126         }
127
128         for (const std::string& service : servicesToStop) {
129                 INFO("Close service - " + service);
130                 systemDBus.methodcall("org.freedesktop.systemd1",
131                                                                 service,
132                                                                 "org.freedesktop.systemd1.Unit",
133                                                                 "Stop",
134                                                                 -1, "", "(s)", "flush");
135         }
136 }
137
138 void showProgressUI(const std::string type) {
139         ::tzplatform_set_user(::tzplatform_getuid(TZ_SYS_DEFAULT_USER));
140         std::string defaultUserHome(::tzplatform_getenv(TZ_USER_HOME));
141         ::tzplatform_reset_user();
142
143         try {
144                 runtime::File shareDirectory("/opt/home/root/share");
145                 if (!shareDirectory.exists()) {
146                         shareDirectory.makeDirectory(true);
147                 }
148
149                 runtime::File elmConfigDir(shareDirectory.getPath() + "/.elementary");
150                 if (!elmConfigDir.exists()) {
151                         runtime::File defaultElmConfigDir(defaultUserHome + "/share/.elementary");
152                         defaultElmConfigDir.copyTo(shareDirectory.getPath());
153                 }
154         } catch (runtime::Exception &e) {
155                 ERROR("Failed to set up elm configuration");
156         }
157
158         std::vector<std::string> args = {
159                 "ode", "progress", type, "Internal"
160         };
161
162         runtime::Process proc("/usr/bin/ode", args);
163         proc.execute();
164 }
165
166 unsigned int getOptions()
167 {
168         unsigned int result = 0;
169         int value;
170
171         value = 0;
172         ::vconf_get_bool(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, &value);
173         if (value) {
174                 result |= InternalEncryption::Option::IncludeUnusedRegion;
175         }
176
177         return result;
178 }
179
180 void setOptions(unsigned int options)
181 {
182         bool value;
183
184         if (options & InternalEncryption::Option::IncludeUnusedRegion) {
185                 value = true;
186         } else {
187                 value = false;
188         }
189         ::vconf_set_bool(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, value);
190 }
191
192 }
193
194 InternalEncryption::InternalEncryption(ODEControlContext& ctx) :
195         context(ctx)
196 {
197         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::mount)(std::string));
198         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::umount)());
199         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::encrypt)(std::string, unsigned int));
200         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::decrypt)(std::string));
201         context.expose(this, "", (int)(InternalEncryption::isPasswordInitialized)());
202         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::initPassword)(std::string));
203         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::cleanPassword)(std::string));
204         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::changePassword)(std::string, std::string));
205         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::verifyPassword)(std::string));
206         context.expose(this, "", (int)(InternalEncryption::getState)());
207         context.expose(this, "", (unsigned int)(InternalEncryption::getSupportedOptions)());
208
209         context.createNotification("InternalEncryption::mount");
210
211         engine.reset(new INTERNAL_ENGINE(
212                 INTERNAL_DEV, INTERNAL_PATH,
213                 ProgressBar([](int v) {
214                         ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
215                                                         std::to_string(v).c_str());
216                 })
217         ));
218 }
219
220 InternalEncryption::~InternalEncryption()
221 {
222 }
223
224 int InternalEncryption::mount(const std::string& password)
225 {
226         if (getState() != State::Encrypted) {
227                 return -1;
228         }
229
230         KeyManager::data pwData(password.begin(), password.end());
231         KeyManager keyManager(engine->getKeyMeta());
232
233         if (!keyManager.verifyPassword(pwData)) {
234                 return -2;
235         }
236
237     if (engine->isMounted()) {
238                 INFO("Already mounted");
239                 return 0;
240         }
241
242         engine->mount(keyManager.getMasterKey(pwData), getOptions());
243         context.notify("InternalEncryption::mount");
244
245         return 0;
246 }
247
248 int InternalEncryption::umount()
249 {
250         if (getState() != State::Encrypted) {
251                 return -1;
252         }
253
254         if (!engine->isMounted()) {
255                 INFO("Already umounted");
256                 return 0;
257         }
258
259         INFO("Close all processes using internal storage...");
260         stopDependedSystemdServices();
261         INFO("Umount internal storage...");
262         engine->umount();
263
264         return 0;
265 }
266
267 int InternalEncryption::encrypt(const std::string& password, unsigned int options)
268 {
269         if (getState() != State::Unencrypted) {
270                 return -1;
271         }
272
273         KeyManager::data pwData(password.begin(), password.end());
274         KeyManager keyManager(engine->getKeyMeta());
275
276         if (!keyManager.verifyPassword(pwData)) {
277                 return -2;
278         }
279
280         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
281         auto encryptWorker = [MasterKey, options, this]() {
282                 try {
283                         INFO("Close all user sessions...");
284                         stopSystemdUserSessions();
285                         INFO("Close all processes using internal storage...");
286                         stopDependedSystemdServices();
287                         INFO("Umount internal storage...");
288                         while (::umount(INTERNAL_PATH) == -1) {
289                                 if (errno != EBUSY) {
290                                         throw runtime::Exception("Umount error - " + std::to_string(errno));
291                                 }
292                                 stopDependedSystemdServices();
293                         }
294
295                         showProgressUI("Encrypting");
296
297                         INFO("Encryption started...");
298                         engine->encrypt(MasterKey, options);
299                         setOptions(options & getSupportedOptions());
300                         INFO("Sync disk...");
301                         sync();
302                         INFO("Encryption completed");
303
304                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "encrypted");
305                         ::reboot(RB_AUTOBOOT);
306                 } catch (runtime::Exception &e) {
307                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
308                         ERROR("Encryption failed - " + std::string(e.what()));
309                 }
310         };
311
312         std::thread asyncWork(encryptWorker);
313         asyncWork.detach();
314
315         return 0;
316 }
317
318 int InternalEncryption::decrypt(const std::string& password)
319 {
320         if (getState() != State::Encrypted) {
321                 return -1;
322         }
323
324         KeyManager::data pwData(password.begin(), password.end());
325         KeyManager keyManager(engine->getKeyMeta());
326
327         if (!keyManager.verifyPassword(pwData)) {
328                 return -2;
329         }
330
331         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
332         auto decryptWorker = [MasterKey, this]() {
333                 try {
334                         INFO("Close all user sessions...");
335                         stopSystemdUserSessions();
336                         INFO("Close all processes using internal storage...");
337                         stopDependedSystemdServices();
338                         INFO("Umount internal storage...");
339                         while (1) {
340                                 try {
341                                         engine->umount();
342                                         break;
343                                 } catch (runtime::Exception& e) {
344                                         stopDependedSystemdServices();
345                                 }
346                         }
347
348                         showProgressUI("Decrypting");
349
350                         INFO("Decryption started...");
351                         engine->decrypt(MasterKey, getOptions());
352                         INFO("Sync disk...");
353                         sync();
354                         INFO("Decryption completed");
355
356                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "unencrypted");
357                         ::reboot(RB_AUTOBOOT);
358                 } catch (runtime::Exception &e) {
359                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
360                         ERROR("Decryption failed - " + std::string(e.what()));
361                 }
362         };
363
364         std::thread asyncWork(decryptWorker);
365         asyncWork.detach();
366
367         return 0;
368 }
369
370 int InternalEncryption::recovery()
371 {
372         if (getState() != State::Unencrypted) {
373                 return -1;
374         }
375
376         //TODO
377         runtime::Process proc(PROG_FACTORY_RESET, wipeCommand);
378         if (proc.execute() == -1) {
379                 ERROR("Failed to launch factory-reset");
380                 return -2;
381         }
382
383         return 0;
384 }
385
386 int InternalEncryption::isPasswordInitialized()
387 {
388         if (engine->isKeyMetaSet()) {
389                 return 1;
390         }
391         return 0;
392 }
393
394 int InternalEncryption::initPassword(const std::string& password)
395 {
396         KeyManager::data pwData(password.begin(), password.end());
397         KeyManager keyManager;
398
399         keyManager.initPassword(pwData);
400         engine->setKeyMeta(keyManager.serialize());
401         return 0;
402 }
403
404 int InternalEncryption::cleanPassword(const std::string& password)
405 {
406         KeyManager::data pwData(password.begin(), password.end());
407         KeyManager keyManager(engine->getKeyMeta());
408
409         if (!keyManager.verifyPassword(pwData)) {
410                 return -2;
411         }
412
413         engine->clearKeyMeta();
414         return 0;
415 }
416
417 int InternalEncryption::changePassword(const std::string& oldPassword,
418                                                                                 const std::string& newPassword)
419 {
420         KeyManager::data oldPwData(oldPassword.begin(), oldPassword.end());
421         KeyManager::data newPwData(newPassword.begin(), newPassword.end());
422         KeyManager keyManager(engine->getKeyMeta());
423
424         if (!keyManager.verifyPassword(oldPwData)) {
425                 return -2;
426         }
427
428         keyManager.changePassword(oldPwData, newPwData);
429         engine->setKeyMeta(keyManager.serialize());
430
431         return 0;
432 }
433
434 int InternalEncryption::verifyPassword(const std::string& password)
435 {
436         KeyManager::data pwData(password.begin(), password.end());
437         KeyManager keyManager(engine->getKeyMeta());
438
439         if (keyManager.verifyPassword(pwData)) {
440                 return 1;
441         }
442         return 0;
443 }
444
445 int InternalEncryption::getState()
446 {
447         char *value = ::vconf_get_str(INTERNAL_STATE_VCONF_KEY);
448         if (value == NULL) {
449                 throw runtime::Exception("Failed to get vconf value");
450         }
451
452         std::string valueStr(value);
453         free(value);
454
455         if (valueStr == "encrypted") {
456                 return State::Encrypted;
457         } else if (valueStr == "unencrypted") {
458                 return State::Unencrypted;
459         } else {
460                 return State::Corrupted;
461         }
462
463         return 0;
464 }
465
466 unsigned int InternalEncryption::getSupportedOptions()
467 {
468         return engine->getSupportedOptions();
469 }
470
471 } // namespace ode