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