Make headers in RMI define pure virtual interfaces
[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 <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(ODEControlContext& ctx) :
232         context(ctx)
233 {
234         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
235         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)());
236         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
237         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
238         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
239         context.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
240         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
241         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
242         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
243         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
244         context.expose(this, "", (int)(InternalEncryptionServer::getState)());
245         context.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
246
247         context.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 (getState() != State::Encrypted) {
280                 return -1;
281         }
282
283     if (engine->isMounted()) {
284                 INFO(SINK, "Already mounted");
285                 return 0;
286         }
287
288         try {
289                 INFO(SINK, "Mount internal storage...");
290                 engine->mount(mountKey, getOptions());
291                 mountKey.clear();
292
293                 context.notify("InternalEncryptionServer::mount");
294
295                 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
296                 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
297         } catch (runtime::Exception &e) {
298                 ERROR(SINK, "Mount failed - " + std::string(e.what()));
299                 return -1;
300         }
301
302         return 0;
303 }
304
305 int InternalEncryptionServer::umount()
306 {
307         if (getState() != State::Encrypted) {
308                 return -1;
309         }
310
311         if (!engine->isMounted()) {
312                 INFO(SINK, "Already umounted");
313                 return 0;
314         }
315
316         try {
317                 INFO(SINK, "Close all processes using internal storage...");
318                 stopDependedSystemdServices();
319                 INFO(SINK, "Umount internal storage...");
320                 engine->umount();
321         } catch (runtime::Exception &e) {
322                 ERROR(SINK, "Umount failed - " + std::string(e.what()));
323                 return -1;
324         }
325
326         return 0;
327 }
328
329 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
330 {
331         if (getState() != State::Unencrypted) {
332                 return -1;
333         }
334
335         KeyManager::data pwData(password.begin(), password.end());
336         KeyManager keyManager(engine->getKeyMeta());
337
338         if (!keyManager.verifyPassword(pwData)) {
339                 return -2;
340         }
341
342         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
343         auto encryptWorker = [MasterKey, options, this]() {
344                 try {
345                         std::string source = engine->getSource();
346                         std::string mntPath = findMntPath(source);
347
348                         if (!mntPath.empty()) {
349                                 INFO(SINK, "Close all known systemd services that might be using internal storage...");
350                                 stopKnownSystemdServices();
351                                 INFO(SINK, "Close all processes using internal storage...");
352                                 stopDependedSystemdServices();
353                         }
354
355                         while (!mntPath.empty()) {
356                                 INFO(SINK, "Umount internal storage...");
357                                 while (::umount(mntPath.c_str()) == -1) {
358                                         if (errno != EBUSY) {
359                                                 throw runtime::Exception("Umount error - " + std::to_string(errno));
360                                         }
361                                         stopDependedSystemdServices();
362                                 }
363                                 mntPath = findMntPath(source);
364                         }
365
366                         showProgressUI("Encrypting");
367
368                         INFO(SINK, "Encryption started...");
369                         engine->encrypt(MasterKey, options);
370                         setOptions(options & getSupportedOptions());
371
372                         INFO(SINK, "Encryption completed");
373                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
374                         context.notify("InternalEncryptionServer::mount");
375
376                         INFO(SINK, "Syncing disk and rebooting...");
377                         ::sync();
378                         ::reboot(RB_AUTOBOOT);
379                 } catch (runtime::Exception &e) {
380                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
381                         ERROR(SINK, "Encryption failed - " + std::string(e.what()));
382                 }
383         };
384
385         std::thread asyncWork(encryptWorker);
386         asyncWork.detach();
387
388         return 0;
389 }
390
391 int InternalEncryptionServer::decrypt(const std::string& password)
392 {
393         if (getState() != State::Encrypted) {
394                 return -1;
395         }
396
397         KeyManager::data pwData(password.begin(), password.end());
398         KeyManager keyManager(engine->getKeyMeta());
399
400         if (!keyManager.verifyPassword(pwData)) {
401                 return -2;
402         }
403
404         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
405         auto decryptWorker = [MasterKey, this]() {
406                 try {
407                         if (engine->isMounted()) {
408                                 INFO(SINK, "Close all known systemd services that might be using internal storage...");
409                                 stopKnownSystemdServices();
410                                 INFO(SINK, "Close all processes using internal storage...");
411                                 stopDependedSystemdServices();
412
413                                 INFO(SINK, "Umount internal storage...");
414                                 while (1) {
415                                         try {
416                                                 engine->umount();
417                                                 break;
418                                         } catch (runtime::Exception& e) {
419                                                 stopDependedSystemdServices();
420                                         }
421                                 }
422                         }
423
424                         showProgressUI("Decrypting");
425
426                         INFO(SINK, "Decryption started...");
427                         engine->decrypt(MasterKey, getOptions());
428
429                         INFO(SINK, "Decryption completed");
430                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
431
432                         INFO(SINK, "Syncing disk and rebooting...");
433                         ::sync();
434                         ::reboot(RB_AUTOBOOT);
435                 } catch (runtime::Exception &e) {
436                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
437                         ERROR(SINK, "Decryption failed - " + std::string(e.what()));
438                 }
439         };
440
441         std::thread asyncWork(decryptWorker);
442         asyncWork.detach();
443
444         return 0;
445 }
446
447 int InternalEncryptionServer::recovery()
448 {
449         if (getState() != State::Unencrypted) {
450                 return -1;
451         }
452
453         //TODO
454         runtime::Process proc(PROG_FACTORY_RESET, wipeCommand);
455         if (proc.execute() == -1) {
456                 ERROR(SINK, "Failed to launch factory-reset");
457                 return -2;
458         }
459
460         return 0;
461 }
462
463 int InternalEncryptionServer::isPasswordInitialized()
464 {
465         if (engine->isKeyMetaSet()) {
466                 return 1;
467         }
468         return 0;
469 }
470
471 int InternalEncryptionServer::initPassword(const std::string& password)
472 {
473         KeyManager::data pwData(password.begin(), password.end());
474         KeyManager keyManager;
475
476         keyManager.initPassword(pwData);
477         engine->setKeyMeta(keyManager.serialize());
478         return 0;
479 }
480
481 int InternalEncryptionServer::cleanPassword(const std::string& password)
482 {
483         KeyManager::data pwData(password.begin(), password.end());
484         KeyManager keyManager(engine->getKeyMeta());
485
486         if (!keyManager.verifyPassword(pwData)) {
487                 return -2;
488         }
489
490         engine->clearKeyMeta();
491         return 0;
492 }
493
494 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
495                                                                                 const std::string& newPassword)
496 {
497         KeyManager::data oldPwData(oldPassword.begin(), oldPassword.end());
498         KeyManager::data newPwData(newPassword.begin(), newPassword.end());
499         KeyManager keyManager(engine->getKeyMeta());
500
501         if (!keyManager.verifyPassword(oldPwData)) {
502                 return -2;
503         }
504
505         keyManager.changePassword(oldPwData, newPwData);
506         engine->setKeyMeta(keyManager.serialize());
507
508         return 0;
509 }
510
511 int InternalEncryptionServer::verifyPassword(const std::string& password)
512 {
513         KeyManager::data pwData(password.begin(), password.end());
514         KeyManager keyManager(engine->getKeyMeta());
515
516         if (keyManager.verifyPassword(pwData)) {
517                 return 1;
518         }
519         return 0;
520 }
521
522 int InternalEncryptionServer::getState()
523 {
524         char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
525         if (value == NULL) {
526                 throw runtime::Exception("Failed to get vconf value");
527         }
528
529         std::string valueStr(value);
530         free(value);
531
532         if (valueStr == "encrypted") {
533                 return State::Encrypted;
534         } else if (valueStr == "unencrypted") {
535                 return State::Unencrypted;
536         } else {
537                 return State::Corrupted;
538         }
539
540         return 0;
541 }
542
543 unsigned int InternalEncryptionServer::getSupportedOptions()
544 {
545         return engine->getSupportedOptions();
546 }
547
548 } // namespace ode