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