Add ode_internal_encryption_mount_ex API
[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)(std::vector<unsigned char>, unsigned int));
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(const std::vector<unsigned char> &mk, unsigned int options)
350 {
351         if (mountKey.empty() && mk.empty()) {
352                 ERROR(SINK, "You need to set master key first.");
353                 return error::NoData;
354         }
355
356         BinaryData key = mk.empty() ? mountKey : mk;
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                         runtime::File file("/opt/etc/.odeprogress");
428                         file.create(0640);
429
430                         INFO(SINK, "Closing all known systemd services that might be using internal storage.");
431                         stopKnownSystemdUnits();
432
433                         std::string source = engine->getSource();
434                         auto mntPaths = findMountPointsByDevice(source);
435
436                         if (!mntPaths.empty()) {
437                                 INFO(SINK, "Closing all processes using internal storage.");
438                                 stopDependedSystemdUnits();
439
440                                 INFO(SINK, "Unmounting internal storage.");
441                                 unmountInternalStorage(source);
442                         }
443
444                         INFO(SINK, "Encryption started.");
445                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
446                         engine->encrypt(masterKey, options);
447                         setOptions(options & getSupportedOptions());
448
449                         INFO(SINK, "Encryption completed.");
450                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
451                         server.notify("InternalEncryptionServer::mount");
452
453                         file.remove();
454
455                         INFO(SINK, "Syncing disk and rebooting.");
456                         ::sync();
457                         ::reboot(RB_AUTOBOOT);
458                 } catch (runtime::Exception &e) {
459                         ERROR(SINK, "Encryption failed: " + std::string(e.what()));
460                 }
461         };
462
463         std::thread asyncWork(encryptWorker);
464         asyncWork.detach();
465
466         return error::None;
467 }
468
469 int InternalEncryptionServer::decrypt(const std::string& password)
470 {
471         if (getState() != State::Encrypted) {
472                 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
473                 return error::NoSuchDevice;
474         }
475
476         BinaryData masterKey;
477         int ret = keyServer.get(engine->getSource(), password, masterKey);
478         if (ret != error::None)
479                 return ret;
480
481         auto decryptWorker = [masterKey, this]() {
482                 try {
483                         showProgressUI("decrypt");
484                         ::sleep(1);
485
486                         runtime::File file("/opt/etc/.odeprogress");
487                         file.create(0640);
488
489                         if (engine->isMounted()) {
490                                 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
491                                 stopKnownSystemdUnits();
492                                 INFO(SINK, "Closing all processes using internal storage.");
493                                 stopDependedSystemdUnits();
494
495                                 INFO(SINK, "Umounting internal storage.");
496                                 while (1) {
497                                         try {
498                                                 engine->umount();
499                                                 break;
500                                         } catch (runtime::Exception& e) {
501                                                 stopDependedSystemdUnits();
502                                         }
503                                 }
504                         }
505
506                         INFO(SINK, "Decryption started.");
507                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
508                         engine->decrypt(masterKey, getOptions());
509
510                         INFO(SINK, "Decryption complete.");
511                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
512
513                         file.remove();
514
515                         INFO(SINK, "Syncing disk and rebooting.");
516                         ::sync();
517                         ::reboot(RB_AUTOBOOT);
518                 } catch (runtime::Exception &e) {
519                         ERROR(SINK, "Decryption failed: " + std::string(e.what()));
520                 }
521         };
522
523         std::thread asyncWork(decryptWorker);
524         asyncWork.detach();
525
526         return error::None;
527 }
528
529 int InternalEncryptionServer::recovery()
530 {
531         int state = getState();
532
533         if (state == State::Unencrypted)
534                 return error::NoSuchDevice;
535
536         runtime::File file("/opt/.factoryreset");
537         file.create(0640);
538
539         ::sync();
540         try {
541                 dbus::Connection& systemDBus = dbus::Connection::getSystem();
542                 systemDBus.methodcall("org.tizen.system.deviced",
543                                                                 "/Org/Tizen/System/DeviceD/Power",
544                                                                 "org.tizen.system.deviced.power",
545                                                                 "reboot",
546                                                                 -1, "()", "(si)", "reboot", 0);
547         } catch (runtime::Exception &e) {
548                 ::reboot(RB_AUTOBOOT);
549         }
550         return error::None;
551 }
552
553 int InternalEncryptionServer::isPasswordInitialized()
554 {
555         return keyServer.isInitialized(engine->getSource());
556 }
557
558 int InternalEncryptionServer::initPassword(const std::string& password)
559 {
560         return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
561 }
562
563 int InternalEncryptionServer::cleanPassword(const std::string& password)
564 {
565         return keyServer.remove(engine->getSource(), password);
566 }
567
568 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
569                                                                                 const std::string& newPassword)
570 {
571         return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
572 }
573
574 int InternalEncryptionServer::verifyPassword(const std::string& password)
575 {
576         return keyServer.verifyPassword(engine->getSource(), password);
577 }
578
579 int InternalEncryptionServer::getState()
580 {
581         char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
582         if (value == NULL) {
583                 throw runtime::Exception("Failed to get vconf value.");
584         }
585
586         std::string valueStr(value);
587         free(value);
588
589         if (valueStr == "encrypted")
590                 return State::Encrypted;
591         else if (valueStr == "unencrypted")
592                 return State::Unencrypted;
593         else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
594                 return State::Corrupted;
595
596         return State::Invalid;
597 }
598
599 unsigned int InternalEncryptionServer::getSupportedOptions()
600 {
601         return engine->getSupportedOptions();
602 }
603
604 std::string InternalEncryptionServer::getDevicePath() const
605 {
606         return engine->getSource();
607 }
608
609 } // namespace ode