xref: /openbmc/estoraged/src/estoraged.cpp (revision be47c8fe)
1 
2 #include "estoraged.hpp"
3 
4 #include "cryptErase.hpp"
5 #include "cryptsetupInterface.hpp"
6 #include "pattern.hpp"
7 #include "sanitize.hpp"
8 #include "verifyDriveGeometry.hpp"
9 #include "zero.hpp"
10 
11 #include <libcryptsetup.h>
12 #include <openssl/rand.h>
13 
14 #include <phosphor-logging/lg2.hpp>
15 #include <sdbusplus/asio/object_server.hpp>
16 #include <xyz/openbmc_project/Common/error.hpp>
17 
18 #include <cstdlib>
19 #include <filesystem>
20 #include <iostream>
21 #include <string>
22 #include <string_view>
23 #include <utility>
24 #include <vector>
25 
26 namespace estoraged
27 {
28 
29 using Association = std::tuple<std::string, std::string, std::string>;
30 using sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
31 using sdbusplus::xyz::openbmc_project::Common::Error::UnsupportedRequest;
32 using sdbusplus::xyz::openbmc_project::Inventory::Item::server::Drive;
33 using sdbusplus::xyz::openbmc_project::Inventory::Item::server::Volume;
34 
35 EStoraged::EStoraged(sdbusplus::asio::object_server& server,
36                      const std::string& configPath, const std::string& devPath,
37                      const std::string& luksName, uint64_t size,
38                      uint8_t lifeTime, const std::string& partNumber,
39                      const std::string& serialNumber,
40                      std::unique_ptr<CryptsetupInterface> cryptInterface,
41                      std::unique_ptr<FilesystemInterface> fsInterface) :
42     devPath(devPath),
43     containerName(luksName), mountPoint("/mnt/" + luksName + "_fs"),
44     cryptIface(std::move(cryptInterface)), fsIface(std::move(fsInterface)),
45     objectServer(server)
46 {
47     /* Get the filename of the device (without "/dev/"). */
48     std::string deviceName = std::filesystem::path(devPath).filename().string();
49     /* DBus object path */
50     std::string objectPath =
51         "/xyz/openbmc_project/inventory/storage/" + deviceName;
52 
53     /* Add Volume interface. */
54     volumeInterface = objectServer.add_interface(
55         objectPath, "xyz.openbmc_project.Inventory.Item.Volume");
56     volumeInterface->register_method(
57         "FormatLuks", [this](const std::vector<uint8_t>& password,
58                              Volume::FilesystemType type) {
59             this->formatLuks(password, type);
60         });
61     volumeInterface->register_method(
62         "Erase",
63         [this](Volume::EraseMethod eraseType) { this->erase(eraseType); });
64     volumeInterface->register_method("Lock", [this]() { this->lock(); });
65     volumeInterface->register_method(
66         "Unlock",
67         [this](std::vector<uint8_t>& password) { this->unlock(password); });
68     volumeInterface->register_method(
69         "ChangePassword", [this](const std::vector<uint8_t>& oldPassword,
70                                  const std::vector<uint8_t>& newPassword) {
71             this->changePassword(oldPassword, newPassword);
72         });
73     volumeInterface->register_property_r(
74         "Locked", lockedProperty, sdbusplus::vtable::property_::emits_change,
75         [this](bool& value) {
76             value = this->isLocked();
77             return value;
78         });
79 
80     /* Add Drive interface. */
81     driveInterface = objectServer.add_interface(
82         objectPath, "xyz.openbmc_project.Inventory.Item.Drive");
83     driveInterface->register_property("Capacity", size);
84     driveInterface->register_property("PredictedMediaLifeLeftPercent",
85                                       lifeTime);
86     /* This registers the Locked property for the Drives interface.
87      * Now it is the same as the volume Locked property */
88     driveInterface->register_property_r(
89         "Locked", lockedProperty, sdbusplus::vtable::property_::emits_change,
90         [this](bool& value) {
91             value = this->isLocked();
92             return value;
93         });
94 
95     driveInterface->register_property_r(
96         "EncryptionStatus", encryptionStatus,
97         sdbusplus::vtable::property_::emits_change,
98         [this](Drive::DriveEncryptionState& value) {
99             value = this->findEncryptionStatus();
100             return value;
101         });
102 
103     embeddedLocationInterface = objectServer.add_interface(
104         objectPath, "xyz.openbmc_project.Inventory.Connector.Embedded");
105 
106     /* Add Asset interface. */
107     assetInterface = objectServer.add_interface(
108         objectPath, "xyz.openbmc_project.Inventory.Decorator.Asset");
109     assetInterface->register_property("PartNumber", partNumber);
110     assetInterface->register_property("SerialNumber", serialNumber);
111 
112     volumeInterface->initialize();
113     driveInterface->initialize();
114     embeddedLocationInterface->initialize();
115     assetInterface->initialize();
116 
117     /* Set up the association between chassis and drive. */
118     association = objectServer.add_interface(
119         objectPath, "xyz.openbmc_project.Association.Definitions");
120 
121     std::vector<Association> associations;
122     associations.emplace_back("chassis", "drive",
123                               std::filesystem::path(configPath).parent_path());
124     association->register_property("Associations", associations);
125     association->initialize();
126 }
127 
128 EStoraged::~EStoraged()
129 {
130     objectServer.remove_interface(volumeInterface);
131     objectServer.remove_interface(driveInterface);
132     objectServer.remove_interface(embeddedLocationInterface);
133     objectServer.remove_interface(assetInterface);
134     objectServer.remove_interface(association);
135 }
136 
137 void EStoraged::formatLuks(const std::vector<uint8_t>& password,
138                            Volume::FilesystemType type)
139 {
140     std::string msg = "OpenBMC.0.1.DriveFormat";
141     lg2::info("Starting format", "REDFISH_MESSAGE_ID", msg);
142 
143     if (type != Volume::FilesystemType::ext4)
144     {
145         lg2::error("Only ext4 filesystems are supported currently",
146                    "REDFISH_MESSAGE_ID", std::string("OpenBMC.0.1.FormatFail"));
147         throw UnsupportedRequest();
148     }
149 
150     formatLuksDev(password);
151     activateLuksDev(password);
152 
153     createFilesystem();
154     mountFilesystem();
155 }
156 
157 void EStoraged::erase(Volume::EraseMethod inEraseMethod)
158 {
159     std::cerr << "Erasing encrypted eMMC" << std::endl;
160     lg2::info("Starting erase", "REDFISH_MESSAGE_ID",
161               std::string("OpenBMC.0.1.DriveErase"));
162     switch (inEraseMethod)
163     {
164         case Volume::EraseMethod::CryptoErase:
165         {
166             CryptErase myCryptErase(devPath);
167             myCryptErase.doErase();
168             break;
169         }
170         case Volume::EraseMethod::VerifyGeometry:
171         {
172             VerifyDriveGeometry myVerifyGeometry(devPath);
173             myVerifyGeometry.geometryOkay();
174             break;
175         }
176         case Volume::EraseMethod::LogicalOverWrite:
177         {
178             Pattern myErasePattern(devPath);
179             myErasePattern.writePattern();
180             break;
181         }
182         case Volume::EraseMethod::LogicalVerify:
183         {
184             Pattern myErasePattern(devPath);
185             myErasePattern.verifyPattern();
186             break;
187         }
188         case Volume::EraseMethod::VendorSanitize:
189         {
190             Sanitize mySanitize(devPath);
191             mySanitize.doSanitize();
192             break;
193         }
194         case Volume::EraseMethod::ZeroOverWrite:
195         {
196             Zero myZero(devPath);
197             myZero.writeZero();
198             break;
199         }
200         case Volume::EraseMethod::ZeroVerify:
201         {
202             Zero myZero(devPath);
203             myZero.verifyZero();
204             break;
205         }
206         case Volume::EraseMethod::SecuredLocked:
207         {
208             if (isLocked())
209             {
210                 lock();
211             }
212             // TODO: implement hardware locking
213             // Until that is done, we can lock using eStoraged::lock()
214             break;
215         }
216     }
217 }
218 
219 void EStoraged::lock()
220 {
221     std::string msg = "OpenBMC.0.1.DriveLock";
222     lg2::info("Starting lock", "REDFISH_MESSAGE_ID", msg);
223 
224     unmountFilesystem();
225     deactivateLuksDev();
226 }
227 
228 void EStoraged::unlock(std::vector<uint8_t> password)
229 {
230     std::string msg = "OpenBMC.0.1.DriveUnlock";
231     lg2::info("Starting unlock", "REDFISH_MESSAGE_ID", msg);
232 
233     activateLuksDev(std::move(password));
234     mountFilesystem();
235 }
236 
237 void EStoraged::changePassword(const std::vector<uint8_t>& /*oldPassword*/,
238                                const std::vector<uint8_t>& /*newPassword*/)
239 {
240     std::cerr << "Changing password for encrypted eMMC" << std::endl;
241     lg2::info("Starting change password", "REDFISH_MESSAGE_ID",
242               std::string("OpenBMC.0.1.DrivePasswordChanged"));
243 }
244 
245 bool EStoraged::isLocked() const
246 {
247     return lockedProperty;
248 }
249 
250 std::string_view EStoraged::getMountPoint() const
251 {
252     return mountPoint;
253 }
254 
255 void EStoraged::formatLuksDev(std::vector<uint8_t> password)
256 {
257     lg2::info("Formatting device {DEV}", "DEV", devPath, "REDFISH_MESSAGE_ID",
258               std::string("OpenBMC.0.1.FormatLuksDev"));
259 
260     /* Generate the volume key. */
261     const std::size_t keySize = 64;
262     std::vector<uint8_t> volumeKey(keySize);
263     if (RAND_bytes(volumeKey.data(), keySize) != 1)
264     {
265         lg2::error("Failed to create volume key", "REDFISH_MESSAGE_ID",
266                    std::string("OpenBMC.0.1.FormatLuksDevFail"));
267         throw InternalFailure();
268     }
269 
270     /* Create the handle. */
271     CryptHandle cryptHandle(devPath);
272 
273     /* Format the LUKS encrypted device. */
274     int retval = cryptIface->cryptFormat(
275         cryptHandle.get(), CRYPT_LUKS2, "aes", "xts-plain64", nullptr,
276         reinterpret_cast<const char*>(volumeKey.data()), volumeKey.size(),
277         nullptr);
278     if (retval < 0)
279     {
280         lg2::error("Failed to format encrypted device: {RETVAL}", "RETVAL",
281                    retval, "REDFISH_MESSAGE_ID",
282                    std::string("OpenBMC.0.1.FormatLuksDevFail"));
283         throw InternalFailure();
284     }
285 
286     /* Device is now encrypted. */
287     locked(true);
288 
289     /* Set the password. */
290     retval = cryptIface->cryptKeyslotAddByVolumeKey(
291         cryptHandle.get(), CRYPT_ANY_SLOT, nullptr, 0,
292         reinterpret_cast<const char*>(password.data()), password.size());
293 
294     if (retval < 0)
295     {
296         lg2::error("Failed to set encryption password", "REDFISH_MESSAGE_ID",
297                    std::string("OpenBMC.0.1.FormatLuksDevFail"));
298         throw InternalFailure();
299     }
300 
301     lg2::info("Encrypted device {DEV} successfully formatted", "DEV", devPath,
302               "REDFISH_MESSAGE_ID",
303               std::string("OpenBMC.0.1.FormatLuksDevSuccess"));
304 }
305 
306 CryptHandle EStoraged::loadLuksHeader()
307 {
308 
309     CryptHandle cryptHandle(devPath);
310 
311     int retval = cryptIface->cryptLoad(cryptHandle.get(), CRYPT_LUKS2, nullptr);
312     if (retval < 0)
313     {
314         lg2::error("Failed to load LUKS header: {RETVAL}", "RETVAL", retval,
315                    "REDFISH_MESSAGE_ID",
316                    std::string("OpenBMC.0.1.ActivateLuksDevFail"));
317         throw InternalFailure();
318     }
319     return cryptHandle;
320 }
321 
322 Drive::DriveEncryptionState EStoraged::findEncryptionStatus()
323 {
324     try
325     {
326         loadLuksHeader();
327         return Drive::DriveEncryptionState::Encrypted;
328     }
329     catch (...)
330     {
331         return Drive::DriveEncryptionState::Unknown;
332     }
333 }
334 
335 void EStoraged::activateLuksDev(std::vector<uint8_t> password)
336 {
337     lg2::info("Activating LUKS dev {DEV}", "DEV", devPath, "REDFISH_MESSAGE_ID",
338               std::string("OpenBMC.0.1.ActivateLuksDev"));
339 
340     /* Create the handle. */
341     CryptHandle cryptHandle = loadLuksHeader();
342 
343     int retval = cryptIface->cryptActivateByPassphrase(
344         cryptHandle.get(), containerName.c_str(), CRYPT_ANY_SLOT,
345         reinterpret_cast<const char*>(password.data()), password.size(), 0);
346 
347     if (retval < 0)
348     {
349         lg2::error("Failed to activate LUKS dev: {RETVAL}", "RETVAL", retval,
350                    "REDFISH_MESSAGE_ID",
351                    std::string("OpenBMC.0.1.ActivateLuksDevFail"));
352         throw InternalFailure();
353     }
354 
355     /* Device is now unlocked. */
356     locked(false);
357 
358     lg2::info("Successfully activated LUKS dev {DEV}", "DEV", devPath,
359               "REDFISH_MESSAGE_ID",
360               std::string("OpenBMC.0.1.ActivateLuksDevSuccess"));
361 }
362 
363 void EStoraged::createFilesystem()
364 {
365     /* Run the command to create the filesystem. */
366     int retval = fsIface->runMkfs(containerName);
367     if (retval != 0)
368     {
369         lg2::error("Failed to create filesystem: {RETVAL}", "RETVAL", retval,
370                    "REDFISH_MESSAGE_ID",
371                    std::string("OpenBMC.0.1.CreateFilesystemFail"));
372         throw InternalFailure();
373     }
374     lg2::info("Successfully created filesystem for /dev/mapper/{CONTAINER}",
375               "CONTAINER", containerName, "REDFISH_MESSAGE_ID",
376               std::string("OpenBMC.0.1.CreateFilesystemSuccess"));
377 }
378 
379 void EStoraged::mountFilesystem()
380 {
381     /*
382      * Create directory for the filesystem, if it's not already present. It
383      * might already exist if, for example, the BMC reboots after creating the
384      * directory.
385      */
386     if (!fsIface->directoryExists(std::filesystem::path(mountPoint)))
387     {
388         bool success =
389             fsIface->createDirectory(std::filesystem::path(mountPoint));
390         if (!success)
391         {
392             lg2::error("Failed to create mount point: {DIR}", "DIR", mountPoint,
393                        "REDFISH_MESSAGE_ID",
394                        std::string("OpenBMC.0.1.MountFilesystemFail"));
395             throw InternalFailure();
396         }
397     }
398 
399     /* Run the command to mount the filesystem. */
400     std::string luksContainer("/dev/mapper/" + containerName);
401     int retval = fsIface->doMount(luksContainer.c_str(), mountPoint.c_str(),
402                                   "ext4", 0, nullptr);
403     if (retval != 0)
404     {
405         lg2::error("Failed to mount filesystem: {RETVAL}", "RETVAL", retval,
406                    "REDFISH_MESSAGE_ID",
407                    std::string("OpenBMC.0.1.MountFilesystemFail"));
408         bool removeSuccess =
409             fsIface->removeDirectory(std::filesystem::path(mountPoint));
410         if (!removeSuccess)
411         {
412             lg2::error("Failed to remove mount point: {DIR}", "DIR", mountPoint,
413                        "REDFISH_MESSAGE_ID",
414                        std::string("OpenBMC.0.1.MountFilesystemFail"));
415         }
416         throw InternalFailure();
417     }
418 
419     lg2::info("Successfully mounted filesystem at {DIR}", "DIR", mountPoint,
420               "REDFISH_MESSAGE_ID",
421               std::string("OpenBMC.0.1.MountFilesystemSuccess"));
422 }
423 
424 void EStoraged::unmountFilesystem()
425 {
426     int retval = fsIface->doUnmount(mountPoint.c_str());
427     if (retval != 0)
428     {
429         lg2::error("Failed to unmount filesystem: {RETVAL}", "RETVAL", retval,
430                    "REDFISH_MESSAGE_ID",
431                    std::string("OpenBMC.0.1.UnmountFilesystemFail"));
432         throw InternalFailure();
433     }
434 
435     /* Remove the mount point. */
436     bool success = fsIface->removeDirectory(std::filesystem::path(mountPoint));
437     if (!success)
438     {
439         lg2::error("Failed to remove mount point {DIR}", "DIR", mountPoint,
440                    "REDFISH_MESSAGE_ID",
441                    std::string("OpenBMC.0.1.UnmountFilesystemFail"));
442         throw InternalFailure();
443     }
444 
445     lg2::info("Successfully unmounted filesystem at {DIR}", "DIR", mountPoint,
446               "REDFISH_MESSAGE_ID",
447               std::string("OpenBMC.0.1.MountFilesystemSuccess"));
448 }
449 
450 void EStoraged::deactivateLuksDev()
451 {
452     lg2::info("Deactivating LUKS device {DEV}", "DEV", devPath,
453               "REDFISH_MESSAGE_ID",
454               std::string("OpenBMC.0.1.DeactivateLuksDev"));
455 
456     int retval = cryptIface->cryptDeactivate(nullptr, containerName.c_str());
457     if (retval < 0)
458     {
459         lg2::error("Failed to deactivate crypt device: {RETVAL}", "RETVAL",
460                    retval, "REDFISH_MESSAGE_ID",
461                    std::string("OpenBMC.0.1.DeactivateLuksDevFail"));
462         throw InternalFailure();
463     }
464 
465     /* Device is now locked. */
466     locked(true);
467 
468     lg2::info("Successfully deactivated LUKS device {DEV}", "DEV", devPath,
469               "REDFISH_MESSAGE_ID",
470               std::string("OpenBMC.0.1.DeactivateLuksDevSuccess"));
471 }
472 
473 void EStoraged::locked(bool isLocked)
474 {
475     lockedProperty = isLocked;
476 }
477 
478 } // namespace estoraged
479