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