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