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