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