Add APIs to managing password
[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::isPasswordCreated));
124         context.registerParametricMethod(this, "", (int)(InternalEncryption::createPassword)(std::string));
125         context.registerParametricMethod(this, "", (int)(InternalEncryption::deletePassword)(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::isPasswordCreated()
253 {
254         if (engine.isKeyMetaCreated()) {
255                 return 1;
256         }
257         return 0;
258 }
259
260 int InternalEncryption::createPassword(const std::string& password)
261 {
262         KeyManager::data pwData(password.begin(), password.end());
263         KeyManager keyManager;
264
265         if (engine.isKeyMetaCreated()) {
266                 return -2;
267         }
268
269         keyManager.initPassword(pwData);
270         engine.setKeyMeta(keyManager.serialize());
271         return 0;
272 }
273
274 int InternalEncryption::deletePassword(const std::string& password)
275 {
276         KeyManager::data pwData(password.begin(), password.end());
277         KeyManager keyManager(engine.getKeyMeta());
278
279         if (!keyManager.verifyPassword(pwData)) {
280                 return -2;
281         }
282
283         engine.clearKeyMeta();
284         return 0;
285 }
286
287 int InternalEncryption::changePassword(const std::string& oldPassword,
288                                                                                 const std::string& newPassword)
289 {
290         KeyManager::data oldPwData(oldPassword.begin(), oldPassword.end());
291         KeyManager::data newPwData(newPassword.begin(), newPassword.end());
292         KeyManager keyManager(engine.getKeyMeta());
293
294         if (!keyManager.verifyPassword(oldPwData)) {
295                 return -2;
296         }
297
298         keyManager.changePassword(oldPwData, newPwData);
299         engine.setKeyMeta(keyManager.serialize());
300
301         return 0;
302 }
303
304 int InternalEncryption::verifyPassword(const std::string& password)
305 {
306         KeyManager::data pwData(password.begin(), password.end());
307         KeyManager keyManager(engine.getKeyMeta());
308
309         if (keyManager.verifyPassword(pwData)) {
310                 return 1;
311         }
312         return 0;
313 }
314
315
316
317 int InternalEncryption::getState()
318 {
319         char *value = ::vconf_get_str(INTERNAL_STATE_VCONF_KEY);
320         if (value == NULL) {
321                 throw runtime::Exception("Failed to get vconf value");
322         }
323
324         std::string valueStr(value);
325         free(value);
326
327         if (valueStr == "encrypted") {
328                 return State::Encrypted;
329         } else if (valueStr == "unencrypted") {
330                 return State::Unencrypted;
331         } else {
332                 return State::Corrupted;
333         }
334
335         return 0;
336 }
337
338 unsigned int InternalEncryption::getSupportedOptions()
339 {
340         return engine.getSupportedOptions();
341 }
342
343 } // namespace ode