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