Treat INTERNAL_DEV_NAME as prefix when traversing dir
[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
19 #include <fcntl.h>
20 #include <signal.h>
21 #include <unistd.h>
22 #include <sys/mount.h>
23 #include <sys/reboot.h>
24 #include <stdio.h>
25 #include <mntent.h>
26 #include <limits.h>
27 #include <stdlib.h>
28 #include <string.h>
29
30 #include <vconf.h>
31 #include <tzplatform_config.h>
32 #include <klay/process.h>
33 #include <klay/file-user.h>
34 #include <klay/filesystem.h>
35 #include <klay/dbus/connection.h>
36
37 #include "vconf.h"
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 #define INTERNAL_ENGINE DMCryptEngine
46 #define INTERNAL_DEV_PATH       "/dev/disk/by-partlabel"
47 #define INTERNAL_DEV_NAME       "USER"
48 #define INTERNAL_PATH           "/opt/usr"
49 #define INTERNAL_STATE_VCONF_KEY                                        VCONFKEY_ODE_CRYPTO_STATE
50 #define INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY      VCONFKEY_ODE_FAST_ENCRYPTION
51
52 #define PRIVILEGE_PLATFORM "http://tizen.org/privilege/internal/default/platform"
53
54 const std::string PROG_FACTORY_RESET = "/usr/bin/dbus-send";
55 const std::vector<std::string> wipeCommand = {
56     PROG_FACTORY_RESET,
57     "--system",
58     "--type=signal",
59     "--print-reply",
60     "--dest=com.samsung.factoryreset",
61     "/com/samsung/factoryreset",
62     "com.samsung.factoryreset.start.setting"
63 };
64
65 namespace ode {
66
67 namespace {
68
69 std::string findDevPath()
70 {
71         std::string source = INTERNAL_DEV_PATH "/" INTERNAL_DEV_NAME;
72         try {
73                 runtime::DirectoryIterator iter(INTERNAL_DEV_PATH), end;
74
75                 while (iter != end) {
76                         const std::string& path = (*iter).getPath();
77                         std::string name = path.substr(path.rfind('/') + 1);
78                         std::string upper;
79                         upper.reserve(name.size());
80                         for (char c : name) {
81                                 upper += std::toupper(c);
82                         }
83                         if (upper.compare(0, strlen(INTERNAL_DEV_NAME), INTERNAL_DEV_NAME) == 0) {
84                                 source = path;
85                                 break;
86                         }
87                         ++iter;
88                 }
89         } catch (runtime::Exception &e) {}
90
91         char *dev = ::realpath(source.c_str(), NULL);
92         if (dev == NULL) {
93                 throw runtime::Exception("Failed to find device path.");
94         }
95
96         std::string devPath(dev);
97         free(dev);
98
99         return devPath;
100 }
101
102 std::string findMntPath(const std::string &devPath)
103 {
104         std::string ret;
105
106         FILE* mtab = ::setmntent("/etc/mtab", "r");
107         struct mntent* entry = NULL;
108         while ((entry = ::getmntent(mtab)) != NULL) {
109                 if (devPath == entry->mnt_fsname) {
110                         ret = entry->mnt_dir;
111                         break;
112                 }
113         }
114         ::endmntent(mtab);
115
116         return ret;
117 }
118
119 std::unique_ptr<INTERNAL_ENGINE> engine;
120 KeyManager::data mountKey;
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(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, &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(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, 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(INTERNAL_STATE_VCONF_KEY, "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(INTERNAL_STATE_VCONF_KEY, "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(INTERNAL_STATE_VCONF_KEY, "unencrypted");
455
456                         INFO(SINK, "Syncing disk and rebooting...");
457                         ::sync();
458                         ::reboot(RB_AUTOBOOT);
459                 } catch (runtime::Exception &e) {
460                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "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(INTERNAL_STATE_VCONF_KEY);
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