Internal encryption: Fix missing elm config files and locales
[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 stopDependedSystemdServices()
64 {
65         dbus::Connection& systemDBus = dbus::Connection::getSystem();
66         std::set<std::string> servicesToStop;
67
68         for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
69                 try {
70                         char *service;
71                         systemDBus.methodcall("org.freedesktop.systemd1",
72                                                                         "/org/freedesktop/systemd1",
73                                                                         "org.freedesktop.systemd1.Manager",
74                                                                         "GetUnitByPID",
75                                                                         -1, "(o)", "(u)", (unsigned int)pid)
76                                                                                 .get("(o)", &service);
77                         servicesToStop.insert(service);
78                 } catch (runtime::Exception &e) {
79                         INFO("Close process - " + std::to_string(pid));
80                         ::kill(pid, SIGKILL);
81                 }
82         }
83
84         for (const std::string& service : servicesToStop) {
85                 INFO("Close service - " + service);
86                 systemDBus.methodcall("org.freedesktop.systemd1",
87                                                                 service,
88                                                                 "org.freedesktop.systemd1.Unit",
89                                                                 "Stop",
90                                                                 -1, "", "(s)", "flush");
91         }
92 }
93
94 void showProgressUI(const std::string type) {
95         ::tzplatform_set_user(::tzplatform_getuid(TZ_SYS_DEFAULT_USER));
96         std::string defaultUserHome(::tzplatform_getenv(TZ_USER_HOME));
97         ::tzplatform_reset_user();
98
99         ::tzplatform_set_user(::getuid());
100         std::string currentUserHome(::tzplatform_getenv(TZ_USER_HOME));
101         ::tzplatform_reset_user();
102
103         INFO("Home directory : " + currentUserHome);
104
105         runtime::File shareDirectory(currentUserHome + "/share");
106         if (!shareDirectory.exists()) {
107                 shareDirectory.makeDirectory();
108         }
109
110         runtime::File elmConfigDir(currentUserHome + "/share/.elementary");
111         if (!elmConfigDir.exists()) {
112                 runtime::File defaultElmConfigDir(defaultUserHome + "/share/.elementary");
113                 defaultElmConfigDir.copyTo(shareDirectory.getPath());
114         }
115
116         std::vector<std::string> args = {
117                 "ode", "progress", type, "Internal"
118         };
119
120         runtime::Process proc("/usr/bin/ode", args);
121         proc.execute();
122 }
123
124 unsigned int getOptions()
125 {
126         unsigned int result = 0;
127         int value;
128
129         value = 0;
130         ::vconf_get_bool(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, &value);
131         if (value) {
132                 result |= InternalEncryption::Option::IncludeUnusedRegion;
133         }
134
135         return result;
136 }
137
138 void setOptions(unsigned int options)
139 {
140         bool value;
141
142         if (options & InternalEncryption::Option::IncludeUnusedRegion) {
143                 value = true;
144         } else {
145                 value = false;
146         }
147         ::vconf_set_bool(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, value);
148 }
149
150 }
151
152 InternalEncryption::InternalEncryption(ODEControlContext& ctx) :
153         context(ctx)
154 {
155         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::mount)(std::string));
156         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::umount)());
157         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::encrypt)(std::string, unsigned int));
158         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::decrypt)(std::string));
159         context.expose(this, "", (int)(InternalEncryption::isPasswordInitialized)());
160         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::initPassword)(std::string));
161         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::cleanPassword)(std::string));
162         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::changePassword)(std::string, std::string));
163         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::verifyPassword)(std::string));
164         context.expose(this, "", (int)(InternalEncryption::getState)());
165         context.expose(this, "", (unsigned int)(InternalEncryption::getSupportedOptions)());
166
167         engine.reset(new INTERNAL_ENGINE(
168                 INTERNAL_DEV, INTERNAL_PATH,
169                 ProgressBar([](int v) {
170                         ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
171                                                         std::to_string(v).c_str());
172                 })
173         ));
174 }
175
176 InternalEncryption::~InternalEncryption()
177 {
178 }
179
180 int InternalEncryption::mount(const std::string& password)
181 {
182         if (getState() != State::Encrypted) {
183                 return -1;
184         }
185
186         KeyManager::data pwData(password.begin(), password.end());
187         KeyManager keyManager(engine->getKeyMeta());
188
189         if (!keyManager.verifyPassword(pwData)) {
190                 return -2;
191         }
192
193         engine->mount(keyManager.getMasterKey(pwData), getOptions());
194         return 0;
195 }
196
197 int InternalEncryption::umount()
198 {
199         if (getState() != State::Encrypted) {
200                 return -1;
201         }
202
203         INFO("Close all processes using internal storage...");
204         stopDependedSystemdServices();
205         INFO("Umount internal storage...");
206         engine->umount();
207
208         return 0;
209 }
210
211 int InternalEncryption::encrypt(const std::string& password, unsigned int options)
212 {
213         if (getState() != State::Unencrypted) {
214                 return -1;
215         }
216
217         KeyManager::data pwData(password.begin(), password.end());
218         KeyManager keyManager(engine->getKeyMeta());
219
220         if (!keyManager.verifyPassword(pwData)) {
221                 return -2;
222         }
223
224         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
225         auto encryptWorker = [MasterKey, options, this]() {
226                 try {
227                         showProgressUI("Encrypting");
228
229                         INFO("Close all processes using internal storage...");
230                         stopDependedSystemdServices();
231                         INFO("Umount internal storage...");
232                         while (::umount(INTERNAL_PATH) == -1) {
233                                 if (errno != EBUSY) {
234                                         throw runtime::Exception("Umount error - " + std::to_string(errno));
235                                 }
236                                 stopDependedSystemdServices();
237                         }
238
239                         INFO("Encryption started...");
240                         engine->encrypt(MasterKey, options);
241                         setOptions(options & getSupportedOptions());
242                         INFO("Sync disk...");
243                         sync();
244                         INFO("Encryption completed");
245
246                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "encrypted");
247                         ::reboot(RB_AUTOBOOT);
248                 } catch (runtime::Exception &e) {
249                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
250                         ERROR("Encryption failed - " + std::string(e.what()));
251                 }
252         };
253
254         std::thread asyncWork(encryptWorker);
255         asyncWork.detach();
256
257         return 0;
258 }
259
260 int InternalEncryption::decrypt(const std::string& password)
261 {
262         if (getState() != State::Encrypted) {
263                 return -1;
264         }
265
266         KeyManager::data pwData(password.begin(), password.end());
267         KeyManager keyManager(engine->getKeyMeta());
268
269         if (!keyManager.verifyPassword(pwData)) {
270                 return -2;
271         }
272
273         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
274         auto decryptWorker = [MasterKey, this]() {
275                 try {
276                         showProgressUI("Decrypting");
277
278                         INFO("Close all processes using internal storage...");
279                         stopDependedSystemdServices();
280                         INFO("Umount internal storage...");
281                         while (1) {
282                                 try {
283                                         engine->umount();
284                                         break;
285                                 } catch (runtime::Exception& e) {
286                                         stopDependedSystemdServices();
287                                 }
288                         }
289
290                         INFO("Decryption started...");
291                         engine->decrypt(MasterKey, getOptions());
292                         INFO("Sync disk...");
293                         sync();
294                         INFO("Decryption completed");
295
296                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "unencrypted");
297                         ::reboot(RB_AUTOBOOT);
298                 } catch (runtime::Exception &e) {
299                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
300                         ERROR("Decryption failed - " + std::string(e.what()));
301                 }
302         };
303
304         std::thread asyncWork(decryptWorker);
305         asyncWork.detach();
306
307         return 0;
308 }
309
310 int InternalEncryption::recovery()
311 {
312         if (getState() != State::Unencrypted) {
313                 return -1;
314         }
315
316         //TODO
317         runtime::Process proc(PROG_FACTORY_RESET, wipeCommand);
318         if (proc.execute() == -1) {
319                 ERROR("Failed to launch factory-reset");
320                 return -2;
321         }
322
323         return 0;
324 }
325
326 int InternalEncryption::isPasswordInitialized()
327 {
328         if (engine->isKeyMetaSet()) {
329                 return 1;
330         }
331         return 0;
332 }
333
334 int InternalEncryption::initPassword(const std::string& password)
335 {
336         KeyManager::data pwData(password.begin(), password.end());
337         KeyManager keyManager;
338
339         keyManager.initPassword(pwData);
340         engine->setKeyMeta(keyManager.serialize());
341         return 0;
342 }
343
344 int InternalEncryption::cleanPassword(const std::string& password)
345 {
346         KeyManager::data pwData(password.begin(), password.end());
347         KeyManager keyManager(engine->getKeyMeta());
348
349         if (!keyManager.verifyPassword(pwData)) {
350                 return -2;
351         }
352
353         engine->clearKeyMeta();
354         return 0;
355 }
356
357 int InternalEncryption::changePassword(const std::string& oldPassword,
358                                                                                 const std::string& newPassword)
359 {
360         KeyManager::data oldPwData(oldPassword.begin(), oldPassword.end());
361         KeyManager::data newPwData(newPassword.begin(), newPassword.end());
362         KeyManager keyManager(engine->getKeyMeta());
363
364         if (!keyManager.verifyPassword(oldPwData)) {
365                 return -2;
366         }
367
368         keyManager.changePassword(oldPwData, newPwData);
369         engine->setKeyMeta(keyManager.serialize());
370
371         return 0;
372 }
373
374 int InternalEncryption::verifyPassword(const std::string& password)
375 {
376         KeyManager::data pwData(password.begin(), password.end());
377         KeyManager keyManager(engine->getKeyMeta());
378
379         if (keyManager.verifyPassword(pwData)) {
380                 return 1;
381         }
382         return 0;
383 }
384
385 int InternalEncryption::getState()
386 {
387         char *value = ::vconf_get_str(INTERNAL_STATE_VCONF_KEY);
388         if (value == NULL) {
389                 throw runtime::Exception("Failed to get vconf value");
390         }
391
392         std::string valueStr(value);
393         free(value);
394
395         if (valueStr == "encrypted") {
396                 return State::Encrypted;
397         } else if (valueStr == "unencrypted") {
398                 return State::Unencrypted;
399         } else {
400                 return State::Corrupted;
401         }
402
403         return 0;
404 }
405
406 unsigned int InternalEncryption::getSupportedOptions()
407 {
408         return engine->getSupportedOptions();
409 }
410
411 } // namespace ode