284e436b14c19d4c1b6233ec7e9da9578f7fe8ff
[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 <klay/process.h>
25 #include <klay/file-user.h>
26 #include <klay/filesystem.h>
27 #include <klay/dbus/connection.h>
28 #include <klay/audit/logger.h>
29
30 #include "vconf.h"
31 #include "progress-bar.h"
32 #include "engine/dmcrypt-engine.h"
33 #include "key-manager/key-manager.h"
34
35 #include "rmi/internal-encryption.h"
36
37 #define INTERNAL_ENGINE DMCryptEngine
38 #define INTERNAL_DEV    "/dev/mmcblk0p25"
39 #define INTERNAL_PATH   "/opt/usr"
40 #define INTERNAL_STATE_VCONF_KEY                                        VCONFKEY_ODE_CRYPTO_STATE
41 #define INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY      VCONFKEY_ODE_FAST_ENCRYPTION
42
43 #define PRIVILEGE_PLATFORM "http://tizen.org/privilege/internal/default/platform"
44
45 namespace ode {
46
47 namespace {
48
49 std::unique_ptr<INTERNAL_ENGINE> engine;
50
51 void stopDependedSystemdServices()
52 {
53         dbus::Connection& systemDBus = dbus::Connection::getSystem();
54         std::set<std::string> servicesToStop;
55
56         for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
57                 try {
58                         char *service;
59                         systemDBus.methodcall("org.freedesktop.systemd1",
60                                                                         "/org/freedesktop/systemd1",
61                                                                         "org.freedesktop.systemd1.Manager",
62                                                                         "GetUnitByPID",
63                                                                         -1, "(o)", "(u)", (unsigned int)pid)
64                                                                                 .get("(o)", &service);
65                         servicesToStop.insert(service);
66                 } catch (runtime::Exception &e) {
67                         INFO("Close process - " + std::to_string(pid));
68                         ::kill(pid, SIGKILL);
69                 }
70         }
71
72         for (const std::string& service : servicesToStop) {
73                 INFO("Close service - " + service);
74                 systemDBus.methodcall("org.freedesktop.systemd1",
75                                                                 service,
76                                                                 "org.freedesktop.systemd1.Unit",
77                                                                 "Stop",
78                                                                 -1, "", "(s)", "flush");
79         }
80 }
81
82 void showProgressUI(const std::string type) {
83         std::vector<std::string> args = {
84                 "ode", "progress", type, "Internal"
85         };
86
87         runtime::Process proc("/usr/bin/ode", args);
88         proc.execute();
89 }
90
91 unsigned int getOptions()
92 {
93         unsigned int result = 0;
94         int value;
95
96         value = 0;
97         ::vconf_get_bool(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, &value);
98         if (value) {
99                 result |= InternalEncryption::Option::IncludeUnusedRegion;
100         }
101
102         return result;
103 }
104
105 void setOptions(unsigned int options)
106 {
107         bool value;
108
109         if (options & InternalEncryption::Option::IncludeUnusedRegion) {
110                 value = true;
111         } else {
112                 value = false;
113         }
114         ::vconf_set_bool(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, value);
115 }
116
117 }
118
119 InternalEncryption::InternalEncryption(ODEControlContext& ctx) :
120         context(ctx)
121 {
122         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::mount)(std::string));
123         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::umount)());
124         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::encrypt)(std::string, unsigned int));
125         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::decrypt)(std::string));
126         context.expose(this, "", (int)(InternalEncryption::isPasswordInitialized)());
127         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::initPassword)(std::string));
128         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::cleanPassword)(std::string));
129         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::changePassword)(std::string, std::string));
130         context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::verifyPassword)(std::string));
131         context.expose(this, "", (int)(InternalEncryption::getState)());
132         context.expose(this, "", (unsigned int)(InternalEncryption::getSupportedOptions)());
133
134         engine.reset(new INTERNAL_ENGINE(
135                 INTERNAL_DEV, INTERNAL_PATH,
136                 ProgressBar([](int v) {
137                         ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
138                                                         std::to_string(v).c_str());
139                 })
140         ));
141 }
142
143 InternalEncryption::~InternalEncryption()
144 {
145 }
146
147 int InternalEncryption::mount(const std::string& password)
148 {
149         if (getState() != State::Encrypted) {
150                 return -1;
151         }
152
153         KeyManager::data pwData(password.begin(), password.end());
154         KeyManager keyManager(engine->getKeyMeta());
155
156         if (!keyManager.verifyPassword(pwData)) {
157                 return -2;
158         }
159
160         engine->mount(keyManager.getMasterKey(pwData), getOptions());
161         return 0;
162 }
163
164 int InternalEncryption::umount()
165 {
166         if (getState() != State::Encrypted) {
167                 return -1;
168         }
169
170         INFO("Close all processes using internal storage...");
171         stopDependedSystemdServices();
172         INFO("Umount internal storage...");
173         engine->umount();
174
175         return 0;
176 }
177
178 int InternalEncryption::encrypt(const std::string& password, unsigned int options)
179 {
180         if (getState() != State::Unencrypted) {
181                 return -1;
182         }
183
184         KeyManager::data pwData(password.begin(), password.end());
185         KeyManager keyManager(engine->getKeyMeta());
186
187         if (!keyManager.verifyPassword(pwData)) {
188                 return -2;
189         }
190
191         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
192         auto encryptWorker = [MasterKey, options, this]() {
193                 try {
194                         showProgressUI("Encrypting");
195
196                         INFO("Close all processes using internal storage...");
197                         stopDependedSystemdServices();
198                         INFO("Umount internal storage...");
199                         while (::umount(INTERNAL_PATH) == -1) {
200                                 if (errno != EBUSY) {
201                                         throw runtime::Exception("Umount error - " + std::to_string(errno));
202                                 }
203                                 stopDependedSystemdServices();
204                         }
205
206                         INFO("Encryption started...");
207                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
208                         engine->encrypt(MasterKey, options);
209                         setOptions(options & getSupportedOptions());
210                         INFO("Sync disk...");
211                         sync();
212                         INFO("Encryption completed");
213
214                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "encrypted");
215                 } catch (runtime::Exception &e) {
216                         ERROR("Encryption failed - " + std::string(e.what()));
217                 }
218                 ::reboot(RB_AUTOBOOT);
219         };
220
221         std::thread asyncWork(encryptWorker);
222         asyncWork.detach();
223
224         return 0;
225 }
226
227 int InternalEncryption::decrypt(const std::string& password)
228 {
229         if (getState() != State::Encrypted) {
230                 return -1;
231         }
232
233         KeyManager::data pwData(password.begin(), password.end());
234         KeyManager keyManager(engine->getKeyMeta());
235
236         if (!keyManager.verifyPassword(pwData)) {
237                 return -2;
238         }
239
240         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
241         auto decryptWorker = [MasterKey, this]() {
242                 try {
243                         showProgressUI("Decrypting");
244
245                         INFO("Close all processes using internal storage...");
246                         stopDependedSystemdServices();
247                         INFO("Umount internal storage...");
248                         while (1) {
249                                 try {
250                                         engine->umount();
251                                         break;
252                                 } catch (runtime::Exception& e) {
253                                         stopDependedSystemdServices();
254                                 }
255                         }
256
257                         INFO("Decryption started...");
258                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
259                         engine->decrypt(MasterKey, getOptions());
260                         INFO("Sync disk...");
261                         sync();
262                         INFO("Decryption completed");
263
264                         ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "unencrypted");
265                 } catch (runtime::Exception &e) {
266                         ERROR("Decryption failed - " + std::string(e.what()));
267                 }
268                 ::reboot(RB_AUTOBOOT);
269         };
270
271         std::thread asyncWork(decryptWorker);
272         asyncWork.detach();
273
274         return 0;
275 }
276
277 int InternalEncryption::isPasswordInitialized()
278 {
279         if (engine->isKeyMetaSet()) {
280                 return 1;
281         }
282         return 0;
283 }
284
285 int InternalEncryption::initPassword(const std::string& password)
286 {
287         KeyManager::data pwData(password.begin(), password.end());
288         KeyManager keyManager;
289
290         keyManager.initPassword(pwData);
291         engine->setKeyMeta(keyManager.serialize());
292         return 0;
293 }
294
295 int InternalEncryption::cleanPassword(const std::string& password)
296 {
297         KeyManager::data pwData(password.begin(), password.end());
298         KeyManager keyManager(engine->getKeyMeta());
299
300         if (!keyManager.verifyPassword(pwData)) {
301                 return -2;
302         }
303
304         engine->clearKeyMeta();
305         return 0;
306 }
307
308 int InternalEncryption::changePassword(const std::string& oldPassword,
309                                                                                 const std::string& newPassword)
310 {
311         KeyManager::data oldPwData(oldPassword.begin(), oldPassword.end());
312         KeyManager::data newPwData(newPassword.begin(), newPassword.end());
313         KeyManager keyManager(engine->getKeyMeta());
314
315         if (!keyManager.verifyPassword(oldPwData)) {
316                 return -2;
317         }
318
319         keyManager.changePassword(oldPwData, newPwData);
320         engine->setKeyMeta(keyManager.serialize());
321
322         return 0;
323 }
324
325 int InternalEncryption::verifyPassword(const std::string& password)
326 {
327         KeyManager::data pwData(password.begin(), password.end());
328         KeyManager keyManager(engine->getKeyMeta());
329
330         if (keyManager.verifyPassword(pwData)) {
331                 return 1;
332         }
333         return 0;
334 }
335
336 int InternalEncryption::getState()
337 {
338         char *value = ::vconf_get_str(INTERNAL_STATE_VCONF_KEY);
339         if (value == NULL) {
340                 throw runtime::Exception("Failed to get vconf value");
341         }
342
343         std::string valueStr(value);
344         free(value);
345
346         if (valueStr == "encrypted") {
347                 return State::Encrypted;
348         } else if (valueStr == "unencrypted") {
349                 return State::Unencrypted;
350         } else {
351                 return State::Corrupted;
352         }
353
354         return 0;
355 }
356
357 unsigned int InternalEncryption::getSupportedOptions()
358 {
359         return engine->getSupportedOptions();
360 }
361
362 } // namespace ode