Change the touch file path /tmp to /run
[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("/run/.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("/run/.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                 context.ref();
249                 try {
250                         INFO(SINK, "Close all processes that use internal storage...");
251                         stopDependedSystemdServices();
252                         killDependedProcesses();
253                         INFO(SINK, "Umount internal storage...");
254                         while (::umount(INTERNAL_PATH) == -1) {
255                                 if (errno != EBUSY) {
256                                         throw runtime::Exception("Umount error - " + std::to_string(errno));
257                                 }
258                                 killDependedProcesses();
259                         }
260
261                         showProgressUI("Encrypting");
262
263                         INFO(SINK, "Encryption started...");
264                         engine->encrypt(MasterKey, options);
265                         setOptions(options & getSupportedOptions());
266                         INFO(SINK, "Sync disk...");
267                         sync();
268                         INFO(SINK, "Encryption completed");
269
270                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "encrypted");
271                         context.notify("InternalEncryption::mount");
272                         ::reboot(RB_AUTOBOOT);
273                 } catch (runtime::Exception &e) {
274                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
275                         ERROR(SINK, "Encryption failed - " + std::string(e.what()));
276                 }
277                 context.unref();
278         };
279
280         std::thread asyncWork(encryptWorker);
281         asyncWork.detach();
282
283         return 0;
284 }
285
286 int InternalEncryption::decrypt(const std::string& password)
287 {
288         if (getState() != State::Encrypted) {
289                 return -1;
290         }
291
292         KeyManager::data pwData(password.begin(), password.end());
293         KeyManager keyManager(engine->getKeyMeta());
294
295         if (!keyManager.verifyPassword(pwData)) {
296                 return -2;
297         }
298
299         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
300         auto decryptWorker = [MasterKey, this]() {
301                 context.ref();
302                 try {
303                         INFO(SINK, "Umount internal storage...");
304                         stopDependedSystemdServices();
305                         killDependedProcesses();
306                         INFO(SINK, "Umount internal storage...");
307                         while (1) {
308                                 try {
309                                         engine->umount();
310                                         break;
311                                 } catch (runtime::Exception& e) {
312                                         killDependedProcesses();
313                                 }
314                         }
315
316                         showProgressUI("Decrypting");
317
318                         INFO(SINK, "Decryption started...");
319                         engine->decrypt(MasterKey, getOptions());
320                         INFO(SINK, "Sync disk...");
321                         sync();
322                         INFO(SINK, "Decryption completed");
323
324                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "unencrypted");
325                         ::reboot(RB_AUTOBOOT);
326                 } catch (runtime::Exception &e) {
327                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
328                         ERROR(SINK, "Decryption failed - " + std::string(e.what()));
329                 }
330                 context.unref();
331         };
332
333         std::thread asyncWork(decryptWorker);
334         asyncWork.detach();
335
336         return 0;
337 }
338
339 int InternalEncryption::recovery()
340 {
341         if (getState() != State::Unencrypted) {
342                 return -1;
343         }
344
345         //TODO
346         runtime::Process proc(PROG_FACTORY_RESET, wipeCommand);
347         if (proc.execute() == -1) {
348                 ERROR(SINK, "Failed to launch factory-reset");
349                 return -2;
350         }
351
352         return 0;
353 }
354
355 int InternalEncryption::isPasswordInitialized()
356 {
357         if (engine->isKeyMetaSet()) {
358                 return 1;
359         }
360         return 0;
361 }
362
363 int InternalEncryption::initPassword(const std::string& password)
364 {
365         KeyManager::data pwData(password.begin(), password.end());
366         KeyManager keyManager;
367
368         keyManager.initPassword(pwData);
369         engine->setKeyMeta(keyManager.serialize());
370         return 0;
371 }
372
373 int InternalEncryption::cleanPassword(const std::string& password)
374 {
375         KeyManager::data pwData(password.begin(), password.end());
376         KeyManager keyManager(engine->getKeyMeta());
377
378         if (!keyManager.verifyPassword(pwData)) {
379                 return -2;
380         }
381
382         engine->clearKeyMeta();
383         return 0;
384 }
385
386 int InternalEncryption::changePassword(const std::string& oldPassword,
387                                                                                 const std::string& newPassword)
388 {
389         KeyManager::data oldPwData(oldPassword.begin(), oldPassword.end());
390         KeyManager::data newPwData(newPassword.begin(), newPassword.end());
391         KeyManager keyManager(engine->getKeyMeta());
392
393         if (!keyManager.verifyPassword(oldPwData)) {
394                 return -2;
395         }
396
397         keyManager.changePassword(oldPwData, newPwData);
398         engine->setKeyMeta(keyManager.serialize());
399
400         return 0;
401 }
402
403 int InternalEncryption::verifyPassword(const std::string& password)
404 {
405         KeyManager::data pwData(password.begin(), password.end());
406         KeyManager keyManager(engine->getKeyMeta());
407
408         if (keyManager.verifyPassword(pwData)) {
409                 return 1;
410         }
411         return 0;
412 }
413
414 int InternalEncryption::getState()
415 {
416         char *value = ::vconf_get_str(INTERNAL_STATE_VCONF_KEY);
417         if (value == NULL) {
418                 throw runtime::Exception("Failed to get vconf value");
419         }
420
421         std::string valueStr(value);
422         free(value);
423
424         if (valueStr == "encrypted") {
425                 return State::Encrypted;
426         } else if (valueStr == "unencrypted") {
427                 return State::Unencrypted;
428         } else {
429                 return State::Corrupted;
430         }
431
432         return 0;
433 }
434
435 unsigned int InternalEncryption::getSupportedOptions()
436 {
437         return engine->getSupportedOptions();
438 }
439
440 } // namespace ode