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