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