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