Add time out to JobWatch
[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         auto stopUnit = [&systemDBus](const std::string &unit) {
195                 INFO(SINK, "Stopping unit: " + unit);
196                 JobWatch watch(systemDBus);
197                 const char* job = NULL;
198                 systemDBus.methodcall("org.freedesktop.systemd1",
199                                                                 "/org/freedesktop/systemd1",
200                                                                 "org.freedesktop.systemd1.Manager",
201                                                                 "StopUnit",
202                                                                 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
203                 INFO(SINK, "Waiting for job: " + std::string(job));
204                 if (!watch.waitForJob(job))
205                         ERROR(SINK, "Stopping unit: " + unit + " failed");
206         };
207
208         for (const std::string &unit : preprocessUnits) {
209                 stopUnit(unit);
210         }
211
212         for (const std::string &unit : unitsToStop) {
213                 stopUnit(unit);
214         }
215 }
216
217 void showProgressUI(const std::string type)
218 {
219         dbus::Connection& systemDBus = dbus::Connection::getSystem();
220         std::string unit("ode-progress-ui@"+type+".service");
221
222         JobWatch watch(systemDBus);
223         INFO(SINK, "Start unit: " + unit);
224
225         const char* job = NULL;
226         systemDBus.methodcall("org.freedesktop.systemd1",
227                                                         "/org/freedesktop/systemd1",
228                                                         "org.freedesktop.systemd1.Manager",
229                                                         "StartUnit",
230                                                         -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
231
232         INFO(SINK, "Waiting for job: " + std::string(job));
233         if (!watch.waitForJob(job))
234                 ERROR(SINK, "Starting unit: " + unit + " failed");
235 }
236
237 unsigned int getOptions()
238 {
239         unsigned int result = 0;
240         int value;
241
242         value = 0;
243         ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
244         if (value) {
245                 result |= InternalEncryption::Option::IncludeUnusedRegion;
246         }
247
248         return result;
249 }
250
251 void setOptions(unsigned int options)
252 {
253         bool value;
254
255         if (options & InternalEncryption::Option::IncludeUnusedRegion) {
256                 value = true;
257         } else {
258                 value = false;
259         }
260         ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
261 }
262
263 void execAndWait(const std::string &path, std::vector<std::string> &args)
264 {
265         runtime::Process proc(path, args);
266         int ret = proc.execute();
267         if (ret < 0)
268                 ERROR(SINK, path + " failed for " + args.back());
269
270         ret = proc.waitForFinished();
271         if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
272                 ERROR(SINK, path + " failed for " + args.back());
273 }
274
275 bool isPartitionTerminated(const std::string &partition)
276 {
277         bool ret = true;
278         const std::string cmd("fuser -m " + partition + " | grep -o '[0-9]*'");
279         char *line = nullptr;
280         size_t len = 0;
281
282         FILE *fp = ::popen(cmd.c_str(), "r");
283         if (fp == nullptr) {
284                 ERROR(SINK, "Failed to get processes on partition");
285                 return false;
286         }
287
288         if (::getline(&line, &len, fp) != -1)
289                 ret = false;
290
291         ::free(line);
292         ::pclose(fp);
293
294         return ret;
295 }
296
297 void unmountInternalStorage(const std::string& source)
298 {
299         if (::umount2("/opt/usr", MNT_DETACH) == -1) {
300                 if (errno != EBUSY && errno != EINVAL) {
301                         throw runtime::Exception("umount() error : " + runtime::GetSystemErrorMessage());
302                 }
303         }
304
305         do {
306                 ::sync();
307                 static const char *fuserPath = "/usr/bin/fuser";
308                 std::vector<std::string> args = {
309                         fuserPath, "-m", "-k", "-s", "-SIGTERM", source,
310                 };
311                 execAndWait(fuserPath, args);
312                 ::usleep((useconds_t)((unsigned int)(500)*1000));
313
314                 args[4] = "-SIGKILL";
315                 execAndWait(fuserPath, args);
316                 ::usleep((useconds_t)((unsigned int)(200)*1000));
317         } while (!isPartitionTerminated(source));
318 }
319
320 }
321
322 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
323                                                                                                    KeyServer& key) :
324         server(srv),
325         keyServer(key)
326 {
327         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
328         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
329         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
330         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::isMounted)());
331         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
332         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
333         server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
334         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
335         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
336         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
337         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
338         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
339         server.expose(this, "", (int)(InternalEncryptionServer::getState)());
340         server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
341         server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
342
343         server.createNotification("InternalEncryptionServer::mount");
344
345         std::string source = findDevPath();
346
347         engine.reset(new INTERNAL_ENGINE(
348                 source, INTERNAL_PATH,
349                 ProgressBar([](int v) {
350                         ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
351                                                         std::to_string(v).c_str());
352                 })
353         ));
354 }
355
356 InternalEncryptionServer::~InternalEncryptionServer()
357 {
358 }
359
360 int InternalEncryptionServer::setMountPassword(const std::string& password)
361 {
362         const std::string& dev = engine->getSource();
363
364         // check if upgrade flag exists
365         if(UpgradeSupport::removeUpgradeFlag()) {
366                 INFO("Upgrade flag detected.");
367                 // try to load the master key
368                 try {
369                         mountKey = UpgradeSupport::loadMasterKey(dev);
370
371                         // encrypt the master key with given password
372                         return keyServer.changePassword2(dev, mountKey, password);
373                 } catch (const runtime::Exception&) {
374                         INFO("Failed to load the master key stored during upgrade.");
375                 }
376         }
377
378         return keyServer.get(dev, password, mountKey);
379 }
380
381 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
382 {
383         if (mountKey.empty() && mk.empty()) {
384                 ERROR(SINK, "You need to set master key first.");
385                 return error::NoData;
386         }
387
388         BinaryData key = mk.empty() ? mountKey : mk;
389         mountKey.clear();
390
391         if (getState() != State::Encrypted) {
392                 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
393                 return error::NoSuchDevice;
394         }
395
396         if (engine->isMounted()) {
397                 INFO(SINK, "Partition already mounted.");
398                 return error::None;
399         }
400
401         INFO(SINK, "Mounting internal storage.");
402         try {
403                 engine->mount(key, getOptions());
404
405                 server.notify("InternalEncryptionServer::mount");
406
407                 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
408                 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
409         } catch (runtime::Exception &e) {
410                 ERROR(SINK, "Mount failed: " + std::string(e.what()));
411                 return error::Unknown;
412         }
413
414         return error::None;
415 }
416
417 int InternalEncryptionServer::isMounted()
418 {
419         int ret = 0;
420         try {
421                 ret = engine->isMounted() ? 1 : 0;
422         } catch (runtime::Exception &e) {
423                 ERROR(SINK, "Failed to access the mount flag");
424                 return error::Unknown;
425         }
426         return ret;
427 }
428
429 int InternalEncryptionServer::umount()
430 {
431         if (getState() != State::Encrypted) {
432                 ERROR(SINK, "Cannot umount, partition's state incorrect.");
433                 return error::NoSuchDevice;
434         }
435
436         if (!engine->isMounted()) {
437                 INFO(SINK, "Partition already umounted.");
438                 return error::None;
439         }
440
441         INFO(SINK, "Closing all processes using internal storage.");
442         try {
443                 stopSystemdUnits();
444                 INFO(SINK, "Umounting internal storage.");
445                 unmountInternalStorage("/dev/mapper/userdata");
446                 engine->umount();
447         } catch (runtime::Exception &e) {
448                 ERROR(SINK, "Umount failed: " + std::string(e.what()));
449                 return error::Unknown;
450         }
451
452         return error::None;
453 }
454
455 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
456 {
457         if (getState() != State::Unencrypted) {
458                 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
459                 return error::NoSuchDevice;
460         }
461
462         BinaryData masterKey;
463         int ret = keyServer.get(engine->getSource(), password, masterKey);
464         if (ret != error::None)
465                 return ret;
466
467         auto encryptWorker = [masterKey, options, this]() {
468                 try {
469                         showProgressUI("encrypt");
470                         ::sleep(1);
471
472                         runtime::File file("/opt/etc/.odeprogress");
473                         file.create(0640);
474
475                         std::string source = engine->getSource();
476                         auto mntPaths = findMountPointsByDevice(source);
477
478                         if (!mntPaths.empty()) {
479                                 INFO(SINK, "Closing all processes using internal storage.");
480                                 stopSystemdUnits();
481
482                                 INFO(SINK, "Unmounting internal storage.");
483                                 unmountInternalStorage(source);
484                         }
485
486                         INFO(SINK, "Encryption started.");
487                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
488                         engine->encrypt(masterKey, options);
489                         setOptions(options & getSupportedOptions());
490
491                         INFO(SINK, "Encryption completed.");
492                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
493                         server.notify("InternalEncryptionServer::mount");
494
495                         file.remove();
496
497                         INFO(SINK, "Syncing disk and rebooting.");
498                         ::sync();
499                         ::reboot(RB_AUTOBOOT);
500                 } catch (runtime::Exception &e) {
501                         ERROR(SINK, "Encryption failed: " + std::string(e.what()));
502                 }
503         };
504
505         std::thread asyncWork(encryptWorker);
506         asyncWork.detach();
507
508         return error::None;
509 }
510
511 int InternalEncryptionServer::decrypt(const std::string& password)
512 {
513         if (getState() != State::Encrypted) {
514                 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
515                 return error::NoSuchDevice;
516         }
517
518         BinaryData masterKey;
519         int ret = keyServer.get(engine->getSource(), password, masterKey);
520         if (ret != error::None)
521                 return ret;
522
523         auto decryptWorker = [masterKey, this]() {
524                 try {
525                         showProgressUI("decrypt");
526                         ::sleep(1);
527
528                         runtime::File file("/opt/etc/.odeprogress");
529                         file.create(0640);
530
531                         if (engine->isMounted()) {
532                                 INFO(SINK, "Closing all processes using internal storage.");
533                                 stopSystemdUnits();
534
535                                 INFO(SINK, "Umounting internal storage.");
536                                 unmountInternalStorage("/dev/mapper/userdata");
537                                 engine->umount();
538                         }
539
540                         INFO(SINK, "Decryption started.");
541                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
542                         engine->decrypt(masterKey, getOptions());
543
544                         INFO(SINK, "Decryption complete.");
545                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
546
547                         file.remove();
548
549                         INFO(SINK, "Syncing disk and rebooting.");
550                         ::sync();
551                         ::reboot(RB_AUTOBOOT);
552                 } catch (runtime::Exception &e) {
553                         ERROR(SINK, "Decryption failed: " + std::string(e.what()));
554                 }
555         };
556
557         std::thread asyncWork(decryptWorker);
558         asyncWork.detach();
559
560         return error::None;
561 }
562
563 int InternalEncryptionServer::recovery()
564 {
565         int state = getState();
566
567         if (state == State::Unencrypted)
568                 return error::NoSuchDevice;
569
570         runtime::File file("/opt/.factoryreset");
571         file.create(0640);
572
573         ::sync();
574         try {
575                 dbus::Connection& systemDBus = dbus::Connection::getSystem();
576                 systemDBus.methodcall("org.tizen.system.deviced",
577                                                                 "/Org/Tizen/System/DeviceD/Power",
578                                                                 "org.tizen.system.deviced.power",
579                                                                 "reboot",
580                                                                 -1, "()", "(si)", "reboot", 0);
581         } catch (runtime::Exception &e) {
582                 ::reboot(RB_AUTOBOOT);
583         }
584         return error::None;
585 }
586
587 int InternalEncryptionServer::isPasswordInitialized()
588 {
589         return keyServer.isInitialized(engine->getSource());
590 }
591
592 int InternalEncryptionServer::initPassword(const std::string& password)
593 {
594         return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
595 }
596
597 int InternalEncryptionServer::cleanPassword(const std::string& password)
598 {
599         return keyServer.remove(engine->getSource(), password);
600 }
601
602 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
603                                                                                 const std::string& newPassword)
604 {
605         return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
606 }
607
608 int InternalEncryptionServer::verifyPassword(const std::string& password)
609 {
610         return keyServer.verifyPassword(engine->getSource(), password);
611 }
612
613 int InternalEncryptionServer::getState()
614 {
615         char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
616         if (value == NULL) {
617                 throw runtime::Exception("Failed to get vconf value.");
618         }
619
620         std::string valueStr(value);
621         free(value);
622
623         if (valueStr == "encrypted")
624                 return State::Encrypted;
625         else if (valueStr == "unencrypted")
626                 return State::Unencrypted;
627         else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
628                 return State::Corrupted;
629
630         return State::Invalid;
631 }
632
633 unsigned int InternalEncryptionServer::getSupportedOptions()
634 {
635         return engine->getSupportedOptions();
636 }
637
638 std::string InternalEncryptionServer::getDevicePath() const
639 {
640         return engine->getSource();
641 }
642
643 } // namespace ode