Fix SVACE and C++ 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 <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 const mode_t MODE_0640 = S_IRUSR | S_IWUSR | S_IRGRP;
56
57 // watches systemd jobs
58 class JobWatch {
59 public:
60         explicit JobWatch(dbus::Connection& systemDBus);
61         ~JobWatch();
62
63         bool waitForJob(const std::string& job);
64
65 private:
66         void jobRemoved(const dbus::Variant& parameters);
67
68         struct Job {
69                 Job(uint32_t id,
70                         const std::string& job,
71                         const std::string& unit,
72                         const std::string& result) : id(id), job(job), unit(unit), result(result) {}
73                 uint32_t id;
74                 std::string job;
75                 std::string unit;
76                 std::string result;
77         };
78
79         dbus::Connection::SubscriptionId id;
80         dbus::Connection& systemDBus;
81         std::list<Job> removedJobs;
82         std::mutex jobsMutex;
83         std::condition_variable jobsCv;
84 };
85
86 JobWatch::JobWatch(dbus::Connection& systemDBus) : systemDBus(systemDBus) {
87         auto callback = [this](dbus::Variant parameters) {
88                 this->jobRemoved(parameters);
89         };
90
91         id = systemDBus.subscribeSignal("",
92                                                                         "/org/freedesktop/systemd1",
93                                                                         "org.freedesktop.systemd1.Manager",
94                                                                         "JobRemoved",
95                                                                         callback);
96 }
97
98 JobWatch::~JobWatch() {
99         systemDBus.unsubscribeSignal(id);
100 }
101
102 bool JobWatch::waitForJob(const std::string& job) {
103         while(true) {
104                 std::unique_lock<std::mutex> lock(jobsMutex);
105                 jobsCv.wait(lock, [this]{ return !removedJobs.empty(); });
106
107                 while(!removedJobs.empty()) {
108                         bool match = (removedJobs.front().job == job);
109                         bool done = (removedJobs.front().result == "done");
110                         removedJobs.pop_front();
111                         if (match)
112                                 return done;
113                 }
114         };
115 }
116
117 void JobWatch::jobRemoved(const dbus::Variant& parameters)
118 {
119         uint32_t id;
120         const char* job;
121         const char* unit;
122         const char* result;
123         parameters.get("(uoss)", &id, &job, &unit, &result);
124         INFO(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
125
126         {
127                 std::lock_guard<std::mutex> guard(jobsMutex);
128                 removedJobs.emplace_back(id, job, unit, result);
129         }
130         jobsCv.notify_one();
131 }
132
133 void stopKnownSystemdUnits()
134 {
135         std::vector<std::string> knownSystemdUnits;
136         dbus::Connection& systemDBus = dbus::Connection::getSystem();
137         dbus::VariantIterator iter;
138
139         systemDBus.methodcall("org.freedesktop.systemd1",
140                                                         "/org/freedesktop/systemd1",
141                                                         "org.freedesktop.systemd1.Manager",
142                                                         "ListUnits",
143                                                         -1, "(a(ssssssouso))", "")
144                                                                 .get("(a(ssssssouso))", &iter);
145
146         while (1) {
147                 unsigned int dataUint;
148                 char *dataStr[9];
149                 int ret;
150
151                 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
152                                                 dataStr + 3, dataStr + 4, dataStr + 5,
153                                                 dataStr + 6, &dataUint, dataStr + 7,
154                                                 dataStr + 8);
155
156                 if (!ret) {
157                         break;
158                 }
159
160                 std::string unit(dataStr[0]);
161                 if (unit == "security-manager.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
192         for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
193                 try {
194                         char *unit;
195                         systemDBus.methodcall("org.freedesktop.systemd1",
196                                                                         "/org/freedesktop/systemd1",
197                                                                         "org.freedesktop.systemd1.Manager",
198                                                                         "GetUnitByPID",
199                                                                         -1, "(o)", "(u)", (unsigned int)pid)
200                                                                                 .get("(o)", &unit);
201                         unitsToStop.insert(unit);
202                 } catch (runtime::Exception &e) {
203                         INFO(SINK, "Killing process: " + std::to_string(pid));
204                         ::kill(pid, SIGKILL);
205                 }
206         }
207
208         JobWatch watch(systemDBus);
209
210         for (const std::string& unit : unitsToStop) {
211                 INFO(SINK, "Stopping unit: " + unit);
212                 const char* job = NULL;
213                 systemDBus.methodcall("org.freedesktop.systemd1",
214                                                                 unit,
215                                                                 "org.freedesktop.systemd1.Unit",
216                                                                 "Stop",
217                                                                 -1, "(o)", "(s)", "flush").get("(o)", &job);
218                 INFO(SINK, "Waiting for job: " + std::string(job));
219                 if (!watch.waitForJob(job))
220                         throw runtime::Exception("Stopping unit: " + unit + " failed");
221         }
222 }
223
224 void showProgressUI(const std::string type)
225 {
226         dbus::Connection& systemDBus = dbus::Connection::getSystem();
227         std::string unit("ode-progress-ui@"+type+".service");
228
229         JobWatch watch(systemDBus);
230         INFO(SINK, "Start unit: " + unit);
231
232         const char* job = NULL;
233         systemDBus.methodcall("org.freedesktop.systemd1",
234                                                         "/org/freedesktop/systemd1",
235                                                         "org.freedesktop.systemd1.Manager",
236                                                         "StartUnit",
237                                                         -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
238
239         INFO(SINK, "Waiting for job: " + std::string(job));
240         if (!watch.waitForJob(job))
241                 throw runtime::Exception("Starting unit: " + unit + " failed");
242 }
243
244 unsigned int getOptions()
245 {
246         unsigned int result = 0;
247         int value;
248
249         value = 0;
250         ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
251         if (value) {
252                 result |= InternalEncryption::Option::IncludeUnusedRegion;
253         }
254
255         return result;
256 }
257
258 void setOptions(unsigned int options)
259 {
260         bool value;
261
262         if (options & InternalEncryption::Option::IncludeUnusedRegion) {
263                 value = true;
264         } else {
265                 value = false;
266         }
267         ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
268 }
269
270 void unmountInternalStorage(const std::string& source)
271 {
272         while(true) {
273                 auto mntPaths = findMountPointsByDevice(source);
274                 if(mntPaths.empty())
275                         break;
276
277                 bool unmounted = true;
278                 for(const auto& path : mntPaths) {
279                         INFO(SINK, "Unmounting " + path);
280                         if (::umount(path.c_str()) == -1) {
281                                 // If it's busy or was already unmounted ignore the error
282                                 if (errno != EBUSY && errno != EINVAL) {
283                                         throw runtime::Exception("umount() error: " + runtime::GetSystemErrorMessage());
284                                 }
285                                 unmounted = false;
286                         }
287                 }
288                 if (!unmounted)
289                         stopDependedSystemdUnits();
290         }
291 }
292
293 }
294
295 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv, 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([](unsigned 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         } catch (runtime::Exception &e) {
362                 ERROR(SINK, "Mount failed: " + std::string(e.what()));
363                 return error::Unknown;
364         }
365
366         return error::None;
367 }
368
369 int InternalEncryptionServer::umount()
370 {
371         if (getState() != State::Encrypted) {
372                 ERROR(SINK, "Cannot umount, partition's state incorrect.");
373                 return error::NoSuchDevice;
374         }
375
376         if (!engine->isMounted()) {
377                 INFO(SINK, "Partition already umounted.");
378                 return error::None;
379         }
380
381         INFO(SINK, "Closing all processes using internal storage.");
382         try {
383                 stopDependedSystemdUnits();
384                 INFO(SINK, "Umounting internal storage.");
385                 engine->umount();
386         } catch (runtime::Exception &e) {
387                 ERROR(SINK, "Umount failed: " + std::string(e.what()));
388                 return error::Unknown;
389         }
390
391         return error::None;
392 }
393
394 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
395 {
396         if (getState() != State::Unencrypted) {
397                 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
398                 return error::NoSuchDevice;
399         }
400
401         BinaryData masterKey;
402         int ret = keyServer.get(engine->getSource(), password, masterKey);
403         if (ret != error::None)
404                 return ret;
405
406         auto encryptWorker = [masterKey, options, this]() {
407                 try {
408                         showProgressUI("encrypt");
409                         ::sleep(1);
410
411                         runtime::File file("/opt/etc/.odeprogress");
412                         file.create(MODE_0640);
413
414                         INFO(SINK, "Closing all known systemd services that might be using internal storage.");
415                         stopKnownSystemdUnits();
416
417                         std::string source = engine->getSource();
418                         auto mntPaths = findMountPointsByDevice(source);
419
420                         if (!mntPaths.empty()) {
421                                 INFO(SINK, "Closing all processes using internal storage.");
422                                 stopDependedSystemdUnits();
423
424                                 INFO(SINK, "Unmounting internal storage.");
425                                 unmountInternalStorage(source);
426                         }
427
428                         INFO(SINK, "Encryption started.");
429                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
430                         engine->encrypt(masterKey, options);
431                         setOptions(options & getSupportedOptions());
432
433                         INFO(SINK, "Encryption completed.");
434                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
435                         server.notify("InternalEncryptionServer::mount");
436
437                         file.remove();
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                         runtime::File file("/opt/etc/.odeprogress");
471                         file.create(MODE_0640);
472
473                         if (engine->isMounted()) {
474                                 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
475                                 stopKnownSystemdUnits();
476                                 INFO(SINK, "Closing all processes using internal storage.");
477                                 stopDependedSystemdUnits();
478
479                                 INFO(SINK, "Umounting internal storage.");
480                                 while (1) {
481                                         try {
482                                                 engine->umount();
483                                                 break;
484                                         } catch (runtime::Exception& e) {
485                                                 stopDependedSystemdUnits();
486                                         }
487                                 }
488                         }
489
490                         INFO(SINK, "Decryption started.");
491                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
492                         engine->decrypt(masterKey, getOptions());
493
494                         INFO(SINK, "Decryption complete.");
495                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
496
497                         file.remove();
498
499                         INFO(SINK, "Syncing disk and rebooting.");
500                         ::sync();
501                         ::reboot(RB_AUTOBOOT);
502                 } catch (runtime::Exception &e) {
503                         ERROR(SINK, "Decryption failed: " + std::string(e.what()));
504                 }
505         };
506
507         std::thread asyncWork(decryptWorker);
508         asyncWork.detach();
509
510         return error::None;
511 }
512
513 int InternalEncryptionServer::recovery()
514 {
515         int state = getState();
516
517         if (state == State::Unencrypted)
518                 return error::NoSuchDevice;
519
520         if (state == State::Corrupted)
521                 Ext4Tool::mkfs(engine->getSource());
522
523         runtime::File file("/opt/.factoryreset");
524         file.create(MODE_0640);
525
526         ::sync();
527         try {
528                 dbus::Connection& systemDBus = dbus::Connection::getSystem();
529                 systemDBus.methodcall("org.tizen.system.deviced",
530                                                                 "/Org/Tizen/System/DeviceD/Power",
531                                                                 "org.tizen.system.deviced.power",
532                                                                 "reboot",
533                                                                 -1, "()", "(si)", "reboot", 0);
534         } catch (runtime::Exception &e) {
535                 ::reboot(RB_AUTOBOOT);
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 if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
581                 return State::Corrupted;
582
583         return State::Invalid;
584 }
585
586 unsigned int InternalEncryptionServer::getSupportedOptions()
587 {
588         return engine->getSupportedOptions();
589 }
590
591 std::string InternalEncryptionServer::getDevicePath() const
592 {
593         return engine->getSource();
594 }
595
596 } // namespace ode