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