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