Apply lazy-umount and kill processes to unmount user partition
[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 #include <mutex>
20 #include <condition_variable>
21 #include <list>
22
23 #include <fstream>
24 #include <fcntl.h>
25 #include <signal.h>
26 #include <unistd.h>
27 #include <sys/mount.h>
28 #include <sys/reboot.h>
29 #include <limits.h>
30 #include <stdlib.h>
31 #include <string.h>
32
33 #include <vconf.h>
34 #include <tzplatform_config.h>
35 #include <klay/process.h>
36 #include <klay/file-user.h>
37 #include <klay/filesystem.h>
38 #include <klay/dbus/connection.h>
39 #include <klay/error.h>
40
41 #include "misc.h"
42 #include "logger.h"
43 #include "progress-bar.h"
44 #include "rmi/common.h"
45
46 #include "ext4-tool.h"
47 #include "internal-encryption.h"
48 #include "internal-encryption-common.h"
49
50 namespace ode {
51
52 namespace {
53
54 const char *PRIVILEGE_PLATFORM  = "http://tizen.org/privilege/internal/default/platform";
55 const std::vector<std::string> blackListSystemdUnits = {
56         "samsung-log-mgr.service",
57 };
58
59 // watches systemd jobs
60 class JobWatch {
61 public:
62         explicit JobWatch(dbus::Connection& systemDBus);
63         ~JobWatch();
64
65         bool waitForJob(const std::string& job);
66
67 private:
68         void jobRemoved(const dbus::Variant& parameters);
69
70         struct Job {
71                 Job(uint32_t id,
72                         const std::string& job,
73                         const std::string& unit,
74                         const std::string& result) : id(id), job(job), unit(unit), result(result) {}
75                 uint32_t id;
76                 std::string job;
77                 std::string unit;
78                 std::string result;
79         };
80
81         dbus::Connection::SubscriptionId id;
82         dbus::Connection& systemDBus;
83         std::list<Job> removedJobs;
84         std::mutex jobsMutex;
85         std::condition_variable jobsCv;
86 };
87
88 JobWatch::JobWatch(dbus::Connection& systemDBus) : systemDBus(systemDBus) {
89         auto callback = [this](dbus::Variant parameters) {
90                 this->jobRemoved(parameters);
91         };
92
93         id = systemDBus.subscribeSignal("",
94                                                                         "/org/freedesktop/systemd1",
95                                                                         "org.freedesktop.systemd1.Manager",
96                                                                         "JobRemoved",
97                                                                         callback);
98 }
99
100 JobWatch::~JobWatch() {
101         systemDBus.unsubscribeSignal(id);
102 }
103
104 bool JobWatch::waitForJob(const std::string& job) {
105         while(true) {
106                 std::unique_lock<std::mutex> lock(jobsMutex);
107                 jobsCv.wait(lock, [this]{ return !removedJobs.empty(); });
108
109                 while(!removedJobs.empty()) {
110                         bool match = (removedJobs.front().job == job);
111                         bool done = (removedJobs.front().result == "done");
112                         removedJobs.pop_front();
113                         if (match)
114                                 return done;
115                 }
116         };
117 }
118
119 void JobWatch::jobRemoved(const dbus::Variant& parameters)
120 {
121         uint32_t id;
122         const char* job;
123         const char* unit;
124         const char* result;
125         parameters.get("(uoss)", &id, &job, &unit, &result);
126         INFO(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
127
128         {
129                 std::lock_guard<std::mutex> guard(jobsMutex);
130                 removedJobs.emplace_back(id, job, unit, result);
131         }
132         jobsCv.notify_one();
133 }
134
135 void stopKnownSystemdUnits()
136 {
137         std::vector<std::string> knownSystemdUnits;
138         dbus::Connection& systemDBus = dbus::Connection::getSystem();
139         dbus::VariantIterator iter;
140
141         systemDBus.methodcall("org.freedesktop.systemd1",
142                                                         "/org/freedesktop/systemd1",
143                                                         "org.freedesktop.systemd1.Manager",
144                                                         "ListUnits",
145                                                         -1, "(a(ssssssouso))", "")
146                                                                 .get("(a(ssssssouso))", &iter);
147
148         while (1) {
149                 unsigned int dataUint;
150                 char *dataStr[9];
151                 int ret;
152
153                 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
154                                                 dataStr + 3, dataStr + 4, dataStr + 5,
155                                                 dataStr + 6, &dataUint, dataStr + 7,
156                                                 dataStr + 8);
157
158                 if (!ret) {
159                         break;
160                 }
161
162                 std::string unit(dataStr[0]);
163                 if (unit == "security-manager.socket" ||
164                                 unit == "connman.socket") {
165                         knownSystemdUnits.insert(knownSystemdUnits.begin(), unit);
166                 } else if (unit.compare(0, 5, "user@") == 0 ||
167                         unit == "tlm.service" ||
168                         unit == "resourced.service" ||
169                         unit == "security-manager.service") {
170                         knownSystemdUnits.push_back(unit);
171                 }
172         }
173
174         JobWatch watch(systemDBus);
175
176         for (const std::string& unit : knownSystemdUnits) {
177                 INFO(SINK, "Stopping unit: " + unit);
178                 const char* job = NULL;
179                 systemDBus.methodcall("org.freedesktop.systemd1",
180                                                                 "/org/freedesktop/systemd1",
181                                                                 "org.freedesktop.systemd1.Manager",
182                                                                 "StopUnit",
183                                                                 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
184                 INFO(SINK, "Waiting for job: " + std::string(job));
185                 if (!watch.waitForJob(job))
186                         throw runtime::Exception("Stopping unit: " + unit + " failed");
187         }
188 }
189
190 std::string getDecodedPath(const std::string &path, const std::string &prefix)
191 {
192         std::string ret = path;
193         size_t pos = 0;
194
195         pos = ret.find(prefix);
196         if (pos != std::string::npos)
197                 ret = ret.substr(prefix.size(), ret.size());
198
199         pos = 0;
200         while ((pos = ret.find("_", pos)) != std::string::npos) {
201                 int a = std::stoi(std::string(1, ret.at(pos+1)), nullptr, 16);
202                 int b = std::stoi(std::string(1, ret.at(pos+2)), nullptr, 16);
203                 if (a < 0 || b < 0)
204                         ret.replace(pos, 3, "_");
205                 else
206                         ret.replace(pos, 3, std::string(1, ((a << 4) | b)));
207                 pos += 1;
208         }
209         return ret;
210 }
211
212 void stopDependedSystemdUnits()
213 {
214         dbus::Connection& systemDBus = dbus::Connection::getSystem();
215         std::set<std::string> unitsToStop;
216
217         for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
218                 try {
219                         char *unit = nullptr;
220                         systemDBus.methodcall("org.freedesktop.systemd1",
221                                                                         "/org/freedesktop/systemd1",
222                                                                         "org.freedesktop.systemd1.Manager",
223                                                                         "GetUnitByPID",
224                                                                         -1, "(o)", "(u)", (unsigned int)pid)
225                                                                                 .get("(o)", &unit);
226
227                         auto unescapedName = getDecodedPath(unit, "/org/freedesktop/systemd1/unit/");
228                         unitsToStop.insert(unescapedName);
229                 } catch (runtime::Exception &e) {
230                         INFO(SINK, "Killing process: " + std::to_string(pid));
231                         ::kill(pid, SIGKILL);
232                 }
233         }
234
235         JobWatch watch(systemDBus);
236         for (auto unit : blackListSystemdUnits) {
237                 unitsToStop.erase(unitsToStop.find(unit));
238         }
239
240         for (const std::string& unit : unitsToStop) {
241                 INFO(SINK, "Stopping unit: " + unit);
242                 const char* job = NULL;
243                 systemDBus.methodcall("org.freedesktop.systemd1",
244                                                                 "/org/freedesktop/systemd1",
245                                                                 "org.freedesktop.systemd1.Manager",
246                                                                 "StopUnit",
247                                                                 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
248                 INFO(SINK, "Waiting for job: " + std::string(job));
249                 if (!watch.waitForJob(job))
250                         throw runtime::Exception("Stopping unit: " + unit + " failed");
251         }
252 }
253
254 void showProgressUI(const std::string type)
255 {
256         dbus::Connection& systemDBus = dbus::Connection::getSystem();
257         std::string unit("ode-progress-ui@"+type+".service");
258
259         JobWatch watch(systemDBus);
260         INFO(SINK, "Start unit: " + unit);
261
262         const char* job = NULL;
263         systemDBus.methodcall("org.freedesktop.systemd1",
264                                                         "/org/freedesktop/systemd1",
265                                                         "org.freedesktop.systemd1.Manager",
266                                                         "StartUnit",
267                                                         -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
268
269         INFO(SINK, "Waiting for job: " + std::string(job));
270         if (!watch.waitForJob(job))
271                 throw runtime::Exception("Starting unit: " + unit + " failed");
272 }
273
274 unsigned int getOptions()
275 {
276         unsigned int result = 0;
277         int value;
278
279         value = 0;
280         ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
281         if (value) {
282                 result |= InternalEncryption::Option::IncludeUnusedRegion;
283         }
284
285         return result;
286 }
287
288 void setOptions(unsigned int options)
289 {
290         bool value;
291
292         if (options & InternalEncryption::Option::IncludeUnusedRegion) {
293                 value = true;
294         } else {
295                 value = false;
296         }
297         ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
298 }
299
300 void execAndWait(const std::string &path, std::vector<std::string> &args)
301 {
302         runtime::Process proc(path, args);
303         int ret = proc.execute();
304         if (ret < 0)
305                 ERROR(SINK, path + " failed for " + args.back());
306
307         ret = proc.waitForFinished();
308         if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
309                 ERROR(SINK, path + " failed for " + args.back());
310 }
311
312 bool isPartitionTerminated(const std::string &partition)
313 {
314         bool ret = true;
315         const std::string cmd("fuser -m " + partition + " | grep -o '[0-9]*'");
316         char *line = nullptr;
317         size_t len = 0;
318
319         FILE *fp = ::popen(cmd.c_str(), "r");
320         if (fp == nullptr) {
321                 ERROR(SINK, "Failed to get processes on partition");
322                 return false;
323         }
324
325         if (::getline(&line, &len, fp) != -1)
326                 ret = false;
327
328         ::free(line);
329         ::pclose(fp);
330
331         return ret;
332 }
333
334 void unmountInternalStorage(const std::string& source)
335 {
336         if (::umount2("/opt/usr", MNT_DETACH) == -1) {
337                 if (errno != EBUSY && errno != EINVAL) {
338                         throw runtime::Exception("umount() error : " + runtime::GetSystemErrorMessage());
339                 }
340         }
341
342         do {
343                 ::sync();
344                 static const char *fuserPath = "/usr/bin/fuser";
345                 std::vector<std::string> args = {
346                         fuserPath, "-m", "-k", "-s", "-SIGTERM", source,
347                 };
348                 execAndWait(fuserPath, args);
349                 ::usleep((useconds_t)((unsigned int)(500)*1000));
350
351                 args[4] = "-SIGKILL";
352                 execAndWait(fuserPath, args);
353                 ::usleep((useconds_t)((unsigned int)(200)*1000));
354         } while (!isPartitionTerminated(source));
355 }
356
357 }
358
359 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
360                                                                                                    KeyServer& key) :
361         server(srv),
362         keyServer(key)
363 {
364         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
365         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
366         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
367         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
368         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
369         server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
370         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
371         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
372         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
373         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
374         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
375         server.expose(this, "", (int)(InternalEncryptionServer::getState)());
376         server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
377         server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
378
379         server.createNotification("InternalEncryptionServer::mount");
380
381         std::string source = findDevPath();
382
383         engine.reset(new INTERNAL_ENGINE(
384                 source, INTERNAL_PATH,
385                 ProgressBar([](int v) {
386                         ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
387                                                         std::to_string(v).c_str());
388                 })
389         ));
390 }
391
392 InternalEncryptionServer::~InternalEncryptionServer()
393 {
394 }
395
396 int InternalEncryptionServer::setMountPassword(const std::string& password)
397 {
398         return keyServer.get(engine->getSource(), password, mountKey);
399 }
400
401 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
402 {
403         if (mountKey.empty() && mk.empty()) {
404                 ERROR(SINK, "You need to set master key first.");
405                 return error::NoData;
406         }
407
408         BinaryData key = mk.empty() ? mountKey : mk;
409         mountKey.clear();
410
411         if (getState() != State::Encrypted) {
412                 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
413                 return error::NoSuchDevice;
414         }
415
416         if (engine->isMounted()) {
417                 INFO(SINK, "Partition already mounted.");
418                 return error::None;
419         }
420
421         INFO(SINK, "Mounting internal storage.");
422         try {
423                 engine->mount(key, getOptions());
424
425                 server.notify("InternalEncryptionServer::mount");
426
427                 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
428                 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
429         } catch (runtime::Exception &e) {
430                 ERROR(SINK, "Mount failed: " + std::string(e.what()));
431                 return error::Unknown;
432         }
433
434         return error::None;
435 }
436
437 int InternalEncryptionServer::umount()
438 {
439         if (getState() != State::Encrypted) {
440                 ERROR(SINK, "Cannot umount, partition's state incorrect.");
441                 return error::NoSuchDevice;
442         }
443
444         if (!engine->isMounted()) {
445                 INFO(SINK, "Partition already umounted.");
446                 return error::None;
447         }
448
449         INFO(SINK, "Closing all processes using internal storage.");
450         try {
451                 stopKnownSystemdUnits();
452                 stopDependedSystemdUnits();
453                 INFO(SINK, "Umounting internal storage.");
454                 unmountInternalStorage("/dev/mapper/userdata");
455                 engine->umount();
456         } catch (runtime::Exception &e) {
457                 ERROR(SINK, "Umount failed: " + std::string(e.what()));
458                 return error::Unknown;
459         }
460
461         return error::None;
462 }
463
464 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
465 {
466         if (getState() != State::Unencrypted) {
467                 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
468                 return error::NoSuchDevice;
469         }
470
471         BinaryData masterKey;
472         int ret = keyServer.get(engine->getSource(), password, masterKey);
473         if (ret != error::None)
474                 return ret;
475
476         auto encryptWorker = [masterKey, options, this]() {
477                 try {
478                         showProgressUI("encrypt");
479                         ::sleep(1);
480
481                         runtime::File file("/opt/etc/.odeprogress");
482                         file.create(0640);
483
484                         INFO(SINK, "Closing all known systemd services that might be using internal storage.");
485                         stopKnownSystemdUnits();
486
487                         std::string source = engine->getSource();
488                         auto mntPaths = findMountPointsByDevice(source);
489
490                         if (!mntPaths.empty()) {
491                                 INFO(SINK, "Closing all processes using internal storage.");
492                                 stopDependedSystemdUnits();
493
494                                 INFO(SINK, "Unmounting internal storage.");
495                                 unmountInternalStorage(source);
496                         }
497
498                         INFO(SINK, "Encryption started.");
499                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
500                         engine->encrypt(masterKey, options);
501                         setOptions(options & getSupportedOptions());
502
503                         INFO(SINK, "Encryption completed.");
504                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
505                         server.notify("InternalEncryptionServer::mount");
506
507                         file.remove();
508
509                         INFO(SINK, "Syncing disk and rebooting.");
510                         ::sync();
511                         ::reboot(RB_AUTOBOOT);
512                 } catch (runtime::Exception &e) {
513                         ERROR(SINK, "Encryption failed: " + std::string(e.what()));
514                 }
515         };
516
517         std::thread asyncWork(encryptWorker);
518         asyncWork.detach();
519
520         return error::None;
521 }
522
523 int InternalEncryptionServer::decrypt(const std::string& password)
524 {
525         if (getState() != State::Encrypted) {
526                 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
527                 return error::NoSuchDevice;
528         }
529
530         BinaryData masterKey;
531         int ret = keyServer.get(engine->getSource(), password, masterKey);
532         if (ret != error::None)
533                 return ret;
534
535         auto decryptWorker = [masterKey, this]() {
536                 try {
537                         showProgressUI("decrypt");
538                         ::sleep(1);
539
540                         runtime::File file("/opt/etc/.odeprogress");
541                         file.create(0640);
542
543                         if (engine->isMounted()) {
544                                 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
545                                 stopKnownSystemdUnits();
546                                 INFO(SINK, "Closing all processes using internal storage.");
547                                 stopDependedSystemdUnits();
548
549                                 INFO(SINK, "Umounting internal storage.");
550                                 unmountInternalStorage("/dev/mapper/userdata");
551                                 engine->umount();
552                         }
553
554                         INFO(SINK, "Decryption started.");
555                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
556                         engine->decrypt(masterKey, getOptions());
557
558                         INFO(SINK, "Decryption complete.");
559                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
560
561                         file.remove();
562
563                         INFO(SINK, "Syncing disk and rebooting.");
564                         ::sync();
565                         ::reboot(RB_AUTOBOOT);
566                 } catch (runtime::Exception &e) {
567                         ERROR(SINK, "Decryption failed: " + std::string(e.what()));
568                 }
569         };
570
571         std::thread asyncWork(decryptWorker);
572         asyncWork.detach();
573
574         return error::None;
575 }
576
577 int InternalEncryptionServer::recovery()
578 {
579         int state = getState();
580
581         if (state == State::Unencrypted)
582                 return error::NoSuchDevice;
583
584         runtime::File file("/opt/.factoryreset");
585         file.create(0640);
586
587         ::sync();
588         try {
589                 dbus::Connection& systemDBus = dbus::Connection::getSystem();
590                 systemDBus.methodcall("org.tizen.system.deviced",
591                                                                 "/Org/Tizen/System/DeviceD/Power",
592                                                                 "org.tizen.system.deviced.power",
593                                                                 "reboot",
594                                                                 -1, "()", "(si)", "reboot", 0);
595         } catch (runtime::Exception &e) {
596                 ::reboot(RB_AUTOBOOT);
597         }
598         return error::None;
599 }
600
601 int InternalEncryptionServer::isPasswordInitialized()
602 {
603         return keyServer.isInitialized(engine->getSource());
604 }
605
606 int InternalEncryptionServer::initPassword(const std::string& password)
607 {
608         return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
609 }
610
611 int InternalEncryptionServer::cleanPassword(const std::string& password)
612 {
613         return keyServer.remove(engine->getSource(), password);
614 }
615
616 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
617                                                                                 const std::string& newPassword)
618 {
619         return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
620 }
621
622 int InternalEncryptionServer::verifyPassword(const std::string& password)
623 {
624         return keyServer.verifyPassword(engine->getSource(), password);
625 }
626
627 int InternalEncryptionServer::getState()
628 {
629         char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
630         if (value == NULL) {
631                 throw runtime::Exception("Failed to get vconf value.");
632         }
633
634         std::string valueStr(value);
635         free(value);
636
637         if (valueStr == "encrypted")
638                 return State::Encrypted;
639         else if (valueStr == "unencrypted")
640                 return State::Unencrypted;
641         else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
642                 return State::Corrupted;
643
644         return State::Invalid;
645 }
646
647 unsigned int InternalEncryptionServer::getSupportedOptions()
648 {
649         return engine->getSupportedOptions();
650 }
651
652 std::string InternalEncryptionServer::getDevicePath() const
653 {
654         return engine->getSource();
655 }
656
657 } // namespace ode