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