Add APIs for the options of each 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 "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.registerNonparametricMethod(this, "", (int)(InternalEncryption::getState));
120         context.registerNonparametricMethod(this, "", (unsigned int)(InternalEncryption::getSupportedOptions));
121         context.registerParametricMethod(this, "", (int)(InternalEncryption::mount)(std::string));
122         context.registerNonparametricMethod(this, "", (int)(InternalEncryption::umount));
123         context.registerParametricMethod(this, "", (int)(InternalEncryption::encrypt)(std::string, unsigned int));
124         context.registerParametricMethod(this, "", (int)(InternalEncryption::decrypt)(std::string));
125         context.registerParametricMethod(this, "", (int)(InternalEncryption::changePassword)(std::string, std::string));
126 }
127
128 InternalEncryption::~InternalEncryption()
129 {
130 }
131
132 int InternalEncryption::mount(const std::string& password)
133 {
134         if (getState() != State::Encrypted) {
135                 return -1;
136         }
137
138         KeyManager::data pwData(password.begin(), password.end());
139         KeyManager keyManager(engine.getKeyMeta());
140
141         if (!keyManager.verifyPassword(pwData)) {
142                 return -2;
143         }
144
145         engine.mount(keyManager.getMasterKey(pwData), getOptions());
146         return 0;
147 }
148
149 int InternalEncryption::umount()
150 {
151         if (getState() != State::Encrypted) {
152                 return -1;
153         }
154
155         INFO("Close all processes using internal storage...");
156         stopDependedSystemdServices();
157         INFO("Umount internal storage...");
158         engine.umount();
159
160         return 0;
161 }
162
163 int InternalEncryption::encrypt(const std::string& password, unsigned int options)
164 {
165         if (getState() != State::Unencrypted) {
166                 return -1;
167         }
168
169         KeyManager::data pwData(password.begin(), password.end());
170         KeyManager keyManager;
171
172         keyManager.initPassword(pwData);
173         engine.setKeyMeta(keyManager.serialize());
174
175         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
176         auto encryptWorker = [&MasterKey, options, this]() {
177                 showProgressUI("Encrypting");
178
179                 INFO("Close all processes using internal storage...");
180                 stopDependedSystemdServices();
181                 INFO("Umount internal storage...");
182                 while (::umount(INTERNAL_STORAGE_PATH) == -1) {
183                         if (errno != EBUSY) {
184                                 break;
185                         }
186                 }
187
188                 INFO("Encryption started...");
189                 ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
190                 engine.encrypt(MasterKey, options);
191                 setOptions(options & getSupportedOptions());
192                 INFO("Sync disk...");
193                 sync();
194                 INFO("Encryption completed");
195
196                 ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "encrypted");
197                 ::reboot(RB_AUTOBOOT);
198         };
199
200         std::thread asyncWork(encryptWorker);
201         asyncWork.detach();
202
203         return 0;
204 }
205
206 int InternalEncryption::decrypt(const std::string& password)
207 {
208         if (getState() != State::Encrypted) {
209                 return -1;
210         }
211
212         KeyManager::data pwData(password.begin(), password.end());
213         KeyManager keyManager(engine.getKeyMeta());
214
215         if (!keyManager.verifyPassword(pwData)) {
216                 return -2;
217         }
218
219         KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
220         auto decryptWorker = [MasterKey, this]() {
221                 showProgressUI("Decrypting");
222
223                 INFO("Close all processes using internal storage...");
224                 stopDependedSystemdServices();
225                 INFO("Umount internal storage...");
226                 try {
227                         engine.umount();
228                 } catch (runtime::Exception& e) {}
229
230                 INFO("Decryption started...");
231                 ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
232                 engine.decrypt(MasterKey, getOptions());
233                 INFO("Sync disk...");
234                 sync();
235                 INFO("Decryption completed");
236
237                 ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "unencrypted");
238                 ::reboot(RB_AUTOBOOT);
239         };
240
241         std::thread asyncWork(decryptWorker);
242         asyncWork.detach();
243
244         return 0;
245 }
246
247 int InternalEncryption::changePassword(const std::string& oldPassword,
248                                                                                 const std::string& newPassword)
249 {
250         KeyManager::data oldPwData(oldPassword.begin(), oldPassword.end());
251         KeyManager::data newPwData(newPassword.begin(), newPassword.end());
252         KeyManager keyManager(engine.getKeyMeta());
253
254         if (!keyManager.verifyPassword(oldPwData)) {
255                 return -2;
256         }
257
258         keyManager.changePassword(oldPwData, newPwData);
259         engine.setKeyMeta(keyManager.serialize());
260
261         return 0;
262 }
263
264 int InternalEncryption::getState()
265 {
266         char *value = ::vconf_get_str(INTERNAL_STATE_VCONF_KEY);
267         if (value == NULL) {
268                 throw runtime::Exception("Failed to get vconf value");
269         }
270
271         std::string valueStr(value);
272         free(value);
273
274         if (valueStr == "encrypted") {
275                 return State::Encrypted;
276         } else if (valueStr == "unencrypted") {
277                 return State::Unencrypted;
278         } else {
279                 return State::Corrupted;
280         }
281
282         return 0;
283 }
284
285 unsigned int InternalEncryption::getSupportedOptions()
286 {
287         return engine.getSupportedOptions();
288 }
289
290 } // namespace ode