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