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