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