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