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