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