Change to stop user session service before the other services
[platform/core/security/ode.git] / server / internal-encryption.cpp
1 /*
2  *  Copyright (c) 2015 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
18 #include <signal.h>
19 #include <unistd.h>
20 #include <sys/mount.h>
21 #include <sys/reboot.h>
22
23 #include <vconf.h>
24 #include <tzplatform_config.h>
25 #include <klay/process.h>
26 #include <klay/file-user.h>
27 #include <klay/filesystem.h>
28 #include <klay/dbus/connection.h>
29 #include <klay/audit/logger.h>
30
31 #include "vconf.h"
32 #include "progress-bar.h"
33 #include "engine/encryption/dmcrypt-engine.h"
34 #include "key-manager/key-manager.h"
35
36 #include "rmi/internal-encryption.h"
37
38 #define INTERNAL_ENGINE DMCryptEngine
39 #define INTERNAL_DEV    "/dev/mmcblk0p25"
40 #define INTERNAL_PATH   "/opt/usr"
41 #define INTERNAL_STATE_VCONF_KEY                                        VCONFKEY_ODE_CRYPTO_STATE
42 #define INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY      VCONFKEY_ODE_FAST_ENCRYPTION
43
44 #define PRIVILEGE_PLATFORM "http://tizen.org/privilege/internal/default/platform"
45
46 const std::string PROG_FACTORY_RESET = "/usr/bin/dbus-send";
47 const std::vector<std::string> wipeCommand = {
48     PROG_FACTORY_RESET,
49     "--system",
50     "--type=signal",
51     "--print-reply",
52     "--dest=com.samsung.factoryreset",
53     "/com/samsung/factoryreset",
54     "com.samsung.factoryreset.start.setting"
55 };
56
57 namespace ode {
58
59 namespace {
60
61 std::unique_ptr<INTERNAL_ENGINE> engine;
62
63 void stopSystemdUserSessions() {
64         std::vector<std::string> userSessionServices;
65         dbus::Connection& systemDBus = dbus::Connection::getSystem();
66         dbus::VariantIterator iter;
67
68         systemDBus.methodcall("org.freedesktop.systemd1",
69                                                         "/org/freedesktop/systemd1",
70                                                         "org.freedesktop.systemd1.Manager",
71                                                         "ListUnits",
72                                                         -1, "(a(ssssssouso))", "")
73                                                                 .get("(a(ssssssouso))", &iter);
74
75         while (1) {
76                 unsigned int dataUint;
77                 char *dataStr[9];
78                 int ret;
79
80                 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
81                                                 dataStr + 3, dataStr + 4, dataStr + 5,
82                                                 dataStr + 6, &dataUint, dataStr + 7,
83                                                 dataStr + 8);
84
85                 if (!ret) {
86                         break;
87                 }
88
89                 std::string service(dataStr[0]);
90                         if (service.compare(0, 5, "user@") == 0) {
91                                 userSessionServices.push_back(service);
92                         }
93                 }
94
95                 for (const std::string& service : userSessionServices) {
96                         INFO("Stop service - " + service);
97                         systemDBus.methodcall("org.freedesktop.systemd1",
98                                                                         "/org/freedesktop/systemd1",
99                                                                         "org.freedesktop.systemd1.Manager",
100                                                                         "StopUnit",
101                                                                         -1, "", "(ss)", service.c_str(), "flush");
102                 }
103 }
104
105 void stopDependedSystemdServices()
106 {
107         dbus::Connection& systemDBus = dbus::Connection::getSystem();
108         std::set<std::string> servicesToStop;
109
110         for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
111                 try {
112                         char *service;
113                         systemDBus.methodcall("org.freedesktop.systemd1",
114                                                                         "/org/freedesktop/systemd1",
115                                                                         "org.freedesktop.systemd1.Manager",
116                                                                         "GetUnitByPID",
117                                                                         -1, "(o)", "(u)", (unsigned int)pid)
118                                                                                 .get("(o)", &service);
119                         servicesToStop.insert(service);
120                 } catch (runtime::Exception &e) {
121                         INFO("Close process - " + std::to_string(pid));
122                         ::kill(pid, SIGKILL);
123                 }
124         }
125
126         for (const std::string& service : servicesToStop) {
127                 INFO("Close service - " + service);
128                 systemDBus.methodcall("org.freedesktop.systemd1",
129                                                                 service,
130                                                                 "org.freedesktop.systemd1.Unit",
131                                                                 "Stop",
132                                                                 -1, "", "(s)", "flush");
133         }
134 }
135
136 void showProgressUI(const std::string type) {
137         ::tzplatform_set_user(::tzplatform_getuid(TZ_SYS_DEFAULT_USER));
138         std::string defaultUserHome(::tzplatform_getenv(TZ_USER_HOME));
139         ::tzplatform_reset_user();
140
141         ::tzplatform_set_user(::getuid());
142         std::string currentUserHome(::tzplatform_getenv(TZ_USER_HOME));
143         ::tzplatform_reset_user();
144
145         INFO("Home directory : " + currentUserHome);
146
147         runtime::File shareDirectory(currentUserHome + "/share");
148         if (!shareDirectory.exists()) {
149                 shareDirectory.makeDirectory();
150         }
151
152         runtime::File elmConfigDir(currentUserHome + "/share/.elementary");
153         if (!elmConfigDir.exists()) {
154                 runtime::File defaultElmConfigDir(defaultUserHome + "/share/.elementary");
155                 defaultElmConfigDir.copyTo(shareDirectory.getPath());
156         }
157
158         std::vector<std::string> args = {
159                 "ode", "progress", type, "Internal"
160         };
161
162         runtime::Process proc("/usr/bin/ode", args);
163         proc.execute();
164 }
165
166 unsigned int getOptions()
167 {
168         unsigned int result = 0;
169         int value;
170
171         value = 0;
172         ::vconf_get_bool(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, &value);
173         if (value) {
174                 result |= InternalEncryption::Option::IncludeUnusedRegion;
175         }
176
177         return result;
178 }
179
180 void setOptions(unsigned int options)
181 {
182         bool value;
183
184         if (options & InternalEncryption::Option::IncludeUnusedRegion) {
185                 value = true;
186         } else {
187                 value = false;
188         }
189         ::vconf_set_bool(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, value);
190 }
191
192 }
193
194 InternalEncryption::InternalEncryption(ODEControlContext& ctx) :
195         context(ctx)
196 {
197         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::mount)(std::string));
198         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::umount)());
199         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::encrypt)(std::string, unsigned int));
200         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::decrypt)(std::string));
201         context.expose(this, "", (int)(InternalEncryption::isPasswordInitialized)());
202         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::initPassword)(std::string));
203         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::cleanPassword)(std::string));
204         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::changePassword)(std::string, std::string));
205         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::verifyPassword)(std::string));
206         context.expose(this, "", (int)(InternalEncryption::getState)());
207         context.expose(this, "", (unsigned int)(InternalEncryption::getSupportedOptions)());
208
209         engine.reset(new INTERNAL_ENGINE(
210                 INTERNAL_DEV, INTERNAL_PATH,
211                 ProgressBar([](int v) {
212                         ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
213                                                         std::to_string(v).c_str());
214                 })
215         ));
216 }
217
218 InternalEncryption::~InternalEncryption()
219 {
220 }
221
222 int InternalEncryption::mount(const std::string& password)
223 {
224         if (getState() != State::Encrypted) {
225                 return -1;
226         }
227
228         KeyManager::data pwData(password.begin(), password.end());
229         KeyManager keyManager(engine->getKeyMeta());
230
231         if (!keyManager.verifyPassword(pwData)) {
232                 return -2;
233         }
234
235         engine->mount(keyManager.getMasterKey(pwData), getOptions());
236         return 0;
237 }
238
239 int InternalEncryption::umount()
240 {
241         if (getState() != State::Encrypted) {
242                 return -1;
243         }
244
245         INFO("Close all processes using internal storage...");
246         stopDependedSystemdServices();
247         INFO("Umount internal storage...");
248         engine->umount();
249
250         return 0;
251 }
252
253 int InternalEncryption::encrypt(const std::string& password, unsigned int options)
254 {
255         if (getState() != State::Unencrypted) {
256                 return -1;
257         }
258
259         KeyManager::data pwData(password.begin(), password.end());
260         KeyManager keyManager(engine->getKeyMeta());
261
262         if (!keyManager.verifyPassword(pwData)) {
263                 return -2;
264         }
265
266         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
267         auto encryptWorker = [MasterKey, options, this]() {
268                 try {
269                         showProgressUI("Encrypting");
270
271                         INFO("Close all user sessions...");
272                         stopSystemdUserSessions();
273                         INFO("Close all processes using internal storage...");
274                         stopDependedSystemdServices();
275                         INFO("Umount internal storage...");
276                         while (::umount(INTERNAL_PATH) == -1) {
277                                 if (errno != EBUSY) {
278                                         throw runtime::Exception("Umount error - " + std::to_string(errno));
279                                 }
280                                 stopDependedSystemdServices();
281                         }
282
283                         INFO("Encryption started...");
284                         engine->encrypt(MasterKey, options);
285                         setOptions(options & getSupportedOptions());
286                         INFO("Sync disk...");
287                         sync();
288                         INFO("Encryption completed");
289
290                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "encrypted");
291                         ::reboot(RB_AUTOBOOT);
292                 } catch (runtime::Exception &e) {
293                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
294                         ERROR("Encryption failed - " + std::string(e.what()));
295                 }
296         };
297
298         std::thread asyncWork(encryptWorker);
299         asyncWork.detach();
300
301         return 0;
302 }
303
304 int InternalEncryption::decrypt(const std::string& password)
305 {
306         if (getState() != State::Encrypted) {
307                 return -1;
308         }
309
310         KeyManager::data pwData(password.begin(), password.end());
311         KeyManager keyManager(engine->getKeyMeta());
312
313         if (!keyManager.verifyPassword(pwData)) {
314                 return -2;
315         }
316
317         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
318         auto decryptWorker = [MasterKey, this]() {
319                 try {
320                         showProgressUI("Decrypting");
321
322                         INFO("Close all processes using internal storage...");
323                         stopDependedSystemdServices();
324                         INFO("Umount internal storage...");
325                         while (1) {
326                                 try {
327                                         engine->umount();
328                                         break;
329                                 } catch (runtime::Exception& e) {
330                                         stopDependedSystemdServices();
331                                 }
332                         }
333
334                         INFO("Decryption started...");
335                         engine->decrypt(MasterKey, getOptions());
336                         INFO("Sync disk...");
337                         sync();
338                         INFO("Decryption completed");
339
340                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "unencrypted");
341                         ::reboot(RB_AUTOBOOT);
342                 } catch (runtime::Exception &e) {
343                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
344                         ERROR("Decryption failed - " + std::string(e.what()));
345                 }
346         };
347
348         std::thread asyncWork(decryptWorker);
349         asyncWork.detach();
350
351         return 0;
352 }
353
354 int InternalEncryption::recovery()
355 {
356         if (getState() != State::Unencrypted) {
357                 return -1;
358         }
359
360         //TODO
361         runtime::Process proc(PROG_FACTORY_RESET, wipeCommand);
362         if (proc.execute() == -1) {
363                 ERROR("Failed to launch factory-reset");
364                 return -2;
365         }
366
367         return 0;
368 }
369
370 int InternalEncryption::isPasswordInitialized()
371 {
372         if (engine->isKeyMetaSet()) {
373                 return 1;
374         }
375         return 0;
376 }
377
378 int InternalEncryption::initPassword(const std::string& password)
379 {
380         KeyManager::data pwData(password.begin(), password.end());
381         KeyManager keyManager;
382
383         keyManager.initPassword(pwData);
384         engine->setKeyMeta(keyManager.serialize());
385         return 0;
386 }
387
388 int InternalEncryption::cleanPassword(const std::string& password)
389 {
390         KeyManager::data pwData(password.begin(), password.end());
391         KeyManager keyManager(engine->getKeyMeta());
392
393         if (!keyManager.verifyPassword(pwData)) {
394                 return -2;
395         }
396
397         engine->clearKeyMeta();
398         return 0;
399 }
400
401 int InternalEncryption::changePassword(const std::string& oldPassword,
402                                                                                 const std::string& newPassword)
403 {
404         KeyManager::data oldPwData(oldPassword.begin(), oldPassword.end());
405         KeyManager::data newPwData(newPassword.begin(), newPassword.end());
406         KeyManager keyManager(engine->getKeyMeta());
407
408         if (!keyManager.verifyPassword(oldPwData)) {
409                 return -2;
410         }
411
412         keyManager.changePassword(oldPwData, newPwData);
413         engine->setKeyMeta(keyManager.serialize());
414
415         return 0;
416 }
417
418 int InternalEncryption::verifyPassword(const std::string& password)
419 {
420         KeyManager::data pwData(password.begin(), password.end());
421         KeyManager keyManager(engine->getKeyMeta());
422
423         if (keyManager.verifyPassword(pwData)) {
424                 return 1;
425         }
426         return 0;
427 }
428
429 int InternalEncryption::getState()
430 {
431         char *value = ::vconf_get_str(INTERNAL_STATE_VCONF_KEY);
432         if (value == NULL) {
433                 throw runtime::Exception("Failed to get vconf value");
434         }
435
436         std::string valueStr(value);
437         free(value);
438
439         if (valueStr == "encrypted") {
440                 return State::Encrypted;
441         } else if (valueStr == "unencrypted") {
442                 return State::Unencrypted;
443         } else {
444                 return State::Corrupted;
445         }
446
447         return 0;
448 }
449
450 unsigned int InternalEncryption::getSupportedOptions()
451 {
452         return engine->getSupportedOptions();
453 }
454
455 } // namespace ode