Add executable for mounting internal memory during FOTA
[platform/core/security/ode.git] / server / internal-encryption.cpp
1 /*
2  *  Copyright (c) 2015-2017 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 #include <algorithm>
18 #include <memory>
19
20 #include <fcntl.h>
21 #include <signal.h>
22 #include <unistd.h>
23 #include <sys/mount.h>
24 #include <sys/reboot.h>
25 #include <limits.h>
26 #include <stdlib.h>
27 #include <string.h>
28
29 #include <vconf.h>
30 #include <tzplatform_config.h>
31 #include <klay/process.h>
32 #include <klay/file-user.h>
33 #include <klay/filesystem.h>
34 #include <klay/dbus/connection.h>
35 #include <klay/error.h>
36
37 #include "misc.h"
38 #include "logger.h"
39 #include "progress-bar.h"
40 #include "rmi/common.h"
41
42 #include "internal-encryption.h"
43 #include "internal-encryption-common.h"
44
45 namespace ode {
46
47 namespace {
48
49 const char *PRIVILEGE_PLATFORM  = "http://tizen.org/privilege/internal/default/platform";
50
51 // TODO: see recovery()
52 const std::string PROG_FACTORY_RESET = "/usr/bin/dbus-send";
53 const std::vector<std::string> wipeCommand = {
54     PROG_FACTORY_RESET,
55     "--system",
56     "--type=signal",
57     "--print-reply",
58     "--dest=com.samsung.factoryreset",
59     "/com/samsung/factoryreset",
60     "com.samsung.factoryreset.start.setting"
61 };
62
63 void stopKnownSystemdServices()
64 {
65         std::vector<std::string> knownSystemdServices;
66         dbus::Connection& systemDBus = dbus::Connection::getSystem();
67         dbus::VariantIterator iter;
68
69         systemDBus.methodcall("org.freedesktop.systemd1",
70                                                         "/org/freedesktop/systemd1",
71                                                         "org.freedesktop.systemd1.Manager",
72                                                         "ListUnits",
73                                                         -1, "(a(ssssssouso))", "")
74                                                                 .get("(a(ssssssouso))", &iter);
75
76         while (1) {
77                 unsigned int dataUint;
78                 char *dataStr[9];
79                 int ret;
80
81                 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
82                                                 dataStr + 3, dataStr + 4, dataStr + 5,
83                                                 dataStr + 6, &dataUint, dataStr + 7,
84                                                 dataStr + 8);
85
86                 if (!ret) {
87                         break;
88                 }
89
90                 std::string service(dataStr[0]);
91                 if (service.compare(0, 5, "user@") == 0 ||
92                         service == "tlm.service" ||
93                         service == "resourced.service") {
94                         knownSystemdServices.push_back(service);
95                 }
96         }
97
98         for (const std::string& service : knownSystemdServices) {
99                 INFO(SINK, "Stopping service: " + service);
100                 systemDBus.methodcall("org.freedesktop.systemd1",
101                                                                 "/org/freedesktop/systemd1",
102                                                                 "org.freedesktop.systemd1.Manager",
103                                                                 "StopUnit",
104                                                                 -1, "", "(ss)", service.c_str(), "flush");
105         }
106
107         sleep(1);
108 }
109
110 void stopDependedSystemdServices()
111 {
112         dbus::Connection& systemDBus = dbus::Connection::getSystem();
113         std::set<std::string> servicesToStop;
114
115         for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
116                 try {
117                         char *service;
118                         systemDBus.methodcall("org.freedesktop.systemd1",
119                                                                         "/org/freedesktop/systemd1",
120                                                                         "org.freedesktop.systemd1.Manager",
121                                                                         "GetUnitByPID",
122                                                                         -1, "(o)", "(u)", (unsigned int)pid)
123                                                                                 .get("(o)", &service);
124                         servicesToStop.insert(service);
125                 } catch (runtime::Exception &e) {
126                         INFO(SINK, "Killing process: " + std::to_string(pid));
127                         ::kill(pid, SIGKILL);
128                 }
129         }
130
131         for (const std::string& service : servicesToStop) {
132                 INFO(SINK, "Stopping service: " + service);
133                 systemDBus.methodcall("org.freedesktop.systemd1",
134                                                                 service,
135                                                                 "org.freedesktop.systemd1.Unit",
136                                                                 "Stop",
137                                                                 -1, "", "(s)", "flush");
138         }
139 }
140
141 void showProgressUI(const std::string type)
142 {
143         ::tzplatform_set_user(::tzplatform_getuid(TZ_SYS_DEFAULT_USER));
144         std::string defaultUserHome(::tzplatform_getenv(TZ_USER_HOME));
145         ::tzplatform_reset_user();
146
147         try {
148                 runtime::File shareDirectory("/opt/home/root/share");
149                 if (!shareDirectory.exists()) {
150                         shareDirectory.makeDirectory(true);
151                 }
152
153                 runtime::File elmConfigDir(shareDirectory.getPath() + "/.elementary");
154                 if (!elmConfigDir.exists()) {
155                         runtime::File defaultElmConfigDir(defaultUserHome + "/share/.elementary");
156                         defaultElmConfigDir.copyTo(shareDirectory.getPath());
157                 }
158         } catch (runtime::Exception &e) {
159                 ERROR(SINK, "Failed to set up elm configuration: " + std::string(e.what()));
160         }
161
162         std::vector<std::string> args = {
163                 "ode", "progress", type, "Internal"
164         };
165
166         runtime::Process proc("/usr/bin/ode", args);
167         proc.execute();
168 }
169
170 unsigned int getOptions()
171 {
172         unsigned int result = 0;
173         int value;
174
175         value = 0;
176         ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
177         if (value) {
178                 result |= InternalEncryption::Option::IncludeUnusedRegion;
179         }
180
181         return result;
182 }
183
184 void setOptions(unsigned int options)
185 {
186         bool value;
187
188         if (options & InternalEncryption::Option::IncludeUnusedRegion) {
189                 value = true;
190         } else {
191                 value = false;
192         }
193         ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
194 }
195
196 }
197
198 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
199                                                                                                    KeyServer& key) :
200         server(srv),
201         keyServer(key)
202 {
203         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
204         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)());
205         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
206         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
207         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
208         server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
209         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
210         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
211         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
212         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
213         server.expose(this, "", (int)(InternalEncryptionServer::getState)());
214         server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
215         server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
216
217         server.createNotification("InternalEncryptionServer::mount");
218
219         std::string source = findDevPath();
220
221         engine.reset(new INTERNAL_ENGINE(
222                 source, INTERNAL_PATH,
223                 ProgressBar([](int v) {
224                         ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
225                                                         std::to_string(v).c_str());
226                 })
227         ));
228 }
229
230 InternalEncryptionServer::~InternalEncryptionServer()
231 {
232 }
233
234 int InternalEncryptionServer::setMountPassword(const std::string& password)
235 {
236         return keyServer.get(engine->getSource(), password, mountKey);
237 }
238
239 int InternalEncryptionServer::mount()
240 {
241         if (mountKey.empty()) {
242                 ERROR(SINK, "You need to call set_mount_password() first.");
243                 return error::NoData;
244         }
245
246         BinaryData key = mountKey;
247         mountKey.clear();
248
249         if (getState() != State::Encrypted) {
250                 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
251                 return error::NoSuchDevice;
252         }
253
254         if (engine->isMounted()) {
255                 INFO(SINK, "Partition already mounted.");
256                 return error::None;
257         }
258
259         INFO(SINK, "Mounting internal storage.");
260         try {
261                 engine->mount(key, getOptions());
262
263                 server.notify("InternalEncryptionServer::mount");
264
265                 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
266                 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
267         } catch (runtime::Exception &e) {
268                 ERROR(SINK, "Mount failed: " + std::string(e.what()));
269                 return error::Unknown;
270         }
271
272         return error::None;
273 }
274
275 int InternalEncryptionServer::umount()
276 {
277         if (getState() != State::Encrypted) {
278                 ERROR(SINK, "Cannot umount, partition's state incorrect.");
279                 return error::NoSuchDevice;
280         }
281
282         if (!engine->isMounted()) {
283                 INFO(SINK, "Partition already umounted.");
284                 return error::None;
285         }
286
287         INFO(SINK, "Closing all processes using internal storage.");
288         try {
289                 stopDependedSystemdServices();
290                 INFO(SINK, "Umounting internal storage.");
291                 engine->umount();
292         } catch (runtime::Exception &e) {
293                 ERROR(SINK, "Umount failed: " + std::string(e.what()));
294                 return error::Unknown;
295         }
296
297         return error::None;
298 }
299
300 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
301 {
302         if (getState() != State::Unencrypted) {
303                 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
304                 return error::NoSuchDevice;
305         }
306
307         BinaryData masterKey;
308         int ret = keyServer.get(engine->getSource(), password, masterKey);
309         if (ret != error::None)
310                 return ret;
311
312         auto encryptWorker = [masterKey, options, this]() {
313                 try {
314                         std::string source = engine->getSource();
315                         std::string mntPath = findMountPointByDevice(source);
316
317                         if (!mntPath.empty()) {
318                                 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
319                                 stopKnownSystemdServices();
320                                 INFO(SINK, "Closing all processes using internal storage.");
321                                 stopDependedSystemdServices();
322                         }
323
324                         while (!mntPath.empty()) {
325                                 INFO(SINK, "Umounting internal storage.");
326                                 while (::umount(mntPath.c_str()) == -1) {
327                                         if (errno != EBUSY) {
328                                                 throw runtime::Exception("Umount error: " + runtime::GetSystemErrorMessage());
329                                         }
330                                         stopDependedSystemdServices();
331                                 }
332                                 mntPath = findMountPointByDevice(source);
333                         }
334
335                         showProgressUI("Encrypting");
336
337                         INFO(SINK, "Encryption started.");
338                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
339                         engine->encrypt(masterKey, options);
340                         setOptions(options & getSupportedOptions());
341
342                         INFO(SINK, "Encryption completed.");
343                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
344                         server.notify("InternalEncryptionServer::mount");
345
346                         INFO(SINK, "Syncing disk and rebooting.");
347                         ::sync();
348                         ::reboot(RB_AUTOBOOT);
349                 } catch (runtime::Exception &e) {
350                         ERROR(SINK, "Encryption failed: " + std::string(e.what()));
351                 }
352         };
353
354         std::thread asyncWork(encryptWorker);
355         asyncWork.detach();
356
357         return error::None;
358 }
359
360 int InternalEncryptionServer::decrypt(const std::string& password)
361 {
362         if (getState() != State::Encrypted) {
363                 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
364                 return error::NoSuchDevice;
365         }
366
367         BinaryData masterKey;
368         int ret = keyServer.get(engine->getSource(), password, masterKey);
369         if (ret != error::None)
370                 return ret;
371
372         auto decryptWorker = [masterKey, this]() {
373                 try {
374                         if (engine->isMounted()) {
375                                 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
376                                 stopKnownSystemdServices();
377                                 INFO(SINK, "Closing all processes using internal storage.");
378                                 stopDependedSystemdServices();
379
380                                 INFO(SINK, "Umounting internal storage.");
381                                 while (1) {
382                                         try {
383                                                 engine->umount();
384                                                 break;
385                                         } catch (runtime::Exception& e) {
386                                                 stopDependedSystemdServices();
387                                         }
388                                 }
389                         }
390
391                         showProgressUI("Decrypting");
392
393                         INFO(SINK, "Decryption started.");
394                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
395                         engine->decrypt(masterKey, getOptions());
396
397                         INFO(SINK, "Decryption complete.");
398                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
399
400                         INFO(SINK, "Syncing disk and rebooting.");
401                         ::sync();
402                         ::reboot(RB_AUTOBOOT);
403                 } catch (runtime::Exception &e) {
404                         ERROR(SINK, "Decryption failed: " + std::string(e.what()));
405                 }
406         };
407
408         std::thread asyncWork(decryptWorker);
409         asyncWork.detach();
410
411         return error::None;
412 }
413
414 int InternalEncryptionServer::recovery()
415 {
416         if (getState() == State::Unencrypted) {
417                 return error::NoSuchDevice;
418         }
419
420         //TODO
421         runtime::Process proc(PROG_FACTORY_RESET, wipeCommand);
422         if (proc.execute() == -1) {
423                 ERROR(SINK, "Failed to launch factory-reset");
424                 return error::WrongPassword;
425         }
426
427         return error::None;
428 }
429
430 int InternalEncryptionServer::isPasswordInitialized()
431 {
432         return keyServer.isInitialized(engine->getSource());
433 }
434
435 int InternalEncryptionServer::initPassword(const std::string& password)
436 {
437         return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
438 }
439
440 int InternalEncryptionServer::cleanPassword(const std::string& password)
441 {
442         return keyServer.remove(engine->getSource(), password);
443 }
444
445 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
446                                                                                 const std::string& newPassword)
447 {
448         return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
449 }
450
451 int InternalEncryptionServer::verifyPassword(const std::string& password)
452 {
453         return keyServer.verifyPassword(engine->getSource(), password);
454 }
455
456 int InternalEncryptionServer::getState()
457 {
458         char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
459         if (value == NULL) {
460                 throw runtime::Exception("Failed to get vconf value.");
461         }
462
463         std::string valueStr(value);
464         free(value);
465
466         if (valueStr == "encrypted") {
467                 return State::Encrypted;
468         } else if (valueStr == "unencrypted") {
469                 return State::Unencrypted;
470         } else {
471                 return State::Corrupted;
472         }
473 }
474
475 unsigned int InternalEncryptionServer::getSupportedOptions()
476 {
477         return engine->getSupportedOptions();
478 }
479
480 std::string InternalEncryptionServer::getDevicePath() const
481 {
482         return engine->getSource();
483 }
484
485 } // namespace ode