Change elmConfig path for applying read-only root filesystem
[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         runtime::File shareDirectory("/opt/home/root/share");
142         if (!shareDirectory.exists()) {
143                 shareDirectory.makeDirectory(true);
144         }
145
146         runtime::File elmConfigDir(shareDirectory.getPath() + "/.elementary");
147         if (!elmConfigDir.exists()) {
148                 runtime::File defaultElmConfigDir(defaultUserHome + "/share/.elementary");
149                 defaultElmConfigDir.copyTo(shareDirectory.getPath());
150         }
151
152         std::vector<std::string> args = {
153                 "ode", "progress", type, "Internal"
154         };
155
156         runtime::Process proc("/usr/bin/ode", args);
157         proc.execute();
158 }
159
160 unsigned int getOptions()
161 {
162         unsigned int result = 0;
163         int value;
164
165         value = 0;
166         ::vconf_get_bool(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, &value);
167         if (value) {
168                 result |= InternalEncryption::Option::IncludeUnusedRegion;
169         }
170
171         return result;
172 }
173
174 void setOptions(unsigned int options)
175 {
176         bool value;
177
178         if (options & InternalEncryption::Option::IncludeUnusedRegion) {
179                 value = true;
180         } else {
181                 value = false;
182         }
183         ::vconf_set_bool(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, value);
184 }
185
186 }
187
188 InternalEncryption::InternalEncryption(ODEControlContext& ctx) :
189         context(ctx)
190 {
191         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::mount)(std::string));
192         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::umount)());
193         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::encrypt)(std::string, unsigned int));
194         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::decrypt)(std::string));
195         context.expose(this, "", (int)(InternalEncryption::isPasswordInitialized)());
196         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::initPassword)(std::string));
197         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::cleanPassword)(std::string));
198         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::changePassword)(std::string, std::string));
199         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::verifyPassword)(std::string));
200         context.expose(this, "", (int)(InternalEncryption::getState)());
201         context.expose(this, "", (unsigned int)(InternalEncryption::getSupportedOptions)());
202
203         engine.reset(new INTERNAL_ENGINE(
204                 INTERNAL_DEV, INTERNAL_PATH,
205                 ProgressBar([](int v) {
206                         ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
207                                                         std::to_string(v).c_str());
208                 })
209         ));
210 }
211
212 InternalEncryption::~InternalEncryption()
213 {
214 }
215
216 int InternalEncryption::mount(const std::string& password)
217 {
218         if (getState() != State::Encrypted) {
219                 return -1;
220         }
221
222         KeyManager::data pwData(password.begin(), password.end());
223         KeyManager keyManager(engine->getKeyMeta());
224
225         if (!keyManager.verifyPassword(pwData)) {
226                 return -2;
227         }
228
229         engine->mount(keyManager.getMasterKey(pwData), getOptions());
230         return 0;
231 }
232
233 int InternalEncryption::umount()
234 {
235         if (getState() != State::Encrypted) {
236                 return -1;
237         }
238
239         INFO("Close all processes using internal storage...");
240         stopDependedSystemdServices();
241         INFO("Umount internal storage...");
242         engine->umount();
243
244         return 0;
245 }
246
247 int InternalEncryption::encrypt(const std::string& password, unsigned int options)
248 {
249         if (getState() != State::Unencrypted) {
250                 return -1;
251         }
252
253         KeyManager::data pwData(password.begin(), password.end());
254         KeyManager keyManager(engine->getKeyMeta());
255
256         if (!keyManager.verifyPassword(pwData)) {
257                 return -2;
258         }
259
260         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
261         auto encryptWorker = [MasterKey, options, this]() {
262                 try {
263                         showProgressUI("Encrypting");
264
265                         INFO("Close all user sessions...");
266                         stopSystemdUserSessions();
267                         INFO("Close all processes using internal storage...");
268                         stopDependedSystemdServices();
269                         INFO("Umount internal storage...");
270                         while (::umount(INTERNAL_PATH) == -1) {
271                                 if (errno != EBUSY) {
272                                         throw runtime::Exception("Umount error - " + std::to_string(errno));
273                                 }
274                                 stopDependedSystemdServices();
275                         }
276
277                         INFO("Encryption started...");
278                         engine->encrypt(MasterKey, options);
279                         setOptions(options & getSupportedOptions());
280                         INFO("Sync disk...");
281                         sync();
282                         INFO("Encryption completed");
283
284                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "encrypted");
285                         ::reboot(RB_AUTOBOOT);
286                 } catch (runtime::Exception &e) {
287                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
288                         ERROR("Encryption failed - " + std::string(e.what()));
289                 }
290         };
291
292         std::thread asyncWork(encryptWorker);
293         asyncWork.detach();
294
295         return 0;
296 }
297
298 int InternalEncryption::decrypt(const std::string& password)
299 {
300         if (getState() != State::Encrypted) {
301                 return -1;
302         }
303
304         KeyManager::data pwData(password.begin(), password.end());
305         KeyManager keyManager(engine->getKeyMeta());
306
307         if (!keyManager.verifyPassword(pwData)) {
308                 return -2;
309         }
310
311         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
312         auto decryptWorker = [MasterKey, this]() {
313                 try {
314                         showProgressUI("Decrypting");
315
316                         INFO("Close all processes using internal storage...");
317                         stopDependedSystemdServices();
318                         INFO("Umount internal storage...");
319                         while (1) {
320                                 try {
321                                         engine->umount();
322                                         break;
323                                 } catch (runtime::Exception& e) {
324                                         stopDependedSystemdServices();
325                                 }
326                         }
327
328                         INFO("Decryption started...");
329                         engine->decrypt(MasterKey, getOptions());
330                         INFO("Sync disk...");
331                         sync();
332                         INFO("Decryption completed");
333
334                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "unencrypted");
335                         ::reboot(RB_AUTOBOOT);
336                 } catch (runtime::Exception &e) {
337                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
338                         ERROR("Decryption failed - " + std::string(e.what()));
339                 }
340         };
341
342         std::thread asyncWork(decryptWorker);
343         asyncWork.detach();
344
345         return 0;
346 }
347
348 int InternalEncryption::recovery()
349 {
350         if (getState() != State::Unencrypted) {
351                 return -1;
352         }
353
354         //TODO
355         runtime::Process proc(PROG_FACTORY_RESET, wipeCommand);
356         if (proc.execute() == -1) {
357                 ERROR("Failed to launch factory-reset");
358                 return -2;
359         }
360
361         return 0;
362 }
363
364 int InternalEncryption::isPasswordInitialized()
365 {
366         if (engine->isKeyMetaSet()) {
367                 return 1;
368         }
369         return 0;
370 }
371
372 int InternalEncryption::initPassword(const std::string& password)
373 {
374         KeyManager::data pwData(password.begin(), password.end());
375         KeyManager keyManager;
376
377         keyManager.initPassword(pwData);
378         engine->setKeyMeta(keyManager.serialize());
379         return 0;
380 }
381
382 int InternalEncryption::cleanPassword(const std::string& password)
383 {
384         KeyManager::data pwData(password.begin(), password.end());
385         KeyManager keyManager(engine->getKeyMeta());
386
387         if (!keyManager.verifyPassword(pwData)) {
388                 return -2;
389         }
390
391         engine->clearKeyMeta();
392         return 0;
393 }
394
395 int InternalEncryption::changePassword(const std::string& oldPassword,
396                                                                                 const std::string& newPassword)
397 {
398         KeyManager::data oldPwData(oldPassword.begin(), oldPassword.end());
399         KeyManager::data newPwData(newPassword.begin(), newPassword.end());
400         KeyManager keyManager(engine->getKeyMeta());
401
402         if (!keyManager.verifyPassword(oldPwData)) {
403                 return -2;
404         }
405
406         keyManager.changePassword(oldPwData, newPwData);
407         engine->setKeyMeta(keyManager.serialize());
408
409         return 0;
410 }
411
412 int InternalEncryption::verifyPassword(const std::string& password)
413 {
414         KeyManager::data pwData(password.begin(), password.end());
415         KeyManager keyManager(engine->getKeyMeta());
416
417         if (keyManager.verifyPassword(pwData)) {
418                 return 1;
419         }
420         return 0;
421 }
422
423 int InternalEncryption::getState()
424 {
425         char *value = ::vconf_get_str(INTERNAL_STATE_VCONF_KEY);
426         if (value == NULL) {
427                 throw runtime::Exception("Failed to get vconf value");
428         }
429
430         std::string valueStr(value);
431         free(value);
432
433         if (valueStr == "encrypted") {
434                 return State::Encrypted;
435         } else if (valueStr == "unencrypted") {
436                 return State::Unencrypted;
437         } else {
438                 return State::Corrupted;
439         }
440
441         return 0;
442 }
443
444 unsigned int InternalEncryption::getSupportedOptions()
445 {
446         return engine->getSupportedOptions();
447 }
448
449 } // namespace ode