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