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