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