Change ode daemon as non-root
[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         INFO(SINK, "Ret - " + std::to_string(ret));
86     }
87 }
88
89 void showProgressUI(const std::string type) {
90         runtime::File fileToTouch("/tmp/.ode-progress-internal@" + type);
91         try {
92                 fileToTouch.remove();
93         } catch(runtime::Exception &e) {}
94         fileToTouch.create(O_WRONLY);
95 }
96
97 unsigned int getOptions()
98 {
99         unsigned int result = 0;
100         int value;
101
102         value = 0;
103         ::vconf_get_bool(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, &value);
104         if (value) {
105                 result |= InternalEncryption::Option::IncludeUnusedRegion;
106         }
107
108         return result;
109 }
110
111 void setOptions(unsigned int options)
112 {
113         bool value;
114
115         if (options & InternalEncryption::Option::IncludeUnusedRegion) {
116                 value = true;
117         } else {
118                 value = false;
119         }
120         ::vconf_set_bool(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, value);
121 }
122
123 }
124
125 InternalEncryption::InternalEncryption(ODEControlContext& ctx) :
126         context(ctx)
127 {
128         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::setMountPassword)(std::string));
129         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::mount)());
130         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::umount)());
131         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::encrypt)(std::string, unsigned int));
132         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::decrypt)(std::string));
133         context.expose(this, "", (int)(InternalEncryption::isPasswordInitialized)());
134         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::initPassword)(std::string));
135         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::cleanPassword)(std::string));
136         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::changePassword)(std::string, std::string));
137         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::verifyPassword)(std::string));
138         context.expose(this, "", (int)(InternalEncryption::getState)());
139         context.expose(this, "", (unsigned int)(InternalEncryption::getSupportedOptions)());
140
141         context.createNotification("InternalEncryption::mount");
142
143         std::string source = INTERNAL_DEV_PATH "/" INTERNAL_DEV_NAME;
144         try {
145                 runtime::DirectoryIterator iter(INTERNAL_DEV_PATH), end;
146
147                 while (iter != end) {
148                         const std::string& path = (*iter).getPath();
149                         std::string name = path.substr(path.rfind('/') + 1);
150                         std::string upper;
151                         upper.reserve(name.size());
152                         for (char c : name) {
153                                 upper += std::toupper(c);
154                         }
155                         if (upper == INTERNAL_DEV_NAME) {
156                                 source = path;
157                                 break;
158                         }
159                         ++iter;
160                 }
161         } catch (runtime::Exception &e) {}
162
163         engine.reset(new INTERNAL_ENGINE(
164                 source, INTERNAL_PATH,
165                 ProgressBar([](int v) {
166                         ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
167                                                         std::to_string(v).c_str());
168                 })
169         ));
170 }
171
172 InternalEncryption::~InternalEncryption()
173 {
174 }
175
176 int InternalEncryption::setMountPassword(const std::string& password)
177 {
178         KeyManager::data pwData(password.begin(), password.end());
179         KeyManager keyManager(engine->getKeyMeta());
180         if (!keyManager.verifyPassword(pwData)) {
181                 return -2;
182         }
183
184         ode::mountKey = keyManager.getMasterKey(pwData);
185
186         return 0;
187 }
188
189 int InternalEncryption::mount()
190 {
191         if (getState() != State::Encrypted) {
192                 return -1;
193         }
194
195     if (engine->isMounted()) {
196                 INFO(SINK, "Already mounted");
197                 return 0;
198         }
199
200         engine->mount(mountKey, getOptions());
201         mountKey.clear();
202
203         context.notify("InternalEncryption::mount");
204
205         runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
206         runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
207
208         return 0;
209 }
210
211 int InternalEncryption::umount()
212 {
213         if (getState() != State::Encrypted) {
214                 return -1;
215         }
216
217         if (!engine->isMounted()) {
218                 INFO(SINK, "Already umounted");
219                 return 0;
220         }
221
222         INFO(SINK, "Close all processes that use internal storage...");
223         stopDependedSystemdServices();
224         killDependedProcesses();
225         INFO(SINK, "Umount internal storage...");
226         engine->umount();
227
228         return 0;
229 }
230
231 int InternalEncryption::encrypt(const std::string& password, unsigned int options)
232 {
233         if (getState() != State::Unencrypted) {
234                 return -1;
235         }
236
237         KeyManager::data pwData(password.begin(), password.end());
238         KeyManager keyManager(engine->getKeyMeta());
239
240         if (!keyManager.verifyPassword(pwData)) {
241                 return -2;
242         }
243
244         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
245         auto encryptWorker = [MasterKey, options, this]() {
246                 try {
247                         INFO(SINK, "Close all processes that use internal storage...");
248                         stopDependedSystemdServices();
249                         killDependedProcesses();
250                         INFO(SINK, "Umount internal storage...");
251                         while (::umount(INTERNAL_PATH) == -1) {
252                                 if (errno != EBUSY) {
253                                         throw runtime::Exception("Umount error - " + std::to_string(errno));
254                                 }
255                                 killDependedProcesses();
256                         }
257
258                         showProgressUI("Encrypting");
259
260                         INFO(SINK, "Encryption started...");
261                         engine->encrypt(MasterKey, options);
262                         setOptions(options & getSupportedOptions());
263                         INFO(SINK, "Sync disk...");
264                         sync();
265                         INFO(SINK, "Encryption completed");
266
267                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "encrypted");
268                         context.notify("InternalEncryption::mount");
269                         ::reboot(RB_AUTOBOOT);
270                 } catch (runtime::Exception &e) {
271                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
272                         ERROR(SINK, "Encryption failed - " + std::string(e.what()));
273                 }
274         };
275
276         std::thread asyncWork(encryptWorker);
277         asyncWork.detach();
278
279         return 0;
280 }
281
282 int InternalEncryption::decrypt(const std::string& password)
283 {
284         if (getState() != State::Encrypted) {
285                 return -1;
286         }
287
288         KeyManager::data pwData(password.begin(), password.end());
289         KeyManager keyManager(engine->getKeyMeta());
290
291         if (!keyManager.verifyPassword(pwData)) {
292                 return -2;
293         }
294
295         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
296         auto decryptWorker = [MasterKey, this]() {
297                 try {
298                         INFO(SINK, "Umount internal storage...");
299                         stopDependedSystemdServices();
300                         killDependedProcesses();
301                         INFO(SINK, "Umount internal storage...");
302                         while (1) {
303                                 try {
304                                         engine->umount();
305                                         break;
306                                 } catch (runtime::Exception& e) {
307                                         killDependedProcesses();
308                                 }
309                         }
310
311                         showProgressUI("Decrypting");
312
313                         INFO(SINK, "Decryption started...");
314                         engine->decrypt(MasterKey, getOptions());
315                         INFO(SINK, "Sync disk...");
316                         sync();
317                         INFO(SINK, "Decryption completed");
318
319                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "unencrypted");
320                         ::reboot(RB_AUTOBOOT);
321                 } catch (runtime::Exception &e) {
322                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
323                         ERROR(SINK, "Decryption failed - " + std::string(e.what()));
324                 }
325         };
326
327         std::thread asyncWork(decryptWorker);
328         asyncWork.detach();
329
330         return 0;
331 }
332
333 int InternalEncryption::recovery()
334 {
335         if (getState() != State::Unencrypted) {
336                 return -1;
337         }
338
339         //TODO
340         runtime::Process proc(PROG_FACTORY_RESET, wipeCommand);
341         if (proc.execute() == -1) {
342                 ERROR(SINK, "Failed to launch factory-reset");
343                 return -2;
344         }
345
346         return 0;
347 }
348
349 int InternalEncryption::isPasswordInitialized()
350 {
351         if (engine->isKeyMetaSet()) {
352                 return 1;
353         }
354         return 0;
355 }
356
357 int InternalEncryption::initPassword(const std::string& password)
358 {
359         KeyManager::data pwData(password.begin(), password.end());
360         KeyManager keyManager;
361
362         keyManager.initPassword(pwData);
363         engine->setKeyMeta(keyManager.serialize());
364         return 0;
365 }
366
367 int InternalEncryption::cleanPassword(const std::string& password)
368 {
369         KeyManager::data pwData(password.begin(), password.end());
370         KeyManager keyManager(engine->getKeyMeta());
371
372         if (!keyManager.verifyPassword(pwData)) {
373                 return -2;
374         }
375
376         engine->clearKeyMeta();
377         return 0;
378 }
379
380 int InternalEncryption::changePassword(const std::string& oldPassword,
381                                                                                 const std::string& newPassword)
382 {
383         KeyManager::data oldPwData(oldPassword.begin(), oldPassword.end());
384         KeyManager::data newPwData(newPassword.begin(), newPassword.end());
385         KeyManager keyManager(engine->getKeyMeta());
386
387         if (!keyManager.verifyPassword(oldPwData)) {
388                 return -2;
389         }
390
391         keyManager.changePassword(oldPwData, newPwData);
392         engine->setKeyMeta(keyManager.serialize());
393
394         return 0;
395 }
396
397 int InternalEncryption::verifyPassword(const std::string& password)
398 {
399         KeyManager::data pwData(password.begin(), password.end());
400         KeyManager keyManager(engine->getKeyMeta());
401
402         if (keyManager.verifyPassword(pwData)) {
403                 return 1;
404         }
405         return 0;
406 }
407
408 int InternalEncryption::getState()
409 {
410         char *value = ::vconf_get_str(INTERNAL_STATE_VCONF_KEY);
411         if (value == NULL) {
412                 throw runtime::Exception("Failed to get vconf value");
413         }
414
415         std::string valueStr(value);
416         free(value);
417
418         if (valueStr == "encrypted") {
419                 return State::Encrypted;
420         } else if (valueStr == "unencrypted") {
421                 return State::Unencrypted;
422         } else {
423                 return State::Corrupted;
424         }
425
426         return 0;
427 }
428
429 unsigned int InternalEncryption::getSupportedOptions()
430 {
431         return engine->getSupportedOptions();
432 }
433
434 } // namespace ode