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