a8f3ad60990cb1cef5651cf6737ecf810f10d123
[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.registerParametricMethod(this, "", (int)(InternalEncryption::mount)(std::string));
120         context.registerNonparametricMethod(this, "", (int)(InternalEncryption::umount));
121         context.registerParametricMethod(this, "", (int)(InternalEncryption::encrypt)(std::string, unsigned int));
122         context.registerParametricMethod(this, "", (int)(InternalEncryption::decrypt)(std::string));
123         context.registerNonparametricMethod(this, "", (int)(InternalEncryption::isPasswordInitialized));
124         context.registerParametricMethod(this, "", (int)(InternalEncryption::initPassword)(std::string));
125         context.registerParametricMethod(this, "", (int)(InternalEncryption::cleanPassword)(std::string));
126         context.registerParametricMethod(this, "", (int)(InternalEncryption::changePassword)(std::string, std::string));
127         context.registerParametricMethod(this, "", (int)(InternalEncryption::verifyPassword)(std::string));
128         context.registerNonparametricMethod(this, "", (int)(InternalEncryption::getState));
129         context.registerNonparametricMethod(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                 showProgressUI("Encrypting");
183
184                 INFO("Close all processes using internal storage...");
185                 stopDependedSystemdServices();
186                 INFO("Umount internal storage...");
187                 while (::umount(INTERNAL_STORAGE_PATH) == -1) {
188                         if (errno != EBUSY) {
189                                 break;
190                         }
191                 }
192
193                 INFO("Encryption started...");
194                 ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
195                 engine.encrypt(MasterKey, options);
196                 setOptions(options & getSupportedOptions());
197                 INFO("Sync disk...");
198                 sync();
199                 INFO("Encryption completed");
200
201                 ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "encrypted");
202                 ::reboot(RB_AUTOBOOT);
203         };
204
205         std::thread asyncWork(encryptWorker);
206         asyncWork.detach();
207
208         return 0;
209 }
210
211 int InternalEncryption::decrypt(const std::string& password)
212 {
213         if (getState() != State::Encrypted) {
214                 return -1;
215         }
216
217         KeyManager::data pwData(password.begin(), password.end());
218         KeyManager keyManager(engine.getKeyMeta());
219
220         if (!keyManager.verifyPassword(pwData)) {
221                 return -2;
222         }
223
224         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
225         auto decryptWorker = [MasterKey, this]() {
226                 showProgressUI("Decrypting");
227
228                 INFO("Close all processes using internal storage...");
229                 stopDependedSystemdServices();
230                 INFO("Umount internal storage...");
231                 try {
232                         engine.umount();
233                 } catch (runtime::Exception& e) {}
234
235                 INFO("Decryption started...");
236                 ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
237                 engine.decrypt(MasterKey, getOptions());
238                 INFO("Sync disk...");
239                 sync();
240                 INFO("Decryption completed");
241
242                 ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "unencrypted");
243                 ::reboot(RB_AUTOBOOT);
244         };
245
246         std::thread asyncWork(decryptWorker);
247         asyncWork.detach();
248
249         return 0;
250 }
251
252 int InternalEncryption::isPasswordInitialized()
253 {
254         if (engine.isKeyMetaSet()) {
255                 return 1;
256         }
257         return 0;
258 }
259
260 int InternalEncryption::initPassword(const std::string& password)
261 {
262         KeyManager::data pwData(password.begin(), password.end());
263         KeyManager keyManager;
264
265         keyManager.initPassword(pwData);
266         engine.setKeyMeta(keyManager.serialize());
267         return 0;
268 }
269
270 int InternalEncryption::cleanPassword(const std::string& password)
271 {
272         KeyManager::data pwData(password.begin(), password.end());
273         KeyManager keyManager(engine.getKeyMeta());
274
275         if (!keyManager.verifyPassword(pwData)) {
276                 return -2;
277         }
278
279         engine.clearKeyMeta();
280         return 0;
281 }
282
283 int InternalEncryption::changePassword(const std::string& oldPassword,
284                                                                                 const std::string& newPassword)
285 {
286         KeyManager::data oldPwData(oldPassword.begin(), oldPassword.end());
287         KeyManager::data newPwData(newPassword.begin(), newPassword.end());
288         KeyManager keyManager(engine.getKeyMeta());
289
290         if (!keyManager.verifyPassword(oldPwData)) {
291                 return -2;
292         }
293
294         keyManager.changePassword(oldPwData, newPwData);
295         engine.setKeyMeta(keyManager.serialize());
296
297         return 0;
298 }
299
300 int InternalEncryption::verifyPassword(const std::string& password)
301 {
302         KeyManager::data pwData(password.begin(), password.end());
303         KeyManager keyManager(engine.getKeyMeta());
304
305         if (keyManager.verifyPassword(pwData)) {
306                 return 1;
307         }
308         return 0;
309 }
310
311
312
313 int InternalEncryption::getState()
314 {
315         char *value = ::vconf_get_str(INTERNAL_STATE_VCONF_KEY);
316         if (value == NULL) {
317                 throw runtime::Exception("Failed to get vconf value");
318         }
319
320         std::string valueStr(value);
321         free(value);
322
323         if (valueStr == "encrypted") {
324                 return State::Encrypted;
325         } else if (valueStr == "unencrypted") {
326                 return State::Unencrypted;
327         } else {
328                 return State::Corrupted;
329         }
330
331         return 0;
332 }
333
334 unsigned int InternalEncryption::getSupportedOptions()
335 {
336         return engine.getSupportedOptions();
337 }
338
339 } // namespace ode