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