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