├── .gitignore ├── ChangeLog ├── LICENSE ├── Makefile ├── README.md ├── chunk.c ├── chunk.h ├── docs ├── Makefile ├── source │ ├── conf.py │ ├── index.rst │ ├── introduction.rst │ ├── problems.rst │ ├── static │ │ └── .keep │ ├── templates │ │ └── .keep │ ├── testing.rst │ └── usage.rst └── update ├── exec.c ├── exec.h ├── exit.c ├── exit.h ├── globals.h ├── keyfile.c ├── keyfile.h ├── logging.c ├── logging.h ├── luks.c ├── luks.h ├── luksipc.c ├── luksipc.h ├── mount.c ├── mount.h ├── parameters.c ├── parameters.h ├── random.c ├── random.h ├── shutdown.c ├── shutdown.h ├── tests ├── CornercaseTests.py ├── ReLUKSTests.py ├── SimpleTests.py ├── TestEngine.py ├── kill_list.txt ├── mkflakey ├── prng │ ├── Makefile │ └── prng_crc64.c ├── rmdm └── runtests ├── utils.c └── utils.h /.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | luksipc 3 | docs/build 4 | .*.swp 5 | __pycache__ 6 | tests/data 7 | tests/logs 8 | tests/prng/prng_crc64 9 | resume.bin 10 | header_backup.img 11 | -------------------------------------------------------------------------------- /ChangeLog: -------------------------------------------------------------------------------- 1 | Summary of changes of v0.05 (2019-10-19) 2 | ======================================== 3 | * Updated default values to handle the new default of 16 MiB headers 4 | * Fixed an issue with uint64_t values in printf and used inttypes.h 5 | definitions 6 | * Fixed a minor display issue in the error message (%ul instead of %lu) 7 | * Tests adapted for new circumstances (512 MiB backup files, 16 MiB 8 | header size) 9 | * Version number now based on git commit during build time 10 | 11 | Summary of changes of v0.04 (2015-05-28) 12 | ======================================== 13 | * Greatly improved handling of disk I/O errors (graceful shutdown in more 14 | situation instead of simply bailing out) 15 | * Separated resume file specification and actual request for resuming an 16 | aborted luksipc process (--resume vs. --resume-file) 17 | * Unified exit code handling 18 | * Possibilities to do fault injection in order to efficiently develop and 19 | test code to increase robustness 20 | * Included whole test framework in release 21 | 22 | Summary of changes of v0.03 (2015-05-25) 23 | ======================================== 24 | * Allow reLUKSification of devices (i.e. converting LUKS to LUKS) 25 | * Checking of mount status of file systems 26 | * Resume files now have additional sanity checks 27 | * Fast CRC64-based PRNG generator for filling volumes with check data 28 | * Major code cleanups and refactoring 29 | * Major regression testing facilities (auto-aborting and resuming on large 30 | volumes and on loop devices) 31 | * Help page of luksipc now looks more professional 32 | * Partition backup file (128 MiB) is always generated at the start of a 33 | LUKSification process 34 | * Option to deactivate safety checks via command line parameter 35 | (--no-seatbelt) 36 | 37 | Summary of changes of v0.02 (2015-05-18) 38 | ======================================== 39 | 40 | * Fixed interpretation of return code of "cryptsetup status" which had 41 | changed with more recent cryptsetup versions to reflect the correct error 42 | if no such LUKS name was known. Thanks to Eric Murray and Christian 43 | Pulvermacher for reporting this issue. 44 | * Forced chunk size to be 10 MiB instead of the default of 3 MiB. Thanks 45 | to John Morrissey for the bug report (under some weird circumstances, the 46 | LUKS header apparently can become a lot larger). 47 | * Fixed a couple of warnings and used stricter compiler flags. 48 | * Switched to -stc=c11 to be able to use static assertions. 49 | * Improved error handling for wrong command line parameters (log level 50 | integer parsing). 51 | * Improved error handling at cleanup (unsynced luksClose may fail at the 52 | first try because the device is still busy, sync() filesystems and try up 53 | to three times now) 54 | * Display estimated remaining time until finish. 55 | * Assert resume file can be written to disk by writing it at very start 56 | once and then seeking to its start. 57 | * Added README file with detailed instructions. 58 | * More helpful help page 59 | 60 | Summary of changes of v0.01 (2011-10-15) 61 | ======================================== 62 | 63 | * Ability to convert devices to LUKS format without having to copy the 64 | contained data over. 65 | 66 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: all clean test valgrind 2 | 3 | EXECUTABLE := luksipc 4 | BUILD_REVISION := $(shell git describe --abbrev=10 --dirty --always) 5 | CFLAGS := -Wall -Wextra -Wshadow -Wswitch -Wpointer-arith -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -Werror=implicit-function-declaration -Werror=format 6 | CFLAGS += -std=c11 -O2 -D_FILE_OFFSET_BITS=64 -D_XOPEN_SOURCE=500 -DBUILD_REVISION='"$(BUILD_REVISION)"' 7 | #CFLAGS += -DDEVELOPMENT -g 8 | 9 | LDFLAGS := 10 | 11 | OBJS := luksipc.o luks.o exec.o chunk.o parameters.o keyfile.o logging.o shutdown.o utils.o mount.o exit.o random.o 12 | 13 | all: $(EXECUTABLE) 14 | 15 | clean: 16 | rm -f $(OBJS) $(EXECUTABLE) initial_keyfile.bin 17 | 18 | test: all 19 | ./luksipc 20 | 21 | valgrind: all 22 | valgrind --leak-check=yes ./luksipc 23 | 24 | luksipc: $(OBJS) 25 | $(CC) $(CFLAGS) $(LDFLAGS) -o $(@) $(OBJS) 26 | 27 | .c.o: 28 | $(CC) $(CFLAGS) -c -o $@ $< 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # luksipc 2 | luksipc is the LUKS in-place-conversion tool. It allows conversion of plain 3 | volumes to LUKS-encrypted volumes. 4 | 5 | ## cryptsetup-reencrypt 6 | luksipc was created before any alternative from dm-crypt/cryptsetup/LUKS side 7 | was available. This is not the case anymore. Therefore I recommend switching to 8 | cryptsetup-reencrypt, which is properly maintained and tested upstream even 9 | when the format of the LUKS header changes (to my knowledge, this has at least 10 | happened twice and can cause luksipc to catastrophically fail, i.e., destroy 11 | all your data in the worst case). 12 | 13 | ## Documentation 14 | All documentation is available at [https://johndoe31415.github.io/luksipc/](https://johndoe31415.github.io/luksipc/). 15 | 16 | ## License 17 | GNU GPL-3. 18 | -------------------------------------------------------------------------------- /chunk.c: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | 31 | #include "logging.h" 32 | #include "chunk.h" 33 | #include "random.h" 34 | 35 | bool allocChunk(struct chunk *aChunk, uint32_t aSize) { 36 | memset(aChunk, 0, sizeof(struct chunk)); 37 | aChunk->size = aSize; 38 | aChunk->data = malloc(aSize); 39 | if (!aChunk->data) { 40 | return false; 41 | } 42 | memset(aChunk->data, 0, aSize); 43 | return true; 44 | } 45 | 46 | void freeChunk(struct chunk *aChunk) { 47 | free(aChunk->data); 48 | memset(aChunk, 0, sizeof(struct chunk)); 49 | } 50 | 51 | static bool checkedSeek(int aFd, off_t aOffset, const char *aCaller) { 52 | off_t curOffset = lseek(aFd, aOffset, SEEK_SET); 53 | if (curOffset != aOffset) { 54 | logmsg(LLVL_WARN, "%s: tried seek to 0x%lx, went to 0x%lx (%s)\n", aCaller, aOffset, curOffset, strerror(errno)); 55 | return false; 56 | } 57 | return true; 58 | } 59 | 60 | ssize_t chunkReadAt(struct chunk *aChunk, int aFd, uint64_t aOffset, uint32_t aSize) { 61 | ssize_t bytesRead; 62 | if (!checkedSeek(aFd, aOffset, "chunkReadAt")) { 63 | return -1; 64 | } 65 | if (aSize > aChunk->size) { 66 | logmsg(LLVL_CRITICAL, "chunkReadAt: Refusing to read %u bytes with only a %u bytes large buffer.\n", aSize, aChunk->size); 67 | return -1; 68 | } 69 | bytesRead = read(aFd, aChunk->data, aSize); 70 | if (bytesRead < 0) { 71 | aChunk->used = 0; 72 | } else { 73 | aChunk->used = bytesRead; 74 | } 75 | return bytesRead; 76 | } 77 | 78 | ssize_t chunkWriteAt(const struct chunk *aChunk, int aFd, uint64_t aOffset) { 79 | ssize_t bytesWritten; 80 | if (!checkedSeek(aFd, aOffset, "chunkWriteAt")) { 81 | return -1; 82 | } 83 | bytesWritten = write(aFd, aChunk->data, aChunk->used); 84 | if (bytesWritten != aChunk->used) { 85 | logmsg(LLVL_WARN, "Requested write of %d bytes unsuccessful (wrote %ld).\n", aChunk->used, bytesWritten); 86 | } 87 | return bytesWritten; 88 | } 89 | 90 | #ifdef DEVELOPMENT 91 | /* Don't even compile these variants in if we're not in a development build so 92 | * there's no possibility they get used accidently */ 93 | 94 | ssize_t unreliableChunkReadAt(struct chunk *aChunk, int aFd, uint64_t aOffset, uint32_t aSize) { 95 | if (randomEvent(100)) { 96 | logmsg(LLVL_WARN, "Fault injection: Failing unreliable read at offset 0x%lx.\n", aOffset); 97 | return -1; 98 | } else { 99 | return chunkReadAt(aChunk, aFd, aOffset, aSize); 100 | } 101 | } 102 | 103 | ssize_t unreliableChunkWriteAt(struct chunk *aChunk, int aFd, uint64_t aOffset) { 104 | if (randomEvent(100)) { 105 | logmsg(LLVL_WARN, "Fault injection: Failing unreliable write at offset 0x%lx.\n", aOffset); 106 | return -1; 107 | } else { 108 | return chunkWriteAt(aChunk, aFd, aOffset); 109 | } 110 | } 111 | #endif 112 | -------------------------------------------------------------------------------- /chunk.h: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #ifndef __CHUNK_H__ 25 | #define __CHUNK_H__ 26 | 27 | #include 28 | #include 29 | 30 | struct chunk { 31 | uint32_t size; /* Total chunk size */ 32 | uint32_t used; /* Used chunk size */ 33 | uint8_t *data; /* Data */ 34 | }; 35 | 36 | /*************** AUTO GENERATED SECTION FOLLOWS ***************/ 37 | bool allocChunk(struct chunk *aChunk, uint32_t aSize); 38 | void freeChunk(struct chunk *aChunk); 39 | ssize_t chunkReadAt(struct chunk *aChunk, int aFd, uint64_t aOffset, uint32_t aSize); 40 | ssize_t chunkWriteAt(const struct chunk *aChunk, int aFd, uint64_t aOffset); 41 | ssize_t unreliableChunkReadAt(struct chunk *aChunk, int aFd, uint64_t aOffset, uint32_t aSize); 42 | ssize_t unreliableChunkWriteAt(struct chunk *aChunk, int aFd, uint64_t aOffset); 43 | /*************** AUTO GENERATED SECTION ENDS ***************/ 44 | 45 | #endif 46 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = python3 -msphinx 7 | SPHINXPROJ = luksipc 8 | SOURCEDIR = source 9 | BUILDDIR = build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # luksipc documentation build configuration file, created by 5 | # sphinx-quickstart on Sat Aug 12 23:46:32 2017. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | # 20 | # import os 21 | # import sys 22 | # sys.path.insert(0, os.path.abspath('.')) 23 | 24 | 25 | # -- General configuration ------------------------------------------------ 26 | 27 | # If your documentation needs a minimal Sphinx version, state it here. 28 | # 29 | # needs_sphinx = '1.0' 30 | 31 | # Add any Sphinx extension module names here, as strings. They can be 32 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 33 | # ones. 34 | extensions = ['sphinx.ext.githubpages'] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['templates'] 38 | 39 | # The suffix(es) of source filenames. 40 | # You can specify multiple suffix as a list of string: 41 | # 42 | # source_suffix = ['.rst', '.md'] 43 | source_suffix = '.rst' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = 'luksipc' 50 | copyright = '2011-2019, Johannes Bauer' 51 | author = 'Johannes Bauer' 52 | 53 | # The version info for the project you're documenting, acts as replacement for 54 | # |version| and |release|, also used in various other places throughout the 55 | # built documents. 56 | # 57 | # The short X.Y version. 58 | version = '0.05' 59 | # The full version, including alpha/beta/rc tags. 60 | release = '0.04' 61 | 62 | # The language for content autogenerated by Sphinx. Refer to documentation 63 | # for a list of supported languages. 64 | # 65 | # This is also used if you do content translation via gettext catalogs. 66 | # Usually you set "language" from the command line for these cases. 67 | language = None 68 | 69 | # List of patterns, relative to source directory, that match files and 70 | # directories to ignore when looking for source files. 71 | # This patterns also effect to html_static_path and html_extra_path 72 | exclude_patterns = [] 73 | 74 | # The name of the Pygments (syntax highlighting) style to use. 75 | pygments_style = 'sphinx' 76 | 77 | # If true, `todo` and `todoList` produce output, else they produce nothing. 78 | todo_include_todos = False 79 | 80 | 81 | # -- Options for HTML output ---------------------------------------------- 82 | 83 | # The theme to use for HTML and HTML Help pages. See the documentation for 84 | # a list of builtin themes. 85 | # 86 | #html_theme = 'alabaster' 87 | html_theme = 'sphinx_rtd_theme' 88 | 89 | # Theme options are theme-specific and customize the look and feel of a theme 90 | # further. For a list of options available for each theme, see the 91 | # documentation. 92 | # 93 | # html_theme_options = {} 94 | 95 | # Add any paths that contain custom static files (such as style sheets) here, 96 | # relative to this directory. They are copied after the builtin static files, 97 | # so a file named "default.css" will overwrite the builtin "default.css". 98 | html_static_path = ['static'] 99 | 100 | # Custom sidebar templates, must be a dictionary that maps document names 101 | # to template names. 102 | # 103 | # This is required for the alabaster theme 104 | # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars 105 | html_sidebars = { 106 | '**': [ 107 | 'about.html', 108 | 'navigation.html', 109 | 'relations.html', # needs 'show_related': True theme option to display 110 | 'searchbox.html', 111 | 'donate.html', 112 | ] 113 | } 114 | 115 | 116 | # -- Options for HTMLHelp output ------------------------------------------ 117 | 118 | # Output file base name for HTML help builder. 119 | htmlhelp_basename = 'luksipcdoc' 120 | 121 | 122 | # -- Options for LaTeX output --------------------------------------------- 123 | 124 | latex_elements = { 125 | # The paper size ('letterpaper' or 'a4paper'). 126 | # 127 | # 'papersize': 'letterpaper', 128 | 129 | # The font size ('10pt', '11pt' or '12pt'). 130 | # 131 | # 'pointsize': '10pt', 132 | 133 | # Additional stuff for the LaTeX preamble. 134 | # 135 | # 'preamble': '', 136 | 137 | # Latex figure (float) alignment 138 | # 139 | # 'figure_align': 'htbp', 140 | } 141 | 142 | # Grouping the document tree into LaTeX files. List of tuples 143 | # (source start file, target name, title, 144 | # author, documentclass [howto, manual, or own class]). 145 | latex_documents = [ 146 | (master_doc, 'luksipc.tex', 'luksipc Documentation', 147 | 'Johannes Bauer', 'manual'), 148 | ] 149 | 150 | 151 | # -- Options for manual page output --------------------------------------- 152 | 153 | # One entry per manual page. List of tuples 154 | # (source start file, name, description, authors, manual section). 155 | man_pages = [ 156 | (master_doc, 'luksipc', 'luksipc Documentation', 157 | [author], 1) 158 | ] 159 | 160 | 161 | # -- Options for Texinfo output ------------------------------------------- 162 | 163 | # Grouping the document tree into Texinfo files. List of tuples 164 | # (source start file, target name, title, author, 165 | # dir menu entry, description, category) 166 | texinfo_documents = [ 167 | (master_doc, 'luksipc', 'luksipc Documentation', 168 | author, 'luksipc', 'One line description of project.', 169 | 'Miscellaneous'), 170 | ] 171 | 172 | 173 | 174 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | luksipc Documentation 2 | ===================== 3 | 4 | .. warning:: luksipc was created before any alternative from dm-crypt/cryptsetup/LUKS side was available. This is not the case anymore. Therefore I recommend switching to cryptsetup-reencrypt, which is properly maintained and tested upstream even when the format of the LUKS header changes (to my knowledge, this has at least happened twice and can cause luksipc to catastrophically fail, i.e., destroy all your data in the worst case). 5 | 6 | .. toctree:: 7 | :maxdepth: 2 8 | :caption: luksipc Documentation 9 | 10 | introduction 11 | usage 12 | problems 13 | testing 14 | 15 | 16 | -------------------------------------------------------------------------------- /docs/source/introduction.rst: -------------------------------------------------------------------------------- 1 | Introduction 2 | ============ 3 | 4 | Authors 5 | ------- 6 | luksipc was written by Johannes Bauer . Please report all 7 | bugs directly to his email address or file a issue at GitHub (URL is below). If 8 | you do not wish to be named in the ChangeLog or this README file, please tell 9 | me and I'll omit your name. Inversely, if I forgot to include you in this list 10 | and you would like to appear, please drop me a note and I'll fix it. 11 | 12 | There are several contributors to the project: 13 | 14 | - Eric Murray (cryptsetup status issue) 15 | - Christian Pulvermacher (cryptsetup status issue) 16 | - John Morrissey (large header issue) 17 | 18 | The current version is maintained at GitHub at the moment: https://github.com/johndoe31415/luksipc 19 | 20 | The project documentation can be found at: https://johndoe31415.github.io/luksipc 21 | 22 | The projects main page is hosted at: https://johannes-bauer.com/linux/luksipc/ 23 | 24 | Please send issues and pull requests to GitHub if you would like to contribute. 25 | I do have a horrible latency sometimes but I'll try to do my best, promise. 26 | 27 | 28 | Disclaimer 29 | ---------- 30 | If you use luksipc and it bricks your disk and destroys all your data then 31 | that's your fault, not mine. luksips comes without any warranty (neither 32 | expressed nor implied). Please have a backup for really, really important data. 33 | 34 | 35 | Compiling 36 | --------- 37 | luksipc has no external dependencies, it should compile just fine if you have a 38 | recent Linux distribution with GNU make and gcc installed. Just type:: 39 | 40 | $ make 41 | 42 | That's it. At runtime, it needs access to the cryptsetup and dmsetup tools in 43 | the PATH. 44 | 45 | 46 | luksipc vs. cryptsetup-reencrypt 47 | -------------------------------- 48 | luksipc has nothing to do with cryptsetup-reencrypt. It was simply created 49 | because at the time that luksipc was written, cryptsetup-reencrypt hadn't been 50 | written just yet. On modern systems, cryptsetup-reencrypt is already shipped 51 | with the LUKS tools and it's also the supported tool by LUKS upstream. 52 | Therefore, to be frank, it seems like the better choice to use nowadays. I've 53 | never used cryptsetup-reencrypt myself so far, but will probably try it out on 54 | the next best occasion (then I can also update this README with a more 55 | insightful comment instead of just clueless jibber jabber). 56 | -------------------------------------------------------------------------------- /docs/source/problems.rst: -------------------------------------------------------------------------------- 1 | Conversion problems 2 | =================== 3 | If anything goes wrong, you will find advice in this section. Again the two 4 | distinct cases will be in different subsections. Errors with plain to LUKS 5 | conversion will be discussed first and errors with LUKS to LUKS conversion 6 | (reLUKSificiation) in a different subsection. 7 | 8 | 9 | Problems during plain to LUKS conversion 10 | ---------------------------------------- 11 | You may find yourself here because a luksipc process has crashed mid-conversion 12 | (accidental Ctrl-C or reboot) and you're panicing. Breathe. luksipc is designed 13 | so that it is robust against these issues. 14 | 15 | Basically, to be able to resume a luksipc process you need to have two things: 16 | 17 | 1. The data of the last overwritten block (there's always one "shadow" block 18 | that needs to be kept in memory, because usually the destination partition is 19 | smaller than the source partition because of the LUKS header) 20 | 2. The exact location of where the interruption occured. 21 | 22 | luksipc stores exactly this (incredibly critical) information in a "resume 23 | file" should the resume process be interrupted. It is usually called 24 | "resume.bin". For example, say I interrupt the LUKS conversion of a disk, this 25 | will be shown:: 26 | 27 | # luksipc -d /dev/sdf1 28 | [...] 29 | [I]: 0:00: 32.1% 110 MiB / 343 MiB 6.4 MiB/s Left: 233 MiB 0:00 h:m 30 | ^C[C]: Shutdown requested by user interrupt, please be patient... 31 | [I]: Gracefully shutting down. 32 | [I]: Synchronizing disk... 33 | [I]: Synchronizing of disk finished. 34 | 35 | If you go into more detail (log level increase) here's what you'll see:: 36 | 37 | # luksipc -d /dev/sdf1 -l4 38 | [...] 39 | [I]: 0:00: 32.1% 110 MiB / 343 MiB 6.2 MiB/s Left: 233 MiB 0:00 h:m 40 | ^C[C]: Shutdown requested by user interrupt, please be patient... 41 | [I]: Gracefully shutting down. 42 | [D]: Wrote resume file: read pointer offset 136314880 write pointer offset 115343360, 10485760 bytes of data in active buffer. 43 | [D]: Closing read/write file descriptors 4 and 5. 44 | [I]: Synchronizing disk... 45 | [I]: Synchronizing of disk finished. 46 | [D]: Subprocess [PID 17857]: Will execute 'cryptsetup luksClose luksipc_f569b0bb' 47 | [D]: Subprocess [PID 17857]: cryptsetup returned 0 48 | [D]: Subprocess [PID 17860]: Will execute 'dmsetup remove /dev/mapper/alias_luksipc_raw_277f5e96' 49 | [D]: Subprocess [PID 17860]: dmsetup returned 0 50 | 51 | You can see the exact location of the interruption: The read pointer was at 52 | offset 136314880 (130 MiB), the write pointer was at offset 115343360 (110 MiB) 53 | and there are currently 10 MiB of data in the shadow buffer. Everything was 54 | saved to a resume file. Here's an illustration of what it looks like. Every 55 | block is 10 MiB in size:: 56 | 57 | 100 110 120 130 140 58 | | | | | | 59 | v v v v v 60 | ----+------+------+------+------+---- 61 | ...| | BUF1 | BUF2 | |... 62 | ----+------+------+------+------+---- 63 | ^ ^ 64 | | | 65 | W R 66 | 67 | At this point in time, luksipc has exactly two blocks in memory, BUF1 and BUF2. 68 | This is why the read pointer is ahead two block sizes of the write pointer. Now 69 | in the next step (if no interruption had occured) the BUF1 buffer would be 70 | written to the LUKS device offset 110 MiB. This would overwrite some of the 71 | plain data in BUF2, too (because the LUKS header means that there's an offset 72 | between read- and write disk!). Therefore both have to be kept in memory. 73 | 74 | But since the system was interrupted, it is fully sufficient to only save BUF1 75 | to disk together with the write pointer location. 76 | 77 | With the help of this resume file, you can continue the conversion process:: 78 | 79 | # luksipc -d /dev/sdf1 --resume resume.bin 80 | [...] 81 | [I]: Starting copying of data, read offset 125829120, write offset 115343360 82 | [I]: 0:00: 64.1% 220 MiB / 343 MiB 6.6 MiB/s Left: 123 MiB 0:00 h:m 83 | [I]: 0:00: 93.3% 320 MiB / 343 MiB 9.2 MiB/s Left: 23 MiB 0:00 h:m 84 | [...] 85 | 86 | Now we see that the process was resumed with the write pointer at the 110 MiB 87 | mark and the read pointer at the 120 MiB mark. The next step would now be for 88 | luksipc to read in BUF2 and we're exatly in the situation in which the abort 89 | occured. Then from there on everything works like usual. 90 | 91 | One thing you have to be very careful about is making copies of the resume 92 | file. You have to be **very** careful about this. Let's say you copied the 93 | resume file to some other location and accidently applied it twice. For 94 | example, you run luksipc a first time and abort it. The resume file is written, 95 | you copy it to resume2.bin. You resume the process (luksipc run 2) and let it 96 | finish. Then you resume the process again with resume2.bin. What will happen is 97 | that all data that was written in the resume run is encrypted **twice** and 98 | will be unintelligible. This can obviously be recovered, but it will require 99 | very careful twiddling and lots of work. Just don't do it. 100 | 101 | To prevent this sort of thing, luksipc truncates the resume file when resuming 102 | only after everything else has worked (and I/O operation starts). This prevents 103 | you from accidently applying a resume file twice to an interrupted conversion 104 | process. 105 | 106 | 107 | 108 | Problems during LUKS to LUKS conversion 109 | --------------------------------------- 110 | When a reLUKSification process aborts unexpectedly (but gracefully), a resume 111 | file is written just as it would have been during LUKSification. So resuming 112 | just like above is easily possible. But suppose the case is a tad bit more 113 | complicated: Let's say that someone accidently issued a reboot command during 114 | reLUKSification. The reboot command causes a SIGTERM to be issued to the 115 | luksipc process. luksipc catches the signal, writes the resume.bin file and 116 | shuts down gracefully. Then the system reboots. 117 | 118 | For reLUKSification to work you need to have access to the plain (unlocked) 119 | source container. Here's the big "but": In order to unlock the original 120 | container, you need to use cryptsetup luksOpen. But the LUKS header has been 121 | overwritten by the destination (final) LUKS header already. Therefore you can't 122 | unlock the source data anymore. 123 | 124 | At least you couldn't if this situation wouldn't have been anticipated by 125 | luksipc. Lucky for you, it has been. When first firing up luksipc, a backup of 126 | the raw device header (typically 128 MiB in size) is done by luksipc in a file 127 | usually called "header_backup.img". You can use this header together with the 128 | raw parition to open the partition using the old key. When you have opened the 129 | device with the old key, we can just resume the process as we normally would. 130 | 131 | First, this is the reLUKSificiation process that aborts. We assume our 132 | container is unlocked at /dev/mapper/oldluks. Let's check the MD5 of the 133 | container first (to verify everything ran smoothly):: 134 | 135 | # md5sum /dev/mapper/oldluks 136 | 41dc86251cba7992719bbc85de5628ab /dev/mapper/oldluks 137 | 138 | Alright, let's start the luksipc process (which will be interrupted):: 139 | 140 | # luksipc -d /dev/loop0 --readdev /dev/mapper/oldluks 141 | [...] 142 | [I]: 0:00: 10.8% 110 MiB / 1022 MiB 0.0 MiB/s Left: 912 MiB 0:00 h:m 143 | ^C[C]: Shutdown requested by user interrupt, please be patient... 144 | [I]: Gracefully shutting down. 145 | [...] 146 | 147 | Now let's say we've closed /dev/mapper/oldluks (e.g. by a system reboot). We 148 | need to find a way to reopen it with the old header and old key in order to 149 | successfully resume the proces. For this, we do:: 150 | 151 | # cryptsetup luksOpen --header=header_backup.img /dev/loop0 oldluks 152 | 153 | And then, finally, we're able to resume luksipc:: 154 | 155 | # luksipc -d /dev/loop0 --readdev /dev/mapper/oldluks --resume resume.bin 156 | [...] 157 | [I]: Starting copying of data, read offset 220200960, write offset 209715200 158 | [I]: 0:00: 30.3% 310 MiB / 1022 MiB 0.0 MiB/s Left: 712 MiB 0:00 h:m 159 | [I]: 0:00: 40.1% 410 MiB / 1022 MiB 147.9 MiB/s Left: 612 MiB 0:00 h:m 160 | 161 | Now after the process is run, let's do some cleanups:: 162 | 163 | # dmsetup remove oldluks 164 | # dmsetup remove hybrid 165 | # losetup -d /dev/loop3 166 | 167 | And open our successfully converted device:: 168 | 169 | # cryptsetup luksOpen /dev/loop0 newluks -d /root/initial_keyfile.bin 170 | 171 | But did it really work? We can check:: 172 | 173 | # md5sum /dev/mapper/newluks 174 | 41dc86251cba7992719bbc85de5628ab /dev/mapper/newluks 175 | 176 | Yes, it sure did :-) 177 | 178 | Be aware that this is an absolute emergency recovery proedure that you'd only 179 | use if everything else fails (i.e. the original source LUKS device was 180 | accidently closed). Any mistake whatsoever (e.g. wrong offsets) will cause you 181 | to completely pulp your disk. So be very very careful with this and double 182 | check everything. 183 | -------------------------------------------------------------------------------- /docs/source/static/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johndoe31415/luksipc/e222ca7ff89e7465345c8ae8786096130e06a30f/docs/source/static/.keep -------------------------------------------------------------------------------- /docs/source/templates/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johndoe31415/luksipc/e222ca7ff89e7465345c8ae8786096130e06a30f/docs/source/templates/.keep -------------------------------------------------------------------------------- /docs/source/testing.rst: -------------------------------------------------------------------------------- 1 | Testing 2 | ======= 3 | It's always a good idea to perform some tests before you give some unknown tool 4 | by some unknown author a shot to handle your precious data. Here's a hint how 5 | you could do this. I've setup some garbage partition on a drive which is 6 | exactly 1234 MiB in size (1293942784 bytes). That partition is filled 7 | completely with zeros:: 8 | 9 | # dd if=/dev/zero of=/dev/sda1 bs=1M 10 | dd: error writing ‘/dev/sda1’: No space left on device 11 | 1235+0 records in 12 | 1234+0 records out 13 | 1293942784 bytes (1,3 GB) copied, 30,6571 s, 42,2 MB/s 14 | 15 | Let's check that the pattern matches:: 16 | 17 | # md5sum /dev/sda1 18 | e83b40511b7b154b1816ef4c03d6be7d /dev/sda1 19 | 20 | # dd if=/dev/zero bs=1M count=1234 | md5sum 21 | 1234+0 records in 22 | 1234+0 records out 23 | 1293942784 bytes (1,3 GB) copied, 2,71539 s, 477 MB/s 24 | e83b40511b7b154b1816ef4c03d6be7d - 25 | 26 | Alright, so the partition is **really** filled with 1234 MiB of zeros. 27 | 28 | Let's LUKSify it:: 29 | 30 | # luksipc -d /dev/sda1 31 | WARNING! luksipc will perform the following actions: 32 | => Normal LUKSification of plain device /dev/sda1 33 | -> luksFormat will be performed on /dev/sda1 34 | 35 | Please confirm you have completed the checklist: 36 | [1] You have resized the contained filesystem(s) appropriately 37 | [2] You have unmounted any contained filesystem(s) 38 | [3] You will ensure secure storage of the keyfile that will be generated at /root/initial_keyfile.bin 39 | [4] Power conditions are satisfied (i.e. your laptop is not running off battery) 40 | [5] You have a backup of all important data on /dev/sda1 41 | 42 | /dev/sda1: 1234 MiB = 1.2 GiB 43 | Chunk size: 10485760 bytes = 10.0 MiB 44 | Keyfile: /root/initial_keyfile.bin 45 | LUKS format parameters: None given 46 | 47 | Are all these conditions satisfied, then answer uppercase yes: YES 48 | [I]: Generated raw device alias: /dev/sda1 -> /dev/mapper/alias_luksipc_raw_944e8f9034a6344f 49 | [I]: Size of reading device /dev/sda1 is 1293942784 bytes (1234 MiB + 0 bytes) 50 | [I]: Performing dm-crypt status lookup on mapper name 'luksipc_41c33f9940708688' 51 | [I]: Performing luksFormat of raw device /dev/mapper/alias_luksipc_raw_944e8f9034a6344f using key file /root/initial_keyfile.bin 52 | [I]: Performing luksOpen of raw device /dev/mapper/alias_luksipc_raw_944e8f9034a6344f using key file /root/initial_keyfile.bin and device mapper handle luksipc_41c33f9940708688 53 | [I]: Size of writing device /dev/mapper/luksipc_41c33f9940708688 is 1291845632 bytes (1232 MiB + 0 bytes) 54 | [I]: Write disk smaller than read disk, 2097152 bytes occupied by LUKS header (2048 kB + 0 bytes) 55 | [I]: Starting copying of data, read offset 10485760, write offset 0 56 | [I]: 0:00: 8.9% 110 MiB / 1232 MiB 44.9 MiB/s Left: 1122 MiB 0:00 h:m 57 | [I]: 0:00: 17.0% 210 MiB / 1232 MiB 43.2 MiB/s Left: 1022 MiB 0:00 h:m 58 | [I]: 0:00: 25.2% 310 MiB / 1232 MiB 18.8 MiB/s Left: 922 MiB 0:00 h:m 59 | [I]: 0:00: 33.3% 410 MiB / 1232 MiB 21.3 MiB/s Left: 822 MiB 0:00 h:m 60 | [I]: 0:00: 41.4% 510 MiB / 1232 MiB 23.4 MiB/s Left: 722 MiB 0:00 h:m 61 | [I]: 0:00: 49.5% 610 MiB / 1232 MiB 22.0 MiB/s Left: 622 MiB 0:00 h:m 62 | [I]: 0:00: 57.6% 710 MiB / 1232 MiB 18.7 MiB/s Left: 522 MiB 0:00 h:m 63 | [I]: 0:00: 65.7% 810 MiB / 1232 MiB 19.8 MiB/s Left: 422 MiB 0:00 h:m 64 | [I]: 0:00: 73.9% 910 MiB / 1232 MiB 20.3 MiB/s Left: 322 MiB 0:00 h:m 65 | [I]: 0:00: 82.0% 1010 MiB / 1232 MiB 17.8 MiB/s Left: 222 MiB 0:00 h:m 66 | [I]: 0:00: 90.1% 1110 MiB / 1232 MiB 18.6 MiB/s Left: 122 MiB 0:00 h:m 67 | [I]: 0:01: 98.2% 1210 MiB / 1232 MiB 19.4 MiB/s Left: 22 MiB 0:00 h:m 68 | [I]: Disk copy completed successfully. 69 | [I]: Synchronizing disk... 70 | [I]: Synchronizing of disk finished. 71 | 72 | Then luksOpen it:: 73 | 74 | # cryptsetup luksOpen /dev/sda1 myluksdev -d /root/initial_keyfile.bin 75 | 76 | And check the hash:: 77 | 78 | # md5sum /dev/mapper/myluksdev 79 | e2226de7d184a3c9bd4c1e3d8a56b1b2 /dev/mapper/myluksdev 80 | 81 | The hash value differs from what it said before - this is absolutely to be 82 | expected! The reason for this is that the device is now shorter (because part 83 | of the space is used for the 2 MiB LUKS header). Proof:: 84 | 85 | # dd if=/dev/zero bs=1M count=1232 | md5sum 86 | 1232+0 records in 87 | 1232+0 records out 88 | 1291845632 bytes (1,3 GB) copied, 2,6588 s, 486 MB/s 89 | e2226de7d184a3c9bd4c1e3d8a56b1b2 - 90 | 91 | Now let's check the current key and reLUKSify it with a different key and 92 | algorithm! First, let's check out the "before" values:: 93 | 94 | # dmsetup table myluksdev --showkeys 95 | 0 2523136 crypt aes-xts-plain64 d164b3fd2b7d482fc6e0a2d0e58f51c5dafe4560507322cb29af4bd8f552ba4f 0 8:1 4096 96 | 97 | # cryptsetup luksDump /dev/sda1 98 | LUKS header information for /dev/sda1 99 | 100 | Version: 1 101 | Cipher name: aes 102 | Cipher mode: xts-plain64 103 | Hash spec: sha1 104 | Payload offset: 4096 105 | MK bits: 256 106 | MK digest: dd 08 3d 43 ae 50 64 7c d9 c6 20 cb de dd 7a 62 69 10 63 fe 107 | MK salt: f1 95 eb 18 2d 90 61 e9 c8 df 4b 4d 44 ab 62 87 108 | 5a f5 39 5a c4 f5 3b 7a 09 8c f1 75 33 a5 f3 25 109 | MK iterations: 50375 110 | UUID: 127277bf-b07b-4209-bf55-37cb1c10c83b 111 | 112 | Key Slot 0: ENABLED 113 | Iterations: 201892 114 | Salt: fc d9 3a 73 b4 73 ee 98 6c 35 34 a0 c7 7d 8a 71 115 | 5b 75 b7 6c 75 af 65 20 eb 90 7c 69 34 10 1e a6 116 | Key material offset: 8 117 | AF stripes: 4000 118 | Key Slot 1: DISABLED 119 | Key Slot 2: DISABLED 120 | Key Slot 3: DISABLED 121 | Key Slot 4: DISABLED 122 | Key Slot 5: DISABLED 123 | Key Slot 6: DISABLED 124 | Key Slot 7: DISABLED 125 | 126 | Then reLUKSify:: 127 | 128 | # my /root/initial_keyfile.bin /root/initial_keyfile_old.bin 129 | 130 | # luksipc -d /dev/sda1 --readdev /dev/mapper/myluksdev --luksparams='-c,twofish-lrw-benbi,-s,320,-h,sha256' 131 | WARNING! luksipc will perform the following actions: 132 | => reLUKSification of LUKS device /dev/sda1 133 | -> Which has been unlocked at /dev/mapper/myluksdev 134 | -> luksFormat will be performed on /dev/sda1 135 | 136 | Please confirm you have completed the checklist: 137 | [1] You have resized the contained filesystem(s) appropriately 138 | [2] You have unmounted any contained filesystem(s) 139 | [3] You will ensure secure storage of the keyfile that will be generated at /root/initial_keyfile.bin 140 | [4] Power conditions are satisfied (i.e. your laptop is not running off battery) 141 | [5] You have a backup of all important data on /dev/sda1 142 | 143 | /dev/sda1: 1234 MiB = 1.2 GiB 144 | Chunk size: 10485760 bytes = 10.0 MiB 145 | Keyfile: /root/initial_keyfile.bin 146 | LUKS format parameters: -c,twofish-lrw-benbi,-s,320,-h,sha256 147 | 148 | Are all these conditions satisfied, then answer uppercase yes: YES 149 | [I]: Generated raw device alias: /dev/sda1 -> /dev/mapper/alias_luksipc_raw_c84651981fc98f36 150 | [I]: Size of reading device /dev/mapper/myluksdev is 1291845632 bytes (1232 MiB + 0 bytes) 151 | [I]: Performing dm-crypt status lookup on mapper name 'luksipc_9afeee69aec4912c' 152 | [I]: Performing luksFormat of raw device /dev/mapper/alias_luksipc_raw_c84651981fc98f36 using key file /root/initial_keyfile.bin 153 | [I]: Performing luksOpen of raw device /dev/mapper/alias_luksipc_raw_c84651981fc98f36 using key file /root/initial_keyfile.bin and device mapper handle luksipc_9afeee69aec4912c 154 | [I]: Size of writing device /dev/mapper/luksipc_9afeee69aec4912c is 1291845632 bytes (1232 MiB + 0 bytes) 155 | [I]: Write disk size equal to read disk size. 156 | [I]: Starting copying of data, read offset 10485760, write offset 0 157 | [I]: 0:00: 8.9% 110 MiB / 1232 MiB 43.1 MiB/s Left: 1122 MiB 0:00 h:m 158 | [I]: 0:00: 17.0% 210 MiB / 1232 MiB 42.0 MiB/s Left: 1022 MiB 0:00 h:m 159 | [I]: 0:00: 25.2% 310 MiB / 1232 MiB 28.3 MiB/s Left: 922 MiB 0:00 h:m 160 | [I]: 0:00: 33.3% 410 MiB / 1232 MiB 19.1 MiB/s Left: 822 MiB 0:00 h:m 161 | [I]: 0:00: 41.4% 510 MiB / 1232 MiB 21.3 MiB/s Left: 722 MiB 0:00 h:m 162 | [I]: 0:00: 49.5% 610 MiB / 1232 MiB 21.6 MiB/s Left: 622 MiB 0:00 h:m 163 | [I]: 0:00: 57.6% 710 MiB / 1232 MiB 19.9 MiB/s Left: 522 MiB 0:00 h:m 164 | [I]: 0:00: 65.7% 810 MiB / 1232 MiB 18.6 MiB/s Left: 422 MiB 0:00 h:m 165 | [I]: 0:00: 73.9% 910 MiB / 1232 MiB 19.8 MiB/s Left: 322 MiB 0:00 h:m 166 | [I]: 0:00: 82.0% 1010 MiB / 1232 MiB 19.4 MiB/s Left: 222 MiB 0:00 h:m 167 | [I]: 0:01: 90.1% 1110 MiB / 1232 MiB 17.6 MiB/s Left: 122 MiB 0:00 h:m 168 | [I]: 0:01: 98.2% 1210 MiB / 1232 MiB 18.4 MiB/s Left: 22 MiB 0:00 h:m 169 | [I]: Disk copy completed successfully. 170 | [I]: Synchronizing disk... 171 | [I]: Synchronizing of disk finished. 172 | 173 | Now, let's detach the mapping of the old LUKS container first (this container 174 | now contains complete garbage):: 175 | 176 | # cryptsetup luksClose myluksdev 177 | 178 | And reopen it with the correct key:: 179 | 180 | # cryptsetup luksOpen /dev/sda1 mynewluksdev -d /root/initial_keyfile.bin 181 | 182 | Check that the content is still the same:: 183 | 184 | # cat /dev/mapper/mynewluksdev | md5sum 185 | e2226de7d184a3c9bd4c1e3d8a56b1b2 - 186 | 187 | It sure is. Now look at the luksDump output:: 188 | 189 | LUKS header information for /dev/sda1 190 | 191 | Version: 1 192 | Cipher name: twofish 193 | Cipher mode: lrw-benbi 194 | Hash spec: sha256 195 | Payload offset: 4096 196 | MK bits: 320 197 | MK digest: 10 b9 35 7b c8 23 d7 c3 2a b9 3e e6 95 74 cf 7f ef 75 1b 32 198 | MK salt: 3f 58 e6 1e 29 e1 c7 a2 f1 14 9e 1f c7 09 fa 23 199 | 93 7c 9c 59 20 67 d7 a7 7e 7d fe a0 12 9f 0f 25 200 | MK iterations: 29000 201 | UUID: 1dd5e426-9e37-4d1e-a6f9-17aa4179eb1e 202 | 203 | Key Slot 0: ENABLED 204 | Iterations: 117215 205 | Salt: 9d 58 5c 30 2b dc 35 33 19 bf 78 ab 3e aa 6e 8a 206 | fa 6c 9b ee 45 f7 db 9e f1 ab 0c fb cb 3c eb 51 207 | Key material offset: 8 208 | AF stripes: 4000 209 | Key Slot 1: DISABLED 210 | Key Slot 2: DISABLED 211 | Key Slot 3: DISABLED 212 | Key Slot 4: DISABLED 213 | Key Slot 5: DISABLED 214 | Key Slot 6: DISABLED 215 | Key Slot 7: DISABLED 216 | 217 | And the used key internally:: 218 | 219 | # dmsetup table mynewluksdev --showkeys 220 | 0 2523136 crypt twofish-lrw-benbi d6b007ce62de58b62331f800edf5864da390eb274b908506b368035e7a0f8ea1c3583c2b939928c3 0 8:1 4096 221 | 222 | As you can see, completely different keys, completely different algorithm -- 223 | but still identical data. It worked :-) 224 | 225 | Of course you can do this test with arbitrary data (not just constant zeros). I 226 | was just too lazy to write a PRNG that outputs easily reproducible results. 227 | Feel free to play around with it and please report any and all bugs if you find 228 | some. 229 | -------------------------------------------------------------------------------- /docs/source/usage.rst: -------------------------------------------------------------------------------- 1 | Usage 2 | ===== 3 | The following section will now cover the basic usage of luksipc. There are two 4 | distinct cases, one is the conversion of a unencrypted (plain) volume to LUKS 5 | and the other is the conversion of an encrypted (LUKS) volume to another LUKS 6 | volume. Both will need the same preparation steps before performing them. 7 | 8 | 9 | Checklist 10 | --------- 11 | If you skip over everything else, **please** at least make sure you do these 12 | steps before starting a conversion: 13 | 14 | - Resized file system size, shrunk size by at least 128 MiB 15 | - Unmounted file system 16 | - Laptop is connected to A/C power (if applicable) 17 | 18 | 19 | 20 | .. _preparation: 21 | 22 | Preparation 23 | ----------- 24 | The first thing you need to do is resize your file system to accomodate for the 25 | fact that the device is going to be a tiny bit smaller in the end (due to the 26 | LUKS header). The LUKS header size is usually 16 MiB (it was 2 MiB in previous 27 | versions or 1028 kiB for even older versions of cryptsetup), but you should 28 | decrease the file system size by more (I suggest 128 MiB) to be on the safe 29 | side. If you decrease the size too much you have no drawbacks (and you can 30 | easily increase after the conversion has been performed). 31 | 32 | .. warning:: 33 | Do not forget to shrink the file system before conversion 34 | 35 | luksipc has no means of detecting wheter or not you have performed this step 36 | and will not warn you if you haven't (it has no knowledge of the underlying 37 | file system). This might lead to very weird file system errors in the case that 38 | your volume ever wants to use the whole space and it might even render your 39 | volume completely unmountable (depending on the check the file system driver 40 | performs on the block device before allowing mounting). 41 | 42 | For example, let's say you have a device at /dev/loop0 that has an ext4 file 43 | system. You want to LUKSify it. We first resize our volume. For this we find 44 | out how large the volume is currently:: 45 | 46 | # tune2fs -l /dev/loop0 47 | tune2fs 1.42.9 (4-Feb-2014) 48 | Filesystem volume name: 49 | Last mounted on: 50 | Filesystem UUID: 713cc62e-b2a2-406a-a82a-c4c1d01464e1 51 | Filesystem magic number: 0xEF53 52 | Filesystem revision #: 1 (dynamic) 53 | Filesystem features: has_journal ext_attr resize_inode dir_index filetype extent flex_bg sparse_super large_file huge_file uninit_bg dir_nlink extra_isize 54 | Filesystem flags: signed_directory_hash 55 | Default mount options: user_xattr acl 56 | Filesystem state: clean 57 | Errors behavior: Continue 58 | Filesystem OS type: Linux 59 | Inode count: 64000 60 | Block count: 256000 61 | Reserved block count: 12800 62 | Free blocks: 247562 63 | Free inodes: 63989 64 | First block: 0 65 | Block size: 4096 66 | [...] 67 | 68 | So we now know that our device is 256000 blocks of 4096 bytes each, so exactly 69 | 1000 MiB. We verify this is correct (it is in this case). So we now want to 70 | decrease the file system size to 900 MiB. 900 MiB = 900 * 1024 * 1024 bytes = 71 | 943718400 bytes. With a file system block size of 4096 bytes we arrive at 72 | 943718400 / 4096 = 230400 blocks for the file system with decreased size. So we 73 | resize the file system:: 74 | 75 | # resize2fs /dev/loop0 230400 76 | resize2fs 1.42.9 (4-Feb-2014) 77 | Resizing the filesystem on /dev/loop0 to 230400 (4k) blocks. 78 | The filesystem on /dev/loop0 is now 230400 blocks long. 79 | 80 | That was successful. Perfect. Now (if you haven't already), umount the volume. 81 | 82 | .. warning:: 83 | Do not forget to unmount the file system before conversion 84 | 85 | 86 | Plain to LUKS conversion 87 | ------------------------ 88 | After having done the preparation as described in the :ref:`preparation` 89 | subsection, we can proceed to LUKSify the device. By default the initial 90 | randomized key is read from /dev/urandom and written to 91 | /root/initial_keyfile.bin. This is okay for us, we will remove the appropriate 92 | keyslot for this random key anyways in the future. It is only used for 93 | bootstrapping. We start the conversion:: 94 | 95 | # ./luksipc -d /dev/loop0 96 | WARNING! luksipc will perform the following actions: 97 | => Normal LUKSification of plain device /dev/loop0 98 | -> luksFormat will be performed on /dev/loop0 99 | 100 | Please confirm you have completed the checklist: 101 | [1] You have resized the contained filesystem(s) appropriately 102 | [2] You have unmounted any contained filesystem(s) 103 | [3] You will ensure secure storage of the keyfile that will be generated at /root/initial_keyfile.bin 104 | [4] Power conditions are satisfied (i.e. your laptop is not running off battery) 105 | [5] You have a backup of all important data on /dev/loop0 106 | 107 | /dev/loop0: 1024 MiB = 1.0 GiB 108 | Chunk size: 10485760 bytes = 10.0 MiB 109 | Keyfile: /root/initial_keyfile.bin 110 | LUKS format parameters: None given 111 | 112 | Are all these conditions satisfied, then answer uppercase yes: 113 | 114 | Please, read the whole message thourougly. There is no going back from this. If 115 | and only if you're 100% sure that all preconditions are satisfied, answer 116 | "YES" and press return:: 117 | 118 | Are all these conditions satisfied, then answer uppercase yes: YES 119 | [I]: Created raw device alias: /dev/loop0 -> /dev/mapper/alias_luksipc_raw_89ee2dc8 120 | [I]: Size of reading device /dev/loop0 is 1073741824 bytes (1024 MiB + 0 bytes) 121 | [I]: Backing up physical disk /dev/loop0 header to backup file header_backup.img 122 | [I]: Performing luksFormat of /dev/loop0 123 | [I]: Performing luksOpen of /dev/loop0 (opening as mapper name luksipc_7a6bfc08) 124 | [I]: Size of luksOpened writing device is 1071644672 bytes (1022 MiB + 0 bytes) 125 | [I]: Write disk smaller than read disk by 2097152 bytes (2048 kB + 0 bytes, occupied by LUKS header) 126 | [I]: Starting copying of data, read offset 10485760, write offset 0 127 | [I]: 0:00: 10.8% 110 MiB / 1022 MiB 0.0 MiB/s Left: 912 MiB 0:00 h:m 128 | [I]: 0:00: 20.5% 210 MiB / 1022 MiB 0.0 MiB/s Left: 812 MiB 0:00 h:m 129 | [I]: 0:00: 30.3% 310 MiB / 1022 MiB 0.0 MiB/s Left: 712 MiB 0:00 h:m 130 | [I]: 0:00: 40.1% 410 MiB / 1022 MiB 0.0 MiB/s Left: 612 MiB 0:00 h:m 131 | [I]: 0:00: 49.9% 510 MiB / 1022 MiB 412.0 MiB/s Left: 512 MiB 0:00 h:m 132 | [I]: 0:00: 59.7% 610 MiB / 1022 MiB 402.4 MiB/s Left: 412 MiB 0:00 h:m 133 | [I]: 0:00: 69.5% 710 MiB / 1022 MiB 401.5 MiB/s Left: 312 MiB 0:00 h:m 134 | [I]: 0:00: 79.3% 810 MiB / 1022 MiB 360.4 MiB/s Left: 212 MiB 0:00 h:m 135 | [I]: 0:00: 89.0% 910 MiB / 1022 MiB 350.0 MiB/s Left: 112 MiB 0:00 h:m 136 | [I]: 0:00: 98.8% 1010 MiB / 1022 MiB 344.8 MiB/s Left: 12 MiB 0:00 h:m 137 | [I]: Disk copy completed successfully. 138 | [I]: Synchronizing disk... 139 | [I]: Synchronizing of disk finished. 140 | 141 | The volume was successfully converted! Now let's first add a passphrase that we 142 | want to use for the volume (or any other method of key, your choice). You can 143 | actually even do this while the copying process is running:: 144 | 145 | # cryptsetup luksAddKey /dev/loop0 --key-file=/root/initial_keyfile.bin 146 | Enter new passphrase for key slot: 147 | Verify passphrase: 148 | 149 | Let's check this worked:: 150 | 151 | # cryptsetup luksDump /dev/loop0 152 | LUKS header information for /dev/loop0 153 | 154 | Version: 1 155 | Cipher name: aes 156 | Cipher mode: xts-plain64 157 | Hash spec: sha1 158 | Payload offset: 4096 159 | MK bits: 256 160 | MK digest: b2 34 b8 7b 70 e8 78 17 a4 12 00 41 dc a4 bc 70 a3 50 02 22 161 | MK salt: ee 25 b4 f0 11 94 25 d1 2b 97 42 6c a6 ff 3d 1d 162 | e7 6d 1e 15 dd a0 07 17 25 82 d1 f9 14 6c ab e9 163 | MK iterations: 50125 164 | UUID: 3e21bbe0-3d70-4189-8f19-04fb7d7c5bb9 165 | 166 | Key Slot 0: ENABLED 167 | Iterations: 201892 168 | Salt: 9d b6 a1 f5 0f 91 ee 24 be 49 0e f7 f9 62 a2 06 169 | aa 45 79 7f 1a 56 5c 8c a3 03 15 a0 d2 9e ca e5 170 | Key material offset: 8 171 | AF stripes: 4000 172 | Key Slot 1: ENABLED 173 | Iterations: 198756 174 | Salt: 46 b4 21 fb e3 12 54 18 ff 8d 05 24 75 fc 3c 4b 175 | 3c 90 77 47 43 b6 0b 28 d9 b6 86 44 30 9e 20 d2 176 | Key material offset: 264 177 | AF stripes: 4000 178 | Key Slot 2: DISABLED 179 | Key Slot 3: DISABLED 180 | Key Slot 4: DISABLED 181 | Key Slot 5: DISABLED 182 | Key Slot 6: DISABLED 183 | Key Slot 7: DISABLED 184 | 185 | You can see the initial keyfile (slot 0) and the passphrase we just added (slot 186 | 1). Let's scrub the initial keyslot so the initial keyfile becomes useless. We 187 | do this by scrubbing slot 0. Don't worry, you cannot choose the wrong slot 188 | here; cryptsetup won't permit you to remove the wrong slot since you must prove 189 | that you still have at least access to one remaining slot (by entering your 190 | passphrase):: 191 | 192 | # cryptsetup luksKillSlot /dev/loop0 0 193 | Enter any remaining passphrase: 194 | 195 | And check again:: 196 | 197 | # cryptsetup luksDump /dev/loop0 198 | LUKS header information for /dev/loop0 199 | 200 | Version: 1 201 | Cipher name: aes 202 | Cipher mode: xts-plain64 203 | Hash spec: sha1 204 | Payload offset: 4096 205 | MK bits: 256 206 | MK digest: b2 34 b8 7b 70 e8 78 17 a4 12 00 41 dc a4 bc 70 a3 50 02 22 207 | MK salt: ee 25 b4 f0 11 94 25 d1 2b 97 42 6c a6 ff 3d 1d 208 | e7 6d 1e 15 dd a0 07 17 25 82 d1 f9 14 6c ab e9 209 | MK iterations: 50125 210 | UUID: 3e21bbe0-3d70-4189-8f19-04fb7d7c5bb9 211 | 212 | Key Slot 0: DISABLED 213 | Key Slot 1: ENABLED 214 | Iterations: 198756 215 | Salt: 46 b4 21 fb e3 12 54 18 ff 8d 05 24 75 fc 3c 4b 216 | 3c 90 77 47 43 b6 0b 28 d9 b6 86 44 30 9e 20 d2 217 | Key material offset: 264 218 | AF stripes: 4000 219 | Key Slot 2: DISABLED 220 | Key Slot 3: DISABLED 221 | Key Slot 4: DISABLED 222 | Key Slot 5: DISABLED 223 | Key Slot 6: DISABLED 224 | Key Slot 7: DISABLED 225 | 226 | Perfect, only our slot 1 (passphrase) is left now, you can safely discard the 227 | initial_keyfile.bin now. 228 | 229 | Last step, resize the filesystem to its original size. For this we must first 230 | mount the cryptographic file system and then call the resize2fs utility again:: 231 | 232 | # cryptsetup luksOpen /dev/loop0 newcryptofs 233 | Enter passphrase for /dev/loop0: 234 | 235 | # resize2fs /dev/mapper/newcryptofs 236 | resize2fs 1.42.9 (4-Feb-2014) 237 | Resizing the filesystem on /dev/mapper/newcryptofs to 255488 (4k) blocks. 238 | The filesystem on /dev/mapper/newcryptofs is now 255488 blocks long. 239 | 240 | You can see that the filesystem now occupies all available space (998 MiB). 241 | 242 | 243 | 244 | LUKS to LUKS conversion 245 | ----------------------- 246 | There are situations in which you might want to re-encrypt your LUKS device. 247 | For example, let's say you have a cryptographic volume and multiple users have 248 | access to it, each with their own keyslot. Now suppose you forfeit the rights 249 | of one person to the volume. Technically you would do this by killing the 250 | appropriate key slot of the key that was assigned to the user. This means the 251 | user can from then on not unlock the volume using the LUKS keyheader. 252 | 253 | But suppose the user you want whose access you want to revoke had -- while 254 | still in possession of a valid key -- access to the file system container 255 | itself. Then with that LUKS header he can still (even when the slot was killed) 256 | derive the underlying cryptographic key that secures the data. The only way to 257 | remedy this is to reencrypt the whole volume with a different bulk-encryption 258 | key. 259 | 260 | Another usecase are old LUKS volumes: the algorithms that were used at creation 261 | may not be suitable anymore. For example, maybe you have switched to some other 262 | hardware platform that has hardware support for specific algorithms and you can 263 | only take advantage of those when you choose a specific encryption algorithm. 264 | Or maybe the alignment that was adequate a couple of years back is not adquate 265 | anymore for you. For example, older cryptsetup instances used 1028 kiB headers, 266 | which is an odd size. Or maybe LUKS gained new features that you want to use. 267 | 268 | In any case, there are numerous cases why you want to turn a LUKS volume into 269 | another LUKS volume. This process is called "reLUKSification" within luksipc 270 | and it is something that is supported from 0.03 onwards. 271 | 272 | Let's say you have a partition called /dev/sdh2 which you want to reLUKSify. 273 | First let's see what the used encryption parameters are:: 274 | 275 | # cryptsetup luksDump /dev/sdh2 276 | LUKS header information for /dev/sdh2 277 | 278 | Version: 1 279 | Cipher name: aes 280 | Cipher mode: xts-plain64 281 | Hash spec: sha1 282 | Payload offset: 4096 283 | MK bits: 256 284 | MK digest: b1 44 6a 73 e3 06 27 27 a2 fe c2 59 e5 3a 39 2e 15 d7 d7 e0 285 | MK salt: 09 6d 6a 24 66 28 43 f7 f3 55 a9 9d 0a 40 77 58 286 | e0 1f 7c 30 b9 63 96 eb 99 34 52 4f 72 ba 57 ac 287 | MK iterations: 49750 288 | UUID: 6495d24d-34ac-41f5-a594-c5058cc31ed3 289 | 290 | Key Slot 0: ENABLED 291 | Iterations: 206119 292 | Salt: 99 c8 48 50 c3 a6 83 0d f9 39 a4 4d 0a 35 b0 ab 293 | 13 83 ee fd 9f 91 8d 92 a6 cf 42 50 9b 89 a6 be 294 | Key material offset: 8 295 | AF stripes: 4000 296 | Key Slot 1: DISABLED 297 | Key Slot 2: DISABLED 298 | Key Slot 3: DISABLED 299 | Key Slot 4: DISABLED 300 | Key Slot 5: DISABLED 301 | Key Slot 6: DISABLED 302 | Key Slot 7: DISABLED 303 | 304 | We'll now open the device with our old key (a passphrase):: 305 | 306 | # cryptsetup luksOpen /dev/sdh2 oldluks 307 | 308 | Just for demonstration purposes, we can calculate the MD5SUM over the whole 309 | block device (you won't need to do that, it's just a demo):: 310 | 311 | # md5sum /dev/mapper/oldluks 312 | 48d9763be76ddb4fb990367f8d6b8c22 /dev/mapper/oldluks 313 | 314 | For reLUKSification to work, you need to supply the path to the unlocked device 315 | (from where data will be read) as well as the path to the underlying raw device 316 | (which will be luksFormatted). 317 | 318 | You currently have your (raw) disk at /dev/sdh2 and your (unlocked) read disk 319 | at /dev/mapper/oldluks. It may be possible that a new LUKS header is even 320 | larger than the old header as now, which will lead to truncation of data at the 321 | very end of the partition. This will be the case, for example, if you reLUKSify 322 | volumes that have a 1028 kiB LUKS header and recreate with a recent version 323 | which writes 2048 kiB LUKS headers. You need to take all measures to decrease 324 | the size of the contained file system, as shown in :ref:`preparation`. These 325 | steps will not be repeated here, but you **must** perform them nevertheless if 326 | you want to avoid losing data. 327 | 328 | After the disk is unlocked, you call luksipc. In addition to the raw device 329 | which you want to convert you will also now have to specify the block device 330 | name of the unlocked device. The raw device is the one that luksFormat and 331 | luksOpen will be called on and the read device is the device from which data 332 | will be read during the copy procedure. Here's how the call to luksipc looks 333 | like. We assume that we want to change the underlying hash function to SHA256:: 334 | 335 | # luksipc --device /dev/sdh2 --readdev /dev/mapper/oldluks --luksparams='-h,sha256' 336 | WARNING! luksipc will perform the following actions: 337 | => reLUKSification of LUKS device /dev/sdh2 338 | -> Which has been unlocked at /dev/mapper/oldluks 339 | -> luksFormat will be performed on /dev/sdh2 340 | 341 | Please confirm you have completed the checklist: 342 | [1] You have resized the contained filesystem(s) appropriately 343 | [2] You have unmounted any contained filesystem(s) 344 | [3] You will ensure secure storage of the keyfile that will be generated at /root/initial_keyfile.bin 345 | [4] Power conditions are satisfied (i.e. your laptop is not running off battery) 346 | [5] You have a backup of all important data on /dev/sdh2 347 | 348 | /dev/sdh2: 2512 MiB = 2.5 GiB 349 | Chunk size: 10485760 bytes = 10.0 MiB 350 | Keyfile: /root/initial_keyfile.bin 351 | LUKS format parameters: -h,sha256 352 | 353 | Are all these conditions satisfied, then answer uppercase yes: YES 354 | [I]: Created raw device alias: /dev/sdh2 -> /dev/mapper/alias_luksipc_raw_60377226 355 | [I]: Size of reading device /dev/mapper/oldluks is 2631925760 bytes (2510 MiB + 0 bytes) 356 | [I]: Backing up physical disk /dev/sdh2 header to backup file header_backup.img 357 | [I]: Performing luksFormat of /dev/sdh2 358 | [I]: Performing luksOpen of /dev/sdh2 (opening as mapper name luksipc_dbb86eda) 359 | [I]: Size of luksOpened writing device is 2631925760 bytes (2510 MiB + 0 bytes) 360 | [I]: Write disk size equal to read disk size. 361 | [I]: Starting copying of data, read offset 10485760, write offset 0 362 | [I]: 0:00: 4.4% 110 MiB / 2510 MiB 43.5 MiB/s Left: 2400 MiB 0:00 h:m 363 | [I]: 0:00: 8.4% 210 MiB / 2510 MiB 34.1 MiB/s Left: 2300 MiB 0:01 h:m 364 | [I]: 0:00: 12.4% 310 MiB / 2510 MiB 21.9 MiB/s Left: 2200 MiB 0:01 h:m 365 | [...] 366 | [I]: 0:02: 88.0% 2210 MiB / 2510 MiB 17.3 MiB/s Left: 300 MiB 0:00 h:m 367 | [I]: 0:02: 92.0% 2310 MiB / 2510 MiB 17.6 MiB/s Left: 200 MiB 0:00 h:m 368 | [I]: 0:02: 96.0% 2410 MiB / 2510 MiB 18.0 MiB/s Left: 100 MiB 0:00 h:m 369 | [I]: 0:02: 100.0% 2510 MiB / 2510 MiB 18.2 MiB/s Left: 0 MiB 0:00 h:m 370 | [I]: Disk copy completed successfully. 371 | [I]: Synchronizing disk... 372 | [I]: Synchronizing of disk finished. 373 | 374 | After the process has finished, the old LUKS device /dev/mapper/oldluks will 375 | still be open. Be very careful not to do anything with that device, however! 376 | It's safe to close it:: 377 | 378 | # cryptsetup luksClose oldluks 379 | 380 | Then, let's open the device with the new key:: 381 | 382 | # cryptsetup luksOpen /dev/sdh2 newluks -d /root/initial_keyfile.bin 383 | 384 | And check that the conversion worked:: 385 | 386 | # md5sum /dev/mapper/newluks 387 | 48d9763be76ddb4fb990367f8d6b8c22 /dev/mapper/newluks 388 | 389 | Which it did :-) 390 | -------------------------------------------------------------------------------- /docs/update: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | make html 3 | -------------------------------------------------------------------------------- /exec.c: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | #include "exec.h" 33 | #include "logging.h" 34 | #include "globals.h" 35 | 36 | int argCount(const char **aArgs) { 37 | int cnt = 0; 38 | while (aArgs[cnt++]); 39 | return cnt - 1; 40 | } 41 | 42 | bool argAppend(const char **aArgs, const char *aNewArg, int *aArgCount, int aArraySize) { 43 | bool success = true; 44 | if ((*aArgCount) < 0) { 45 | *aArgCount = argCount(aArgs); 46 | } 47 | if ((*aArgCount + 2) > aArraySize) { 48 | /* Cannot copy next argument */ 49 | success = false; 50 | } else { 51 | aArgs[*aArgCount] = aNewArg; 52 | (*aArgCount)++; 53 | aArgs[*aArgCount] = NULL; 54 | } 55 | return success; 56 | } 57 | 58 | bool argAppendParse(const char **aArgs, char *aNewArgs, int *aArgCount, int aArraySize) { 59 | bool success = true; 60 | char *savePtr = NULL; 61 | char *nextToken; 62 | if ((*aArgCount) < 0) { 63 | *aArgCount = argCount(aArgs); 64 | } 65 | while ((nextToken = strtok_r(aNewArgs, ",", &savePtr))) { 66 | if ((*aArgCount + 2) > aArraySize) { 67 | /* Cannot copy next argument */ 68 | success = false; 69 | break; 70 | } else { 71 | aArgs[*aArgCount] = nextToken; 72 | (*aArgCount)++; 73 | } 74 | aNewArgs = NULL; 75 | } 76 | aArgs[*aArgCount] = NULL; 77 | return success; 78 | } 79 | 80 | void argDump(const char **aArgs) { 81 | int i = 0; 82 | while (aArgs[i]) { 83 | printf(" %2d: '%s'\n", i, aArgs[i]); 84 | i++; 85 | } 86 | } 87 | 88 | static char **argCopy(const char **aArgs) { 89 | char **result = NULL; 90 | int i; 91 | result = malloc(sizeof(char*) * EXEC_MAX_ARGCNT); 92 | if (!result) { 93 | perror("malloc"); 94 | exit(EXIT_FAILURE); 95 | } 96 | result[EXEC_MAX_ARGCNT - 1] = NULL; 97 | for (i = 0; i < EXEC_MAX_ARGCNT - 1; i++) { 98 | if (aArgs[i] == NULL) { 99 | result[i] = NULL; 100 | break; 101 | } 102 | result[i] = strdup(aArgs[i]); 103 | if (!result[i]) { 104 | perror("strdup"); 105 | exit(EXIT_FAILURE); 106 | } 107 | } 108 | return result; 109 | } 110 | 111 | static void freeArgCopy(char** aArgCopy) { 112 | int i; 113 | for (i = 0; i < EXEC_MAX_ARGCNT - 1; i++) { 114 | if (aArgCopy[i] == NULL) { 115 | break; 116 | } 117 | free(aArgCopy[i]); 118 | } 119 | free((void*)aArgCopy); 120 | } 121 | 122 | static void convertCommandLine(char *aBuffer, int aBufSize, const char **aArguments) { 123 | if ((!aBuffer) || (aBufSize < 4)) { 124 | return; 125 | } 126 | aBuffer[0] = 0; 127 | 128 | int remaining = aBufSize - 4; 129 | int position = 0; 130 | int i = 0; 131 | bool truncated = false; 132 | while (aArguments[i]) { 133 | int newChars = snprintf(aBuffer + position, remaining, "%s ", aArguments[i]); 134 | if (newChars >= remaining) { 135 | truncated = true; 136 | break; 137 | } 138 | position += newChars; 139 | remaining -= newChars; 140 | i++; 141 | } 142 | if (truncated) { 143 | strcpy(aBuffer + aBufSize - 5, "..."); 144 | } else { 145 | aBuffer[position - 1] = 0; 146 | } 147 | } 148 | 149 | struct execResult_t execGetReturnCode(const char **aArguments) { 150 | struct execResult_t execResult; 151 | char **argcopy = argCopy(aArguments); 152 | pid_t pid; 153 | int status; 154 | 155 | memset(&execResult, 0, sizeof(execResult)); 156 | execResult.success = true; 157 | 158 | pid = fork(); 159 | if (pid == -1) { 160 | perror("fork"); 161 | execResult.success = false; 162 | return execResult; 163 | } 164 | if (pid > 0) { 165 | char commandLineBuffer[256]; 166 | convertCommandLine(commandLineBuffer, sizeof(commandLineBuffer), aArguments); 167 | logmsg(LLVL_DEBUG, "Subprocess [PID %d]: Will execute '%s'\n", pid, commandLineBuffer); 168 | } 169 | if (pid == 0) { 170 | /* Child */ 171 | if (getLogLevel() < LLVL_DEBUG) { 172 | /* Shut up the child if user did not request debug output */ 173 | close(1); 174 | close(2); 175 | } 176 | execvp(aArguments[0], argcopy); 177 | perror("execvp"); 178 | logmsg(LLVL_ERROR, "Execution of %s in forked child process failed at execvp: %s\n", aArguments[0], strerror(errno)); 179 | 180 | /* Exec failed, terminate chExec failed, terminate child process 181 | * (parent will catch this as the return code) */ 182 | exit(EXIT_FAILURE); 183 | } 184 | 185 | if (waitpid(pid, &status, 0) == (pid_t)-1) { 186 | perror("waitpid"); 187 | execResult.success = false; 188 | return execResult; 189 | } 190 | 191 | freeArgCopy(argcopy); 192 | execResult.returnCode = WEXITSTATUS(status); 193 | logmsg(LLVL_DEBUG, "Subprocess [PID %d]: %s returned %d\n", pid, aArguments[0], execResult.returnCode); 194 | return execResult; 195 | } 196 | 197 | 198 | -------------------------------------------------------------------------------- /exec.h: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #ifndef __EXEC_H__ 25 | #define __EXEC_H__ 26 | 27 | #include 28 | 29 | struct execResult_t { 30 | bool success; 31 | int returnCode; 32 | }; 33 | 34 | /*************** AUTO GENERATED SECTION FOLLOWS ***************/ 35 | int argCount(const char **aArgs); 36 | bool argAppend(const char **aArgs, const char *aNewArg, int *aArgCount, int aArraySize); 37 | bool argAppendParse(const char **aArgs, char *aNewArgs, int *aArgCount, int aArraySize); 38 | void argDump(const char **aArgs); 39 | struct execResult_t execGetReturnCode(const char **aArguments); 40 | /*************** AUTO GENERATED SECTION ENDS ***************/ 41 | 42 | #endif 43 | -------------------------------------------------------------------------------- /exit.c: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #include 25 | 26 | #include "logging.h" 27 | #include "exit.h" 28 | 29 | #define MAX_VALID_ERROR_CODE 28 30 | static const char *exitCodeAbbr[] = { 31 | [EC_SUCCESS] = "EC_SUCCESS", 32 | [EC_UNSPECIFIED_ERROR] = "EC_UNSPECIFIED_ERROR", 33 | [EC_COPY_ABORTED_RESUME_FILE_WRITTEN] = "EC_COPY_ABORTED_RESUME_FILE_WRITTEN", 34 | [EC_CANNOT_ALLOCATE_CHUNK_MEMORY] = "EC_CANNOT_ALLOCATE_CHUNK_MEMORY", 35 | [EC_CANNOT_GENERATE_KEY_FILE] = "EC_CANNOT_GENERATE_KEY_FILE", 36 | [EC_CANNOT_INITIALIZE_DEVICE_ALIAS] = "EC_CANNOT_INITIALIZE_DEVICE_ALIAS", 37 | [EC_CANNOT_OPEN_READ_DEVICE] = "EC_CANNOT_OPEN_READ_DEVICE", 38 | [EC_CANNOT_OPEN_RESUME_FILE] = "EC_CANNOT_OPEN_RESUME_FILE", 39 | [EC_COPY_ABORTED_FAILED_TO_WRITE_WRITE_RESUME_FILE] = "EC_COPY_ABORTED_FAILED_TO_WRITE_WRITE_RESUME_FILE", 40 | [EC_DEVICE_SIZES_IMPLAUSIBLE] = "EC_DEVICE_SIZES_IMPLAUSIBLE", 41 | [EC_FAILED_TO_BACKUP_HEADER] = "EC_FAILED_TO_BACKUP_HEADER", 42 | [EC_FAILED_TO_CLOSE_LUKS_DEVICE] = "EC_FAILED_TO_CLOSE_LUKS_DEVICE", 43 | [EC_FAILED_TO_OPEN_UNLOCKED_CRYPTO_DEVICE] = "EC_FAILED_TO_OPEN_UNLOCKED_CRYPTO_DEVICE", 44 | [EC_FAILED_TO_PERFORM_LUKSFORMAT] = "EC_FAILED_TO_PERFORM_LUKSFORMAT", 45 | [EC_FAILED_TO_PERFORM_LUKSOPEN] = "EC_FAILED_TO_PERFORM_LUKSOPEN", 46 | [EC_FAILED_TO_READ_RESUME_FILE] = "EC_FAILED_TO_READ_RESUME_FILE", 47 | [EC_FAILED_TO_REMOVE_DEVICE_MAPPER_ALIAS] = "EC_FAILED_TO_REMOVE_DEVICE_MAPPER_ALIAS", 48 | [EC_LUKSIPC_WRITE_DEVICE_HANDLE_UNAVAILABLE] = "EC_LUKSIPC_WRITE_DEVICE_HANDLE_UNAVAILABLE", 49 | [EC_PRECONDITIONS_NOT_SATISFIED] = "EC_PRECONDITIONS_NOT_SATISFIED", 50 | [EC_UNABLE_TO_GET_RAW_DISK_SIZE] = "EC_UNABLE_TO_GET_RAW_DISK_SIZE", 51 | [EC_UNABLE_TO_READ_FIRST_CHUNK] = "EC_UNABLE_TO_READ_FIRST_CHUNK", 52 | [EC_UNABLE_TO_READ_FROM_STDIN] = "EC_UNABLE_TO_READ_FROM_STDIN", 53 | [EC_UNSUPPORTED_SMALL_DISK_CORNER_CASE] = "EC_UNSUPPORTED_SMALL_DISK_CORNER_CASE", 54 | [EC_USER_ABORTED_PROCESS] = "EC_USER_ABORTED_PROCESS", 55 | [EC_CANNOT_INIT_SIGNAL_HANDLERS] = "EC_CANNOT_INIT_SIGNAL_HANDLERS", 56 | [EC_CMDLINE_PARSING_ERROR] = "EC_CMDLINE_PARSING_ERROR", 57 | [EC_CMDLINE_ARGUMENT_ERROR] = "EC_CMDLINE_ARGUMENT_ERROR", 58 | [EC_CANNOT_GENERATE_WRITE_HANDLE] = "EC_CANNOT_GENERATE_WRITE_HANDLE", 59 | [EC_PRNG_INITIALIZATION_FAILED] = "EC_PRNG_INITIALIZATION_FAILED", 60 | }; 61 | static const char *exitCodeDesc[] = { 62 | [EC_SUCCESS] = "Success", 63 | [EC_UNSPECIFIED_ERROR] = "Unspecified error", 64 | [EC_COPY_ABORTED_RESUME_FILE_WRITTEN] = "Copy aborted gracefully, resume file successfully written", 65 | [EC_CANNOT_ALLOCATE_CHUNK_MEMORY] = "Cannot allocate memory for copy chunks", 66 | [EC_CANNOT_GENERATE_KEY_FILE] = "Cannot generate key file", 67 | [EC_CANNOT_INITIALIZE_DEVICE_ALIAS] = "Cannot initialize device mapper alias", 68 | [EC_CANNOT_OPEN_READ_DEVICE] = "Cannot open reading block device", 69 | [EC_CANNOT_OPEN_RESUME_FILE] = "Cannot open resume file", 70 | [EC_COPY_ABORTED_FAILED_TO_WRITE_WRITE_RESUME_FILE] = "Copy aborted, failed to write resume file", 71 | [EC_DEVICE_SIZES_IMPLAUSIBLE] = "Device sizes are implausible", 72 | [EC_FAILED_TO_BACKUP_HEADER] = "Failed to backup raw device header", 73 | [EC_FAILED_TO_CLOSE_LUKS_DEVICE] = "Failed to close LUKS device", 74 | [EC_FAILED_TO_OPEN_UNLOCKED_CRYPTO_DEVICE] = "Failed to open unlocked crypto device", 75 | [EC_FAILED_TO_PERFORM_LUKSFORMAT] = "Failed to perform luksFormat", 76 | [EC_FAILED_TO_PERFORM_LUKSOPEN] = "Failed to perform luksOpen", 77 | [EC_FAILED_TO_READ_RESUME_FILE] = "Failed to read resume file", 78 | [EC_FAILED_TO_REMOVE_DEVICE_MAPPER_ALIAS] = "Failed to remove device mapper alias", 79 | [EC_LUKSIPC_WRITE_DEVICE_HANDLE_UNAVAILABLE] = "Device mapper handle for luksipc write device is unavailable", 80 | [EC_PRECONDITIONS_NOT_SATISFIED] = "Process preconditions are unsatisfied", 81 | [EC_UNABLE_TO_GET_RAW_DISK_SIZE] = "Unable to determine raw disk size", 82 | [EC_UNABLE_TO_READ_FIRST_CHUNK] = "Unable to read first chunk", 83 | [EC_UNABLE_TO_READ_FROM_STDIN] = "Unable to read from standard input", 84 | [EC_UNSUPPORTED_SMALL_DISK_CORNER_CASE] = "Unsupported small disk corner case", 85 | [EC_USER_ABORTED_PROCESS] = "User aborted process", 86 | [EC_CANNOT_INIT_SIGNAL_HANDLERS] = "Unable to install signal handlers", 87 | [EC_CMDLINE_PARSING_ERROR] = "Error parsing the parameters given on command line (programming bug)", 88 | [EC_CMDLINE_ARGUMENT_ERROR] = "Error with a parameter which was given on the command line", 89 | [EC_CANNOT_GENERATE_WRITE_HANDLE] = "Error generating device mapper write handle", 90 | [EC_PRNG_INITIALIZATION_FAILED] = "Initialization of PRNG failed", 91 | }; 92 | 93 | void terminate(enum terminationCode_t aTermCode) { 94 | int logLevel = (aTermCode == EC_SUCCESS) ? LLVL_DEBUG : LLVL_ERROR; 95 | if (aTermCode <= MAX_VALID_ERROR_CODE) { 96 | logmsg(logLevel, "Exit with code %d [%s]: %s\n", aTermCode, exitCodeAbbr[aTermCode], exitCodeDesc[aTermCode]); 97 | } else { 98 | logmsg(LLVL_ERROR, "Exit with code %d: No description available.\n", aTermCode); 99 | } 100 | exit(aTermCode); 101 | } 102 | -------------------------------------------------------------------------------- /exit.h: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #ifndef __EXIT_H__ 25 | #define __EXIT_H__ 26 | 27 | /* 28 | * The error codes and messages are maintained here. All C code is generated 29 | * from these stubs from a small Python script. When adding new error codes, 30 | * please add them here and regenerate the appropriate code. The format should 31 | * be fairly obvious. 32 | * 33 | :0 EC_SUCCESS Success 34 | :1 EC_UNSPECIFIED_ERROR Unspecified error 35 | :2 EC_COPY_ABORTED_RESUME_FILE_WRITTEN Copy aborted gracefully, resume file successfully written 36 | :3 EC_CANNOT_ALLOCATE_CHUNK_MEMORY Cannot allocate memory for copy chunks 37 | :4 EC_CANNOT_GENERATE_KEY_FILE Cannot generate key file 38 | :5 EC_CANNOT_INITIALIZE_DEVICE_ALIAS Cannot initialize device mapper alias 39 | :6 EC_CANNOT_OPEN_READ_DEVICE Cannot open reading block device 40 | :7 EC_CANNOT_OPEN_RESUME_FILE Cannot open resume file 41 | :8 EC_COPY_ABORTED_FAILED_TO_WRITE_WRITE_RESUME_FILE Copy aborted, failed to write resume file 42 | :9 EC_DEVICE_SIZES_IMPLAUSIBLE Device sizes are implausible 43 | :10 EC_FAILED_TO_BACKUP_HEADER Failed to backup raw device header 44 | :11 EC_FAILED_TO_CLOSE_LUKS_DEVICE Failed to close LUKS device 45 | :12 EC_FAILED_TO_OPEN_UNLOCKED_CRYPTO_DEVICE Failed to open unlocked crypto device 46 | :13 EC_FAILED_TO_PERFORM_LUKSFORMAT Failed to perform luksFormat 47 | :14 EC_FAILED_TO_PERFORM_LUKSOPEN Failed to perform luksOpen 48 | :15 EC_FAILED_TO_READ_RESUME_FILE Failed to read resume file 49 | :16 EC_FAILED_TO_REMOVE_DEVICE_MAPPER_ALIAS Failed to remove device mapper alias 50 | :17 EC_LUKSIPC_WRITE_DEVICE_HANDLE_UNAVAILABLE Device mapper handle for luksipc write device is unavailable 51 | :18 EC_PRECONDITIONS_NOT_SATISFIED Process preconditions are unsatisfied 52 | :19 EC_UNABLE_TO_GET_RAW_DISK_SIZE Unable to determine raw disk size 53 | :20 EC_UNABLE_TO_READ_FIRST_CHUNK Unable to read first chunk 54 | :21 EC_UNABLE_TO_READ_FROM_STDIN Unable to read from standard input 55 | :22 EC_UNSUPPORTED_SMALL_DISK_CORNER_CASE Unsupported small disk corner case 56 | :23 EC_USER_ABORTED_PROCESS User aborted process 57 | :24 EC_CANNOT_INIT_SIGNAL_HANDLERS Unable to install signal handlers 58 | :25 EC_CMDLINE_PARSING_ERROR Error parsing the parameters given on command line (programming bug) 59 | :26 EC_CMDLINE_ARGUMENT_ERROR Error with a parameter which was given on the command line 60 | :27 EC_CANNOT_GENERATE_WRITE_HANDLE Error generating device mapper write handle 61 | :28 EC_PRNG_INITIALIZATION_FAILED Initialization of PRNG failed 62 | */ 63 | 64 | enum terminationCode_t { 65 | EC_SUCCESS = 0, 66 | EC_UNSPECIFIED_ERROR = 1, 67 | EC_COPY_ABORTED_RESUME_FILE_WRITTEN = 2, 68 | EC_CANNOT_ALLOCATE_CHUNK_MEMORY = 3, 69 | EC_CANNOT_GENERATE_KEY_FILE = 4, 70 | EC_CANNOT_INITIALIZE_DEVICE_ALIAS = 5, 71 | EC_CANNOT_OPEN_READ_DEVICE = 6, 72 | EC_CANNOT_OPEN_RESUME_FILE = 7, 73 | EC_COPY_ABORTED_FAILED_TO_WRITE_WRITE_RESUME_FILE = 8, 74 | EC_DEVICE_SIZES_IMPLAUSIBLE = 9, 75 | EC_FAILED_TO_BACKUP_HEADER = 10, 76 | EC_FAILED_TO_CLOSE_LUKS_DEVICE = 11, 77 | EC_FAILED_TO_OPEN_UNLOCKED_CRYPTO_DEVICE = 12, 78 | EC_FAILED_TO_PERFORM_LUKSFORMAT = 13, 79 | EC_FAILED_TO_PERFORM_LUKSOPEN = 14, 80 | EC_FAILED_TO_READ_RESUME_FILE = 15, 81 | EC_FAILED_TO_REMOVE_DEVICE_MAPPER_ALIAS = 16, 82 | EC_LUKSIPC_WRITE_DEVICE_HANDLE_UNAVAILABLE = 17, 83 | EC_PRECONDITIONS_NOT_SATISFIED = 18, 84 | EC_UNABLE_TO_GET_RAW_DISK_SIZE = 19, 85 | EC_UNABLE_TO_READ_FIRST_CHUNK = 20, 86 | EC_UNABLE_TO_READ_FROM_STDIN = 21, 87 | EC_UNSUPPORTED_SMALL_DISK_CORNER_CASE = 22, 88 | EC_USER_ABORTED_PROCESS = 23, 89 | EC_CANNOT_INIT_SIGNAL_HANDLERS = 24, 90 | EC_CMDLINE_PARSING_ERROR = 25, 91 | EC_CMDLINE_ARGUMENT_ERROR = 26, 92 | EC_CANNOT_GENERATE_WRITE_HANDLE = 27, 93 | EC_PRNG_INITIALIZATION_FAILED = 28 94 | }; 95 | 96 | /*************** AUTO GENERATED SECTION FOLLOWS ***************/ 97 | void terminate(enum terminationCode_t aTermCode); 98 | /*************** AUTO GENERATED SECTION ENDS ***************/ 99 | 100 | #endif 101 | -------------------------------------------------------------------------------- /globals.h: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #ifndef __GLOBALS_H__ 25 | #define __GLOBALS_H__ 26 | 27 | #define MAX_HANDLE_LENGTH 32 28 | 29 | #define MAX_ARG_CNT 32 30 | #define MAX_ARGLENGTH 256 31 | 32 | #define EXEC_MAX_ARGCNT 64 33 | 34 | #define RESUME_FILE_HEADER_MAGIC "luksipc RESUME v1\0\xde\xad\xbe\xef & \xc0\xff\xee\0\0\0\0" 35 | #define RESUME_FILE_HEADER_MAGIC_LEN 32 36 | 37 | #define HEADER_BACKUP_BLOCKSIZE (128 * 1024) 38 | #define HEADER_BACKUP_BLOCKCNT 4096 39 | #define HEADER_BACKUP_SIZE_BYTES (HEADER_BACKUP_BLOCKSIZE * HEADER_BACKUP_BLOCKCNT) 40 | 41 | #define DEFAULT_RESUME_FILENAME "resume.bin" 42 | 43 | #endif 44 | -------------------------------------------------------------------------------- /keyfile.c: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | #include "logging.h" 34 | #include "keyfile.h" 35 | #include "utils.h" 36 | #include "random.h" 37 | 38 | bool genKeyfile(const char *aFilename, bool aForce) { 39 | /* Does the file already exist? */ 40 | struct stat statBuf; 41 | int statResult = stat(aFilename, &statBuf); 42 | if (statResult == 0) { 43 | /* Keyfile already exists */ 44 | if (!aForce) { 45 | logmsg(LLVL_ERROR, "Keyfile %s already exists, refusing to overwrite.\n", aFilename); 46 | return false; 47 | } else { 48 | logmsg(LLVL_WARN, "Keyfile %s already exists, overwriting because safety checks have been disabled.\n", aFilename); 49 | } 50 | } 51 | 52 | int fd = open(aFilename, O_WRONLY | O_CREAT | O_TRUNC, 0600); 53 | if (fd == -1) { 54 | /* Cannot create keyfile */ 55 | logmsg(LLVL_ERROR, "Cannot create keyfile %s: %s\n", aFilename, strerror(errno)); 56 | return false; 57 | } 58 | 59 | uint8_t keyData[4096]; 60 | if (!readRandomData(keyData, sizeof(keyData))) { 61 | logmsg(LLVL_ERROR, "Error reading random data.\n"); 62 | close(fd); 63 | return false; 64 | } 65 | 66 | int dataWritten = write(fd, keyData, sizeof(keyData)); 67 | if (dataWritten != sizeof(keyData)) { 68 | logmsg(LLVL_ERROR, "Short write to keyfile: wanted %ld, read %d bytes\n", sizeof(keyData), dataWritten); 69 | close(fd); 70 | return false; 71 | } 72 | 73 | close(fd); 74 | return true; 75 | } 76 | -------------------------------------------------------------------------------- /keyfile.h: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #ifndef __KEYFILE_H__ 25 | #define __KEYFILE_H__ 26 | 27 | #include 28 | 29 | /*************** AUTO GENERATED SECTION FOLLOWS ***************/ 30 | bool genKeyfile(const char *aFilename, bool aForce); 31 | /*************** AUTO GENERATED SECTION ENDS ***************/ 32 | 33 | #endif 34 | -------------------------------------------------------------------------------- /logging.c: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #include 25 | #include 26 | 27 | #include "logging.h" 28 | 29 | static int currentLogLevel; 30 | 31 | int getLogLevel(void) { 32 | return currentLogLevel; 33 | } 34 | 35 | void setLogLevel(int aLogLevel) { 36 | currentLogLevel = aLogLevel; 37 | } 38 | 39 | static const char* logLevelToStr(int aLogLvl) { 40 | switch (aLogLvl) { 41 | case LLVL_CRITICAL: return "C"; 42 | case LLVL_ERROR: return "E"; 43 | case LLVL_WARN: return "W"; 44 | case LLVL_INFO: return "I"; 45 | case LLVL_DEBUG: return "D"; 46 | } 47 | return "?"; 48 | } 49 | 50 | void logmsg(int aLogLvl, const char *aFmtString, ...) { 51 | if (aLogLvl <= currentLogLevel) { 52 | va_list ap; 53 | fprintf(stderr, "[%s]: ", logLevelToStr(aLogLvl)); 54 | 55 | va_start(ap, aFmtString); 56 | vfprintf(stderr, aFmtString, ap); 57 | va_end(ap); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /logging.h: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #ifndef __LOGGING_H__ 25 | #define __LOGGING_H__ 26 | 27 | #define LLVL_DEBUG 4 28 | #define LLVL_INFO 3 29 | #define LLVL_WARN 2 30 | #define LLVL_ERROR 1 31 | #define LLVL_CRITICAL 0 32 | 33 | /*************** AUTO GENERATED SECTION FOLLOWS ***************/ 34 | int getLogLevel(void); 35 | void setLogLevel(int aLogLevel); 36 | void logmsg(int aLogLvl, const char *aFmtString, ...); 37 | /*************** AUTO GENERATED SECTION ENDS ***************/ 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /luks.c: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | #include "exec.h" 33 | #include "luks.h" 34 | #include "logging.h" 35 | #include "globals.h" 36 | #include "utils.h" 37 | #include "random.h" 38 | 39 | /* Checks is the given block device has already been formatted with LUKS. */ 40 | bool isLuks(const char *aBlockDevice) { 41 | const char *arguments[] = { 42 | "cryptsetup", 43 | "isLuks", 44 | aBlockDevice, 45 | NULL 46 | }; 47 | struct execResult_t execResult = execGetReturnCode(arguments); 48 | return execResult.success && (execResult.returnCode == 0); 49 | } 50 | 51 | 52 | /* Returns if the given device mapper name is available (i.e. not active at the 53 | * moment) */ 54 | bool isLuksMapperAvailable(const char *aMapperName) { 55 | const char *arguments[] = { 56 | "cryptsetup", 57 | "status", 58 | aMapperName, 59 | NULL 60 | }; 61 | 62 | logmsg(LLVL_DEBUG, "Performing dm-crypt status lookup on mapper name '%s'\n", aMapperName); 63 | struct execResult_t execResult = execGetReturnCode(arguments); 64 | bool mapperAvailable = execResult.success && (execResult.returnCode == 4); 65 | logmsg(LLVL_DEBUG, "Device mapper name '%s' is %savailable (execution %s, returncode %d).\n", aMapperName, mapperAvailable ? "" : "NOT ", execResult.success ? "successful" : "failed", execResult.returnCode); 66 | return mapperAvailable; 67 | } 68 | 69 | /* Formats a block device with LUKS using the given key file for slot 0 and 70 | * passes some optional parameters (comma-separated) to cryptsetup */ 71 | bool luksFormat(const char *aBlkDevice, const char *aKeyFile, const char *aOptionalParams) { 72 | int argcnt = -1; 73 | char userSuppliedArguments[MAX_ARGLENGTH]; 74 | const char *arguments[MAX_ARG_CNT] = { 75 | "cryptsetup", 76 | "luksFormat", 77 | "-q", 78 | "--key-file", 79 | aKeyFile, 80 | NULL 81 | }; 82 | if (aOptionalParams) { 83 | if (!safestrcpy(userSuppliedArguments, aOptionalParams, MAX_ARGLENGTH)) { 84 | logmsg(LLVL_ERROR, "Unable to copy user supplied argument, %d bytes max.\n", MAX_ARGLENGTH); 85 | return false; 86 | } 87 | 88 | if (!argAppendParse(arguments, userSuppliedArguments, &argcnt, MAX_ARG_CNT)) { 89 | logmsg(LLVL_ERROR, "Unable to copy user supplied argument, %d count max.\n", MAX_ARG_CNT); 90 | return false; 91 | } 92 | } 93 | 94 | if (!argAppend(arguments, aBlkDevice, &argcnt, MAX_ARG_CNT)) { 95 | logmsg(LLVL_ERROR, "Unable to copy last user supplied argument, %d count max.\n", MAX_ARG_CNT); 96 | return false; 97 | } 98 | 99 | logmsg(LLVL_DEBUG, "Performing luksFormat of block device %s using key file %s\n", aBlkDevice, aKeyFile); 100 | struct execResult_t execResult = execGetReturnCode(arguments); 101 | if ((!execResult.success) || (execResult.returnCode != 0)) { 102 | logmsg(LLVL_ERROR, "luksFormat failed (execution %s, return code %d), aborting.\n", execResult.success ? "successful" : "failed", execResult.returnCode); 103 | return false; 104 | } 105 | 106 | return true; 107 | } 108 | 109 | bool luksOpen(const char *aBlkDevice, const char *aKeyFile, const char *aHandle) { 110 | const char *arguments[] = { 111 | "cryptsetup", 112 | "luksOpen", 113 | "--key-file", 114 | aKeyFile, 115 | aBlkDevice, 116 | aHandle, 117 | NULL 118 | }; 119 | logmsg(LLVL_DEBUG, "Performing luksOpen of block device %s using key file %s and device mapper handle %s\n", aBlkDevice, aKeyFile, aHandle); 120 | struct execResult_t execResult = execGetReturnCode(arguments); 121 | if ((!execResult.success) || (execResult.returnCode != 0)) { 122 | logmsg(LLVL_ERROR, "luksOpen failed (execution %s, return code %d).\n", execResult.success ? "successful" : "failed", execResult.returnCode); 123 | return false; 124 | } 125 | 126 | return true; 127 | } 128 | 129 | bool dmCreateAlias(const char *aSrcDevice, const char *aMapperHandle) { 130 | uint64_t devSize = getDiskSizeOfPath(aSrcDevice); 131 | if (devSize % 512) { 132 | logmsg(LLVL_ERROR, "Device size of %s (%" PRIu64 " bytes) is not divisible by even 512 bytes sector size.\n", aSrcDevice, devSize); 133 | return false; 134 | } 135 | 136 | char mapperTable[256]; 137 | snprintf(mapperTable, sizeof(mapperTable), "0 %" PRIu64 " linear %s 0", devSize / 512, aSrcDevice); 138 | 139 | const char *arguments[] = { 140 | "dmsetup", 141 | "create", 142 | aMapperHandle, 143 | "--table", 144 | mapperTable, 145 | NULL 146 | }; 147 | 148 | struct execResult_t execResult = execGetReturnCode(arguments); 149 | if ((!execResult.success) || (execResult.returnCode != 0)) { 150 | logmsg(LLVL_ERROR, "dmsetup alias creation failed (execution %s, returncode %d).\n", execResult.success ? "successful" : "failed", execResult.returnCode); 151 | return false; 152 | } 153 | 154 | char aliasDeviceFilename[256]; 155 | snprintf(aliasDeviceFilename, sizeof(aliasDeviceFilename), "/dev/mapper/%s", aMapperHandle); 156 | uint64_t aliasDevSize = getDiskSizeOfPath(aliasDeviceFilename); 157 | if (devSize != aliasDevSize) { 158 | logmsg(LLVL_ERROR, "Source device (%s) and its supposed alias device (%s) have different sizes (src = %" PRIu64 " and alias = %" PRIu64 ").\n", aSrcDevice, aliasDeviceFilename, devSize, aliasDevSize); 159 | dmRemove(aMapperHandle); 160 | return false; 161 | } 162 | 163 | logmsg(LLVL_DEBUG, "Created device mapper alias: %s -> %s\n", aliasDeviceFilename, aSrcDevice); 164 | return true; 165 | } 166 | 167 | char *dmCreateDynamicAlias(const char *aSrcDevice, const char *aAliasPrefix) { 168 | char alias[64]; 169 | if (aAliasPrefix && (strlen(aAliasPrefix) < 32)) { 170 | snprintf(alias, sizeof(alias), "alias_%s_", aAliasPrefix); 171 | } else { 172 | strcpy(alias, "alias_"); 173 | } 174 | if (!randomHexStrCat(alias, 4)) { 175 | return NULL; 176 | } 177 | 178 | char *aliasPathname = malloc(strlen("/dev/mapper/") + strlen(alias) + 1); 179 | if (!aliasPathname) { 180 | logmsg(LLVL_ERROR, "malloc error for full filename of dynamic alias: %s\n", strerror(errno)); 181 | return NULL; 182 | } 183 | sprintf(aliasPathname, "/dev/mapper/%s", alias); 184 | 185 | bool aliasSuccessful = dmCreateAlias(aSrcDevice, alias); 186 | if (!aliasSuccessful) { 187 | free(aliasPathname); 188 | return NULL; 189 | } 190 | 191 | return aliasPathname; 192 | } 193 | 194 | bool dmRemove(const char *aMapperHandle) { 195 | const char *arguments[] = { 196 | "dmsetup", 197 | "remove", 198 | aMapperHandle, 199 | NULL 200 | }; 201 | 202 | /* Device cannot be closed if it is still open. udev will usually call 203 | * blkid on the device after it is closed after been written to. Therefore 204 | * it is possible that "dmsetup remove" fails immediately after closing the 205 | * device (because blkid will have an open handle). We simply wait a bit 206 | * and try again later if this happens. */ 207 | struct execResult_t execResult; 208 | for (int try = 0; try < 10; try++) { 209 | execResult = execGetReturnCode(arguments); 210 | if (!execResult.success) { 211 | return false; 212 | } 213 | if ((execResult.success) && (execResult.returnCode == 0)) { 214 | break; 215 | } 216 | sleep(1); 217 | } 218 | 219 | bool success = (execResult.success) && (execResult.returnCode == 0) && isLuksMapperAvailable(aMapperHandle); 220 | if (!success) { 221 | logmsg(LLVL_ERROR, "Cannot remove device mapper handle %s (execution %s, return code %d)\n", aMapperHandle, execResult.success ? "successful" : "failed", execResult.returnCode); 222 | } 223 | 224 | return success; 225 | } 226 | 227 | -------------------------------------------------------------------------------- /luks.h: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #ifndef __LUKS_H__ 25 | #define __LUKS_H__ 26 | 27 | #include 28 | 29 | /*************** AUTO GENERATED SECTION FOLLOWS ***************/ 30 | bool isLuks(const char *aBlockDevice); 31 | bool isLuksMapperAvailable(const char *aMapperName); 32 | bool luksFormat(const char *aBlkDevice, const char *aKeyFile, const char *aOptionalParams); 33 | bool luksOpen(const char *aBlkDevice, const char *aKeyFile, const char *aHandle); 34 | bool dmCreateAlias(const char *aSrcDevice, const char *aMapperHandle); 35 | char *dmCreateDynamicAlias(const char *aSrcDevice, const char *aAliasPrefix); 36 | bool dmRemove(const char *aMapperHandle); 37 | /*************** AUTO GENERATED SECTION ENDS ***************/ 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /luksipc.h: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #ifndef __LUKSIPC_H__ 25 | #define __LUKSIPC_H__ 26 | 27 | /*************** AUTO GENERATED SECTION FOLLOWS ***************/ 28 | int main(int argc, char **argv); 29 | /*************** AUTO GENERATED SECTION ENDS ***************/ 30 | 31 | #endif 32 | -------------------------------------------------------------------------------- /mount.c: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | #include "mount.h" 34 | #include "logging.h" 35 | 36 | bool isBlockDeviceMounted(const char *aBlkDevice) { 37 | FILE *f = fopen("/proc/mounts", "r"); 38 | struct mntent *entry; 39 | bool isMounted = false; 40 | struct stat blkDevStat; 41 | 42 | if (stat(aBlkDevice, &blkDevStat) != 0) { 43 | logmsg(LLVL_ERROR, "Unable to stat %s to determine if it's mounted. Assuming it is mounted for safety. Stat reported: %s\n", aBlkDevice, strerror(errno)); 44 | return true; 45 | } 46 | 47 | while ((entry = getmntent(f)) != NULL) { 48 | if (strcmp(entry->mnt_fsname, aBlkDevice) == 0) { 49 | /* Names match, definitely mounted! */ 50 | logmsg(LLVL_DEBUG, "%s mounted at %s\n", aBlkDevice, entry->mnt_dir); 51 | isMounted = true; 52 | break; 53 | } 54 | 55 | if (strcmp(entry->mnt_fsname, "none")) { 56 | /* Check major/minor number of device */ 57 | struct stat newDevStat; 58 | if (stat(entry->mnt_fsname, &newDevStat) == 0) { 59 | if (newDevStat.st_rdev == blkDevStat.st_rdev) { 60 | /* Major/minor is identical */ 61 | logmsg(LLVL_DEBUG, "%s has identical struct stat.st_rdev with %s, mounted at %s\n", aBlkDevice, entry->mnt_fsname, entry->mnt_dir); 62 | isMounted = true; 63 | break; 64 | } 65 | 66 | } 67 | } 68 | 69 | } 70 | 71 | fclose(f); 72 | return isMounted; 73 | } 74 | -------------------------------------------------------------------------------- /mount.h: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #ifndef __MOUNT_H__ 25 | #define __MOUNT_H__ 26 | 27 | /*************** AUTO GENERATED SECTION FOLLOWS ***************/ 28 | bool isBlockDeviceMounted(const char *aBlkDevice); 29 | /*************** AUTO GENERATED SECTION ENDS ***************/ 30 | 31 | #endif 32 | -------------------------------------------------------------------------------- /parameters.c: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | #include "utils.h" 33 | #include "logging.h" 34 | #include "parameters.h" 35 | #include "globals.h" 36 | #include "exit.h" 37 | 38 | static void defaultParameters(struct conversionParameters *aParams) { 39 | memset(aParams, 0, sizeof(struct conversionParameters)); 40 | aParams->blocksize = 48 * 1024 * 1024; 41 | aParams->safetyChecks = true; 42 | aParams->batchMode = false; 43 | aParams->keyFile = "/root/initial_keyfile.bin"; 44 | aParams->logLevel = LLVL_INFO; 45 | aParams->backupFile = "header_backup.img"; 46 | aParams->resumeFilename = "resume.bin"; 47 | } 48 | 49 | static void syntax(char **argv, const char *aMessage, enum terminationCode_t aExitCode) { 50 | if (aMessage) { 51 | fprintf(stderr, "Error: %s\n", aMessage); 52 | fprintf(stderr, "\n"); 53 | } 54 | fprintf(stderr, "luksipc: Tool to convert block devices to LUKS-encrypted block devices on the fly\n"); 55 | fprintf(stderr, "\n"); 56 | fprintf(stderr, "%s (-d, --device=RAWDEV) (--readdev=DEV) (-b, --blocksize=BYTES)\n", argv[0]); 57 | fprintf(stderr, " (-c, --backupfile=FILE) (-k, --keyfile=FILE) (-p, --luksparam=PARAMS)\n"); 58 | fprintf(stderr, " (-l, --loglevel=LVL) (--resume) (--resume-file=FILE) (--no-seatbelt)\n"); 59 | fprintf(stderr, " (--i-know-what-im-doing) (-h, --help)\n"); 60 | fprintf(stderr, "\n"); 61 | fprintf(stderr, " -d, --device=RAWDEV Raw device that is about to be converted to LUKS. This is\n"); 62 | fprintf(stderr, " the device that luksFormat will be called on to create the\n"); 63 | fprintf(stderr, " new LUKS container. Mandatory argument.\n"); 64 | fprintf(stderr, " --readdev=DEV The device that the unencrypted data should be read from.\n"); 65 | fprintf(stderr, " This is only different from the raw device if the volume is\n"); 66 | fprintf(stderr, " already LUKS (or another container) and you want to\n"); 67 | fprintf(stderr, " reLUKSify it.\n"); 68 | fprintf(stderr, " -b, --blocksize=BYTES Specify block size for copying in bytes. Default (and\n"); 69 | fprintf(stderr, " minimum) size is 48 MiB (50331648 bytes). This value is\n"); 70 | fprintf(stderr, " rounded up to closest 4096-byte value automatically. It must\n"); 71 | fprintf(stderr, " be at least size of LUKS header (usually 2048 kiB, but may\n"); 72 | fprintf(stderr, " vary).\n"); 73 | fprintf(stderr, " -c, --backupfile=FILE Specify the file in which a header backup will be written.\n"); 74 | fprintf(stderr, " Essentially the header backup is a dump of the first 128 MiB\n"); 75 | fprintf(stderr, " of the raw device. By default this will be written to a file\n"); 76 | fprintf(stderr, " named backup.bin.\n"); 77 | fprintf(stderr, " -k, --keyfile=FILE Filename for the initial keyfile. A 4096 bytes long file\n"); 78 | fprintf(stderr, " will be generated under this location which has /dev/urandom\n"); 79 | fprintf(stderr, " as the input. It will be added as the first keyslot in the\n"); 80 | fprintf(stderr, " luksFormat process. If you put this file on a volatile\n"); 81 | fprintf(stderr, " device such as /dev/shm, remember that all your data is\n"); 82 | fprintf(stderr, " garbage after a reboot if you forget to add a second key to\n"); 83 | fprintf(stderr, " the LUKS keyring. The default filename is\n"); 84 | fprintf(stderr, " /root/initial_keyfile.bin. This file will always be created\n"); 85 | fprintf(stderr, " with 0o600 permissions.\n"); 86 | fprintf(stderr, " -p, --luksparam=PARAMS Pass these additional options to luksFormat, for example to\n"); 87 | fprintf(stderr, " select a different cipher. Parameters have to be passed\n"); 88 | fprintf(stderr, " comma-separated.\n"); 89 | fprintf(stderr, " -l, --loglevel=LVL Integer value that specifies the level of logging verbosity\n"); 90 | fprintf(stderr, " from 0 to 4 (critical, error, warn, info, debug). Default\n"); 91 | fprintf(stderr, " loglevel is 3 (info).\n"); 92 | fprintf(stderr, " --resume Resume a interrupted conversion with the help of a resume\n"); 93 | fprintf(stderr, " file. This file is generated when luksipc aborts, is by\n"); 94 | fprintf(stderr, " default called resume.bin (this can be changed by --resume-\n"); 95 | fprintf(stderr, " file).\n"); 96 | fprintf(stderr, " --resume-file=FILE Change the file name from which the resume information is\n"); 97 | fprintf(stderr, " read (when resuming a previously aborted conversion) and to\n"); 98 | fprintf(stderr, " which resume information is written (in the case of an\n"); 99 | fprintf(stderr, " abort). By default this will be resume.bin.\n"); 100 | fprintf(stderr, " --no-seatbelt Disable several safetly checks which are in place to keep\n"); 101 | fprintf(stderr, " you from losing data. You really need to know what you're\n"); 102 | fprintf(stderr, " doing if you use this.\n"); 103 | fprintf(stderr, " --i-know-what-im-doing Enable batch mode (will not ask any questions or\n"); 104 | fprintf(stderr, " confirmations interactively). Please note that you will have\n"); 105 | fprintf(stderr, " to perform any and all sanity checks by yourself if you use\n"); 106 | fprintf(stderr, " this option in order to avoid losing data.\n"); 107 | fprintf(stderr, " -h, --help Show this help screen.\n"); 108 | fprintf(stderr, "\n"); 109 | fprintf(stderr, "Examples:\n"); 110 | fprintf(stderr, " %s -d /dev/sda9\n", argv[0]); 111 | fprintf(stderr, " Converts /dev/sda9 to a LUKS partition with default parameters.\n"); 112 | fprintf(stderr, " %s -d /dev/sda9 --resume-file myresume.dat\n", argv[0]); 113 | fprintf(stderr, " Converts /dev/sda9 to a LUKS partition with default parameters and store resume\n"); 114 | fprintf(stderr, " information in myresume.dat in case of an abort.\n"); 115 | fprintf(stderr, " %s -d /dev/sda9 -k /root/secure_key/keyfile.bin --luksparams='-c,twofish-lrw-benbi,-s,320,-h,sha256'\n", argv[0]); 116 | fprintf(stderr, " Converts /dev/sda9 to a LUKS partition and stores the initially used keyfile in\n"); 117 | fprintf(stderr, " /root/secure_key/keyfile.bin. Additionally some LUKS parameters are passed that\n"); 118 | fprintf(stderr, " specify that the Twofish cipher should be used with a 320 bit keysize and\n"); 119 | fprintf(stderr, " SHA-256 as a hash function.\n"); 120 | fprintf(stderr, " %s -d /dev/sda9 --resume --resume-file /root/resume.bin\n", argv[0]); 121 | fprintf(stderr, " Resumes a crashed LUKS conversion of /dev/sda9 using the file /root/resume.bin\n"); 122 | fprintf(stderr, " which was generated at the first (crashed) luksipc run.\n"); 123 | fprintf(stderr, " %s -d /dev/sda9 --readdev /dev/mapper/oldluks\n", argv[0]); 124 | fprintf(stderr, " Convert the raw device /dev/sda9, which is already a LUKS container, to a new\n"); 125 | fprintf(stderr, " LUKS container. For example, this can be used to change the encryption\n"); 126 | fprintf(stderr, " parameters of the LUKS container (different cipher) or to change the bulk\n"); 127 | fprintf(stderr, " encryption key. In this example the old container is unlocked and accessible\n"); 128 | fprintf(stderr, " under /dev/mapper/oldluks.\n"); 129 | fprintf(stderr, "\n"); 130 | fprintf(stderr, "luksipc version: " BUILD_REVISION "\n"); 131 | #ifdef DEVELOPMENT 132 | fprintf(stderr, "\n"); 133 | fprintf(stderr, "WARNING: You're using a development build of luksipc. This is not recommended\n"); 134 | fprintf(stderr, "unless you're actually doing software development of luksipc.\n"); 135 | fprintf(stderr, "\n"); 136 | fprintf(stderr, "Additional (undocumented) options for development release:\n"); 137 | fprintf(stderr, " --development-slowdown\n"); 138 | fprintf(stderr, " --development-ioerrors\n"); 139 | #endif 140 | terminate(aExitCode); 141 | } 142 | 143 | static void checkParameters(char **argv, const struct conversionParameters *aParams) { 144 | char errorMessage[256]; 145 | if (!aParams->readDevice) { 146 | syntax(argv, "No device to convert was given on the command line", EC_CMDLINE_ARGUMENT_ERROR); 147 | } 148 | if ((aParams->luksFormatParams) && ((strlen(aParams->luksFormatParams) + 1) > MAX_ARGLENGTH)) { 149 | snprintf(errorMessage, sizeof(errorMessage), "Length of LUKS format parameters exceeds maximum of %d.", MAX_ARGLENGTH); 150 | syntax(argv, errorMessage, EC_CMDLINE_ARGUMENT_ERROR); 151 | } 152 | if (aParams->blocksize < MINBLOCKSIZE) { 153 | snprintf(errorMessage, sizeof(errorMessage), "Blocksize needs to be at the very least %d bytes (size of LUKS header), user specified %d bytes.", MINBLOCKSIZE, aParams->blocksize); 154 | syntax(argv, errorMessage, EC_CMDLINE_ARGUMENT_ERROR); 155 | } 156 | if ((aParams->logLevel < 0) || (aParams->logLevel > LLVL_DEBUG)) { 157 | snprintf(errorMessage, sizeof(errorMessage), "Loglevel needs to be inbetween 0 and %d, user specified %d.", LLVL_DEBUG, aParams->logLevel); 158 | syntax(argv, errorMessage, EC_CMDLINE_ARGUMENT_ERROR); 159 | } 160 | } 161 | 162 | enum longOnlyOptions_t { 163 | OPT_IKNOWWHATIMDOING = 0x1000, 164 | OPT_RESUME, 165 | OPT_RESUME_FILE, 166 | OPT_READDEVICE, 167 | OPT_NOSEATBELT, 168 | #ifdef DEVELOPMENT 169 | OPT_DEV_IOERRORS, 170 | OPT_DEV_SLOWDOWN 171 | #endif 172 | }; 173 | 174 | void parseParameters(struct conversionParameters *aParams, int argc, char **argv) { 175 | struct option longOptions[] = { 176 | { "device", 1, NULL, 'd' }, 177 | { "readdev", 1, NULL, OPT_READDEVICE }, 178 | { "blocksize", 1, NULL, 'b' }, 179 | { "backupfile", 1, NULL, 'c' }, 180 | { "keyfile", 1, NULL, 'k' }, 181 | { "luksparams", 1, NULL, 'p' }, 182 | { "loglevel", 1, NULL, 'l' }, 183 | { "resume", 0, NULL, OPT_RESUME }, 184 | { "resume-file", 1, NULL, OPT_RESUME_FILE }, 185 | { "no-seatbelt", 0, NULL, OPT_NOSEATBELT }, 186 | { "i-know-what-im-doing", 0, NULL, OPT_IKNOWWHATIMDOING }, 187 | { "i-know-what-im-doinx", 0, NULL, 'h' }, /* Do not allow abbreviation of --i-know-what-im-doing */ 188 | #ifdef DEVELOPMENT 189 | { "development-slowdown", 0, NULL, OPT_DEV_SLOWDOWN }, 190 | { "development-slowdowx", 0, NULL, 'h' }, /* Do not allow abbreviation of --development-slowdown */ 191 | { "development-ioerrors", 0, NULL, OPT_DEV_IOERRORS }, 192 | { "development-ioerrorx", 0, NULL, 'h' }, /* Do not allow abbreviation of --development-ioerrors */ 193 | #endif 194 | { "help", 0, NULL, 'h' }, 195 | { 0 } 196 | }; 197 | int character; 198 | 199 | defaultParameters(aParams); 200 | while ((character = getopt_long(argc, argv, "hb:d:l:k:p:c:", longOptions, NULL)) != -1) { 201 | switch (character) { 202 | case 'd': 203 | aParams->rawDevice = optarg; 204 | break; 205 | 206 | case OPT_READDEVICE: 207 | aParams->readDevice = optarg; 208 | break; 209 | 210 | case 'b': 211 | aParams->blocksize = atoi(optarg); 212 | break; 213 | 214 | case 'c': 215 | aParams->backupFile = optarg; 216 | break; 217 | 218 | case 'k': 219 | aParams->keyFile = optarg; 220 | break; 221 | 222 | case 'p': 223 | aParams->luksFormatParams = optarg; 224 | break; 225 | 226 | case 'l': { 227 | char *endPtr = NULL; 228 | aParams->logLevel = strtol(optarg, &endPtr, 10); 229 | if ((endPtr == NULL) || (*endPtr != 0)) { 230 | fprintf(stderr, "Error: Cannot convert the value '%s' you passed as a log level (must be an integer).\n", optarg); 231 | terminate(EC_CMDLINE_ARGUMENT_ERROR); 232 | } 233 | if ((aParams->logLevel < 0) || (aParams->logLevel > 4)) { 234 | fprintf(stderr, "Error: Log level must be between 0 and 4.\n"); 235 | terminate(EC_CMDLINE_ARGUMENT_ERROR); 236 | } 237 | break; 238 | } 239 | 240 | case OPT_RESUME: 241 | aParams->resuming = true; 242 | break; 243 | 244 | case OPT_RESUME_FILE: 245 | aParams->resumeFilename = optarg; 246 | break; 247 | 248 | case OPT_NOSEATBELT: 249 | aParams->safetyChecks = false; 250 | break; 251 | 252 | case OPT_IKNOWWHATIMDOING: 253 | aParams->batchMode = true; 254 | break; 255 | #ifdef DEVELOPMENT 256 | case OPT_DEV_IOERRORS: 257 | aParams->dev.ioErrors = true; 258 | break; 259 | 260 | case OPT_DEV_SLOWDOWN: 261 | aParams->dev.slowDown = true; 262 | break; 263 | #endif 264 | 265 | case '?': 266 | fprintf(stderr, "\n"); 267 | // fall-through 268 | 269 | case 'h': 270 | syntax(argv, NULL, EC_SUCCESS); 271 | break; 272 | 273 | default: 274 | fprintf(stderr, "Error: Lazy programmer caused bug in getopt parsing (character 0x%x = '%c').\n", character, character); 275 | terminate(EC_CMDLINE_PARSING_ERROR); 276 | } 277 | } 278 | 279 | /* Round up block size to 4096 bytes multiple */ 280 | aParams->blocksize = ((aParams->blocksize + 4095) / 4096) * 4096; 281 | 282 | /* If read device is not set, we're not doing reLUKSification (i.e. read 283 | * device = raw device) */ 284 | if (!aParams->readDevice) { 285 | aParams->readDevice = aParams->rawDevice; 286 | } else { 287 | aParams->reluksification = true; 288 | } 289 | 290 | checkParameters(argv, aParams); 291 | } 292 | 293 | -------------------------------------------------------------------------------- /parameters.h: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #ifndef __PARAMETERS_H__ 25 | #define __PARAMETERS_H__ 26 | 27 | #include 28 | 29 | #define MINBLOCKSIZE (1024 * 1024 * 10) 30 | 31 | struct conversionParameters { 32 | int blocksize; 33 | const char *rawDevice; /* Partition that the actual LUKS is created on (e.g. /dev/sda9) */ 34 | const char *readDevice; /* Partition that data is read from (for initial conversion idential to rawDevice, but for reLUKSification maybe /dev/mapper/oldluks) */ 35 | const char *keyFile; 36 | const char *luksFormatParams; 37 | bool resuming; /* Should the process resume using the given file? */ 38 | const char *resumeFilename; /* Use this file for storing resume data */ 39 | 40 | const char *backupFile; /* File in which header backup is written before luksFormat */ 41 | bool batchMode; 42 | bool safetyChecks; 43 | int logLevel; 44 | bool reluksification; 45 | 46 | #ifdef DEVELOPMENT 47 | struct { 48 | bool slowDown; /* Simulate slow devices */ 49 | bool ioErrors; /* Simulate I/O errors */ 50 | } dev; 51 | #endif 52 | }; 53 | 54 | /*************** AUTO GENERATED SECTION FOLLOWS ***************/ 55 | void parseParameters(struct conversionParameters *aParams, int argc, char **argv); 56 | /*************** AUTO GENERATED SECTION ENDS ***************/ 57 | 58 | #endif 59 | 60 | -------------------------------------------------------------------------------- /random.c: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | #include "random.h" 31 | #include "logging.h" 32 | 33 | static uint64_t xorShiftState = 0x135b78d8e29a4d5c; 34 | 35 | /* Marsaglia Xorshift PRNG */ 36 | static uint64_t xorShift64(uint64_t x) { 37 | x ^= x << 13; 38 | x ^= x >> 7; 39 | x ^= x << 17; 40 | return x; 41 | } 42 | 43 | /* This is only used for testing luksipc and is not cryptographically safe in 44 | * any way. It uses the internal PRNG */ 45 | bool randomEvent(uint32_t aOneIn) { 46 | xorShiftState = xorShift64(xorShiftState); 47 | return (xorShiftState % aOneIn) == 0; 48 | } 49 | 50 | bool readRandomData(void *aData, uint32_t aLength) { 51 | const char *randomDevice = "/dev/urandom"; 52 | FILE *f = fopen(randomDevice, "rb"); 53 | if (!f) { 54 | logmsg(LLVL_ERROR, "Error opening %s for reading entropy: %s\n", randomDevice, strerror(errno)); 55 | return false; 56 | } 57 | 58 | if (fread(aData, aLength, 1, f) != 1) { 59 | logmsg(LLVL_ERROR, "Short read from %s for reading entropy: %s\n", randomDevice, strerror(errno)); 60 | fclose(f); 61 | return false; 62 | } 63 | 64 | fclose(f); 65 | return true; 66 | } 67 | 68 | bool randomHexStrCat(char *aString, int aByteLen) { 69 | /* Generate hex data */ 70 | uint8_t rnd[aByteLen]; 71 | if (!readRandomData(rnd, aByteLen)) { 72 | logmsg(LLVL_ERROR, "Cannot generate randomized hex tag.\n"); 73 | return false; 74 | } 75 | 76 | /* Walk string until the end */ 77 | aString = aString + strlen(aString); 78 | 79 | /* Then append hex data there */ 80 | for (int i = 0; i < aByteLen; i++) { 81 | sprintf(aString, "%02x", rnd[i]); 82 | aString += 2; 83 | } 84 | return true; 85 | } 86 | 87 | bool initPrng(void) { 88 | uint64_t xorValue; 89 | if (!readRandomData(&xorValue, sizeof(xorValue))) { 90 | logmsg(LLVL_ERROR, "Failed to seed internal PRNG.\n"); 91 | return false; 92 | } 93 | xorShiftState ^= xorValue; 94 | return true; 95 | } 96 | 97 | -------------------------------------------------------------------------------- /random.h: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #ifndef __RANDOM_H__ 25 | #define __RANDOM_H__ 26 | 27 | #include 28 | #include 29 | 30 | /*************** AUTO GENERATED SECTION FOLLOWS ***************/ 31 | bool randomEvent(uint32_t aOneIn); 32 | bool readRandomData(void *aData, uint32_t aLength); 33 | bool randomHexStrCat(char *aString, int aByteLen); 34 | bool initPrng(void); 35 | /*************** AUTO GENERATED SECTION ENDS ***************/ 36 | 37 | #endif 38 | -------------------------------------------------------------------------------- /shutdown.c: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | 31 | #include "logging.h" 32 | #include "shutdown.h" 33 | 34 | static volatile bool quit = false; 35 | 36 | static void signalInterrupt(int aSignal) { 37 | (void)aSignal; 38 | quit = true; 39 | logmsg(LLVL_CRITICAL, "Shutdown requested by user interrupt, please be patient...\n"); 40 | } 41 | 42 | bool receivedSigQuit(void) { 43 | return quit; 44 | } 45 | 46 | void issueSigQuit(void) { 47 | quit = true; 48 | } 49 | 50 | bool initSignalHandlers(void) { 51 | struct sigaction action; 52 | memset(&action, 0, sizeof(struct sigaction)); 53 | action.sa_handler = signalInterrupt; 54 | sigemptyset(&action.sa_mask); 55 | action.sa_flags = SA_RESTART; 56 | 57 | if (sigaction(SIGINT, &action, NULL) == -1) { 58 | fprintf(stderr, "Could not install SIGINT handler: %s\n", strerror(errno)); 59 | return false; 60 | } 61 | 62 | if (sigaction(SIGTERM, &action, NULL) == -1) { 63 | fprintf(stderr, "Could not install SIGTERM handler: %s\n", strerror(errno)); 64 | return false; 65 | } 66 | 67 | if (sigaction(SIGHUP, &action, NULL) == -1) { 68 | fprintf(stderr, "Could not install SIGHUP handler: %s\n", strerror(errno)); 69 | return false; 70 | } 71 | 72 | return true; 73 | } 74 | 75 | -------------------------------------------------------------------------------- /shutdown.h: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #ifndef __SHUTDOWN_H__ 25 | #define __SHUTDOWN_H__ 26 | 27 | #include 28 | 29 | /*************** AUTO GENERATED SECTION FOLLOWS ***************/ 30 | bool receivedSigQuit(void); 31 | void issueSigQuit(void); 32 | bool initSignalHandlers(void); 33 | /*************** AUTO GENERATED SECTION ENDS ***************/ 34 | 35 | #endif 36 | -------------------------------------------------------------------------------- /tests/CornercaseTests.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | from TestEngine import LUKSIPCTest 4 | 5 | class LargeHeaderLUKSIPCTest(LUKSIPCTest): 6 | def run(self): 7 | luks_header_sectors = 9999 8 | luks_header_bytes = luks_header_sectors * 512 9 | params = self.prepare_device(luks_header_bytes) 10 | self._assert(self._engine.luksify(additional_params = [ "--luksparams=--align-payload=%d" % (luks_header_sectors) ]) == 0, "LUKSification failed") 11 | self.verify_container(params) 12 | 13 | -------------------------------------------------------------------------------- /tests/ReLUKSTests.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | from TestEngine import LUKSIPCTest 4 | 5 | class SimpleReLUKSIPCBaseTest(LUKSIPCTest): 6 | def run(self): 7 | params = self.prepare_luksdevice(self.luksformat_params) 8 | container = self._engine.luksOpen() 9 | try: 10 | # Now reluksify the opened container 11 | self._engine.cleanup_files() 12 | self._assert(self._engine.luksify(unlockedcontainer = container) == 0, "LUKSification failed") 13 | finally: 14 | self._engine.luksClose(container) 15 | self.verify_container(params) 16 | 17 | 18 | class SimpleReLUKSIPCTest1(SimpleReLUKSIPCBaseTest): 19 | def run(self): 20 | self.luksformat_params = [ ] 21 | SimpleReLUKSIPCBaseTest.run(self) 22 | 23 | 24 | class SimpleReLUKSIPCTest2(LUKSIPCTest): 25 | def run(self): 26 | self.luksformat_params = [ "-c", "twofish-lrw-benbi", "-s", "320", "-h", "sha256" ] 27 | SimpleReLUKSIPCBaseTest.run(self) 28 | 29 | 30 | class AbortedReLUKSIPCTest(LUKSIPCTest): 31 | def run(self): 32 | params = self.prepare_luksdevice() 33 | container = self._engine.luksOpen() 34 | try: 35 | # Now reluksify the opened container 36 | self._engine.cleanup_files() 37 | returncode = self._engine.luksify(unlockedcontainer = container, abort = 20) 38 | self._engine.verify_hdrbackup_file(params.backup_header_hash) 39 | while returncode == 2: 40 | returncode = self._engine.luksify(unlockedcontainer = container, abort = random.randint(10, 60), resume = True) 41 | self._engine.verify_hdrbackup_file(params.backup_header_hash) 42 | finally: 43 | self._engine.luksClose(container) 44 | self.verify_container(params) 45 | 46 | 47 | class IOErrorReLUKSIPCTest(LUKSIPCTest): 48 | def run(self): 49 | params = self.prepare_luksdevice() 50 | container = self._engine.luksOpen() 51 | try: 52 | # Now reluksify the opened container 53 | self._engine.cleanup_files() 54 | returncode = self._engine.luksify(unlockedcontainer = container, additional_params = [ "--development-ioerrors" ], success_codes = [ 0, 2 ]) 55 | self._engine.verify_hdrbackup_file(params.backup_header_hash) 56 | while returncode == 2: 57 | returncode = self._engine.luksify(unlockedcontainer = container, resume = True, additional_params = [ "--development-ioerrors" ], success_codes = [ 0, 2 ]) 58 | self._engine.verify_hdrbackup_file(params.backup_header_hash) 59 | finally: 60 | self._engine.luksClose(container) 61 | self.verify_container(params) 62 | 63 | 64 | -------------------------------------------------------------------------------- /tests/SimpleTests.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | from TestEngine import LUKSIPCTest 4 | 5 | class SimpleLUKSIPCTest(LUKSIPCTest): 6 | def run(self): 7 | params = self.prepare_device() 8 | self._assert(self._engine.luksify() == 0, "LUKSification failed") 9 | self.verify_container(params) 10 | 11 | 12 | class AbortedLUKSIPCTest(LUKSIPCTest): 13 | def run(self): 14 | params = self.prepare_device() 15 | 16 | returncode = self._engine.luksify(abort = 20) 17 | self._engine.verify_hdrbackup_file(params.backup_header_hash) 18 | while returncode == 2: 19 | returncode = self._engine.luksify(abort = random.randint(10, 60), resume = True) 20 | self._engine.verify_hdrbackup_file(params.backup_header_hash) 21 | 22 | self.verify_container(params) 23 | 24 | 25 | class IOErrorLUKSIPCTest(LUKSIPCTest): 26 | def run(self): 27 | params = self.prepare_device() 28 | 29 | returncode = self._engine.luksify(additional_params = [ "--development-ioerrors" ], success_codes = [ 0, 2 ]) 30 | self._engine.verify_hdrbackup_file(params.backup_header_hash) 31 | while returncode == 2: 32 | returncode = self._engine.luksify(resume = True, additional_params = [ "--development-ioerrors" ], success_codes = [ 0, 2 ]) 33 | self._engine.verify_hdrbackup_file(params.backup_header_hash) 34 | 35 | self.verify_container(params) 36 | -------------------------------------------------------------------------------- /tests/TestEngine.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import os 3 | import subprocess 4 | import hashlib 5 | import collections 6 | import random 7 | import string 8 | import signal 9 | import time 10 | import sys 11 | import datetime 12 | 13 | _DEFAULTS = { 14 | "hdrbackup_file": "data/backup.img", 15 | "resume_file": "data/resume.bin", 16 | "key_file": "data/keyfile.bin", 17 | } 18 | 19 | class LUKSIPCTest(object): 20 | _PreTestParameters = collections.namedtuple("PreTestParameters", [ "seed", "plain_data_hash", "backup_header_hash", "source", "expected_sizediff", "devsize_pre", "devsize_post" ]) 21 | def __init__(self, testengine, assumptions): 22 | self._engine = testengine 23 | self._assumptions = assumptions 24 | 25 | def __getitem__(self, key): 26 | return self._assumptions[key] 27 | 28 | def run(self): 29 | raise Exception(NotImplemented) 30 | 31 | def prepare_device(self, expected_sizediff = None): 32 | """Prepare a plain device (no LUKS) with a PRNG pattern. Hash the 33 | device excluding the trailing part that is going to be cut away by 34 | LUKSification and also hash the part that is going to be in the header 35 | backup (128 MiB). Typically called to test LUKSification.""" 36 | if expected_sizediff is None: 37 | expected_sizediff = self["default_luks_hdr_size"] 38 | 39 | devsize_pre = self._engine.rawdevsize 40 | devsize_post = devsize_pre + expected_sizediff 41 | 42 | seed = random.randint(0, 0xffffffff) 43 | plain_data_hash = self._engine.patternize_rawdev(expected_sizediff, seed) 44 | backup_header_hash = self._engine.hash_rawdev(total_size = self["default_backup_hdr_size"]) 45 | return self._PreTestParameters(seed = seed, plain_data_hash = plain_data_hash, backup_header_hash = backup_header_hash, source = "plain", expected_sizediff = expected_sizediff, devsize_pre = devsize_pre, devsize_post = devsize_post) 46 | 47 | def prepare_luksdevice(self, luksformat_params = None, expected_sizediff = 0): 48 | """Prepare a LUKS device and fill the plain part of the device with a 49 | PRNG pattern. Hash the whole plain data of the LUKS device container 50 | (unlocked) and hash the part of the raw device that is going to end up 51 | in the header backup (128 MiB). Typically called to test 52 | reLUKSification.""" 53 | if luksformat_params is None: 54 | luksformat_params = [ ] 55 | 56 | seed = random.randint(0, 0xffffffff) 57 | self._engine.luksFormat(luksformat_params) 58 | try: 59 | container = self._engine.luksOpen() 60 | devsize_pre = self._engine._getsizeof(container.unlockedblkdev) 61 | plain_data_hash = self._engine.patternize_device(container.unlockedblkdev, seed = seed) 62 | finally: 63 | self._engine.luksClose(container) 64 | 65 | devsize_post = devsize_pre + expected_sizediff 66 | backup_header_hash = self._engine.hash_rawdev(total_size = self["default_backup_hdr_size"]) 67 | return self._PreTestParameters(seed = seed, plain_data_hash = plain_data_hash, backup_header_hash = backup_header_hash, source = "luks", expected_sizediff = expected_sizediff, devsize_pre = devsize_pre, devsize_post = devsize_post) 68 | 69 | def verify_container(self, pretestparams): 70 | """Verify the container integrity against the parameters that were 71 | determined at generation from the prepare_xyz() function by checking 72 | the MD5SUM of the (unlocked) device.""" 73 | self._engine.verify_file(_DEFAULTS["hdrbackup_file"], pretestparams.backup_header_hash) 74 | 75 | # Verify initial luksification worked by decrypting and verifying hash 76 | container = self._engine.luksOpen() 77 | try: 78 | self._engine.verify_device(container.unlockedblkdev, pretestparams.plain_data_hash) 79 | finally: 80 | self._engine.luksClose(container) 81 | 82 | def _assert(self, cond, msg): 83 | if not cond: 84 | raise Exception("Assertion failed: %s" % (msg)) 85 | 86 | class TestEngine(object): 87 | _OpenLUKSContainer = collections.namedtuple("OpenLUKSContainer", [ "rawdatablkdev", "unlockedblkdev", "keyfile", "dmname" ]) 88 | 89 | def __init__(self, destroy_data_dev, luksipc_binary, logdir, additional_params): 90 | self._destroy_dev = destroy_data_dev 91 | self._luksipc_bin = luksipc_binary 92 | self._logdir = logdir 93 | if not self._logdir.endswith("/"): 94 | self._logdir += "/" 95 | try: 96 | os.makedirs(self._logdir) 97 | except FileExistsError: 98 | pass 99 | try: 100 | os.makedirs("data/") 101 | except FileExistsError: 102 | pass 103 | self._patternizer_bin = "prng/prng_crc64" 104 | self._rawdevsize = self._getsizeof(self._destroy_dev) 105 | self._total_log = open(self._logdir + "summary.txt", "a") 106 | self._lastlogfile = self._get_lastlogfile() 107 | self._additional_params = additional_params 108 | 109 | self._kill_list = set() 110 | try: 111 | for line in open("kill_list.txt"): 112 | line = line.rstrip("\r\n").strip() 113 | if line.startswith("#") or line.startswith(";"): 114 | continue 115 | if line == "": 116 | continue 117 | self._kill_list.add(line) 118 | except FileNotFoundError: 119 | print("Warning: no kill list found.") 120 | if self._destroy_dev not in self._kill_list: 121 | raise Exception("The device you want to work with for testing purposes is not on the kill list, refusing to work with that device. Please add it to the file 'kill_list.txt' if you're okay with the irrevocable destruction of all data on it.") 122 | 123 | def _log(self, msg): 124 | msg = "%s: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), msg) 125 | print(msg) 126 | print(msg, file = self._total_log) 127 | self._total_log.flush() 128 | 129 | def _get_lastlogfile(self): 130 | lastlog = 0 131 | for filename in os.listdir(self._logdir): 132 | if not filename.endswith(".log"): 133 | continue 134 | lastlog = max(int(filename[:-4]), lastlog) 135 | return lastlog 136 | 137 | @property 138 | def rawdevsize(self): 139 | return self._rawdevsize 140 | 141 | @staticmethod 142 | def _randstr(length): 143 | return "".join(random.choice(string.ascii_lowercase) for i in range(length)) 144 | 145 | @staticmethod 146 | def _getsizeof(blkdev): 147 | f = open(blkdev, "rb") 148 | f.seek(0, os.SEEK_END) 149 | devsize = f.tell() 150 | f.close() 151 | return devsize 152 | 153 | def _get_log_file(self, purpose): 154 | self._lastlogfile += 1 155 | filename = "%s%04d.log" % (self._logdir, self._lastlogfile) 156 | f = open(filename, "w") 157 | print("%s" % (purpose), file = f) 158 | print("=" * 120, file = f) 159 | self._log("Execute: %s -> %s" % (purpose, filename)) 160 | f.flush() 161 | return f 162 | 163 | def hash_device(self, blkdevname, exclude_bytes = 0, total_size = None): 164 | if total_size is not None: 165 | hash_length = total_size 166 | else: 167 | hash_length = self._getsizeof(blkdevname) - exclude_bytes 168 | assert(hash_length >= 0) 169 | 170 | f = open(blkdevname, "rb") 171 | datahash = hashlib.md5() 172 | remaining = hash_length 173 | while remaining > 0: 174 | if remaining > 1024 * 1024: 175 | data = f.read(1024 * 1024) 176 | else: 177 | data = f.read(remaining) 178 | datahash.update(data) 179 | if len(data) == 0: 180 | break 181 | remaining -= len(data) 182 | datahash = datahash.hexdigest() 183 | self._log("Hash device %s (length %d): %s" % (blkdevname, hash_length, datahash)) 184 | f.close() 185 | return datahash 186 | 187 | def hash_rawdev(self, exclude_bytes = 0, total_size = None): 188 | return self.hash_device(self._destroy_dev, exclude_bytes, total_size) 189 | 190 | def verify_device(self, blkdevname, expect_hash, exclude_bytes = 0, total_size = None): 191 | self._log("Verification of hash of block device %s" % (blkdevname)) 192 | calc_hash = self.hash_device(blkdevname, exclude_bytes, total_size) 193 | if calc_hash == expect_hash: 194 | self._log("PASS: '%s' has the correct hash value (%s)." % (blkdevname, expect_hash)) 195 | else: 196 | msg = "FAIL: %s is supposed to have hash %s, but had hash %s." % (blkdevname, expect_hash, calc_hash) 197 | self._log(msg) 198 | raise Exception(msg) 199 | 200 | def verify_file(self, filename, expect_hash): 201 | self._log("Verification of hash of file %s" % (filename)) 202 | f = open(filename, "rb") 203 | datahash = hashlib.md5() 204 | while True: 205 | data = f.read(1024 * 1024) 206 | if len(data) == 0: 207 | break 208 | datahash.update(data) 209 | f.close() 210 | calc_hash = datahash.hexdigest() 211 | if calc_hash == expect_hash: 212 | self._log("PASS: '%s' has the correct hash value (%s)." % (filename, expect_hash)) 213 | else: 214 | msg = "FAIL: %s is supposed to have hash %s, but had hash %s." % (filename, expect_hash, calc_hash) 215 | self._log(msg) 216 | raise Exception(msg) 217 | 218 | def verify_hdrbackup_file(self, expect_hash): 219 | return self.verify_file(_DEFAULTS["hdrbackup_file"], expect_hash) 220 | 221 | def scrub_device(self): 222 | self._log("Scrubbing raw device") 223 | self._execute_sync([ "dd", "if=/dev/zero", "of=" + self._destroy_dev, "bs=1M" ], success_codes = [ 1 ]) 224 | 225 | def scrub_device_hdr(self): 226 | self._log("Scrubbing raw device header") 227 | self._execute_sync([ "dd", "if=/dev/zero", "of=" + self._destroy_dev, "bs=1M", "count=32" ]) 228 | 229 | def patternize_device(self, device, exclude_bytes = 0, seed = 0): 230 | pattern_size = self._getsizeof(device) - exclude_bytes 231 | self._log("Patternizing %s with seed %d for %d bytes (%.1f MiB)" % (device, seed, pattern_size, pattern_size / 1024 / 1024)) 232 | assert(pattern_size > 0) 233 | proc = subprocess.Popen([ self._patternizer_bin, str(pattern_size), str(seed) ], stdout = subprocess.PIPE) 234 | datahash = hashlib.md5() 235 | outfile = open(device, "wb") 236 | while True: 237 | data = proc.stdout.read(1024 * 1024) 238 | datahash.update(data) 239 | outfile.write(data) 240 | if len(data) == 0: 241 | break 242 | outfile.close() 243 | datahash = datahash.hexdigest() 244 | self._log("Patternized %s (excluded %d): %s" % (device, exclude_bytes, datahash)) 245 | return datahash 246 | 247 | def patternize_rawdev(self, exclude_bytes = 0, seed = 0): 248 | return self.patternize_device(self._destroy_dev, exclude_bytes = exclude_bytes, seed = seed) 249 | 250 | def _execute_sync(self, cmd, **kwargs): 251 | success_codes = kwargs.get("success_codes", [ 0 ]) 252 | cmd_str = " ".join(cmd) 253 | logfile = self._get_log_file(cmd_str) 254 | proc = subprocess.Popen(cmd, stdout = logfile, stderr = logfile) 255 | if "abort" in kwargs: 256 | time.sleep(kwargs["abort"]) 257 | os.kill(proc.pid, signal.SIGHUP) 258 | proc.wait() 259 | logfile.flush() 260 | print("=" * 120, file = logfile) 261 | print("Process returned with returncode %d" % (proc.returncode), file = logfile) 262 | returncode = proc.returncode 263 | if proc.returncode not in success_codes: 264 | failmsg = "Execution of %s failed with return code %d (success would be %s)." % (cmd_str, proc.returncode, "/".join(str(x) for x in sorted(success_codes) )) 265 | self._log(failmsg) 266 | raise Exception(failmsg) 267 | return returncode 268 | 269 | def cleanup_files(self): 270 | self._log("Cleanup all files") 271 | for filename in [ _DEFAULTS["hdrbackup_file"], _DEFAULTS["key_file"], _DEFAULTS["resume_file"] ]: 272 | try: 273 | os.unlink(filename) 274 | except FileNotFoundError: 275 | pass 276 | 277 | def luksify(self, **kwargs): 278 | self._log("Luksification (parameters: %s)" % (str(kwargs))) 279 | cmd = [ self._luksipc_bin ] 280 | cmd += [ "-d", self._destroy_dev ] 281 | cmd += [ "-l", "4", ] 282 | cmd += [ "--i-know-what-im-doing" ] 283 | cmd += [ "--keyfile", _DEFAULTS["key_file"] ] 284 | cmd += [ "--backupfile", _DEFAULTS["hdrbackup_file"] ] 285 | cmd += [ "--resume-file", _DEFAULTS["resume_file"] ] 286 | if "resume" in kwargs: 287 | cmd += [ "--resume" ] 288 | if "unlockedcontainer" in kwargs: 289 | cmd += [ "--readdev", kwargs["unlockedcontainer"].unlockedblkdev ] 290 | cmd += self._additional_params 291 | if "additional_params" in kwargs: 292 | cmd += kwargs["additional_params"] 293 | if "success_codes" in kwargs: 294 | success_codes = kwargs["success_codes"] 295 | else: 296 | if "abort" not in kwargs: 297 | success_codes = [ 0 ] 298 | else: 299 | success_codes = [ 0, 2 ] 300 | 301 | if "abort" not in kwargs: 302 | return self._execute_sync(cmd, success_codes = success_codes) 303 | else: 304 | return self._execute_sync(cmd, abort = kwargs["abort"], success_codes = success_codes) 305 | 306 | def luksOpen(self): 307 | dmname = self._randstr(8) 308 | cmd = [ "cryptsetup", "luksOpen", self._destroy_dev, dmname, "-d", _DEFAULTS["key_file"] ] 309 | self._execute_sync(cmd) 310 | return self._OpenLUKSContainer(rawdatablkdev = self._destroy_dev, dmname = dmname, keyfile = _DEFAULTS["key_file"], unlockedblkdev = "/dev/mapper/" + dmname) 311 | 312 | def luksClose(self, openlukscontainer): 313 | self._execute_sync([ "cryptsetup", "luksClose", openlukscontainer.dmname ]) 314 | 315 | def luksFormat(self, params = None): 316 | if params is None: 317 | params = [ ] 318 | open(_DEFAULTS["key_file"], "w").write(self._randstr(32)) 319 | self._execute_sync([ "cryptsetup", "luksFormat", "-q", "--key-file", _DEFAULTS["key_file"] ] + params + [ self._destroy_dev ]) 320 | 321 | def new_testcase(self, tcname): 322 | self._log(("=" * 60) + " " + tcname + " " + ("=" * 60)) 323 | 324 | def finished_testcase(self, tcname, verdict): 325 | self._log(("=" * 60) + " " + tcname + " " + verdict + " " + ("=" * 60)) 326 | 327 | def setup_loopdev(self, ldsize): 328 | assert(self._destroy_dev.startswith("/dev/loop")) 329 | self._log("Resetting loop device %s to %d bytes (%.1f MiB = %d kiB + %d)" % (self._destroy_dev, ldsize, ldsize / 1024 / 1024, ldsize // 1024, ldsize % 1024)) 330 | ldbase = "/dev/shm/loopy" 331 | fullmegs = (ldsize + (1024 * 1024) - 1) // (1024 * 1024) 332 | self._execute_sync([ "losetup", "-d", self._destroy_dev ], success_codes = [ 0, 1 ]) 333 | self._execute_sync([ "dd", "if=/dev/zero", "of=%s" % (ldbase), "bs=1M", "count=%d" % (fullmegs) ]) 334 | 335 | # Then truncate loopy file 336 | f = open(ldbase, "r+") 337 | f.truncate(ldsize) 338 | f.close() 339 | 340 | # Then attach loop device again 341 | self._execute_sync([ "losetup", self._destroy_dev, ldbase ]) 342 | 343 | self._rawdevsize = self._getsizeof(self._destroy_dev) 344 | 345 | if __name__ == "__main__": 346 | print("Please check code first!") 347 | sys.exit(1) 348 | # teng = TestEngine(destroy_data_dev = "/dev/loop0", luksipc_binary = "../luksipc", logdir = "logs/") 349 | # teng.setup_loopdev(543 * 1024 * 1024) 350 | teng = TestEngine(destroy_data_dev = "/dev/sdh1", luksipc_binary = "../luksipc", logdir = "logs/") 351 | 352 | expected_lukshdr_len = 4096 * 512 353 | 354 | conversion_parameters = { 355 | "filltype": ("prng_rnd", ), 356 | # "filltype": ("prng_constant", 123456), 357 | # "filltype": ("zero", ), 358 | } 359 | 360 | for iteration in range(10): 361 | teng.new_testcase("basic") 362 | teng.cleanup_files() 363 | teng.scrub_device_hdr() 364 | 365 | if conversion_parameters["filltype"][0] == "prng_rnd": 366 | seed = random.randint(0, 0xffffffff) 367 | plain_datahash = teng.patternize_rawdev(expected_lukshdr_len, seed) 368 | elif conversion_parameters["filltype"][0] == "prng_constant": 369 | seed = conversion_parameters["filltype"][1] 370 | plain_datahash = teng.patternize_rawdev(expected_lukshdr_len, seed) 371 | else: 372 | teng.scrub_device() 373 | plain_datahash = teng.hash_rawdev(expected_lukshdr_len) 374 | header_hash = teng.hash_rawdev(total_size = 128 * 1024 * 1024) 375 | 376 | # Luksify with abort 377 | returncode = teng.luksify(abort = 15) 378 | teng.verify_file(_DEFAULTS["hdrbackup_file"], header_hash) 379 | while returncode == 2: 380 | # Resume luksification 381 | returncode = teng.luksify(resume = _DEFAULTS["resume_file"], abort = random.randint(20, 50)) 382 | teng.verify_file(_DEFAULTS["hdrbackup_file"], header_hash) 383 | 384 | # Verify initial luksification worked 385 | container = teng.luksOpen() 386 | try: 387 | teng.verify_device(container.unlockedblkdev, plain_datahash) 388 | finally: 389 | teng.luksClose(container) 390 | 391 | # Reluksify 392 | header_hash = teng.hash_rawdev(total_size = 128 * 1024 * 1024) 393 | container = teng.luksOpen() 394 | try: 395 | # Now reluksify 396 | teng.cleanup_files() 397 | returncode = teng.luksify(unlockedcontainer = container, abort = 15) 398 | teng.verify_file(_DEFAULTS["hdrbackup_file"], header_hash) 399 | while returncode == 2: 400 | # Resume reluksification 401 | returncode = teng.luksify(unlockedcontainer = container, resume = _DEFAULTS["resume_file"], abort = random.randint(20, 50)) 402 | teng.verify_file(_DEFAULTS["hdrbackup_file"], header_hash) 403 | finally: 404 | teng.luksClose(container) 405 | 406 | # And verify again 407 | container = teng.luksOpen() 408 | try: 409 | teng.verify_device(container.unlockedblkdev, plain_datahash) 410 | finally: 411 | teng.luksClose(container) 412 | 413 | 414 | -------------------------------------------------------------------------------- /tests/kill_list.txt: -------------------------------------------------------------------------------- 1 | # This list contains all devices that may be used during testing (and which 2 | # will be overwritten in the process) 3 | #/dev/loop0 4 | #/dev/sdh1 5 | -------------------------------------------------------------------------------- /tests/mkflakey: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import os 3 | import sys 4 | import subprocess 5 | import random 6 | 7 | if len(sys.argv) == 1: 8 | print("%s [Blockdevice]" % (sys.argv[0])) 9 | print() 10 | print("Create a flakey device mapper alias for given block device as /dev/mapper/flakey.") 11 | sys.exit(1) 12 | 13 | def getdevsize(devname): 14 | f = open(devname, "rb") 15 | f.seek(0, os.SEEK_END) 16 | devsize = f.tell() 17 | f.close() 18 | return devsize 19 | 20 | devname = sys.argv[1] 21 | subprocess.call([ "dmsetup", "remove", "flakey" ], stdout = subprocess.PIPE, stderr = subprocess.PIPE) 22 | devsize = getdevsize(devname) 23 | devsize_sects = devsize // 512 24 | 25 | error_begin_sect = random.randint(0, devsize_sects - 1) // 4 * 4 26 | error_sect_length = random.randint(1, 10) * 4 27 | 28 | print("Error region: %d len %d" % (error_begin_sect, error_sect_length)) 29 | 30 | after_err_begin = error_begin_sect + error_sect_length 31 | after_err_length = devsize_sects - after_err_begin 32 | 33 | tblfile = open("tmp_table.txt", "w") 34 | print("0 %d linear %s 0" % (error_begin_sect, devname), file = tblfile) 35 | print("%d %d error" % (error_begin_sect, error_sect_length), file = tblfile) 36 | print("%d %d linear %s %d" % (after_err_begin, after_err_length, devname, after_err_begin), file = tblfile) 37 | tblfile.close() 38 | subprocess.check_call([ "dmsetup", "create", "flakey", "tmp_table.txt" ], stdout = subprocess.PIPE, stderr = subprocess.PIPE) 39 | os.unlink("tmp_table.txt") 40 | 41 | -------------------------------------------------------------------------------- /tests/prng/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: all clean 2 | 3 | CC := gcc 4 | CFLAGS := -Wall -Wextra -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -std=c11 -Wall -O3 5 | 6 | LDFLAGS := 7 | 8 | OBJS := prng_crc64.o 9 | 10 | all: prng_crc64 11 | 12 | clean: 13 | rm -f $(OBJS) prng_crc64 14 | 15 | test: all 16 | ./prng_crc64 123456789 17 | 18 | valgrind: all 19 | valgrind --leak-check=yes ./prng_crc64 20 | 21 | prng_crc64: $(OBJS) 22 | $(CC) $(CFLAGS) $(LDFLAGS) -o $(@) $(OBJS) 23 | 24 | .c.o: 25 | $(CC) $(CFLAGS) -c -o $@ $< 26 | -------------------------------------------------------------------------------- /tests/prng/prng_crc64.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define staticassert(cond) _Static_assert(cond, #cond) 7 | 8 | #define BLOCK_WORDCNT 32768 9 | #define BLOCK_BYTECNT (BLOCK_WORDCNT * (int)sizeof(uint64_t)) 10 | 11 | const uint64_t polynomial = 0xc96c5795d7870f42; // ECMA-182 12 | uint64_t intState = 0xb55dd361fcaa9779; 13 | 14 | staticassert(sizeof(long) == 8); 15 | 16 | static uint64_t nextValue(void) { 17 | for (int i = 0; i < 2; i++) { 18 | if (intState & 1) { 19 | intState = (intState >> 1) ^ polynomial; 20 | } else { 21 | intState = (intState >> 1); 22 | } 23 | } 24 | return intState; 25 | } 26 | 27 | int main(int argc, char **argv) { 28 | if (argc < 2) { 29 | fprintf(stderr, "%s [Bytecount] [(Seed)]\n", argv[0]); 30 | exit(EXIT_FAILURE); 31 | } 32 | 33 | int64_t byteCount = atol(argv[1]); 34 | if (byteCount < 0) { 35 | fprintf(stderr, "Bytecount must be nonnegative.\n"); 36 | exit(EXIT_FAILURE); 37 | } 38 | 39 | if (byteCount == 0) { 40 | byteCount = ((int64_t)1 << 62); 41 | } 42 | 43 | if (argc >= 3) { 44 | intState ^= atol(argv[2]); 45 | } 46 | 47 | /* Complete blocks first */ 48 | { 49 | uint64_t bufferBlock[BLOCK_WORDCNT]; 50 | for (int64_t i = 0; i < byteCount / BLOCK_BYTECNT; i++) { 51 | for (int j = 0; j < BLOCK_WORDCNT; j++) { 52 | bufferBlock[j] = nextValue(); 53 | } 54 | fwrite(bufferBlock, BLOCK_BYTECNT, 1, stdout); 55 | } 56 | byteCount %= BLOCK_BYTECNT; 57 | } 58 | 59 | /* Complete words afterwards */ 60 | for (int64_t i = 0; i < byteCount / 8; i++) { 61 | uint64_t state = nextValue(); 62 | (void)fwrite(&state, 8, 1, stdout); 63 | } 64 | 65 | /* Then last bytes */ 66 | uint64_t state = nextValue(); 67 | for (int i = 0; i < byteCount % 8; i++) { 68 | (void)fwrite(&state, 1, 1, stdout); 69 | state >>= 8; 70 | } 71 | 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /tests/rmdm: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # 4 | 5 | 6 | remove_all() { 7 | ANY_SUCCESS="0" 8 | for name in /dev/mapper/*; do 9 | dmsetup remove "$name" >/dev/null 2>&1 10 | if [ "$?" == "0" ]; then 11 | ANY_SUCCESS="1" 12 | fi 13 | done 14 | return $ANY_SUCCESS 15 | } 16 | 17 | while true; do 18 | remove_all 19 | success="$?" 20 | if [ "$success" == "0" ]; then 21 | break 22 | fi 23 | done 24 | 25 | -------------------------------------------------------------------------------- /tests/runtests: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import traceback 3 | from SimpleTests import SimpleLUKSIPCTest, AbortedLUKSIPCTest, IOErrorLUKSIPCTest 4 | from ReLUKSTests import SimpleReLUKSIPCTest1, SimpleReLUKSIPCTest2, AbortedReLUKSIPCTest, IOErrorReLUKSIPCTest 5 | from CornercaseTests import LargeHeaderLUKSIPCTest 6 | from TestEngine import TestEngine 7 | 8 | test_classes = [ 9 | SimpleLUKSIPCTest, 10 | AbortedLUKSIPCTest, 11 | IOErrorLUKSIPCTest, 12 | SimpleReLUKSIPCTest1, 13 | SimpleReLUKSIPCTest2, 14 | AbortedReLUKSIPCTest, 15 | IOErrorReLUKSIPCTest, 16 | LargeHeaderLUKSIPCTest, 17 | ] 18 | 19 | assumptions = { 20 | "default_luks_hdr_size": 16 * 1024 * 1024, 21 | "default_backup_hdr_size": 512 * 1024 * 1024, 22 | } 23 | 24 | #device = "/dev/sdh1" 25 | device = "/dev/loop0" 26 | #additional_params = [ "--development-slowdown" ] 27 | additional_params = [ ] 28 | 29 | engine = TestEngine(destroy_data_dev = device, luksipc_binary = "../luksipc", logdir = "logs/", additional_params = additional_params) 30 | 31 | pass_cnt = 0 32 | fail_cnt = 0 33 | for test_class in test_classes: 34 | test_name = test_class.__name__ 35 | engine.new_testcase(test_name) 36 | test_passed = True 37 | try: 38 | engine.cleanup_files() 39 | engine.scrub_device_hdr() 40 | 41 | test_instance = test_class(testengine = engine, assumptions = assumptions) 42 | test_instance.run() 43 | except Exception as e: 44 | test_passed = False 45 | traceback.print_exc() 46 | if test_passed: 47 | pass_cnt += 1 48 | engine.finished_testcase(test_name, "PASSED") 49 | else: 50 | fail_cnt += 1 51 | engine.finished_testcase(test_name, "FAILED") 52 | engine._log("Finished testcases: %d PASS, %d FAIL" % (pass_cnt, fail_cnt)) 53 | -------------------------------------------------------------------------------- /utils.c: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | #include "utils.h" 40 | #include "logging.h" 41 | 42 | bool safestrcpy(char *aDest, const char *aSrc, size_t aDestArraySize) { 43 | bool success = true; 44 | size_t srcLen = strlen(aSrc); 45 | if ((srcLen + 1) > aDestArraySize) { 46 | /* String does not fit, copy best effort */ 47 | memcpy(aDest, aSrc, aDestArraySize - 1); 48 | success = false; 49 | } else { 50 | /* String does fit, simply copy */ 51 | strcpy(aDest, aSrc); 52 | } 53 | return success; 54 | } 55 | 56 | uint64_t getDiskSizeOfFd(int aFd) { 57 | uint64_t result; 58 | if (ioctl(aFd, BLKGETSIZE64, &result) == -1) { 59 | perror("ioctl BLKGETSIZE64"); 60 | result = 0; 61 | } 62 | return result; 63 | } 64 | 65 | uint64_t getDiskSizeOfPath(const char *aPath) { 66 | uint64_t diskSize; 67 | int fd = open(aPath, O_RDONLY); 68 | if (fd == -1) { 69 | perror("open getDiskSizeOfPath"); 70 | diskSize = 0; 71 | } 72 | diskSize = getDiskSizeOfFd(fd); 73 | close(fd); 74 | return diskSize; 75 | } 76 | 77 | double getTime(void) { 78 | struct timeval tv; 79 | gettimeofday(&tv, NULL); 80 | return (double)tv.tv_sec + (1e-6 * tv.tv_usec); 81 | } 82 | 83 | bool doesFileExist(const char *aFilename) { 84 | struct stat statBuf; 85 | int statResult = stat(aFilename, &statBuf); 86 | return statResult == 0; 87 | } 88 | -------------------------------------------------------------------------------- /utils.h: -------------------------------------------------------------------------------- 1 | /* 2 | luksipc - Tool to convert block devices to LUKS in-place. 3 | Copyright (C) 2011-2015 Johannes Bauer 4 | 5 | This file is part of luksipc. 6 | 7 | luksipc is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; this program is ONLY licensed under 10 | version 3 of the License, later versions are explicitly excluded. 11 | 12 | luksipc is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with luksipc; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | 21 | Johannes Bauer 22 | */ 23 | 24 | #ifndef __UTILS_H__ 25 | #define __UTILS_H__ 26 | 27 | #include 28 | #include 29 | 30 | /*************** AUTO GENERATED SECTION FOLLOWS ***************/ 31 | bool safestrcpy(char *aDest, const char *aSrc, size_t aDestArraySize); 32 | uint64_t getDiskSizeOfFd(int aFd); 33 | uint64_t getDiskSizeOfPath(const char *aPath); 34 | double getTime(void); 35 | bool doesFileExist(const char *aFilename); 36 | /*************** AUTO GENERATED SECTION ENDS ***************/ 37 | 38 | #endif 39 | --------------------------------------------------------------------------------