pax_global_header 0000666 0000000 0000000 00000000064 12531634264 0014520 g ustar 00root root 0000000 0000000 52 comment=a681b41482a8641df93550f14f1fe8c189463656
luksipc-0.04/ 0000775 0000000 0000000 00000000000 12531634264 0013115 5 ustar 00root root 0000000 0000000 luksipc-0.04/ChangeLog 0000664 0000000 0000000 00000004753 12531634264 0014700 0 ustar 00root root 0000000 0000000 Summary of changes of v0.04 (2015-05-28)
========================================
* Greatly improved handling of disk I/O errors (graceful shutdown in more
situation instead of simply bailing out)
* Separated resume file specification and actual request for resuming an
aborted luksipc process (--resume vs. --resume-file)
* Unified exit code handling
* Possibilities to do fault injection in order to efficiently develop and
test code to increase robustness
* Included whole test framework in release
Summary of changes of v0.03 (2015-05-25)
========================================
* Allow reLUKSification of devices (i.e. converting LUKS to LUKS)
* Checking of mount status of file systems
* Resume files now have additional sanity checks
* Fast CRC64-based PRNG generator for filling volumes with check data
* Major code cleanups and refactoring
* Major regression testing facilities (auto-aborting and resuming on large
volumes and on loop devices)
* Help page of luksipc now looks more professional
* Partition backup file (128 MiB) is always generated at the start of a
LUKSification process
* Option to deactivate safety checks via command line parameter
(--no-seatbelt)
Summary of changes of v0.02 (2015-05-18)
========================================
* Fixed interpretation of return code of "cryptsetup status" which had
changed with more recent cryptsetup versions to reflect the correct error
if no such LUKS name was known. Thanks to Eric Murray and Christian
Pulvermacher for reporting this issue.
* Forced chunk size to be 10 MiB instead of the default of 3 MiB. Thanks
to John Morrissey for the bug report (under some weird circumstances, the
LUKS header apparently can become a lot larger).
* Fixed a couple of warnings and used stricter compiler flags.
* Switched to -stc=c11 to be able to use static assertions.
* Improved error handling for wrong command line parameters (log level
integer parsing).
* Improved error handling at cleanup (unsynced luksClose may fail at the
first try because the device is still busy, sync() filesystems and try up
to three times now)
* Display estimated remaining time until finish.
* Assert resume file can be written to disk by writing it at very start
once and then seeking to its start.
* Added README file with detailed instructions.
* More helpful help page
Summary of changes of v0.01 (2011-10-15)
========================================
* Ability to convert devices to LUKS format without having to copy the
contained data over.
luksipc-0.04/LICENSE 0000664 0000000 0000000 00000104506 12531634264 0014130 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
luksipc-0.04/Makefile 0000664 0000000 0000000 00000001164 12531634264 0014557 0 ustar 00root root 0000000 0000000 .PHONY: all clean test valgrind
EXECUTABLE := luksipc
CC := gcc
CFLAGS := -Wall -Wextra -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -std=c11 -O2 -D_LARGEFILE64_SOURCE -D_XOPEN_SOURCE=500
#CFLAGS += -DDEVELOPMENT -g
LDFLAGS :=
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
all: $(EXECUTABLE)
clean:
rm -f $(OBJS) $(EXECUTABLE) initial_keyfile.bin
test: all
./luksipc
valgrind: all
valgrind --leak-check=yes ./luksipc
luksipc: $(OBJS)
$(CC) $(CFLAGS) $(LDFLAGS) -o $(@) $(OBJS)
.c.o:
$(CC) $(CFLAGS) -c -o $@ $<
luksipc-0.04/README 0000664 0000000 0000000 00000121052 12531634264 0013776 0 ustar 00root root 0000000 0000000 AUTHORS
=======
luksipc is written by Johannes Bauer . Please report all
bugs directly to this email address. If you do not wish to be named in the
changelog or this README file, please say so immediately in the mail, I'll omit
your name then. Inversely, if I forgot to include you in this list and you
would like to appear, please drop me a note and I'll fix it.
There are several contributors to the project:
- Eric Murray (cryptsetup status issue)
- Christian Pulvermacher (cryptsetup status issue)
- John Morrissey (large header issue)
DISCLAIMER
==========
If you use luksipc and it bricks your disk and destroys all your data then
that's your fault, not mine. luksips comes without any warranty (neither
expressed nor implied). Please have a backup for really, really important data.
CHECKLIST
=========
If you skip over everything else, PLEASE at least read this:
[ ] Resized file system size, decreased size by at least 10 MiB
[ ] Umounted file system
[ ] Laptop is connected to A/C power (if applicable)
COMPILING
=========
luksipc has no external dependencies, it should compile just fine if you have a
recent Linux distribution with GNU make and gcc installed. Just type
$ make
That's it.
USAGE: PLAIN TO LUKS FILE SYSTEM CONVERSION
===========================================
The first thing you need to do is resize your file system to accomodate for the
fact that the device is going to be a tiny bit smaller in the end (due to the
LUKS header). The LUKS header size is usually 2048 kiB (it was 1028 kiB for
previous versions of cryptsetup), but you can safely decrease the file system
size by more (like 100 MiB) to be on the safe side. If you decrease the size
too much you have no drawbacks (and you can easily increase after the
conversion has been performed).
WARNING: DO NOT FORGET THIS STEP (resize file system)
luksipc has no means of detecting wheter or not you have performed this step
and will not warn you if you haven't (it has no knowledge of the underlying
file system). This might lead to very weird file system errors in the case that
your volume ever wants to use the whole space and it might even render your
volume completely unmountable (depending on the check the file system driver
performs on the block device before allowing mounting).
For example, let's say you have a device at /dev/loop0 that has an ext4 file
system. You want to LUKSify it. We first resize our volume. For this we find
out how large the volume is currently:
----------8<----------8<----------8<----------8<----------8<----------
# tune2fs -l /dev/loop0
tune2fs 1.42.9 (4-Feb-2014)
Filesystem volume name:
Last mounted on:
Filesystem UUID: 713cc62e-b2a2-406a-a82a-c4c1d01464e1
Filesystem magic number: 0xEF53
Filesystem revision #: 1 (dynamic)
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
Filesystem flags: signed_directory_hash
Default mount options: user_xattr acl
Filesystem state: clean
Errors behavior: Continue
Filesystem OS type: Linux
Inode count: 64000
Block count: 256000
Reserved block count: 12800
Free blocks: 247562
Free inodes: 63989
First block: 0
Block size: 4096
[...]
----------8<----------8<----------8<----------8<----------8<----------
So we now know that our device is 256000 blocks of 4096 bytes each, so exactly
1000 MiB. We verify this is correct (it is in this case). So we now want to
decrease the file system size to 900 MiB. 900 MiB = 900 * 1024 * 1024 bytes =
943718400 bytes. With a file system block size of 4096 bytes we arrive at
943718400 / 4096 = 230400 blocks for the file system with decreased size. So we
resize the file system:
----------8<----------8<----------8<----------8<----------8<----------
# resize2fs /dev/loop0 230400
resize2fs 1.42.9 (4-Feb-2014)
Resizing the filesystem on /dev/loop0 to 230400 (4k) blocks.
The filesystem on /dev/loop0 is now 230400 blocks long.
----------8<----------8<----------8<----------8<----------8<----------
That was successful. Perfect. Now (if you haven't already), umount the volume.
WARNING: DO NOT FORGET THIS STEP (umount file system)
Then we can proceed to LUKSify the device. By default the initial randomized
key is read from /dev/urandom and written to /root/initial_keyfile.bin. This is
okay for us, we will remove the appropriate keyslot for this random key anyways
in the future. It is only used for bootstrapping.
----------8<----------8<----------8<----------8<----------8<----------
# ./luksipc -d /dev/loop0
WARNING! luksipc will perform the following actions:
=> Normal LUKSification of plain device /dev/loop0
-> luksFormat will be performed on /dev/loop0
Please confirm you have completed the checklist:
[1] You have resized the contained filesystem(s) appropriately
[2] You have unmounted any contained filesystem(s)
[3] You will ensure secure storage of the keyfile that will be generated at /root/initial_keyfile.bin
[4] Power conditions are satisfied (i.e. your laptop is not running off battery)
[5] You have a backup of all important data on /dev/loop0
/dev/loop0: 1024 MiB = 1.0 GiB
Chunk size: 10485760 bytes = 10.0 MiB
Keyfile: /root/initial_keyfile.bin
LUKS format parameters: None given
Are all these conditions satisfied, then answer uppercase yes:
----------8<----------8<----------8<----------8<----------8<----------
Please, read the whole message thourougly. There is no going back from this. If
and only if you're 100% sure that all preconditions are satisfied, answer
"YES" and press return.
----------8<----------8<----------8<----------8<----------8<----------
Are all these conditions satisfied, then answer uppercase yes: YES
[I]: Created raw device alias: /dev/loop0 -> /dev/mapper/alias_luksipc_raw_89ee2dc8
[I]: Size of reading device /dev/loop0 is 1073741824 bytes (1024 MiB + 0 bytes)
[I]: Backing up physical disk /dev/loop0 header to backup file header_backup.img
[I]: Performing luksFormat of /dev/loop0
[I]: Performing luksOpen of /dev/loop0 (opening as mapper name luksipc_7a6bfc08)
[I]: Size of luksOpened writing device is 1071644672 bytes (1022 MiB + 0 bytes)
[I]: Write disk smaller than read disk by 2097152 bytes (2048 kB + 0 bytes, occupied by LUKS header)
[I]: Starting copying of data, read offset 10485760, write offset 0
[I]: 0:00: 10.8% 110 MiB / 1022 MiB 0.0 MiB/s Left: 912 MiB 0:00 h:m
[I]: 0:00: 20.5% 210 MiB / 1022 MiB 0.0 MiB/s Left: 812 MiB 0:00 h:m
[I]: 0:00: 30.3% 310 MiB / 1022 MiB 0.0 MiB/s Left: 712 MiB 0:00 h:m
[I]: 0:00: 40.1% 410 MiB / 1022 MiB 0.0 MiB/s Left: 612 MiB 0:00 h:m
[I]: 0:00: 49.9% 510 MiB / 1022 MiB 412.0 MiB/s Left: 512 MiB 0:00 h:m
[I]: 0:00: 59.7% 610 MiB / 1022 MiB 402.4 MiB/s Left: 412 MiB 0:00 h:m
[I]: 0:00: 69.5% 710 MiB / 1022 MiB 401.5 MiB/s Left: 312 MiB 0:00 h:m
[I]: 0:00: 79.3% 810 MiB / 1022 MiB 360.4 MiB/s Left: 212 MiB 0:00 h:m
[I]: 0:00: 89.0% 910 MiB / 1022 MiB 350.0 MiB/s Left: 112 MiB 0:00 h:m
[I]: 0:00: 98.8% 1010 MiB / 1022 MiB 344.8 MiB/s Left: 12 MiB 0:00 h:m
[I]: Disk copy completed successfully.
[I]: Synchronizing disk...
[I]: Synchronizing of disk finished.
----------8<----------8<----------8<----------8<----------8<----------
The volume was successfully converted! Now let's first add a passphrase that we
want to use for the volume (or any other method of key, your choice). You can
actually even do this while the copying process is running.
----------8<----------8<----------8<----------8<----------8<----------
# cryptsetup luksAddKey /dev/loop0 --key-file=/root/initial_keyfile.bin
Enter new passphrase for key slot:
Verify passphrase:
----------8<----------8<----------8<----------8<----------8<----------
Let's check this worked:
----------8<----------8<----------8<----------8<----------8<----------
# cryptsetup luksDump /dev/loop0
LUKS header information for /dev/loop0
Version: 1
Cipher name: aes
Cipher mode: xts-plain64
Hash spec: sha1
Payload offset: 4096
MK bits: 256
MK digest: b2 34 b8 7b 70 e8 78 17 a4 12 00 41 dc a4 bc 70 a3 50 02 22
MK salt: ee 25 b4 f0 11 94 25 d1 2b 97 42 6c a6 ff 3d 1d
e7 6d 1e 15 dd a0 07 17 25 82 d1 f9 14 6c ab e9
MK iterations: 50125
UUID: 3e21bbe0-3d70-4189-8f19-04fb7d7c5bb9
Key Slot 0: ENABLED
Iterations: 201892
Salt: 9d b6 a1 f5 0f 91 ee 24 be 49 0e f7 f9 62 a2 06
aa 45 79 7f 1a 56 5c 8c a3 03 15 a0 d2 9e ca e5
Key material offset: 8
AF stripes: 4000
Key Slot 1: ENABLED
Iterations: 198756
Salt: 46 b4 21 fb e3 12 54 18 ff 8d 05 24 75 fc 3c 4b
3c 90 77 47 43 b6 0b 28 d9 b6 86 44 30 9e 20 d2
Key material offset: 264
AF stripes: 4000
Key Slot 2: DISABLED
Key Slot 3: DISABLED
Key Slot 4: DISABLED
Key Slot 5: DISABLED
Key Slot 6: DISABLED
Key Slot 7: DISABLED
----------8<----------8<----------8<----------8<----------8<----------
You can see the initial keyfile (slot 0) and the passphrase we just added (slot
1). Let's scrub the initial keyslot so the initial keyfile becomes useless. We
do this by scrubbing slot 0. Don't worry, you cannot choose the wrong slot
here; cryptsetup won't permit you to remove the wrong slot since you must prove
that you still have at least access to one remaining slot (by entering your
passphrase).
----------8<----------8<----------8<----------8<----------8<----------
# cryptsetup luksKillSlot /dev/loop0 0
Enter any remaining passphrase:
----------8<----------8<----------8<----------8<----------8<----------
And check again:
----------8<----------8<----------8<----------8<----------8<----------
# cryptsetup luksDump /dev/loop0
LUKS header information for /dev/loop0
Version: 1
Cipher name: aes
Cipher mode: xts-plain64
Hash spec: sha1
Payload offset: 4096
MK bits: 256
MK digest: b2 34 b8 7b 70 e8 78 17 a4 12 00 41 dc a4 bc 70 a3 50 02 22
MK salt: ee 25 b4 f0 11 94 25 d1 2b 97 42 6c a6 ff 3d 1d
e7 6d 1e 15 dd a0 07 17 25 82 d1 f9 14 6c ab e9
MK iterations: 50125
UUID: 3e21bbe0-3d70-4189-8f19-04fb7d7c5bb9
Key Slot 0: DISABLED
Key Slot 1: ENABLED
Iterations: 198756
Salt: 46 b4 21 fb e3 12 54 18 ff 8d 05 24 75 fc 3c 4b
3c 90 77 47 43 b6 0b 28 d9 b6 86 44 30 9e 20 d2
Key material offset: 264
AF stripes: 4000
Key Slot 2: DISABLED
Key Slot 3: DISABLED
Key Slot 4: DISABLED
Key Slot 5: DISABLED
Key Slot 6: DISABLED
Key Slot 7: DISABLED
----------8<----------8<----------8<----------8<----------8<----------
Perfect, only our slot 1 (passphrase) is left now, you can safely discard the
initial_keyfile.bin now.
Last step, resize the filesystem to its original size. For this we must first
mount the cryptographic file system and then call the resize2fs utility again:
----------8<----------8<----------8<----------8<----------8<----------
# cryptsetup luksOpen /dev/loop0 newcryptofs
Enter passphrase for /dev/loop0:
# resize2fs /dev/mapper/newcryptofs
resize2fs 1.42.9 (4-Feb-2014)
Resizing the filesystem on /dev/mapper/newcryptofs to 255488 (4k) blocks.
The filesystem on /dev/mapper/newcryptofs is now 255488 blocks long.
----------8<----------8<----------8<----------8<----------8<----------
You can see that the filesystem now occupies all available space (998 MiB).
USAGE: LUKS TO LUKS FILE SYSTEM CONVERSION
==========================================
There are situations in which you might want to re-encrypt your LUKS device.
For example, let's say you have a cryptographic volume and multiple users have
access to it, each with their own keyslot. Now suppose you forfeit the rights
of one person to the volume. Technically you would do this by killing the
appropriate key slot of the key that was assigned to the user. This means the
user can from then on not unlock the volume using the LUKS keyheader.
But suppose the user you want whose access you want to revoke had -- while
still in possession of a valid key -- access to the file system container
itself. Then with that LUKS header he can still (even when the slot was killed)
derive the underlying cryptographic key that secures the data. The only way to
remedy this is to reencrypt the whole volume with a different bulk-encryption
key.
Another usecase are old LUKS volumes: the algorithms that were used at creation
may not be suitable anymore. For example, maybe you have switched to some other
hardware platform that has hardware support for specific algorithms and you can
only take advantage of those when you choose a specific encryption algorithm.
Or maybe the alignment that was adequate a couple of years back is not adquate
anymore for you. For example, older cryptsetup instances used 1028 kiB headers,
which is an odd size. Or maybe LUKS gained new features that you want to use.
In any case, there are numerous cases why you want to turn a LUKS volume into
another LUKS volume. This process is called "reLUKSification" within luksipc
and it is something that is supported from 0.03 onwards.
Let's say you have a partition called /dev/sdh2 which you want to reLUKSify.
First let's see what the used encryption parameters are:
----------8<----------8<----------8<----------8<----------8<----------
# cryptsetup luksDump /dev/sdh2
LUKS header information for /dev/sdh2
Version: 1
Cipher name: aes
Cipher mode: xts-plain64
Hash spec: sha1
Payload offset: 4096
MK bits: 256
MK digest: b1 44 6a 73 e3 06 27 27 a2 fe c2 59 e5 3a 39 2e 15 d7 d7 e0
MK salt: 09 6d 6a 24 66 28 43 f7 f3 55 a9 9d 0a 40 77 58
e0 1f 7c 30 b9 63 96 eb 99 34 52 4f 72 ba 57 ac
MK iterations: 49750
UUID: 6495d24d-34ac-41f5-a594-c5058cc31ed3
Key Slot 0: ENABLED
Iterations: 206119
Salt: 99 c8 48 50 c3 a6 83 0d f9 39 a4 4d 0a 35 b0 ab
13 83 ee fd 9f 91 8d 92 a6 cf 42 50 9b 89 a6 be
Key material offset: 8
AF stripes: 4000
Key Slot 1: DISABLED
Key Slot 2: DISABLED
Key Slot 3: DISABLED
Key Slot 4: DISABLED
Key Slot 5: DISABLED
Key Slot 6: DISABLED
Key Slot 7: DISABLED
----------8<----------8<----------8<----------8<----------8<----------
We'll now open the device with our old key (a passphrase):
----------8<----------8<----------8<----------8<----------8<----------
# cryptsetup luksOpen /dev/sdh2 oldluks
----------8<----------8<----------8<----------8<----------8<----------
Just for demonstration purposes, we can calculate the MD5SUM over the whole
block device (you won't need to do that, it's just a demo):
----------8<----------8<----------8<----------8<----------8<----------
# md5sum /dev/mapper/oldluks
48d9763be76ddb4fb990367f8d6b8c22 /dev/mapper/oldluks
----------8<----------8<----------8<----------8<----------8<----------
For reLUKSification to work, you need to supply the path to the unlocked device
(from where data will be read) as well as the path to the underlying raw device
(which will be luksFormatted).
You currently have your (raw) disk at /dev/sdh2 and your (unlocked) read disk
at /dev/mapper/oldluks. It may be possible that a new LUKS header is even
larger than the old header as now, which will lead to truncation of data at the
very end of the partition. This will be the case, for example, if you reLUKSify
volumes that have a 1028 kiB LUKS header and recreate with a recent version
which writes 2048 kiB LUKS headers. You need to take all measures to decrease
the size of the contained file system, as shown in the previous section. These
steps will not be repeated here, but you MUST perform them nevertheless if you
want to avoid losing data.
After the disk is unlocked, you call luksipc. In addition to the raw device
which you want to convert you will also now have to specify the block device
name of the unlocked device. The raw device is the one that luksFormat and
luksOpen will be called on and the read device is the device from which data
will be read during the copy procedure. Here's how the call to luksipc looks
like. We assume that we want to change the underlying hash function to SHA256.
----------8<----------8<----------8<----------8<----------8<----------
# luksipc --device /dev/sdh2 --readdev /dev/mapper/oldluks --luksparams='-h,sha256'
WARNING! luksipc will perform the following actions:
=> reLUKSification of LUKS device /dev/sdh2
-> Which has been unlocked at /dev/mapper/oldluks
-> luksFormat will be performed on /dev/sdh2
Please confirm you have completed the checklist:
[1] You have resized the contained filesystem(s) appropriately
[2] You have unmounted any contained filesystem(s)
[3] You will ensure secure storage of the keyfile that will be generated at /root/initial_keyfile.bin
[4] Power conditions are satisfied (i.e. your laptop is not running off battery)
[5] You have a backup of all important data on /dev/sdh2
/dev/sdh2: 2512 MiB = 2.5 GiB
Chunk size: 10485760 bytes = 10.0 MiB
Keyfile: /root/initial_keyfile.bin
LUKS format parameters: -h,sha256
Are all these conditions satisfied, then answer uppercase yes: YES
[I]: Created raw device alias: /dev/sdh2 -> /dev/mapper/alias_luksipc_raw_60377226
[I]: Size of reading device /dev/mapper/oldluks is 2631925760 bytes (2510 MiB + 0 bytes)
[I]: Backing up physical disk /dev/sdh2 header to backup file header_backup.img
[I]: Performing luksFormat of /dev/sdh2
[I]: Performing luksOpen of /dev/sdh2 (opening as mapper name luksipc_dbb86eda)
[I]: Size of luksOpened writing device is 2631925760 bytes (2510 MiB + 0 bytes)
[I]: Write disk size equal to read disk size.
[I]: Starting copying of data, read offset 10485760, write offset 0
[I]: 0:00: 4.4% 110 MiB / 2510 MiB 43.5 MiB/s Left: 2400 MiB 0:00 h:m
[I]: 0:00: 8.4% 210 MiB / 2510 MiB 34.1 MiB/s Left: 2300 MiB 0:01 h:m
[I]: 0:00: 12.4% 310 MiB / 2510 MiB 21.9 MiB/s Left: 2200 MiB 0:01 h:m
[...]
[I]: 0:02: 88.0% 2210 MiB / 2510 MiB 17.3 MiB/s Left: 300 MiB 0:00 h:m
[I]: 0:02: 92.0% 2310 MiB / 2510 MiB 17.6 MiB/s Left: 200 MiB 0:00 h:m
[I]: 0:02: 96.0% 2410 MiB / 2510 MiB 18.0 MiB/s Left: 100 MiB 0:00 h:m
[I]: 0:02: 100.0% 2510 MiB / 2510 MiB 18.2 MiB/s Left: 0 MiB 0:00 h:m
[I]: Disk copy completed successfully.
[I]: Synchronizing disk...
[I]: Synchronizing of disk finished.
----------8<----------8<----------8<----------8<----------8<----------
After the process has finished, the old LUKS device /dev/mapper/oldluks will
still be open. Be very careful not to do anything with that device, however!
It's safe to close it.
----------8<----------8<----------8<----------8<----------8<----------
# cryptsetup luksClose oldluks
----------8<----------8<----------8<----------8<----------8<----------
Then, let's open the device with the new key:
----------8<----------8<----------8<----------8<----------8<----------
# cryptsetup luksOpen /dev/sdh2 newluks -d /root/initial_keyfile.bin
----------8<----------8<----------8<----------8<----------8<----------
And check that the conversion worked:
----------8<----------8<----------8<----------8<----------8<----------
# md5sum /dev/mapper/newluks
48d9763be76ddb4fb990367f8d6b8c22 /dev/mapper/newluks
----------8<----------8<----------8<----------8<----------8<----------
Which it did :-)
DEALING WITH PROBLEMS
=====================
You may find yourself here because a luksipc process has crashed mid-conversion
(accidental Ctrl-C or reboot) and you're panicing. Breathe. luksipc is designed
so that it is robust against these issues.
Basically, to be able to resume a luksipc process you need to have two things:
1. The data of the last overwritten block (there's always one "shadow" block
that needs to be kept in memory, because usually the destination partition is
smaller than the source partition because of the LUKS header)
2. The exact location of where the interruption occured.
luksipc stores exactly this (incredibly critical) information in a "resume
file" should the resume process be interrupted. It is usually called
"resume.bin". For example, say I interrupt the LUKS conversion of a disk, this
will be shown:
----------8<----------8<----------8<----------8<----------8<----------
# luksipc -d /dev/sdf1
[...]
[I]: 0:00: 32.1% 110 MiB / 343 MiB 6.4 MiB/s Left: 233 MiB 0:00 h:m
^C[C]: Shutdown requested by user interrupt, please be patient...
[I]: Gracefully shutting down.
[I]: Synchronizing disk...
[I]: Synchronizing of disk finished.
----------8<----------8<----------8<----------8<----------8<----------
If you go into more detail (log level increase) here's what you'll see:
----------8<----------8<----------8<----------8<----------8<----------
# luksipc -d /dev/sdf1 -l4
[...]
[I]: 0:00: 32.1% 110 MiB / 343 MiB 6.2 MiB/s Left: 233 MiB 0:00 h:m
^C[C]: Shutdown requested by user interrupt, please be patient...
[I]: Gracefully shutting down.
[D]: Wrote resume file: read pointer offset 136314880 write pointer offset 115343360, 10485760 bytes of data in active buffer.
[D]: Closing read/write file descriptors 4 and 5.
[I]: Synchronizing disk...
[I]: Synchronizing of disk finished.
[D]: Subprocess [PID 17857]: Will execute 'cryptsetup luksClose luksipc_f569b0bb'
[D]: Subprocess [PID 17857]: cryptsetup returned 0
[D]: Subprocess [PID 17860]: Will execute 'dmsetup remove /dev/mapper/alias_luksipc_raw_277f5e96'
[D]: Subprocess [PID 17860]: dmsetup returned 0
----------8<----------8<----------8<----------8<----------8<----------
You can see the exact location of the interruption: The read pointer was at
offset 136314880 (130 MiB), the write pointer was at offset 115343360 (110 MiB)
and there are currently 10 MiB of data in the shadow buffer. Everything was
saved to a resume file. Here's an illustration of what it looks like. Every block is 10 MiB in size:
100 110 120 130 140
| | | | |
v v v v v
----+------+------+------+------+----
...| | BUF1 | BUF2 | |...
----+------+------+------+------+----
^ ^
| |
W R
At this point in time, luksipc has exactly two blocks in memory, BUF1 and BUF2.
This is why the read pointer is ahead two block sizes of the write pointer. Now
in the next step (if no interruption had occured) the BUF1 buffer would be
written to the LUKS device offset 110 MiB. This would overwrite some of the
plain data in BUF2, too (because the LUKS header means that there's an offset
between read- and write disk!). Therefore both have to be kept in memory.
But since the system was interrupted, it is fully sufficient to only save BUF1
to disk together with the write pointer location.
With the help of this resume file, you can continue the conversion process:
----------8<----------8<----------8<----------8<----------8<----------
# luksipc -d /dev/sdf1 --resume resume.bin
[...]
[I]: Starting copying of data, read offset 125829120, write offset 115343360
[I]: 0:00: 64.1% 220 MiB / 343 MiB 6.6 MiB/s Left: 123 MiB 0:00 h:m
[I]: 0:00: 93.3% 320 MiB / 343 MiB 9.2 MiB/s Left: 23 MiB 0:00 h:m
[...]
----------8<----------8<----------8<----------8<----------8<----------
Now we see that the process was resumed with the write pointer at the 110 MiB
mark and the read pointer at the 120 MiB mark. The next step would now be for
luksipc to read in BUF2 and we're exatly in the situation in which the abort
occured. Then from there on everything works like usual.
One thing you have to be very careful about is making copies of the resume
file. You have to be VERY careful about this. Let's say you copied the resume
file to some other location and accidently applied it twice. For example, you
run luksipc a first time and abort it. The resume file is written, you copy it
to resume2.bin. You resume the process (luksipc run 2) and let it finish. Then
you resume the process again with resume2.bin. What will happen is that all
data that was written in the resume run is encrypted TWICE and will be
unintelligible. This can obviously be recovered, but it will require very
careful twiddling and lots of work. Just don't do it.
To prevent this sort of thing, luksipc truncates the resume file when resuming
only after everything else has worked (and I/O operation starts). This prevents
you from accidently applying a resume file twice to an interrupted conversion
process.
DEALING WITH PROBLEMS DURING RELUKSIFICATION
============================================
When a reLUKSification process aborts unexpectedly (but gracefully), a resume
file is written just as it would have been during LUKSification. So resuming
just like above is easily possible. But suppose the case is a tad bit more
complicated: Let's say that someone accidently issued a reboot command during
reLUKSification. The reboot command causes a SIGTERM to be issued to the
luksipc process. luksipc catches the signal, writes the resume.bin file and
shuts down gracefully. Then the system reboots.
For reLUKSification to work you need to have access to the plain (unlocked)
source container. Here's the big "but": In order to unlock the original
container, you need to use cryptsetup luksOpen. But the LUKS header has been
overwritten by the destination (final) LUKS header already. Therefore you can't
unlock the source data anymore.
At least you couldn't if this situation wouldn't have been anticipated by
luksipc. Lucky for you, it has been. When first firing up luksipc, a backup of
the raw device header (typically 128 MiB in size) is done by luksipc in a file
usually called "header_backup.img". You can use this header together with the
raw parition to open the partition using the old key. When you have opened the
device with the old key, we can just resume the process as we normally would.
First, this is the reLUKSificiation process that aborts. We assume our
container is unlocked at /dev/mapper/oldluks. Let's check the MD5 of the
container first (to verify everything ran smoothly):
----------8<----------8<----------8<----------8<----------8<----------
# md5sum /dev/mapper/oldluks
41dc86251cba7992719bbc85de5628ab /dev/mapper/oldluks
----------8<----------8<----------8<----------8<----------8<----------
Alright, let's start the luksipc process (which will be interrupted):
----------8<----------8<----------8<----------8<----------8<----------
# luksipc -d /dev/loop0 --readdev /dev/mapper/oldluks
[...]
[I]: 0:00: 10.8% 110 MiB / 1022 MiB 0.0 MiB/s Left: 912 MiB 0:00 h:m
^C[C]: Shutdown requested by user interrupt, please be patient...
[I]: Gracefully shutting down.
[...]
----------8<----------8<----------8<----------8<----------8<----------
Now let's say we've closed /dev/mapper/oldluks (e.g. by a system reboot). We
need to find a way to reopen it with the old header and old key in order to
successfully resume the proces. For this, we do:
----------8<----------8<----------8<----------8<----------8<----------
# cryptsetup luksOpen --header=header_backup.img /dev/loop0 oldluks
----------8<----------8<----------8<----------8<----------8<----------
And then, finally, we're able to resume luksipc:
----------8<----------8<----------8<----------8<----------8<----------
# luksipc -d /dev/loop0 --readdev /dev/mapper/oldluks --resume resume.bin
[...]
[I]: Starting copying of data, read offset 220200960, write offset 209715200
[I]: 0:00: 30.3% 310 MiB / 1022 MiB 0.0 MiB/s Left: 712 MiB 0:00 h:m
[I]: 0:00: 40.1% 410 MiB / 1022 MiB 147.9 MiB/s Left: 612 MiB 0:00 h:m
----------8<----------8<----------8<----------8<----------8<----------
Now after the process is run, let's do some cleanups:
----------8<----------8<----------8<----------8<----------8<----------
# dmsetup remove oldluks
# dmsetup remove hybrid
# losetup -d /dev/loop3
----------8<----------8<----------8<----------8<----------8<----------
And open our successfully converted device:
----------8<----------8<----------8<----------8<----------8<----------
# cryptsetup luksOpen /dev/loop0 newluks -d /root/initial_keyfile.bin
----------8<----------8<----------8<----------8<----------8<----------
But did it really work?
----------8<----------8<----------8<----------8<----------8<----------
# md5sum /dev/mapper/newluks
41dc86251cba7992719bbc85de5628ab /dev/mapper/newluks
----------8<----------8<----------8<----------8<----------8<----------
Yes, it sure did :-)
Be aware that this is an absolute emergency recovery proedure that you'd only
use if everything else fails (i.e. the original source LUKS device was
accidently closed). Any mistake whatsoever (e.g. wrong offsets) will cause you
to completely pulp your disk. So be very very careful with this and double
check everything.
TESTING
=======
It's always a good idea to perform some tests before you give some unknown tool
by some unknown author a shot to handle your precious data. Here's a hint how
you could do this. I've setup some garbage partition on a drive which is
exactly 1234 MiB in size (1293942784 bytes). That partition is filled
completely with zeros:
----------8<----------8<----------8<----------8<----------8<----------
# dd if=/dev/zero of=/dev/sda1 bs=1M
dd: error writing ‘/dev/sda1’: No space left on device
1235+0 records in
1234+0 records out
1293942784 bytes (1,3 GB) copied, 30,6571 s, 42,2 MB/s
----------8<----------8<----------8<----------8<----------8<----------
Let's check that the pattern matches:
----------8<----------8<----------8<----------8<----------8<----------
# md5sum /dev/sda1
e83b40511b7b154b1816ef4c03d6be7d /dev/sda1
# dd if=/dev/zero bs=1M count=1234 | md5sum
1234+0 records in
1234+0 records out
1293942784 bytes (1,3 GB) copied, 2,71539 s, 477 MB/s
e83b40511b7b154b1816ef4c03d6be7d -
----------8<----------8<----------8<----------8<----------8<----------
Alright, so the partition is REALLY filled with 1234 MiB of zeros.
Let's LUKSify it:
----------8<----------8<----------8<----------8<----------8<----------
# luksipc -d /dev/sda1
WARNING! luksipc will perform the following actions:
=> Normal LUKSification of plain device /dev/sda1
-> luksFormat will be performed on /dev/sda1
Please confirm you have completed the checklist:
[1] You have resized the contained filesystem(s) appropriately
[2] You have unmounted any contained filesystem(s)
[3] You will ensure secure storage of the keyfile that will be generated at /root/initial_keyfile.bin
[4] Power conditions are satisfied (i.e. your laptop is not running off battery)
[5] You have a backup of all important data on /dev/sda1
/dev/sda1: 1234 MiB = 1.2 GiB
Chunk size: 10485760 bytes = 10.0 MiB
Keyfile: /root/initial_keyfile.bin
LUKS format parameters: None given
Are all these conditions satisfied, then answer uppercase yes: YES
[I]: Generated raw device alias: /dev/sda1 -> /dev/mapper/alias_luksipc_raw_944e8f9034a6344f
[I]: Size of reading device /dev/sda1 is 1293942784 bytes (1234 MiB + 0 bytes)
[I]: Performing dm-crypt status lookup on mapper name 'luksipc_41c33f9940708688'
[I]: Performing luksFormat of raw device /dev/mapper/alias_luksipc_raw_944e8f9034a6344f using key file /root/initial_keyfile.bin
[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
[I]: Size of writing device /dev/mapper/luksipc_41c33f9940708688 is 1291845632 bytes (1232 MiB + 0 bytes)
[I]: Write disk smaller than read disk, 2097152 bytes occupied by LUKS header (2048 kB + 0 bytes)
[I]: Starting copying of data, read offset 10485760, write offset 0
[I]: 0:00: 8.9% 110 MiB / 1232 MiB 44.9 MiB/s Left: 1122 MiB 0:00 h:m
[I]: 0:00: 17.0% 210 MiB / 1232 MiB 43.2 MiB/s Left: 1022 MiB 0:00 h:m
[I]: 0:00: 25.2% 310 MiB / 1232 MiB 18.8 MiB/s Left: 922 MiB 0:00 h:m
[I]: 0:00: 33.3% 410 MiB / 1232 MiB 21.3 MiB/s Left: 822 MiB 0:00 h:m
[I]: 0:00: 41.4% 510 MiB / 1232 MiB 23.4 MiB/s Left: 722 MiB 0:00 h:m
[I]: 0:00: 49.5% 610 MiB / 1232 MiB 22.0 MiB/s Left: 622 MiB 0:00 h:m
[I]: 0:00: 57.6% 710 MiB / 1232 MiB 18.7 MiB/s Left: 522 MiB 0:00 h:m
[I]: 0:00: 65.7% 810 MiB / 1232 MiB 19.8 MiB/s Left: 422 MiB 0:00 h:m
[I]: 0:00: 73.9% 910 MiB / 1232 MiB 20.3 MiB/s Left: 322 MiB 0:00 h:m
[I]: 0:00: 82.0% 1010 MiB / 1232 MiB 17.8 MiB/s Left: 222 MiB 0:00 h:m
[I]: 0:00: 90.1% 1110 MiB / 1232 MiB 18.6 MiB/s Left: 122 MiB 0:00 h:m
[I]: 0:01: 98.2% 1210 MiB / 1232 MiB 19.4 MiB/s Left: 22 MiB 0:00 h:m
[I]: Disk copy completed successfully.
[I]: Synchronizing disk...
[I]: Synchronizing of disk finished.
----------8<----------8<----------8<----------8<----------8<----------
Then luksOpen it:
----------8<----------8<----------8<----------8<----------8<----------
# cryptsetup luksOpen /dev/sda1 myluksdev -d /root/initial_keyfile.bin
----------8<----------8<----------8<----------8<----------8<----------
And check the hash:
----------8<----------8<----------8<----------8<----------8<----------
# md5sum /dev/mapper/myluksdev
e2226de7d184a3c9bd4c1e3d8a56b1b2 /dev/mapper/myluksdev
----------8<----------8<----------8<----------8<----------8<----------
The hash value differs from what it said before - this is absolutely to be
expected! The reason for this is that the device is now shorter (because part
of the space is used for the 2 MiB LUKS header). Proof:
----------8<----------8<----------8<----------8<----------8<----------
# dd if=/dev/zero bs=1M count=1232 | md5sum
1232+0 records in
1232+0 records out
1291845632 bytes (1,3 GB) copied, 2,6588 s, 486 MB/s
e2226de7d184a3c9bd4c1e3d8a56b1b2 -
----------8<----------8<----------8<----------8<----------8<----------
Now let's check the current key and reLUKSify it with a different key and
algorithm! First, let's check out the "before" values:
----------8<----------8<----------8<----------8<----------8<----------
# dmsetup table myluksdev --showkeys
0 2523136 crypt aes-xts-plain64 d164b3fd2b7d482fc6e0a2d0e58f51c5dafe4560507322cb29af4bd8f552ba4f 0 8:1 4096
# cryptsetup luksDump /dev/sda1
LUKS header information for /dev/sda1
Version: 1
Cipher name: aes
Cipher mode: xts-plain64
Hash spec: sha1
Payload offset: 4096
MK bits: 256
MK digest: dd 08 3d 43 ae 50 64 7c d9 c6 20 cb de dd 7a 62 69 10 63 fe
MK salt: f1 95 eb 18 2d 90 61 e9 c8 df 4b 4d 44 ab 62 87
5a f5 39 5a c4 f5 3b 7a 09 8c f1 75 33 a5 f3 25
MK iterations: 50375
UUID: 127277bf-b07b-4209-bf55-37cb1c10c83b
Key Slot 0: ENABLED
Iterations: 201892
Salt: fc d9 3a 73 b4 73 ee 98 6c 35 34 a0 c7 7d 8a 71
5b 75 b7 6c 75 af 65 20 eb 90 7c 69 34 10 1e a6
Key material offset: 8
AF stripes: 4000
Key Slot 1: DISABLED
Key Slot 2: DISABLED
Key Slot 3: DISABLED
Key Slot 4: DISABLED
Key Slot 5: DISABLED
Key Slot 6: DISABLED
Key Slot 7: DISABLED
----------8<----------8<----------8<----------8<----------8<----------
Then reLUKSify!
----------8<----------8<----------8<----------8<----------8<----------
# my /root/initial_keyfile.bin /root/initial_keyfile_old.bin
# luksipc -d /dev/sda1 --readdev /dev/mapper/myluksdev --luksparams='-c,twofish-lrw-benbi,-s,320,-h,sha256'
WARNING! luksipc will perform the following actions:
=> reLUKSification of LUKS device /dev/sda1
-> Which has been unlocked at /dev/mapper/myluksdev
-> luksFormat will be performed on /dev/sda1
Please confirm you have completed the checklist:
[1] You have resized the contained filesystem(s) appropriately
[2] You have unmounted any contained filesystem(s)
[3] You will ensure secure storage of the keyfile that will be generated at /root/initial_keyfile.bin
[4] Power conditions are satisfied (i.e. your laptop is not running off battery)
[5] You have a backup of all important data on /dev/sda1
/dev/sda1: 1234 MiB = 1.2 GiB
Chunk size: 10485760 bytes = 10.0 MiB
Keyfile: /root/initial_keyfile.bin
LUKS format parameters: -c,twofish-lrw-benbi,-s,320,-h,sha256
Are all these conditions satisfied, then answer uppercase yes: YES
[I]: Generated raw device alias: /dev/sda1 -> /dev/mapper/alias_luksipc_raw_c84651981fc98f36
[I]: Size of reading device /dev/mapper/myluksdev is 1291845632 bytes (1232 MiB + 0 bytes)
[I]: Performing dm-crypt status lookup on mapper name 'luksipc_9afeee69aec4912c'
[I]: Performing luksFormat of raw device /dev/mapper/alias_luksipc_raw_c84651981fc98f36 using key file /root/initial_keyfile.bin
[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
[I]: Size of writing device /dev/mapper/luksipc_9afeee69aec4912c is 1291845632 bytes (1232 MiB + 0 bytes)
[I]: Write disk size equal to read disk size.
[I]: Starting copying of data, read offset 10485760, write offset 0
[I]: 0:00: 8.9% 110 MiB / 1232 MiB 43.1 MiB/s Left: 1122 MiB 0:00 h:m
[I]: 0:00: 17.0% 210 MiB / 1232 MiB 42.0 MiB/s Left: 1022 MiB 0:00 h:m
[I]: 0:00: 25.2% 310 MiB / 1232 MiB 28.3 MiB/s Left: 922 MiB 0:00 h:m
[I]: 0:00: 33.3% 410 MiB / 1232 MiB 19.1 MiB/s Left: 822 MiB 0:00 h:m
[I]: 0:00: 41.4% 510 MiB / 1232 MiB 21.3 MiB/s Left: 722 MiB 0:00 h:m
[I]: 0:00: 49.5% 610 MiB / 1232 MiB 21.6 MiB/s Left: 622 MiB 0:00 h:m
[I]: 0:00: 57.6% 710 MiB / 1232 MiB 19.9 MiB/s Left: 522 MiB 0:00 h:m
[I]: 0:00: 65.7% 810 MiB / 1232 MiB 18.6 MiB/s Left: 422 MiB 0:00 h:m
[I]: 0:00: 73.9% 910 MiB / 1232 MiB 19.8 MiB/s Left: 322 MiB 0:00 h:m
[I]: 0:00: 82.0% 1010 MiB / 1232 MiB 19.4 MiB/s Left: 222 MiB 0:00 h:m
[I]: 0:01: 90.1% 1110 MiB / 1232 MiB 17.6 MiB/s Left: 122 MiB 0:00 h:m
[I]: 0:01: 98.2% 1210 MiB / 1232 MiB 18.4 MiB/s Left: 22 MiB 0:00 h:m
[I]: Disk copy completed successfully.
[I]: Synchronizing disk...
[I]: Synchronizing of disk finished.
----------8<----------8<----------8<----------8<----------8<----------
Now, let's detach the mapping of the old LUKS container first (this container
now contains complete garbage):
----------8<----------8<----------8<----------8<----------8<----------
# cryptsetup luksClose myluksdev
----------8<----------8<----------8<----------8<----------8<----------
And reopen it with the correct key:
----------8<----------8<----------8<----------8<----------8<----------
# cryptsetup luksOpen /dev/sda1 mynewluksdev -d /root/initial_keyfile.bin
----------8<----------8<----------8<----------8<----------8<----------
Check that the content is still the same:
----------8<----------8<----------8<----------8<----------8<----------
# cat /dev/mapper/mynewluksdev | md5sum
e2226de7d184a3c9bd4c1e3d8a56b1b2 -
----------8<----------8<----------8<----------8<----------8<----------
It sure is. Now look at the luksDump output:
----------8<----------8<----------8<----------8<----------8<----------
LUKS header information for /dev/sda1
Version: 1
Cipher name: twofish
Cipher mode: lrw-benbi
Hash spec: sha256
Payload offset: 4096
MK bits: 320
MK digest: 10 b9 35 7b c8 23 d7 c3 2a b9 3e e6 95 74 cf 7f ef 75 1b 32
MK salt: 3f 58 e6 1e 29 e1 c7 a2 f1 14 9e 1f c7 09 fa 23
93 7c 9c 59 20 67 d7 a7 7e 7d fe a0 12 9f 0f 25
MK iterations: 29000
UUID: 1dd5e426-9e37-4d1e-a6f9-17aa4179eb1e
Key Slot 0: ENABLED
Iterations: 117215
Salt: 9d 58 5c 30 2b dc 35 33 19 bf 78 ab 3e aa 6e 8a
fa 6c 9b ee 45 f7 db 9e f1 ab 0c fb cb 3c eb 51
Key material offset: 8
AF stripes: 4000
Key Slot 1: DISABLED
Key Slot 2: DISABLED
Key Slot 3: DISABLED
Key Slot 4: DISABLED
Key Slot 5: DISABLED
Key Slot 6: DISABLED
Key Slot 7: DISABLED
----------8<----------8<----------8<----------8<----------8<----------
And the used key internally:
----------8<----------8<----------8<----------8<----------8<----------
# dmsetup table mynewluksdev --showkeys
0 2523136 crypt twofish-lrw-benbi d6b007ce62de58b62331f800edf5864da390eb274b908506b368035e7a0f8ea1c3583c2b939928c3 0 8:1 4096
----------8<----------8<----------8<----------8<----------8<----------
As you can see, completely different keys, completely different algorithm --
but still identical data. It worked :-)
Of course you can do this test with arbitrary data (not just constant zeros). I
was just too lazy to write a PRNG that outputs easily reproducible results.
Feel free to play around with it and please report any and all bugs if you find
some.
luksipc-0.04/chunk.c 0000664 0000000 0000000 00000006413 12531634264 0014375 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#include
#include
#include
#include
#include
#include
#include "logging.h"
#include "chunk.h"
#include "random.h"
bool allocChunk(struct chunk *aChunk, uint32_t aSize) {
memset(aChunk, 0, sizeof(struct chunk));
aChunk->size = aSize;
aChunk->data = malloc(aSize);
if (!aChunk->data) {
return false;
}
memset(aChunk->data, 0, aSize);
return true;
}
void freeChunk(struct chunk *aChunk) {
free(aChunk->data);
memset(aChunk, 0, sizeof(struct chunk));
}
static bool checkedSeek(int aFd, off64_t aOffset, const char *aCaller) {
off64_t curOffset = lseek64(aFd, aOffset, SEEK_SET);
if (curOffset != aOffset) {
logmsg(LLVL_WARN, "%s: tried seek to 0x%lx, went to 0x%lx (%s)\n", aCaller, aOffset, curOffset, strerror(errno));
return false;
}
return true;
}
ssize_t chunkReadAt(struct chunk *aChunk, int aFd, uint64_t aOffset, uint32_t aSize) {
ssize_t bytesRead;
if (!checkedSeek(aFd, aOffset, "chunkReadAt")) {
return -1;
}
if (aSize > aChunk->size) {
logmsg(LLVL_CRITICAL, "chunkReadAt: Refusing to read %u bytes with only a %u bytes large buffer.\n", aSize, aChunk->size);
return -1;
}
bytesRead = read(aFd, aChunk->data, aSize);
if (bytesRead < 0) {
aChunk->used = 0;
} else {
aChunk->used = bytesRead;
}
return bytesRead;
}
ssize_t chunkWriteAt(const struct chunk *aChunk, int aFd, uint64_t aOffset) {
ssize_t bytesWritten;
if (!checkedSeek(aFd, aOffset, "chunkWriteAt")) {
return -1;
}
bytesWritten = write(aFd, aChunk->data, aChunk->used);
if (bytesWritten != aChunk->used) {
logmsg(LLVL_WARN, "Requested write of %d bytes unsuccessful (wrote %ld).\n", aChunk->used, bytesWritten);
}
return bytesWritten;
}
#ifdef DEVELOPMENT
/* Don't even compile these variants in if we're not in a development build so
* there's no possibility they get used accidently */
ssize_t unreliableChunkReadAt(struct chunk *aChunk, int aFd, uint64_t aOffset, uint32_t aSize) {
if (randomEvent(100)) {
logmsg(LLVL_WARN, "Fault injection: Failing unreliable read at offset 0x%lx.\n", aOffset);
return -1;
} else {
return chunkReadAt(aChunk, aFd, aOffset, aSize);
}
}
ssize_t unreliableChunkWriteAt(struct chunk *aChunk, int aFd, uint64_t aOffset) {
if (randomEvent(100)) {
logmsg(LLVL_WARN, "Fault injection: Failing unreliable write at offset 0x%lx.\n", aOffset);
return -1;
} else {
return chunkWriteAt(aChunk, aFd, aOffset);
}
}
#endif
luksipc-0.04/chunk.h 0000664 0000000 0000000 00000003200 12531634264 0014371 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#ifndef __CHUNK_H__
#define __CHUNK_H__
#include
#include
struct chunk {
uint32_t size; /* Total chunk size */
uint32_t used; /* Used chunk size */
uint8_t *data; /* Data */
};
/*************** AUTO GENERATED SECTION FOLLOWS ***************/
bool allocChunk(struct chunk *aChunk, uint32_t aSize);
void freeChunk(struct chunk *aChunk);
ssize_t chunkReadAt(struct chunk *aChunk, int aFd, uint64_t aOffset, uint32_t aSize);
ssize_t chunkWriteAt(const struct chunk *aChunk, int aFd, uint64_t aOffset);
ssize_t unreliableChunkReadAt(struct chunk *aChunk, int aFd, uint64_t aOffset, uint32_t aSize);
ssize_t unreliableChunkWriteAt(struct chunk *aChunk, int aFd, uint64_t aOffset);
/*************** AUTO GENERATED SECTION ENDS ***************/
#endif
luksipc-0.04/exec.c 0000664 0000000 0000000 00000011236 12531634264 0014210 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#include
#include
#include
#include
#include
#include
#include
#include "exec.h"
#include "logging.h"
#include "globals.h"
int argCount(const char **aArgs) {
int cnt = 0;
while (aArgs[cnt++]);
return cnt - 1;
}
bool argAppend(const char **aArgs, const char *aNewArg, int *aArgCount, int aArraySize) {
bool success = true;
if ((*aArgCount) < 0) {
*aArgCount = argCount(aArgs);
}
if ((*aArgCount + 2) > aArraySize) {
/* Cannot copy next argument */
success = false;
} else {
aArgs[*aArgCount] = aNewArg;
(*aArgCount)++;
aArgs[*aArgCount] = NULL;
}
return success;
}
bool argAppendParse(const char **aArgs, char *aNewArgs, int *aArgCount, int aArraySize) {
bool success = true;
char *savePtr = NULL;
char *nextToken;
if ((*aArgCount) < 0) {
*aArgCount = argCount(aArgs);
}
while ((nextToken = strtok_r(aNewArgs, ",", &savePtr))) {
if ((*aArgCount + 2) > aArraySize) {
/* Cannot copy next argument */
success = false;
break;
} else {
aArgs[*aArgCount] = nextToken;
(*aArgCount)++;
}
aNewArgs = NULL;
}
aArgs[*aArgCount] = NULL;
return success;
}
void argDump(const char **aArgs) {
int i = 0;
while (aArgs[i]) {
printf(" %2d: '%s'\n", i, aArgs[i]);
i++;
}
}
static char **argCopy(const char **aArgs) {
char **result = NULL;
int i;
result = malloc(sizeof(char*) * EXEC_MAX_ARGCNT);
if (!result) {
perror("malloc");
exit(EXIT_FAILURE);
}
result[EXEC_MAX_ARGCNT - 1] = NULL;
for (i = 0; i < EXEC_MAX_ARGCNT - 1; i++) {
if (aArgs[i] == NULL) {
result[i] = NULL;
break;
}
result[i] = strdup(aArgs[i]);
if (!result[i]) {
perror("strdup");
exit(EXIT_FAILURE);
}
}
return result;
}
static void freeArgCopy(char** aArgCopy) {
int i;
for (i = 0; i < EXEC_MAX_ARGCNT - 1; i++) {
if (aArgCopy[i] == NULL) {
break;
}
free(aArgCopy[i]);
}
free((void*)aArgCopy);
}
static void convertCommandLine(char *aBuffer, int aBufSize, const char **aArguments) {
if ((!aBuffer) || (aBufSize < 4)) {
return;
}
aBuffer[0] = 0;
int remaining = aBufSize - 4;
int position = 0;
int i = 0;
bool truncated = false;
while (aArguments[i]) {
int newChars = snprintf(aBuffer + position, remaining, "%s ", aArguments[i]);
if (newChars >= remaining) {
truncated = true;
break;
}
position += newChars;
remaining -= newChars;
i++;
}
if (truncated) {
strcpy(aBuffer + aBufSize - 5, "...");
} else {
aBuffer[position - 1] = 0;
}
}
struct execResult_t execGetReturnCode(const char **aArguments) {
struct execResult_t execResult;
char **argcopy = argCopy(aArguments);
pid_t pid;
int status;
memset(&execResult, 0, sizeof(execResult));
execResult.success = true;
pid = fork();
if (pid == -1) {
perror("fork");
execResult.success = false;
return execResult;
}
if (pid > 0) {
char commandLineBuffer[256];
convertCommandLine(commandLineBuffer, sizeof(commandLineBuffer), aArguments);
logmsg(LLVL_DEBUG, "Subprocess [PID %d]: Will execute '%s'\n", pid, commandLineBuffer);
}
if (pid == 0) {
/* Child */
if (getLogLevel() < LLVL_DEBUG) {
/* Shut up the child if user did not request debug output */
close(1);
close(2);
}
execvp(aArguments[0], argcopy);
perror("execvp");
logmsg(LLVL_ERROR, "Execution of %s in forked child process failed at execvp: %s\n", aArguments[0], strerror(errno));
/* Exec failed, terminate chExec failed, terminate child process
* (parent will catch this as the return code) */
exit(EXIT_FAILURE);
}
if (waitpid(pid, &status, 0) == (pid_t)-1) {
perror("waitpid");
execResult.success = false;
return execResult;
}
freeArgCopy(argcopy);
execResult.returnCode = WEXITSTATUS(status);
logmsg(LLVL_DEBUG, "Subprocess [PID %d]: %s returned %d\n", pid, aArguments[0], execResult.returnCode);
return execResult;
}
luksipc-0.04/exec.h 0000664 0000000 0000000 00000002650 12531634264 0014215 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#ifndef __EXEC_H__
#define __EXEC_H__
#include
struct execResult_t {
bool success;
int returnCode;
};
/*************** AUTO GENERATED SECTION FOLLOWS ***************/
int argCount(const char **aArgs);
bool argAppend(const char **aArgs, const char *aNewArg, int *aArgCount, int aArraySize);
bool argAppendParse(const char **aArgs, char *aNewArgs, int *aArgCount, int aArraySize);
void argDump(const char **aArgs);
struct execResult_t execGetReturnCode(const char **aArguments);
/*************** AUTO GENERATED SECTION ENDS ***************/
#endif
luksipc-0.04/exit.c 0000664 0000000 0000000 00000012764 12531634264 0014244 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#include
#include "logging.h"
#include "exit.h"
#define MAX_VALID_ERROR_CODE 28
static const char *exitCodeAbbr[] = {
[EC_SUCCESS] = "EC_SUCCESS",
[EC_UNSPECIFIED_ERROR] = "EC_UNSPECIFIED_ERROR",
[EC_COPY_ABORTED_RESUME_FILE_WRITTEN] = "EC_COPY_ABORTED_RESUME_FILE_WRITTEN",
[EC_CANNOT_ALLOCATE_CHUNK_MEMORY] = "EC_CANNOT_ALLOCATE_CHUNK_MEMORY",
[EC_CANNOT_GENERATE_KEY_FILE] = "EC_CANNOT_GENERATE_KEY_FILE",
[EC_CANNOT_INITIALIZE_DEVICE_ALIAS] = "EC_CANNOT_INITIALIZE_DEVICE_ALIAS",
[EC_CANNOT_OPEN_READ_DEVICE] = "EC_CANNOT_OPEN_READ_DEVICE",
[EC_CANNOT_OPEN_RESUME_FILE] = "EC_CANNOT_OPEN_RESUME_FILE",
[EC_COPY_ABORTED_FAILED_TO_WRITE_WRITE_RESUME_FILE] = "EC_COPY_ABORTED_FAILED_TO_WRITE_WRITE_RESUME_FILE",
[EC_DEVICE_SIZES_IMPLAUSIBLE] = "EC_DEVICE_SIZES_IMPLAUSIBLE",
[EC_FAILED_TO_BACKUP_HEADER] = "EC_FAILED_TO_BACKUP_HEADER",
[EC_FAILED_TO_CLOSE_LUKS_DEVICE] = "EC_FAILED_TO_CLOSE_LUKS_DEVICE",
[EC_FAILED_TO_OPEN_UNLOCKED_CRYPTO_DEVICE] = "EC_FAILED_TO_OPEN_UNLOCKED_CRYPTO_DEVICE",
[EC_FAILED_TO_PERFORM_LUKSFORMAT] = "EC_FAILED_TO_PERFORM_LUKSFORMAT",
[EC_FAILED_TO_PERFORM_LUKSOPEN] = "EC_FAILED_TO_PERFORM_LUKSOPEN",
[EC_FAILED_TO_READ_RESUME_FILE] = "EC_FAILED_TO_READ_RESUME_FILE",
[EC_FAILED_TO_REMOVE_DEVICE_MAPPER_ALIAS] = "EC_FAILED_TO_REMOVE_DEVICE_MAPPER_ALIAS",
[EC_LUKSIPC_WRITE_DEVICE_HANDLE_UNAVAILABLE] = "EC_LUKSIPC_WRITE_DEVICE_HANDLE_UNAVAILABLE",
[EC_PRECONDITIONS_NOT_SATISFIED] = "EC_PRECONDITIONS_NOT_SATISFIED",
[EC_UNABLE_TO_GET_RAW_DISK_SIZE] = "EC_UNABLE_TO_GET_RAW_DISK_SIZE",
[EC_UNABLE_TO_READ_FIRST_CHUNK] = "EC_UNABLE_TO_READ_FIRST_CHUNK",
[EC_UNABLE_TO_READ_FROM_STDIN] = "EC_UNABLE_TO_READ_FROM_STDIN",
[EC_UNSUPPORTED_SMALL_DISK_CORNER_CASE] = "EC_UNSUPPORTED_SMALL_DISK_CORNER_CASE",
[EC_USER_ABORTED_PROCESS] = "EC_USER_ABORTED_PROCESS",
[EC_CANNOT_INIT_SIGNAL_HANDLERS] = "EC_CANNOT_INIT_SIGNAL_HANDLERS",
[EC_CMDLINE_PARSING_ERROR] = "EC_CMDLINE_PARSING_ERROR",
[EC_CMDLINE_ARGUMENT_ERROR] = "EC_CMDLINE_ARGUMENT_ERROR",
[EC_CANNOT_GENERATE_WRITE_HANDLE] = "EC_CANNOT_GENERATE_WRITE_HANDLE",
[EC_PRNG_INITIALIZATION_FAILED] = "EC_PRNG_INITIALIZATION_FAILED",
};
static const char *exitCodeDesc[] = {
[EC_SUCCESS] = "Success",
[EC_UNSPECIFIED_ERROR] = "Unspecified error",
[EC_COPY_ABORTED_RESUME_FILE_WRITTEN] = "Copy aborted gracefully, resume file successfully written",
[EC_CANNOT_ALLOCATE_CHUNK_MEMORY] = "Cannot allocate memory for copy chunks",
[EC_CANNOT_GENERATE_KEY_FILE] = "Cannot generate key file",
[EC_CANNOT_INITIALIZE_DEVICE_ALIAS] = "Cannot initialize device mapper alias",
[EC_CANNOT_OPEN_READ_DEVICE] = "Cannot open reading block device",
[EC_CANNOT_OPEN_RESUME_FILE] = "Cannot open resume file",
[EC_COPY_ABORTED_FAILED_TO_WRITE_WRITE_RESUME_FILE] = "Copy aborted, failed to write resume file",
[EC_DEVICE_SIZES_IMPLAUSIBLE] = "Device sizes are implausible",
[EC_FAILED_TO_BACKUP_HEADER] = "Failed to backup raw device header",
[EC_FAILED_TO_CLOSE_LUKS_DEVICE] = "Failed to close LUKS device",
[EC_FAILED_TO_OPEN_UNLOCKED_CRYPTO_DEVICE] = "Failed to open unlocked crypto device",
[EC_FAILED_TO_PERFORM_LUKSFORMAT] = "Failed to perform luksFormat",
[EC_FAILED_TO_PERFORM_LUKSOPEN] = "Failed to perform luksOpen",
[EC_FAILED_TO_READ_RESUME_FILE] = "Failed to read resume file",
[EC_FAILED_TO_REMOVE_DEVICE_MAPPER_ALIAS] = "Failed to remove device mapper alias",
[EC_LUKSIPC_WRITE_DEVICE_HANDLE_UNAVAILABLE] = "Device mapper handle for luksipc write device is unavailable",
[EC_PRECONDITIONS_NOT_SATISFIED] = "Process preconditions are unsatisfied",
[EC_UNABLE_TO_GET_RAW_DISK_SIZE] = "Unable to determine raw disk size",
[EC_UNABLE_TO_READ_FIRST_CHUNK] = "Unable to read first chunk",
[EC_UNABLE_TO_READ_FROM_STDIN] = "Unable to read from standard input",
[EC_UNSUPPORTED_SMALL_DISK_CORNER_CASE] = "Unsupported small disk corner case",
[EC_USER_ABORTED_PROCESS] = "User aborted process",
[EC_CANNOT_INIT_SIGNAL_HANDLERS] = "Unable to install signal handlers",
[EC_CMDLINE_PARSING_ERROR] = "Error parsing the parameters given on command line (programming bug)",
[EC_CMDLINE_ARGUMENT_ERROR] = "Error with a parameter which was given on the command line",
[EC_CANNOT_GENERATE_WRITE_HANDLE] = "Error generating device mapper write handle",
[EC_PRNG_INITIALIZATION_FAILED] = "Initialization of PRNG failed",
};
void terminate(enum terminationCode_t aTermCode) {
int logLevel = (aTermCode == EC_SUCCESS) ? LLVL_DEBUG : LLVL_ERROR;
if (aTermCode <= MAX_VALID_ERROR_CODE) {
logmsg(logLevel, "Exit with code %d [%s]: %s\n", aTermCode, exitCodeAbbr[aTermCode], exitCodeDesc[aTermCode]);
} else {
logmsg(LLVL_ERROR, "Exit with code %d: No description available.\n", aTermCode);
}
exit(aTermCode);
}
luksipc-0.04/exit.h 0000664 0000000 0000000 00000011115 12531634264 0014236 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#ifndef __EXIT_H__
#define __EXIT_H__
/*
* The error codes and messages are maintained here. All C code is generated
* from these stubs from a small Python script. When adding new error codes,
* please add them here and regenerate the appropriate code. The format should
* be fairly obvious.
*
:0 EC_SUCCESS Success
:1 EC_UNSPECIFIED_ERROR Unspecified error
:2 EC_COPY_ABORTED_RESUME_FILE_WRITTEN Copy aborted gracefully, resume file successfully written
:3 EC_CANNOT_ALLOCATE_CHUNK_MEMORY Cannot allocate memory for copy chunks
:4 EC_CANNOT_GENERATE_KEY_FILE Cannot generate key file
:5 EC_CANNOT_INITIALIZE_DEVICE_ALIAS Cannot initialize device mapper alias
:6 EC_CANNOT_OPEN_READ_DEVICE Cannot open reading block device
:7 EC_CANNOT_OPEN_RESUME_FILE Cannot open resume file
:8 EC_COPY_ABORTED_FAILED_TO_WRITE_WRITE_RESUME_FILE Copy aborted, failed to write resume file
:9 EC_DEVICE_SIZES_IMPLAUSIBLE Device sizes are implausible
:10 EC_FAILED_TO_BACKUP_HEADER Failed to backup raw device header
:11 EC_FAILED_TO_CLOSE_LUKS_DEVICE Failed to close LUKS device
:12 EC_FAILED_TO_OPEN_UNLOCKED_CRYPTO_DEVICE Failed to open unlocked crypto device
:13 EC_FAILED_TO_PERFORM_LUKSFORMAT Failed to perform luksFormat
:14 EC_FAILED_TO_PERFORM_LUKSOPEN Failed to perform luksOpen
:15 EC_FAILED_TO_READ_RESUME_FILE Failed to read resume file
:16 EC_FAILED_TO_REMOVE_DEVICE_MAPPER_ALIAS Failed to remove device mapper alias
:17 EC_LUKSIPC_WRITE_DEVICE_HANDLE_UNAVAILABLE Device mapper handle for luksipc write device is unavailable
:18 EC_PRECONDITIONS_NOT_SATISFIED Process preconditions are unsatisfied
:19 EC_UNABLE_TO_GET_RAW_DISK_SIZE Unable to determine raw disk size
:20 EC_UNABLE_TO_READ_FIRST_CHUNK Unable to read first chunk
:21 EC_UNABLE_TO_READ_FROM_STDIN Unable to read from standard input
:22 EC_UNSUPPORTED_SMALL_DISK_CORNER_CASE Unsupported small disk corner case
:23 EC_USER_ABORTED_PROCESS User aborted process
:24 EC_CANNOT_INIT_SIGNAL_HANDLERS Unable to install signal handlers
:25 EC_CMDLINE_PARSING_ERROR Error parsing the parameters given on command line (programming bug)
:26 EC_CMDLINE_ARGUMENT_ERROR Error with a parameter which was given on the command line
:27 EC_CANNOT_GENERATE_WRITE_HANDLE Error generating device mapper write handle
:28 EC_PRNG_INITIALIZATION_FAILED Initialization of PRNG failed
*/
enum terminationCode_t {
EC_SUCCESS = 0,
EC_UNSPECIFIED_ERROR = 1,
EC_COPY_ABORTED_RESUME_FILE_WRITTEN = 2,
EC_CANNOT_ALLOCATE_CHUNK_MEMORY = 3,
EC_CANNOT_GENERATE_KEY_FILE = 4,
EC_CANNOT_INITIALIZE_DEVICE_ALIAS = 5,
EC_CANNOT_OPEN_READ_DEVICE = 6,
EC_CANNOT_OPEN_RESUME_FILE = 7,
EC_COPY_ABORTED_FAILED_TO_WRITE_WRITE_RESUME_FILE = 8,
EC_DEVICE_SIZES_IMPLAUSIBLE = 9,
EC_FAILED_TO_BACKUP_HEADER = 10,
EC_FAILED_TO_CLOSE_LUKS_DEVICE = 11,
EC_FAILED_TO_OPEN_UNLOCKED_CRYPTO_DEVICE = 12,
EC_FAILED_TO_PERFORM_LUKSFORMAT = 13,
EC_FAILED_TO_PERFORM_LUKSOPEN = 14,
EC_FAILED_TO_READ_RESUME_FILE = 15,
EC_FAILED_TO_REMOVE_DEVICE_MAPPER_ALIAS = 16,
EC_LUKSIPC_WRITE_DEVICE_HANDLE_UNAVAILABLE = 17,
EC_PRECONDITIONS_NOT_SATISFIED = 18,
EC_UNABLE_TO_GET_RAW_DISK_SIZE = 19,
EC_UNABLE_TO_READ_FIRST_CHUNK = 20,
EC_UNABLE_TO_READ_FROM_STDIN = 21,
EC_UNSUPPORTED_SMALL_DISK_CORNER_CASE = 22,
EC_USER_ABORTED_PROCESS = 23,
EC_CANNOT_INIT_SIGNAL_HANDLERS = 24,
EC_CMDLINE_PARSING_ERROR = 25,
EC_CMDLINE_ARGUMENT_ERROR = 26,
EC_CANNOT_GENERATE_WRITE_HANDLE = 27,
EC_PRNG_INITIALIZATION_FAILED = 28
};
/*************** AUTO GENERATED SECTION FOLLOWS ***************/
void terminate(enum terminationCode_t aTermCode);
/*************** AUTO GENERATED SECTION ENDS ***************/
#endif
luksipc-0.04/globals.h 0000664 0000000 0000000 00000002650 12531634264 0014714 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#ifndef __GLOBALS_H__
#define __GLOBALS_H__
#define LUKSIPC_VERSION "0.04"
#define MAX_HANDLE_LENGTH 32
#define MAX_ARG_CNT 32
#define MAX_ARGLENGTH 256
#define EXEC_MAX_ARGCNT 64
#define RESUME_FILE_HEADER_MAGIC "luksipc RESUME v1\0\xde\xad\xbe\xef & \xc0\xff\xee\0\0\0\0"
#define RESUME_FILE_HEADER_MAGIC_LEN 32
#define HEADER_BACKUP_BLOCKSIZE (128 * 1024)
#define HEADER_BACKUP_BLOCKCNT 1024
#define HEADER_BACKUP_SIZE_BYTES (HEADER_BACKUP_BLOCKSIZE * HEADER_BACKUP_BLOCKCNT)
#define DEFAULT_RESUME_FILENAME "resume.bin"
#endif
luksipc-0.04/keyfile.c 0000664 0000000 0000000 00000004276 12531634264 0014722 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include "logging.h"
#include "keyfile.h"
#include "utils.h"
#include "random.h"
bool genKeyfile(const char *aFilename, bool aForce) {
/* Does the file already exist? */
struct stat statBuf;
int statResult = stat(aFilename, &statBuf);
if (statResult == 0) {
/* Keyfile already exists */
if (!aForce) {
logmsg(LLVL_ERROR, "Keyfile %s already exists, refusing to overwrite.\n", aFilename);
return false;
} else {
logmsg(LLVL_WARN, "Keyfile %s already exists, overwriting because safety checks have been disabled.\n", aFilename);
}
}
int fd = open(aFilename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (fd == -1) {
/* Cannot create keyfile */
logmsg(LLVL_ERROR, "Cannot create keyfile %s: %s\n", aFilename, strerror(errno));
return false;
}
uint8_t keyData[4096];
if (!readRandomData(keyData, sizeof(keyData))) {
logmsg(LLVL_ERROR, "Error reading random data.\n");
close(fd);
return false;
}
int dataWritten = write(fd, keyData, sizeof(keyData));
if (dataWritten != sizeof(keyData)) {
logmsg(LLVL_ERROR, "Short write to keyfile: wanted %ld, read %d bytes\n", sizeof(keyData), dataWritten);
close(fd);
return false;
}
close(fd);
return true;
}
luksipc-0.04/keyfile.h 0000664 0000000 0000000 00000002163 12531634264 0014720 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#ifndef __KEYFILE_H__
#define __KEYFILE_H__
#include
/*************** AUTO GENERATED SECTION FOLLOWS ***************/
bool genKeyfile(const char *aFilename, bool aForce);
/*************** AUTO GENERATED SECTION ENDS ***************/
#endif
luksipc-0.04/logging.c 0000664 0000000 0000000 00000003052 12531634264 0014707 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#include
#include
#include "logging.h"
static int currentLogLevel;
int getLogLevel(void) {
return currentLogLevel;
}
void setLogLevel(int aLogLevel) {
currentLogLevel = aLogLevel;
}
static const char* logLevelToStr(int aLogLvl) {
switch (aLogLvl) {
case LLVL_CRITICAL: return "C";
case LLVL_ERROR: return "E";
case LLVL_WARN: return "W";
case LLVL_INFO: return "I";
case LLVL_DEBUG: return "D";
}
return "?";
}
void logmsg(int aLogLvl, const char *aFmtString, ...) {
if (aLogLvl <= currentLogLevel) {
va_list ap;
fprintf(stderr, "[%s]: ", logLevelToStr(aLogLvl));
va_start(ap, aFmtString);
vfprintf(stderr, aFmtString, ap);
va_end(ap);
}
}
luksipc-0.04/logging.h 0000664 0000000 0000000 00000002413 12531634264 0014714 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#ifndef __LOGGING_H__
#define __LOGGING_H__
#define LLVL_DEBUG 4
#define LLVL_INFO 3
#define LLVL_WARN 2
#define LLVL_ERROR 1
#define LLVL_CRITICAL 0
/*************** AUTO GENERATED SECTION FOLLOWS ***************/
int getLogLevel(void);
void setLogLevel(int aLogLevel);
void logmsg(int aLogLvl, const char *aFmtString, ...);
/*************** AUTO GENERATED SECTION ENDS ***************/
#endif
luksipc-0.04/luks.c 0000664 0000000 0000000 00000016375 12531634264 0014253 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#include
#include
#include
#include
#include
#include
#include "exec.h"
#include "luks.h"
#include "logging.h"
#include "globals.h"
#include "utils.h"
#include "random.h"
/* Checks is the given block device has already been formatted with LUKS. */
bool isLuks(const char *aBlockDevice) {
const char *arguments[] = {
"cryptsetup",
"isLuks",
aBlockDevice,
NULL
};
struct execResult_t execResult = execGetReturnCode(arguments);
return execResult.success && (execResult.returnCode == 0);
}
/* Returns if the given device mapper name is available (i.e. not active at the
* moment) */
bool isLuksMapperAvailable(const char *aMapperName) {
const char *arguments[] = {
"cryptsetup",
"status",
aMapperName,
NULL
};
logmsg(LLVL_DEBUG, "Performing dm-crypt status lookup on mapper name '%s'\n", aMapperName);
struct execResult_t execResult = execGetReturnCode(arguments);
bool mapperAvailable = execResult.success && (execResult.returnCode == 4);
logmsg(LLVL_DEBUG, "Device mapper name '%s' is %savailable (execution %s, returncode %d).\n", aMapperName, mapperAvailable ? "" : "NOT ", execResult.success ? "successful" : "failed", execResult.returnCode);
return mapperAvailable;
}
/* Formats a block device with LUKS using the given key file for slot 0 and
* passes some optional parameters (comma-separated) to cryptsetup */
bool luksFormat(const char *aBlkDevice, const char *aKeyFile, const char *aOptionalParams) {
int argcnt = -1;
char userSuppliedArguments[MAX_ARGLENGTH];
const char *arguments[MAX_ARG_CNT] = {
"cryptsetup",
"luksFormat",
"-q",
"--key-file",
aKeyFile,
NULL
};
if (aOptionalParams) {
if (!safestrcpy(userSuppliedArguments, aOptionalParams, MAX_ARGLENGTH)) {
logmsg(LLVL_ERROR, "Unable to copy user supplied argument, %d bytes max.\n", MAX_ARGLENGTH);
return false;
}
if (!argAppendParse(arguments, userSuppliedArguments, &argcnt, MAX_ARG_CNT)) {
logmsg(LLVL_ERROR, "Unable to copy user supplied argument, %d count max.\n", MAX_ARG_CNT);
return false;
}
}
if (!argAppend(arguments, aBlkDevice, &argcnt, MAX_ARG_CNT)) {
logmsg(LLVL_ERROR, "Unable to copy last user supplied argument, %d count max.\n", MAX_ARG_CNT);
return false;
}
logmsg(LLVL_DEBUG, "Performing luksFormat of block device %s using key file %s\n", aBlkDevice, aKeyFile);
struct execResult_t execResult = execGetReturnCode(arguments);
if ((!execResult.success) || (execResult.returnCode != 0)) {
logmsg(LLVL_ERROR, "luksFormat failed (execution %s, return code %d), aborting.\n", execResult.success ? "successful" : "failed", execResult.returnCode);
return false;
}
return true;
}
bool luksOpen(const char *aBlkDevice, const char *aKeyFile, const char *aHandle) {
const char *arguments[] = {
"cryptsetup",
"luksOpen",
"--key-file",
aKeyFile,
aBlkDevice,
aHandle,
NULL
};
logmsg(LLVL_DEBUG, "Performing luksOpen of block device %s using key file %s and device mapper handle %s\n", aBlkDevice, aKeyFile, aHandle);
struct execResult_t execResult = execGetReturnCode(arguments);
if ((!execResult.success) || (execResult.returnCode != 0)) {
logmsg(LLVL_ERROR, "luksOpen failed (execution %s, return code %d).\n", execResult.success ? "successful" : "failed", execResult.returnCode);
return false;
}
return true;
}
bool dmCreateAlias(const char *aSrcDevice, const char *aMapperHandle) {
uint64_t devSize = getDiskSizeOfPath(aSrcDevice);
if (devSize % 512) {
logmsg(LLVL_ERROR, "Device size of %s (%lu bytes) is not divisible by even 512 bytes sector size.\n", aSrcDevice, devSize);
return false;
}
char mapperTable[256];
snprintf(mapperTable, sizeof(mapperTable), "0 %lu linear %s 0", devSize / 512, aSrcDevice);
const char *arguments[] = {
"dmsetup",
"create",
aMapperHandle,
"--table",
mapperTable,
NULL
};
struct execResult_t execResult = execGetReturnCode(arguments);
if ((!execResult.success) || (execResult.returnCode != 0)) {
logmsg(LLVL_ERROR, "dmsetup alias creation failed (execution %s, returncode %d).\n", execResult.success ? "successful" : "failed", execResult.returnCode);
return false;
}
char aliasDeviceFilename[256];
snprintf(aliasDeviceFilename, sizeof(aliasDeviceFilename), "/dev/mapper/%s", aMapperHandle);
uint64_t aliasDevSize = getDiskSizeOfPath(aliasDeviceFilename);
if (devSize != aliasDevSize) {
logmsg(LLVL_ERROR, "Source device (%s) and its supposed alias device (%s) have different sizes (src = %lu and alias = %lu).\n", aSrcDevice, aliasDeviceFilename, devSize, aliasDevSize);
dmRemove(aMapperHandle);
return false;
}
logmsg(LLVL_DEBUG, "Created device mapper alias: %s -> %s\n", aliasDeviceFilename, aSrcDevice);
return true;
}
char *dmCreateDynamicAlias(const char *aSrcDevice, const char *aAliasPrefix) {
char alias[64];
if (aAliasPrefix && (strlen(aAliasPrefix) < 32)) {
snprintf(alias, sizeof(alias), "alias_%s_", aAliasPrefix);
} else {
strcpy(alias, "alias_");
}
if (!randomHexStrCat(alias, 4)) {
return NULL;
}
char *aliasPathname = malloc(strlen("/dev/mapper/") + strlen(alias) + 1);
if (!aliasPathname) {
logmsg(LLVL_ERROR, "malloc error for full filename of dynamic alias: %s\n", strerror(errno));
return NULL;
}
sprintf(aliasPathname, "/dev/mapper/%s", alias);
bool aliasSuccessful = dmCreateAlias(aSrcDevice, alias);
if (!aliasSuccessful) {
free(aliasPathname);
return NULL;
}
return aliasPathname;
}
bool dmRemove(const char *aMapperHandle) {
const char *arguments[] = {
"dmsetup",
"remove",
aMapperHandle,
NULL
};
/* Device cannot be closed if it is still open. udev will usually call
* blkid on the device after it is closed after been written to. Therefore
* it is possible that "dmsetup remove" fails immediately after closing the
* device (because blkid will have an open handle). We simply wait a bit
* and try again later if this happens. */
struct execResult_t execResult;
for (int try = 0; try < 10; try++) {
execResult = execGetReturnCode(arguments);
if (!execResult.success) {
return false;
}
if ((execResult.success) && (execResult.returnCode == 0)) {
break;
}
sleep(1);
}
bool success = (execResult.success) && (execResult.returnCode == 0) && isLuksMapperAvailable(aMapperHandle);
if (!success) {
logmsg(LLVL_ERROR, "Cannot remove device mapper handle %s (execution %s, return code %d)\n", aMapperHandle, execResult.success ? "successful" : "failed", execResult.returnCode);
}
return success;
}
luksipc-0.04/luks.h 0000664 0000000 0000000 00000003001 12531634264 0014236 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#ifndef __LUKS_H__
#define __LUKS_H__
#include
/*************** AUTO GENERATED SECTION FOLLOWS ***************/
bool isLuks(const char *aBlockDevice);
bool isLuksMapperAvailable(const char *aMapperName);
bool luksFormat(const char *aBlkDevice, const char *aKeyFile, const char *aOptionalParams);
bool luksOpen(const char *aBlkDevice, const char *aKeyFile, const char *aHandle);
bool dmCreateAlias(const char *aSrcDevice, const char *aMapperHandle);
char *dmCreateDynamicAlias(const char *aSrcDevice, const char *aAliasPrefix);
bool dmRemove(const char *aMapperHandle);
/*************** AUTO GENERATED SECTION ENDS ***************/
#endif
luksipc-0.04/luksipc.c 0000664 0000000 0000000 00000106611 12531634264 0014740 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "luksipc.h"
#include "shutdown.h"
#include "logging.h"
#include "exec.h"
#include "luks.h"
#include "parameters.h"
#include "chunk.h"
#include "keyfile.h"
#include "utils.h"
#include "globals.h"
#include "mount.h"
#include "exit.h"
#include "random.h"
#define staticassert(cond) _Static_assert(cond, #cond)
/* Assert that lseek(2) has 64-bit file offsets */
staticassert(sizeof(off_t) == 8);
#define REMAINING_BYTES(aconvptr) (((aconvptr)->endOutOffset) - ((aconvptr)->outOffset))
struct conversionProcess {
int readDevFd, writeDevFd;
uint64_t readDevSize, writeDevSize;
struct chunk dataBuffer[2];
int usedBufferIndex;
int resumeFd;
char *rawDeviceAlias;
bool reluksification;
uint64_t inOffset, outOffset;
uint64_t endOutOffset;
char *writeDeviceHandle;
char writeDevicePath[48];
struct {
double startTime;
double lastShowTime;
uint64_t lastOutOffset;
uint64_t copied;
} stats;
};
enum copyResult_t {
COPYRESULT_SUCCESS_FINISHED,
COPYRESULT_SUCCESS_RESUMABLE,
COPYRESULT_ERROR_WRITING_RESUME_FILE,
};
static bool checkedWrite(int aFd, void *aData, int aLength) {
ssize_t result = write(aFd, aData, aLength);
if (result != aLength) {
logmsg(LLVL_ERROR, "Error while trying to write %d bytes to file with FD #%d: only %ld bytes written: %s\n", aLength, aFd, result, strerror(errno));
return false;
}
return true;
}
static bool checkedRead(int aFd, void *aData, int aLength) {
ssize_t result = read(aFd, aData, aLength);
if (result != aLength) {
logmsg(LLVL_ERROR, "Error while trying to read %d bytes from file with FD #%d: only %ld bytes read: %s\n", aLength, aFd, result, strerror(errno));
return false;
}
return true;
}
static bool writeResumeFile(struct conversionProcess *aConvProcess) {
bool success = true;
char header[RESUME_FILE_HEADER_MAGIC_LEN];
memcpy(header, RESUME_FILE_HEADER_MAGIC, RESUME_FILE_HEADER_MAGIC_LEN);
success = (lseek(aConvProcess->resumeFd, 0, SEEK_SET) != -1) && success;
success = checkedWrite(aConvProcess->resumeFd, header, sizeof(header)) && success;
success = checkedWrite(aConvProcess->resumeFd, &aConvProcess->outOffset, sizeof(uint64_t)) && success;
success = checkedWrite(aConvProcess->resumeFd, &aConvProcess->readDevSize, sizeof(uint64_t)) && success;
success = checkedWrite(aConvProcess->resumeFd, &aConvProcess->writeDevSize, sizeof(uint64_t)) && success;
success = checkedWrite(aConvProcess->resumeFd, &aConvProcess->reluksification, sizeof(bool)) && success;
success = checkedWrite(aConvProcess->resumeFd, &aConvProcess->dataBuffer[aConvProcess->usedBufferIndex].used, sizeof(uint32_t)) && success;
success = checkedWrite(aConvProcess->resumeFd, aConvProcess->dataBuffer[aConvProcess->usedBufferIndex].data, aConvProcess->dataBuffer[aConvProcess->usedBufferIndex].size) && success;
fsync(aConvProcess->resumeFd);
logmsg(LLVL_DEBUG, "Wrote resume file: read pointer offset %lu write pointer offset %lu, %lu bytes of data in active buffer.\n", aConvProcess->inOffset, aConvProcess->outOffset, aConvProcess->dataBuffer[aConvProcess->usedBufferIndex].used);
return success;
}
static bool readResumeFile(struct conversionParameters const *aParameters, struct conversionProcess *aConvProcess) {
bool success = true;
char header[RESUME_FILE_HEADER_MAGIC_LEN];
success = (lseek(aConvProcess->resumeFd, 0, SEEK_SET) != -1) && success;
if (!success) {
logmsg(LLVL_ERROR, "Seek error while trying to read resume file: %s\n", strerror(errno));
return false;
}
success = checkedRead(aConvProcess->resumeFd, header, sizeof(header)) && success;
if (!success) {
logmsg(LLVL_ERROR, "Read error while trying to read resume file header.\n");
return false;
}
if (memcmp(header, RESUME_FILE_HEADER_MAGIC, RESUME_FILE_HEADER_MAGIC_LEN) != 0) {
logmsg(LLVL_ERROR, "Header magic mismatch in resume file.\n");
return false;
}
uint64_t origReadDevSize, origWriteDevSize;
bool origReluksification;
success = checkedRead(aConvProcess->resumeFd, &aConvProcess->outOffset, sizeof(uint64_t)) && success;
success = checkedRead(aConvProcess->resumeFd, &origReadDevSize, sizeof(uint64_t)) && success;
success = checkedRead(aConvProcess->resumeFd, &origWriteDevSize, sizeof(uint64_t)) && success;
success = checkedRead(aConvProcess->resumeFd, &origReluksification, sizeof(bool)) && success;
if (!success) {
logmsg(LLVL_ERROR, "Read error while trying to read resume file offset metadata.\n");
return false;
}
if (origReadDevSize != aConvProcess->readDevSize) {
if (aParameters->safetyChecks) {
logmsg(LLVL_ERROR, "Resume file used read device of size %lu bytes, but currently read device size is %lu bytes. Refusing to continue in spite of mismatch.\n", origReadDevSize, aConvProcess->readDevSize);
return false;
} else {
logmsg(LLVL_WARN, "Resume file used read device of size %lu bytes, but currently read device size is %lu bytes. Continuing only because safety checks are disabled.\n", origReadDevSize, aConvProcess->readDevSize);
}
}
if (origWriteDevSize != aConvProcess->writeDevSize) {
if (aParameters->safetyChecks) {
logmsg(LLVL_ERROR, "Resume file used write device of size %lu bytes, but currently write device size is %lu bytes. Refusing to continue in spite of mismatch.\n", origWriteDevSize, aConvProcess->writeDevSize);
return false;
} else {
logmsg(LLVL_WARN, "Resume file used write device of size %lu bytes, but currently write device size is %lu bytes. Continuing only because safety checks are disabled.\n", origWriteDevSize, aConvProcess->writeDevSize);
}
}
if (origReluksification != aConvProcess->reluksification) {
if (aParameters->safetyChecks) {
logmsg(LLVL_ERROR, "Resume file was performing reLUKSification, command line specification indicates you do not want reLUKSification. Refusing to continue in spite of mismatch.\n");
return false;
} else {
logmsg(LLVL_WARN, "Resume file was performing reLUKSification, command line specification indicates you do not want reLUKSification. Continuing only because safety checks are disabled.\n");
}
}
logmsg(LLVL_DEBUG, "Read write pointer offset %lu from resume file.\n", aConvProcess->outOffset);
aConvProcess->usedBufferIndex = 0;
success = checkedRead(aConvProcess->resumeFd, &aConvProcess->dataBuffer[0].used, sizeof(uint32_t)) && success;
success = checkedRead(aConvProcess->resumeFd, aConvProcess->dataBuffer[0].data, aConvProcess->dataBuffer[0].used) && success;
return success;
}
static void showProgress(struct conversionProcess *aConvProcess) {
double curTime = getTime();
if (aConvProcess->stats.startTime < 1) {
aConvProcess->stats.startTime = curTime;
aConvProcess->stats.lastOutOffset = aConvProcess->outOffset;
aConvProcess->stats.lastShowTime = curTime;
} else {
uint64_t progressBytes = aConvProcess->outOffset - aConvProcess->stats.lastOutOffset;
double progressTime = curTime - aConvProcess->stats.lastShowTime;
bool showStats = ((progressBytes >= 100 * 1024 * 1024) && (progressTime >= 5));
showStats = showStats || (progressTime >= 60);
if (showStats) {
double runtimeSeconds = curTime - aConvProcess->stats.startTime;
int runtimeSecondsInteger = (int)runtimeSeconds;
double copySpeedBytesPerSecond = 0;
if (runtimeSeconds > 1) {
copySpeedBytesPerSecond = (double)aConvProcess->stats.copied / runtimeSeconds;
}
uint64_t remainingBytes = aConvProcess->endOutOffset - aConvProcess->outOffset;
double remainingSecs = 0;
if (copySpeedBytesPerSecond > 10) {
remainingSecs = (double)remainingBytes / copySpeedBytesPerSecond;
}
int remainingSecsInteger = 0;
if ((remainingSecs > 0) && (remainingSecs < (100 * 3600))) {
remainingSecsInteger = (int)remainingSecs;
}
logmsg(LLVL_INFO, "%2d:%02d: "
"%5.1f%% "
"%7lu MiB / %lu MiB "
"%5.1f MiB/s "
"Left: "
"%7lu MiB "
"%2d:%02d h:m"
"\n",
runtimeSecondsInteger / 3600, runtimeSecondsInteger % 3600 / 60,
100.0 * (double)aConvProcess->outOffset / (double)aConvProcess->endOutOffset,
aConvProcess->outOffset / 1024 / 1024,
aConvProcess->endOutOffset / 1024 / 1024,
copySpeedBytesPerSecond / 1024. / 1024.,
remainingBytes / 1024 / 1024,
remainingSecsInteger / 3600, remainingSecsInteger % 3600 / 60
);
aConvProcess->stats.lastOutOffset = aConvProcess->outOffset;
aConvProcess->stats.lastShowTime = curTime;
}
}
}
static void closeFileDescriptorsAndSync(struct conversionProcess *aConvProcess) {
logmsg(LLVL_DEBUG, "Closing read/write file descriptors %d and %d.\n", aConvProcess->readDevFd, aConvProcess->writeDevFd);
close(aConvProcess->readDevFd);
close(aConvProcess->writeDevFd);
aConvProcess->readDevFd = -1;
aConvProcess->writeDevFd = -1;
logmsg(LLVL_INFO, "Synchronizing disk...\n");
sync();
logmsg(LLVL_INFO, "Synchronizing of disk finished.\n");
}
static enum copyResult_t issueGracefulShutdown(struct conversionParameters const *aParameters, struct conversionProcess *aConvProcess) {
logmsg(LLVL_INFO, "Gracefully shutting down.\n");
if (!writeResumeFile(aConvProcess)) {
logmsg(LLVL_WARN, "There were errors writing the resume file %s.\n", aParameters->resumeFilename);
return COPYRESULT_ERROR_WRITING_RESUME_FILE;
} else {
logmsg(LLVL_INFO, "Sucessfully written resume file %s.\n", aParameters->resumeFilename);
return COPYRESULT_SUCCESS_RESUMABLE;
}
}
static enum copyResult_t startDataCopy(struct conversionParameters const *aParameters, struct conversionProcess *aConvProcess) {
logmsg(LLVL_INFO, "Starting copying of data, read offset %lu, write offset %lu\n", aConvProcess->inOffset, aConvProcess->outOffset);
while (true) {
ssize_t bytesTransferred;
int unUsedBufferIndex = (1 - aConvProcess->usedBufferIndex);
int bytesToRead;
#ifdef DEVELOPMENT
if (aParameters->dev.slowDown) {
usleep(500 * 1000);
}
#endif
if (REMAINING_BYTES(aConvProcess) - (aConvProcess->dataBuffer[aConvProcess->usedBufferIndex].used) < aConvProcess->dataBuffer[unUsedBufferIndex].size) {
/* Remaining is not a full chunk */
bytesToRead = REMAINING_BYTES(aConvProcess) - (aConvProcess->dataBuffer[aConvProcess->usedBufferIndex].used);
if (bytesToRead > 0) {
logmsg(LLVL_DEBUG, "Preparing to write last (partial) chunk of %d bytes.\n", bytesToRead);
}
} else {
bytesToRead = aConvProcess->dataBuffer[unUsedBufferIndex].size;
}
if (bytesToRead > 0) {
#ifdef DEVELOPMENT
if (aParameters->dev.ioErrors) {
bytesTransferred = unreliableChunkReadAt(&aConvProcess->dataBuffer[unUsedBufferIndex], aConvProcess->readDevFd, aConvProcess->inOffset, bytesToRead);
} else {
bytesTransferred = chunkReadAt(&aConvProcess->dataBuffer[unUsedBufferIndex], aConvProcess->readDevFd, aConvProcess->inOffset, bytesToRead);
}
#else
bytesTransferred = chunkReadAt(&aConvProcess->dataBuffer[unUsedBufferIndex], aConvProcess->readDevFd, aConvProcess->inOffset, bytesToRead);
#endif
if (bytesTransferred == -1) {
/* Error reading from device, handle this! */
logmsg(LLVL_ERROR, "Error reading from device at offset 0x%lx, will shutdown.\n", aConvProcess->inOffset);
issueSigQuit();
} else if (bytesTransferred > 0) {
aConvProcess->inOffset += aConvProcess->dataBuffer[unUsedBufferIndex].used;
} else {
logmsg(LLVL_WARN, "Read of %d transferred %d hit EOF at inOffset = %ld remaining = %ld\n", bytesToRead, bytesTransferred, aConvProcess->inOffset, REMAINING_BYTES(aConvProcess));
}
} else {
if (bytesToRead == 0) {
logmsg(LLVL_DEBUG, "No more bytes to read, will finish writing last partial chunk of %d bytes.\n", REMAINING_BYTES(aConvProcess));
} else {
logmsg(LLVL_WARN, "Odd: %d bytes to read at inOffset = %ld remaining = %ld\n", bytesToRead, aConvProcess->inOffset, REMAINING_BYTES(aConvProcess));
}
}
if (receivedSigQuit()) {
return issueGracefulShutdown(aParameters, aConvProcess);
}
if (REMAINING_BYTES(aConvProcess) < aConvProcess->dataBuffer[aConvProcess->usedBufferIndex].used) {
/* Remaining is not a full chunk */
aConvProcess->dataBuffer[aConvProcess->usedBufferIndex].used = REMAINING_BYTES(aConvProcess);
}
#ifdef DEVELOPMENT
if (aParameters->dev.ioErrors) {
bytesTransferred = unreliableChunkWriteAt(&aConvProcess->dataBuffer[aConvProcess->usedBufferIndex], aConvProcess->writeDevFd, aConvProcess->outOffset);
} else {
bytesTransferred = chunkWriteAt(&aConvProcess->dataBuffer[aConvProcess->usedBufferIndex], aConvProcess->writeDevFd, aConvProcess->outOffset);
}
#else
bytesTransferred = chunkWriteAt(&aConvProcess->dataBuffer[aConvProcess->usedBufferIndex], aConvProcess->writeDevFd, aConvProcess->outOffset);
#endif
if (bytesTransferred == -1) {
logmsg(LLVL_ERROR, "Error writing to device at offset 0x%lx, shutting down.\n", aConvProcess->outOffset);
return issueGracefulShutdown(aParameters, aConvProcess);
} else if (bytesTransferred > 0) {
aConvProcess->outOffset += bytesTransferred;
aConvProcess->stats.copied += bytesTransferred;
showProgress(aConvProcess);
if (aConvProcess->outOffset == aConvProcess->endOutOffset) {
logmsg(LLVL_INFO, "Disk copy completed successfully.\n");
return COPYRESULT_SUCCESS_FINISHED;
}
aConvProcess->dataBuffer[aConvProcess->usedBufferIndex].used = 0;
aConvProcess->usedBufferIndex = unUsedBufferIndex;
}
}
}
static bool openResumeFile(struct conversionParameters const *aParameters, struct conversionProcess *aConvProcess) {
bool createResumeFile = (!aParameters->resuming);
int openFlags = createResumeFile ? (O_TRUNC | O_WRONLY | O_CREAT) : O_RDWR;
/* Open resume file */
aConvProcess->resumeFd = open(aParameters->resumeFilename, openFlags, 0600);
if (aConvProcess->resumeFd == -1) {
logmsg(LLVL_ERROR, "Opening '%s' for %s failed: %s\n", aParameters->resumeFilename, createResumeFile ? "writing" : "reading/writing", strerror(errno));
return false;
}
if (createResumeFile) {
/* Truncate resume file to zero and set to size of block */
if (ftruncate(aConvProcess->resumeFd, 0) == -1) {
logmsg(LLVL_ERROR, "Truncation of resume file failed: %s\n", strerror(errno));
return false;
}
/* Write zeros in that resume file to assert we have the necessary disk
* space available */
if (!writeResumeFile(aConvProcess)) {
logmsg(LLVL_ERROR, "Error writing the resume file: %s\n", strerror(errno));
return false;
}
/* Then seek to start of resume file in case it needs to be written later on */
if (lseek(aConvProcess->resumeFd, 0, SEEK_SET) == (off_t)-1) {
logmsg(LLVL_ERROR, "Seek in resume file failed: %s\n", strerror(errno));
return false;
}
}
return true;
}
static bool openDevice(const char *aPath, int *aFd, int aOpenFlags, uint64_t *aDeviceSize) {
/* Open device in requested mode first */
*aFd = open(aPath, aOpenFlags, 0600);
if (*aFd == -1) {
logmsg(LLVL_ERROR, "open %s failed: %s\n", aPath, strerror(errno));
return false;
}
/* Then determine its size */
*aDeviceSize = getDiskSizeOfFd(*aFd);
if (*aDeviceSize == 0) {
logmsg(LLVL_ERROR, "Determine disk size of %s failed: %s\n", aPath, strerror(errno));
return false;
}
return true;
}
static uint64_t absDiff(uint64_t aValue1, uint64_t aValue2) {
if (aValue1 > aValue2) {
return aValue1 - aValue2;
} else {
return aValue2 - aValue1;
}
}
/* Determine size difference of the reading and writing devices and if this
* is at all possible (if the block size has been smaller than the header
* size, the disk is probably screwed already) */
static bool plausibilizeReadWriteDeviceSizes(struct conversionParameters const *aParameters, struct conversionProcess *aConvProcess) {
uint64_t absSizeDiff = absDiff(aConvProcess->readDevSize, aConvProcess->writeDevSize);
if (absSizeDiff > 0x10000000) {
logmsg(LLVL_WARN, "Absolute size difference if implausibly large (%lu), something is very wrong.", absSizeDiff);
return false;
}
int32_t hdrSize = aConvProcess->readDevSize - aConvProcess->writeDevSize;
if (hdrSize > 0) {
logmsg(LLVL_INFO, "Write disk smaller than read disk by %d bytes (%d kiB + %d bytes, occupied by LUKS header)\n", hdrSize, hdrSize / 1024, hdrSize % 1024);
if (hdrSize > aParameters->blocksize) {
logmsg(LLVL_WARN, "LUKS header larger than chunk copy size. LUKS format probably has overwritten data that cannot be recovered.\n");
return false;
}
} else if (hdrSize < 0) {
logmsg(LLVL_INFO, "Write disk larger than read disk, %d bytes were freed (%d kiB + %d bytes)\n", -hdrSize, -hdrSize / 1024, -hdrSize % 1024);
} else {
logmsg(LLVL_INFO, "Write disk size equal to read disk size.\n");
}
return true;
}
static bool initializeDeviceAlias(struct conversionParameters const *aParameters, struct conversionProcess *aConvProcess) {
aConvProcess->rawDeviceAlias = dmCreateDynamicAlias(aParameters->rawDevice, "luksipc_raw");
if (!aConvProcess->rawDeviceAlias) {
logmsg(LLVL_ERROR, "Unable to initialize raw device alias.\n");
return false;
}
logmsg(LLVL_INFO, "Created raw device alias: %s -> %s\n", aParameters->rawDevice, aConvProcess->rawDeviceAlias);
return true;
}
static bool backupPhysicalDisk(struct conversionParameters const *aParameters, struct conversionProcess *aConvProcess) {
logmsg(LLVL_INFO, "Backing up physical disk %s header to backup file %s\n", aParameters->rawDevice, aParameters->backupFile);
if (doesFileExist(aParameters->backupFile)) {
if (aParameters->safetyChecks) {
logmsg(LLVL_ERROR, "Backup file %s already exists, refusing to overwrite.\n", aParameters->backupFile);
return false;
} else {
logmsg(LLVL_WARN, "Backup file %s already exists. Overwriting because safety checks have been disabled.\n", aParameters->backupFile);
}
}
/* Open raw disk for reading (cannot use aConvProcess->readDevFd here since
* we might be doing reLUKSification) */
int readFd = open(aParameters->rawDevice, O_RDONLY);
if (readFd == -1) {
logmsg(LLVL_ERROR, "Opening raw disk device %s for reading failed: %s\n", aParameters->rawDevice, strerror(errno));
return false;
}
/* Open backup file */
int writeFd = open(aParameters->backupFile, O_TRUNC | O_WRONLY | O_CREAT, 0600);
if (writeFd == -1) {
logmsg(LLVL_ERROR, "Opening backup file %s for writing failed: %s\n", aParameters->backupFile, strerror(errno));
return false;
}
/* Determine the amount of blocks that need to be copied */
int copyBlockCount = (HEADER_BACKUP_SIZE_BYTES < aConvProcess->readDevSize) ? HEADER_BACKUP_BLOCKCNT : (aConvProcess->readDevSize / HEADER_BACKUP_BLOCKSIZE);
logmsg(LLVL_DEBUG, "Backup file %s will consist of %d blocks of %d bytes each (%d bytes total, %d kiB)\n", aParameters->backupFile, copyBlockCount, HEADER_BACKUP_BLOCKSIZE, copyBlockCount * HEADER_BACKUP_BLOCKSIZE, copyBlockCount * HEADER_BACKUP_BLOCKSIZE / 1024);
/* Start copying */
uint8_t copyBuffer[HEADER_BACKUP_BLOCKSIZE];
for (int i = 0; i < copyBlockCount; i++) {
if (!checkedRead(readFd, copyBuffer, HEADER_BACKUP_BLOCKSIZE)) {
logmsg(LLVL_ERROR, "Read failed when trying to copy to backup file: %s\n", strerror(errno));
return false;
}
if (!checkedWrite(writeFd, copyBuffer, HEADER_BACKUP_BLOCKSIZE)) {
logmsg(LLVL_ERROR, "Write failed when trying to copy to backup file: %s\n", strerror(errno));
return false;
}
}
fsync(writeFd);
close(writeFd);
close(readFd);
return true;
}
static bool generateRandomizedWriteHandle(struct conversionProcess *aConvProcess) {
strcpy(aConvProcess->writeDevicePath, "/dev/mapper/luksipc_");
if (!randomHexStrCat(aConvProcess->writeDevicePath, 4)) {
logmsg(LLVL_ERROR, "Cannot generate randomized luksipc write handle.\n");
return false;
}
aConvProcess->writeDeviceHandle = aConvProcess->writeDevicePath + 12;
return true;
}
static void convert(struct conversionParameters const *parameters) {
/* Initialize conversion process status */
struct conversionProcess convProcess;
memset(&convProcess, 0, sizeof(struct conversionProcess));
/* Generate a randomized conversion handle */
if (!generateRandomizedWriteHandle(&convProcess)) {
terminate(EC_CANNOT_GENERATE_WRITE_HANDLE);
}
/* Initialize device aliases. Actually they're technically only needed for
* reLUKSification, but basically are a noop if not using reLUKSification.
* To keep the code as simple as possible, we only want to have one case
* here */
if (!initializeDeviceAlias(parameters, &convProcess)) {
terminate(EC_CANNOT_INITIALIZE_DEVICE_ALIAS);
}
/* Allocate two block chunks */
for (int i = 0; i < 2; i++) {
if (!allocChunk(&convProcess.dataBuffer[i], parameters->blocksize)) {
logmsg(LLVL_ERROR, "Failed to allocate chunk buffer %d: %s\n", i, strerror(errno));
terminate(EC_CANNOT_ALLOCATE_CHUNK_MEMORY);
}
}
/* Open resume file for writing (conversion) or reading/writing (resume) */
if (!openResumeFile(parameters, &convProcess)) {
terminate(EC_CANNOT_OPEN_RESUME_FILE);
}
/* Open unencrypted device for reading/writing (need write permissions in
* case we need to unpulp the disk) */
if (!openDevice(parameters->readDevice, &convProcess.readDevFd, O_RDWR, &convProcess.readDevSize)) {
terminate(EC_CANNOT_OPEN_READ_DEVICE);
}
logmsg(LLVL_INFO, "Size of reading device %s is %lu bytes (%lu MiB + %lu bytes)\n", parameters->readDevice, convProcess.readDevSize, convProcess.readDevSize / (1024 * 1024), convProcess.readDevSize % (1024 * 1024));
/* Do a backup of the physical disk first if we're just starting out our
* conversion */
if (!parameters->resuming) {
if (!backupPhysicalDisk(parameters, &convProcess)) {
terminate(EC_FAILED_TO_BACKUP_HEADER);
}
}
/* If the whole device is smaller than one copy block, we bail. This would
* obviously be possible to handle, but we won't. If your hard disk is so
* small, then recreate it. */
if (convProcess.readDevSize < (uint32_t)parameters->blocksize) {
logmsg(LLVL_ERROR, "Error: Volume size of %s (%lu bytes) is smaller than chunksize (%u). Weird and unsupported corner case.\n", parameters->readDevice, convProcess.readDevSize, parameters->blocksize);
terminate(EC_UNSUPPORTED_SMALL_DISK_CORNER_CASE);
}
if (!parameters->resuming) {
/* Read the first chunk of data from the unencrypted device (because it
* will be overwritten with the LUKS header after the luksFormat action) */
logmsg(LLVL_DEBUG, "%s: Reading first chunk.\n", parameters->readDevice);
if (chunkReadAt(&convProcess.dataBuffer[0], convProcess.readDevFd, 0, convProcess.dataBuffer[0].size) != parameters->blocksize) {
logmsg(LLVL_ERROR, "%s: Unable to read chunk data.\n", parameters->readDevice);
terminate(EC_UNABLE_TO_READ_FIRST_CHUNK);
}
logmsg(LLVL_DEBUG, "%s: Read %d bytes from first chunk.\n", parameters->readDevice, convProcess.dataBuffer[0].used);
/* Check availability of device mapper handle before performing format */
if (!isLuksMapperAvailable(convProcess.writeDeviceHandle)) {
logmsg(LLVL_ERROR, "Error: luksipc conversion handle '%s' not available.\n", convProcess.writeDeviceHandle);
terminate(EC_LUKSIPC_WRITE_DEVICE_HANDLE_UNAVAILABLE);
}
/* Format the device while keeping unencrypted disk header in memory (Chunk 0) */
logmsg(LLVL_INFO, "Performing luksFormat of %s\n", parameters->rawDevice);
if (!luksFormat(convProcess.rawDeviceAlias, parameters->keyFile, parameters->luksFormatParams)) {
terminate(EC_FAILED_TO_PERFORM_LUKSFORMAT);
}
}
/* luksOpen the writing block device using the generated keyfile */
logmsg(LLVL_INFO, "Performing luksOpen of %s (opening as mapper name %s)\n", parameters->rawDevice, convProcess.writeDeviceHandle);
if (!luksOpen(convProcess.rawDeviceAlias, parameters->keyFile, convProcess.writeDeviceHandle)) {
if (!parameters->resuming) {
/* Open failed, but we already formatted the disk. Try to unpulp,
* but only if we already messed with the disk! */
chunkWriteAt(&convProcess.dataBuffer[0], convProcess.readDevFd, 0);
}
terminate(EC_FAILED_TO_PERFORM_LUKSOPEN);
}
/* Open LUKS device for reading/writing */
if (!openDevice(convProcess.writeDevicePath, &convProcess.writeDevFd, O_RDWR, &convProcess.writeDevSize)) {
logmsg(LLVL_ERROR, "Opening LUKS device %s failed: %s\n", convProcess.writeDevicePath, strerror(errno));
if (!parameters->resuming) {
/* Open failed, but we already formatted the disk. Try to unpulp,
* but only if we already messed with the disk! */
chunkWriteAt(&convProcess.dataBuffer[0], convProcess.readDevFd, 0);
}
terminate(EC_FAILED_TO_OPEN_UNLOCKED_CRYPTO_DEVICE);
}
logmsg(LLVL_INFO, "Size of luksOpened writing device is %lu bytes (%lu MiB + %lu bytes)\n", convProcess.writeDevSize, convProcess.writeDevSize / (1024 * 1024), convProcess.writeDevSize % (1024 * 1024));
/* Check that the sizes of reading and writing device are in a sane
* relationship to each other (i.e. writing device is maybe slightly
* smaller than reading device, but no significant size differences occur).
* */
if (!plausibilizeReadWriteDeviceSizes(parameters, &convProcess)) {
logmsg(LLVL_ERROR, "Implausible values encountered in regards to disk sizes (R = %ul, W = %ul), aborting.\n", convProcess.readDevSize, convProcess.writeDevSize);
if (!parameters->resuming) {
/* Open failed, but we already formatted the disk. Try to unpulp
* only if we already messed with the disk! We probably have
* permapulped the disk at this point ;-( */
chunkWriteAt(&convProcess.dataBuffer[0], convProcess.readDevFd, 0);
}
terminate(EC_DEVICE_SIZES_IMPLAUSIBLE);
}
if (!parameters->resuming) {
convProcess.outOffset = 0;
} else {
/* Now it's time to read in the resume file. */
if (!readResumeFile(parameters, &convProcess)) {
logmsg(LLVL_ERROR, "Failed to read resume file, aborting.\n");
terminate(EC_FAILED_TO_READ_RESUME_FILE);
}
}
/* These values are identical for resume and non resume cases */
convProcess.usedBufferIndex = 0;
convProcess.endOutOffset = (convProcess.readDevSize < convProcess.writeDevSize) ? convProcess.readDevSize : convProcess.writeDevSize;
convProcess.inOffset = convProcess.dataBuffer[0].used + convProcess.outOffset;
/* Then start the copying process */
enum copyResult_t copyResult = startDataCopy(parameters, &convProcess);
if (copyResult == COPYRESULT_ERROR_WRITING_RESUME_FILE) {
terminate(EC_COPY_ABORTED_FAILED_TO_WRITE_WRITE_RESUME_FILE);
}
/* Sync the disk and close open file descriptors to partition */
closeFileDescriptorsAndSync(&convProcess);
/* Then close the LUKS device */
if (!dmRemove(convProcess.writeDeviceHandle)) {
logmsg(LLVL_ERROR, "Failed to close LUKS device %s.\n", convProcess.writeDeviceHandle);
terminate(EC_FAILED_TO_CLOSE_LUKS_DEVICE);
}
/* Finally remove the device mapper alias */
if (!dmRemove(convProcess.rawDeviceAlias)) {
logmsg(LLVL_ERROR, "Removing device mapper alias %s failed.\n", convProcess.rawDeviceAlias);
terminate(EC_FAILED_TO_REMOVE_DEVICE_MAPPER_ALIAS);
}
/* Free memory of copy buffers */
for (int i = 0; i < 2; i++) {
freeChunk(&convProcess.dataBuffer[i]);
}
/* Return with a code that depends on whether the copying was finished
* completely or if it was aborted gracefully (i.e. resuming is possible)
**/
terminate((copyResult == COPYRESULT_SUCCESS_FINISHED) ? EC_SUCCESS : EC_COPY_ABORTED_RESUME_FILE_WRITTEN);
}
static void printCheckListItem(int *aNumber, const char *aMsg, ...) {
(*aNumber)++;
fprintf(stderr, " [%d] ", *aNumber);
va_list argList;
va_start(argList, aMsg);
vfprintf(stderr, aMsg, argList);
va_end(argList);
}
static void checkPreconditions(struct conversionParameters const *aParameters) {
bool abortProcess = false;
bool reluksification = strcmp(aParameters->rawDevice, aParameters->readDevice) != 0;
if ((!aParameters->resuming) && (!reluksification)) {
logmsg(LLVL_DEBUG, "Checking if device %s is already a LUKS device...\n", aParameters->rawDevice);
if (isLuks(aParameters->rawDevice)) {
if (aParameters->safetyChecks) {
logmsg(LLVL_ERROR, "%s: Already LUKS, refuse to do anything.\n", aParameters->rawDevice);
abortProcess = true;
} else {
logmsg(LLVL_WARN, "%s: Already LUKS. Continuing only because safety checks have been disabled.\n", aParameters->rawDevice);
}
} else {
logmsg(LLVL_DEBUG, "%s: Not yet a LUKS device.\n", aParameters->rawDevice);
}
}
if (!aParameters->resuming) {
/* Initial conversion, not resuming */
if (doesFileExist(aParameters->backupFile)) {
if (aParameters->safetyChecks) {
logmsg(LLVL_ERROR, "Backup file %s already exists, refusing to overwrite.\n", aParameters->backupFile);
abortProcess = true;
} else {
logmsg(LLVL_WARN, "Backup file %s already exists. Will be overwritten when process continues because safety checks have been disabled.\n", aParameters->backupFile);
}
}
if (doesFileExist(DEFAULT_RESUME_FILENAME)) {
if (aParameters->safetyChecks) {
logmsg(LLVL_ERROR, "Resume file %s already exists, refusing to overwrite.\n", DEFAULT_RESUME_FILENAME);
abortProcess = true;
} else {
logmsg(LLVL_WARN, "Resume file %s already exists. Will be overwritten when process continues because safety checks have been disabled.\n", DEFAULT_RESUME_FILENAME);
}
}
if (doesFileExist(aParameters->keyFile)) {
if (aParameters->safetyChecks) {
logmsg(LLVL_ERROR, "Key file %s already exists, refusing to overwrite.\n", aParameters->keyFile);
abortProcess = true;
} else {
logmsg(LLVL_WARN, "Key file %s already exists. Will be overwritten when process continues because safety checks have been disabled.\n", aParameters->keyFile);
}
}
}
if (isBlockDeviceMounted(aParameters->rawDevice)) {
if (aParameters->safetyChecks) {
logmsg(LLVL_ERROR, "Raw block device %s appears to be mounted, refusing to continue.\n", aParameters->rawDevice);
abortProcess = true;
} else {
logmsg(LLVL_WARN, "Raw block device %s appears to be mounted, still continuing because safety checks have been disabled.\n", aParameters->rawDevice);
}
}
if (reluksification && isBlockDeviceMounted(aParameters->readDevice)) {
if (aParameters->safetyChecks) {
logmsg(LLVL_ERROR, "Unlocked read block device %s appears to be mounted, refusing to continue.\n", aParameters->readDevice);
abortProcess = true;
} else {
logmsg(LLVL_WARN, "Unlocked read block device %s appears to be mounted, still continuing because safety checks have been disabled.\n", aParameters->readDevice);
}
}
if (abortProcess) {
terminate(EC_PRECONDITIONS_NOT_SATISFIED);
}
}
static void askUserConfirmation(struct conversionParameters const *parameters) {
bool reluksification = strcmp(parameters->rawDevice, parameters->readDevice) != 0;
if (!parameters->batchMode) {
uint64_t devSize = getDiskSizeOfPath(parameters->rawDevice);
if (devSize == 0) {
logmsg(LLVL_ERROR, "%s: Cannot determine disk size.\n", parameters->rawDevice);
terminate(EC_UNABLE_TO_GET_RAW_DISK_SIZE);
}
fprintf(stderr, "WARNING! luksipc will perform the following actions:\n");
if (!reluksification) {
if (!parameters->resuming) {
fprintf(stderr, " => Normal LUKSification of plain device %s\n", parameters->rawDevice);
fprintf(stderr, " -> luksFormat will be performed on %s\n", parameters->rawDevice);
} else {
fprintf(stderr, " => Resume LUKSification of (partially encrypted) plain device %s\n", parameters->rawDevice);
fprintf(stderr, " -> Using the information in resume file %s\n", parameters->resumeFilename);
}
} else {
if (!parameters->resuming) {
fprintf(stderr, " => reLUKSification of LUKS device %s\n", parameters->rawDevice);
fprintf(stderr, " -> Which has been unlocked at %s\n", parameters->readDevice);
fprintf(stderr, " -> luksFormat will be performed on %s\n", parameters->rawDevice);
} else {
fprintf(stderr, " => Resume reLUKSification of (partially re-encrypted) LUKS device %s\n", parameters->rawDevice);
fprintf(stderr, " -> Which has been unlocked with the OLD key at %s\n", parameters->readDevice);
fprintf(stderr, " -> Using the information in resume file %s\n", parameters->resumeFilename);
}
}
fprintf(stderr, "\n");
fprintf(stderr, "Please confirm you have completed the checklist:\n");
int checkPoint = 0;
if (!parameters->resuming) {
printCheckListItem(&checkPoint, "You have resized the contained filesystem(s) appropriately\n");
printCheckListItem(&checkPoint, "You have unmounted any contained filesystem(s)\n");
printCheckListItem(&checkPoint, "You will ensure secure storage of the keyfile that will be generated at %s\n", parameters->keyFile);
} else {
printCheckListItem(&checkPoint, "The resume file %s belongs to the partially encrypted volume %s\n", parameters->resumeFilename, parameters->rawDevice);
}
printCheckListItem(&checkPoint, "Power conditions are satisfied (i.e. your laptop is not running off battery)\n");
if (!parameters->resuming) {
printCheckListItem(&checkPoint, "You have a backup of all important data on %s\n", parameters->rawDevice);
}
fprintf(stderr, "\n");
fprintf(stderr, " %s: %lu MiB = %.1f GiB\n", parameters->rawDevice, devSize / 1024 / 1024, (double)(devSize / 1024 / 1024) / 1024);
fprintf(stderr, " Chunk size: %u bytes = %.1f MiB\n", parameters->blocksize, (double)parameters->blocksize / 1024 / 1024);
fprintf(stderr, " Keyfile: %s\n", parameters->keyFile);
fprintf(stderr, " LUKS format parameters: %s\n", parameters->luksFormatParams ? parameters->luksFormatParams : "None given");
#ifdef DEVELOPMENT
if (parameters->dev.ioErrors) {
fprintf(stderr, " Simulating device I/O errors\n");
}
if (parameters->dev.slowDown) {
fprintf(stderr, " Simulating slow I/O device\n");
}
#endif
fprintf(stderr, "\n");
fprintf(stderr, "Are all these conditions satisfied, then answer uppercase yes: ");
char yes[16];
if (!fgets(yes, sizeof(yes) - 1, stdin)) {
perror("fgets");
terminate(EC_UNABLE_TO_READ_FROM_STDIN);
}
if (strcmp(yes, "YES\n")) {
fprintf(stderr, "Wrong answer. Aborting.\n");
terminate(EC_USER_ABORTED_PROCESS);
}
}
}
int main(int argc, char **argv) {
struct conversionParameters pgmParameters;
parseParameters(&pgmParameters, argc, argv);
/* Initialize internal PRNG */
if (!initPrng()) {
terminate(EC_PRNG_INITIALIZATION_FAILED);
}
/* Set loglevel to value given on command line */
setLogLevel(pgmParameters.logLevel);
/* Check if all preconditions are satisfied */
checkPreconditions(&pgmParameters);
/* Ask for user confirmation if necessary */
askUserConfirmation(&pgmParameters);
/* Then generate the keyfile if we're converting (not in resume mode) */
if (!pgmParameters.resuming) {
if (!genKeyfile(pgmParameters.keyFile, !pgmParameters.safetyChecks)) {
logmsg(LLVL_ERROR, "Key generation failed, aborting.\n");
terminate(EC_CANNOT_GENERATE_KEY_FILE);
}
}
/* Initialize signal handlers that will take care of abort */
if (!initSignalHandlers()) {
terminate(EC_CANNOT_INIT_SIGNAL_HANDLERS);
}
/* Then start the actual conversion */
convert(&pgmParameters);
return 0;
}
luksipc-0.04/luksipc.h 0000664 0000000 0000000 00000002111 12531634264 0014733 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#ifndef __LUKSIPC_H__
#define __LUKSIPC_H__
/*************** AUTO GENERATED SECTION FOLLOWS ***************/
int main(int argc, char **argv);
/*************** AUTO GENERATED SECTION ENDS ***************/
#endif
luksipc-0.04/mount.c 0000664 0000000 0000000 00000004224 12531634264 0014425 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include "mount.h"
#include "logging.h"
bool isBlockDeviceMounted(const char *aBlkDevice) {
FILE *f = fopen("/proc/mounts", "r");
struct mntent *entry;
bool isMounted = false;
struct stat blkDevStat;
if (stat(aBlkDevice, &blkDevStat) != 0) {
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));
return true;
}
while ((entry = getmntent(f)) != NULL) {
if (strcmp(entry->mnt_fsname, aBlkDevice) == 0) {
/* Names match, definitely mounted! */
logmsg(LLVL_DEBUG, "%s mounted at %s\n", aBlkDevice, entry->mnt_dir);
isMounted = true;
break;
}
if (strcmp(entry->mnt_fsname, "none")) {
/* Check major/minor number of device */
struct stat newDevStat;
if (stat(entry->mnt_fsname, &newDevStat) == 0) {
if (newDevStat.st_rdev == blkDevStat.st_rdev) {
/* Major/minor is identical */
logmsg(LLVL_DEBUG, "%s has identical struct stat.st_rdev with %s, mounted at %s\n", aBlkDevice, entry->mnt_fsname, entry->mnt_dir);
isMounted = true;
break;
}
}
}
}
fclose(f);
return isMounted;
}
luksipc-0.04/mount.h 0000664 0000000 0000000 00000002127 12531634264 0014432 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#ifndef __MOUNT_H__
#define __MOUNT_H__
/*************** AUTO GENERATED SECTION FOLLOWS ***************/
bool isBlockDeviceMounted(const char *aBlkDevice);
/*************** AUTO GENERATED SECTION ENDS ***************/
#endif
luksipc-0.04/parameters.c 0000664 0000000 0000000 00000032757 12531634264 0015442 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#include
#include
#include
#include
#include
#include
#include
#include "utils.h"
#include "logging.h"
#include "parameters.h"
#include "globals.h"
#include "exit.h"
static void defaultParameters(struct conversionParameters *aParams) {
memset(aParams, 0, sizeof(struct conversionParameters));
aParams->blocksize = 10 * 1024 * 1024;
aParams->safetyChecks = true;
aParams->batchMode = false;
aParams->keyFile = "/root/initial_keyfile.bin";
aParams->logLevel = LLVL_INFO;
aParams->backupFile = "header_backup.img";
aParams->resumeFilename = "resume.bin";
}
static void syntax(char **argv, const char *aMessage, enum terminationCode_t aExitCode) {
if (aMessage) {
fprintf(stderr, "Error: %s\n", aMessage);
fprintf(stderr, "\n");
}
fprintf(stderr, "luksipc: Tool to convert block devices to LUKS-encrypted block devices on the fly\n");
fprintf(stderr, "\n");
fprintf(stderr, "%s (-d, --device=RAWDEV) (--readdev=DEV) (-b, --blocksize=BYTES)\n", argv[0]);
fprintf(stderr, " (-c, --backupfile=FILE) (-k, --keyfile=FILE) (-p, --luksparam=PARAMS)\n");
fprintf(stderr, " (-l, --loglevel=LVL) (--resume) (--resume-file=FILE) (--no-seatbelt)\n");
fprintf(stderr, " (--i-know-what-im-doing) (-h, --help)\n");
fprintf(stderr, "\n");
fprintf(stderr, " -d, --device=RAWDEV Raw device that is about to be converted to LUKS. This is\n");
fprintf(stderr, " the device that luksFormat will be called on to create the\n");
fprintf(stderr, " new LUKS container. Mandatory argument.\n");
fprintf(stderr, " --readdev=DEV The device that the unencrypted data should be read from.\n");
fprintf(stderr, " This is only different from the raw device if the volume is\n");
fprintf(stderr, " already LUKS (or another container) and you want to\n");
fprintf(stderr, " reLUKSify it.\n");
fprintf(stderr, " -b, --blocksize=BYTES Specify block size for copying in bytes. Default (and\n");
fprintf(stderr, " minimum) size is 10 MiB (10485760 bytes). This value is\n");
fprintf(stderr, " rounded up to closest 4096-byte value automatically. It must\n");
fprintf(stderr, " be at least size of LUKS header (usually 2048 kiB, but may\n");
fprintf(stderr, " vary).\n");
fprintf(stderr, " -c, --backupfile=FILE Specify the file in which a header backup will be written.\n");
fprintf(stderr, " Essentially the header backup is a dump of the first 128 MiB\n");
fprintf(stderr, " of the raw device. By default this will be written to a file\n");
fprintf(stderr, " named backup.bin.\n");
fprintf(stderr, " -k, --keyfile=FILE Filename for the initial keyfile. A 4096 bytes long file\n");
fprintf(stderr, " will be generated under this location which has /dev/urandom\n");
fprintf(stderr, " as the input. It will be added as the first keyslot in the\n");
fprintf(stderr, " luksFormat process. If you put this file on a volatile\n");
fprintf(stderr, " device such as /dev/shm, remember that all your data is\n");
fprintf(stderr, " garbage after a reboot if you forget to add a second key to\n");
fprintf(stderr, " the LUKS keyring. The default filename is\n");
fprintf(stderr, " /root/initial_keyfile.bin. This file will always be created\n");
fprintf(stderr, " with 0o600 permissions.\n");
fprintf(stderr, " -p, --luksparam=PARAMS Pass these additional options to luksFormat, for example to\n");
fprintf(stderr, " select a different cipher. Parameters have to be passed\n");
fprintf(stderr, " comma-separated.\n");
fprintf(stderr, " -l, --loglevel=LVL Integer value that specifies the level of logging verbosity\n");
fprintf(stderr, " from 0 to 4 (critical, error, warn, info, debug). Default\n");
fprintf(stderr, " loglevel is 3 (info).\n");
fprintf(stderr, " --resume Resume a interrupted conversion with the help of a resume\n");
fprintf(stderr, " file. This file is generated when luksipc aborts, is by\n");
fprintf(stderr, " default called resume.bin (this can be changed by --resume-\n");
fprintf(stderr, " file).\n");
fprintf(stderr, " --resume-file=FILE Change the file name from which the resume information is\n");
fprintf(stderr, " read (when resuming a previously aborted conversion) and to\n");
fprintf(stderr, " which resume information is written (in the case of an\n");
fprintf(stderr, " abort). By default this will be resume.bin.\n");
fprintf(stderr, " --no-seatbelt Disable several safetly checks which are in place to keep\n");
fprintf(stderr, " you from losing data. You really need to know what you're\n");
fprintf(stderr, " doing if you use this.\n");
fprintf(stderr, " --i-know-what-im-doing Enable batch mode (will not ask any questions or\n");
fprintf(stderr, " confirmations interactively). Please note that you will have\n");
fprintf(stderr, " to perform any and all sanity checks by yourself if you use\n");
fprintf(stderr, " this option in order to avoid losing data.\n");
fprintf(stderr, " -h, --help Show this help screen.\n");
fprintf(stderr, "\n");
fprintf(stderr, "Examples:\n");
fprintf(stderr, " %s -d /dev/sda9\n", argv[0]);
fprintf(stderr, " Converts /dev/sda9 to a LUKS partition with default parameters.\n");
fprintf(stderr, " %s -d /dev/sda9 --resume-file myresume.dat\n", argv[0]);
fprintf(stderr, " Converts /dev/sda9 to a LUKS partition with default parameters and store resume\n");
fprintf(stderr, " information in myresume.dat in case of an abort.\n");
fprintf(stderr, " %s -d /dev/sda9 -k /root/secure_key/keyfile.bin --luksparams='-c,twofish-lrw-benbi,-s,320,-h,sha256'\n", argv[0]);
fprintf(stderr, " Converts /dev/sda9 to a LUKS partition and stores the initially used keyfile in\n");
fprintf(stderr, " /root/secure_key/keyfile.bin. Additionally some LUKS parameters are passed that\n");
fprintf(stderr, " specify that the Twofish cipher should be used with a 320 bit keysize and\n");
fprintf(stderr, " SHA-256 as a hash function.\n");
fprintf(stderr, " %s -d /dev/sda9 --resume --resume-file /root/resume.bin\n", argv[0]);
fprintf(stderr, " Resumes a crashed LUKS conversion of /dev/sda9 using the file /root/resume.bin\n");
fprintf(stderr, " which was generated at the first (crashed) luksipc run.\n");
fprintf(stderr, " %s -d /dev/sda9 --readdev /dev/mapper/oldluks\n", argv[0]);
fprintf(stderr, " Convert the raw device /dev/sda9, which is already a LUKS container, to a new\n");
fprintf(stderr, " LUKS container. For example, this can be used to change the encryption\n");
fprintf(stderr, " parameters of the LUKS container (different cipher) or to change the bulk\n");
fprintf(stderr, " encryption key. In this example the old container is unlocked and accessible\n");
fprintf(stderr, " under /dev/mapper/oldluks.\n");
fprintf(stderr, "\n");
fprintf(stderr, "luksipc version: " LUKSIPC_VERSION "\n");
#ifdef DEVELOPMENT
fprintf(stderr, "\n");
fprintf(stderr, "WARNING: You're using a development build of luksipc. This is not recommended\n");
fprintf(stderr, "unless you're actually doing software development of luksipc.\n");
fprintf(stderr, "\n");
fprintf(stderr, "Additional (undocumented) options for development release:\n");
fprintf(stderr, " --development-slowdown\n");
fprintf(stderr, " --development-ioerrors\n");
#endif
terminate(aExitCode);
}
static void checkParameters(char **argv, const struct conversionParameters *aParams) {
char errorMessage[256];
if (!aParams->readDevice) {
syntax(argv, "No device to convert was given on the command line", EC_CMDLINE_ARGUMENT_ERROR);
}
if ((aParams->luksFormatParams) && ((strlen(aParams->luksFormatParams) + 1) > MAX_ARGLENGTH)) {
snprintf(errorMessage, sizeof(errorMessage), "Length of LUKS format parameters exceeds maximum of %d.", MAX_ARGLENGTH);
syntax(argv, errorMessage, EC_CMDLINE_ARGUMENT_ERROR);
}
if (aParams->blocksize < MINBLOCKSIZE) {
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);
syntax(argv, errorMessage, EC_CMDLINE_ARGUMENT_ERROR);
}
if ((aParams->logLevel < 0) || (aParams->logLevel > LLVL_DEBUG)) {
snprintf(errorMessage, sizeof(errorMessage), "Loglevel needs to be inbetween 0 and %d, user specified %d.", LLVL_DEBUG, aParams->logLevel);
syntax(argv, errorMessage, EC_CMDLINE_ARGUMENT_ERROR);
}
}
enum longOnlyOptions_t {
OPT_IKNOWWHATIMDOING = 0x1000,
OPT_RESUME,
OPT_RESUME_FILE,
OPT_READDEVICE,
OPT_NOSEATBELT,
#ifdef DEVELOPMENT
OPT_DEV_IOERRORS,
OPT_DEV_SLOWDOWN
#endif
};
void parseParameters(struct conversionParameters *aParams, int argc, char **argv) {
struct option longOptions[] = {
{ "device", 1, NULL, 'd' },
{ "readdev", 1, NULL, OPT_READDEVICE },
{ "blocksize", 1, NULL, 'b' },
{ "backupfile", 1, NULL, 'c' },
{ "keyfile", 1, NULL, 'k' },
{ "luksparams", 1, NULL, 'p' },
{ "loglevel", 1, NULL, 'l' },
{ "resume", 0, NULL, OPT_RESUME },
{ "resume-file", 1, NULL, OPT_RESUME_FILE },
{ "no-seatbelt", 0, NULL, OPT_NOSEATBELT },
{ "i-know-what-im-doing", 0, NULL, OPT_IKNOWWHATIMDOING },
{ "i-know-what-im-doinx", 0, NULL, 'h' }, /* Do not allow abbreviation of --i-know-what-im-doing */
#ifdef DEVELOPMENT
{ "development-slowdown", 0, NULL, OPT_DEV_SLOWDOWN },
{ "development-slowdowx", 0, NULL, 'h' }, /* Do not allow abbreviation of --development-slowdown */
{ "development-ioerrors", 0, NULL, OPT_DEV_IOERRORS },
{ "development-ioerrorx", 0, NULL, 'h' }, /* Do not allow abbreviation of --development-ioerrors */
#endif
{ "help", 0, NULL, 'h' },
{ 0 }
};
int character;
defaultParameters(aParams);
while ((character = getopt_long(argc, argv, "hb:d:l:k:p:c:", longOptions, NULL)) != -1) {
switch (character) {
case 'd':
aParams->rawDevice = optarg;
break;
case OPT_READDEVICE:
aParams->readDevice = optarg;
break;
case 'b':
aParams->blocksize = atoi(optarg);
break;
case 'c':
aParams->backupFile = optarg;
break;
case 'k':
aParams->keyFile = optarg;
break;
case 'p':
aParams->luksFormatParams = optarg;
break;
case 'l': {
char *endPtr = NULL;
aParams->logLevel = strtol(optarg, &endPtr, 10);
if ((endPtr == NULL) || (*endPtr != 0)) {
fprintf(stderr, "Error: Cannot convert the value '%s' you passed as a log level (must be an integer).\n", optarg);
terminate(EC_CMDLINE_ARGUMENT_ERROR);
}
if ((aParams->logLevel < 0) || (aParams->logLevel > 4)) {
fprintf(stderr, "Error: Log level must be between 0 and 4.\n");
terminate(EC_CMDLINE_ARGUMENT_ERROR);
}
break;
}
case OPT_RESUME:
aParams->resuming = true;
break;
case OPT_RESUME_FILE:
aParams->resumeFilename = optarg;
break;
case OPT_NOSEATBELT:
aParams->safetyChecks = false;
break;
case OPT_IKNOWWHATIMDOING:
aParams->batchMode = true;
break;
#ifdef DEVELOPMENT
case OPT_DEV_IOERRORS:
aParams->dev.ioErrors = true;
break;
case OPT_DEV_SLOWDOWN:
aParams->dev.slowDown = true;
break;
#endif
case '?':
fprintf(stderr, "\n");
case 'h':
syntax(argv, NULL, EC_SUCCESS);
break;
default:
fprintf(stderr, "Error: Lazy programmer caused bug in getopt parsing (character 0x%x = '%c').\n", character, character);
terminate(EC_CMDLINE_PARSING_ERROR);
}
}
/* Round up block size to 4096 bytes multiple */
aParams->blocksize = ((aParams->blocksize + 4095) / 4096) * 4096;
/* If read device is not set, we're not doing reLUKSification (i.e. read
* device = raw device) */
if (!aParams->readDevice) {
aParams->readDevice = aParams->rawDevice;
} else {
aParams->reluksification = true;
}
checkParameters(argv, aParams);
}
luksipc-0.04/parameters.h 0000664 0000000 0000000 00000003770 12531634264 0015440 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#ifndef __PARAMETERS_H__
#define __PARAMETERS_H__
#include
#define MINBLOCKSIZE (1024 * 1024 * 10)
struct conversionParameters {
int blocksize;
const char *rawDevice; /* Partition that the actual LUKS is created on (e.g. /dev/sda9) */
const char *readDevice; /* Partition that data is read from (for initial conversion idential to rawDevice, but for reLUKSification maybe /dev/mapper/oldluks) */
const char *keyFile;
const char *luksFormatParams;
bool resuming; /* Should the process resume using the given file? */
const char *resumeFilename; /* Use this file for storing resume data */
const char *backupFile; /* File in which header backup is written before luksFormat */
bool batchMode;
bool safetyChecks;
int logLevel;
bool reluksification;
#ifdef DEVELOPMENT
struct {
bool slowDown; /* Simulate slow devices */
bool ioErrors; /* Simulate I/O errors */
} dev;
#endif
};
/*************** AUTO GENERATED SECTION FOLLOWS ***************/
void parseParameters(struct conversionParameters *aParams, int argc, char **argv);
/*************** AUTO GENERATED SECTION ENDS ***************/
#endif
luksipc-0.04/random.c 0000664 0000000 0000000 00000005012 12531634264 0014537 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#include
#include
#include
#include
#include
#include "random.h"
#include "logging.h"
static uint64_t xorShiftState = 0x135b78d8e29a4d5c;
/* Marsaglia Xorshift PRNG */
static uint64_t xorShift64(uint64_t x) {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
return x;
}
/* This is only used for testing luksipc and is not cryptographically safe in
* any way. It uses the internal PRNG */
bool randomEvent(uint32_t aOneIn) {
xorShiftState = xorShift64(xorShiftState);
return (xorShiftState % aOneIn) == 0;
}
bool readRandomData(void *aData, uint32_t aLength) {
const char *randomDevice = "/dev/urandom";
FILE *f = fopen(randomDevice, "rb");
if (!f) {
logmsg(LLVL_ERROR, "Error opening %s for reading entropy: %s\n", randomDevice, strerror(errno));
return false;
}
if (fread(aData, aLength, 1, f) != 1) {
logmsg(LLVL_ERROR, "Short read from %s for reading entropy: %s\n", randomDevice, strerror(errno));
fclose(f);
return false;
}
fclose(f);
return true;
}
bool randomHexStrCat(char *aString, int aByteLen) {
/* Generate hex data */
uint8_t rnd[aByteLen];
if (!readRandomData(rnd, aByteLen)) {
logmsg(LLVL_ERROR, "Cannot generate randomized hex tag.\n");
return false;
}
/* Walk string until the end */
aString = aString + strlen(aString);
/* Then append hex data there */
for (int i = 0; i < aByteLen; i++) {
sprintf(aString, "%02x", rnd[i]);
aString += 2;
}
return true;
}
bool initPrng(void) {
uint64_t xorValue;
if (!readRandomData(&xorValue, sizeof(xorValue))) {
logmsg(LLVL_ERROR, "Failed to seed internal PRNG.\n");
return false;
}
xorShiftState ^= xorValue;
return true;
}
luksipc-0.04/random.h 0000664 0000000 0000000 00000002357 12531634264 0014555 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#ifndef __RANDOM_H__
#define __RANDOM_H__
#include
#include
/*************** AUTO GENERATED SECTION FOLLOWS ***************/
bool randomEvent(uint32_t aOneIn);
bool readRandomData(void *aData, uint32_t aLength);
bool randomHexStrCat(char *aString, int aByteLen);
bool initPrng(void);
/*************** AUTO GENERATED SECTION ENDS ***************/
#endif
luksipc-0.04/shutdown.c 0000664 0000000 0000000 00000003712 12531634264 0015137 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#include
#include
#include
#include
#include
#include
#include "logging.h"
#include "shutdown.h"
static volatile bool quit = false;
static void signalInterrupt(int aSignal) {
(void)aSignal;
quit = true;
logmsg(LLVL_CRITICAL, "Shutdown requested by user interrupt, please be patient...\n");
}
bool receivedSigQuit(void) {
return quit;
}
void issueSigQuit(void) {
quit = true;
}
bool initSignalHandlers(void) {
struct sigaction action;
memset(&action, 0, sizeof(struct sigaction));
action.sa_handler = signalInterrupt;
sigemptyset(&action.sa_mask);
action.sa_flags = SA_RESTART;
if (sigaction(SIGINT, &action, NULL) == -1) {
fprintf(stderr, "Could not install SIGINT handler: %s\n", strerror(errno));
return false;
}
if (sigaction(SIGTERM, &action, NULL) == -1) {
fprintf(stderr, "Could not install SIGTERM handler: %s\n", strerror(errno));
return false;
}
if (sigaction(SIGHUP, &action, NULL) == -1) {
fprintf(stderr, "Could not install SIGHUP handler: %s\n", strerror(errno));
return false;
}
return true;
}
luksipc-0.04/shutdown.h 0000664 0000000 0000000 00000002224 12531634264 0015141 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#ifndef __SHUTDOWN_H__
#define __SHUTDOWN_H__
#include
/*************** AUTO GENERATED SECTION FOLLOWS ***************/
bool receivedSigQuit(void);
void issueSigQuit(void);
bool initSignalHandlers(void);
/*************** AUTO GENERATED SECTION ENDS ***************/
#endif
luksipc-0.04/tests/ 0000775 0000000 0000000 00000000000 12531634264 0014257 5 ustar 00root root 0000000 0000000 luksipc-0.04/tests/CornercaseTests.py 0000664 0000000 0000000 00000000643 12531634264 0017743 0 ustar 00root root 0000000 0000000 import random
from TestEngine import LUKSIPCTest
class LargeHeaderLUKSIPCTest(LUKSIPCTest):
def run(self):
luks_header_sectors = 9999
luks_header_bytes = luks_header_sectors * 512
params = self.prepare_device(luks_header_bytes)
self._assert(self._engine.luksify(additional_params = [ "--luksparams=--align-payload=%d" % (luks_header_sectors) ]) == 0, "LUKSification failed")
self.verify_container(params)
luksipc-0.04/tests/ReLUKSTests.py 0000664 0000000 0000000 00000004222 12531634264 0016721 0 ustar 00root root 0000000 0000000 import random
from TestEngine import LUKSIPCTest
class SimpleReLUKSIPCBaseTest(LUKSIPCTest):
def run(self):
params = self.prepare_luksdevice(self.luksformat_params)
container = self._engine.luksOpen()
try:
# Now reluksify the opened container
self._engine.cleanup_files()
self._assert(self._engine.luksify(unlockedcontainer = container) == 0, "LUKSification failed")
finally:
self._engine.luksClose(container)
self.verify_container(params)
class SimpleReLUKSIPCTest1(SimpleReLUKSIPCBaseTest):
def run(self):
self.luksformat_params = [ ]
SimpleReLUKSIPCBaseTest.run(self)
class SimpleReLUKSIPCTest2(LUKSIPCTest):
def run(self):
self.luksformat_params = [ "-c", "twofish-lrw-benbi", "-s", "320", "-h", "sha256" ]
SimpleReLUKSIPCBaseTest.run(self)
class AbortedReLUKSIPCTest(LUKSIPCTest):
def run(self):
params = self.prepare_luksdevice()
container = self._engine.luksOpen()
try:
# Now reluksify the opened container
self._engine.cleanup_files()
returncode = self._engine.luksify(unlockedcontainer = container, abort = 20)
self._engine.verify_hdrbackup_file(params.backup_header_hash)
while returncode == 2:
returncode = self._engine.luksify(unlockedcontainer = container, abort = random.randint(10, 60), resume = True)
self._engine.verify_hdrbackup_file(params.backup_header_hash)
finally:
self._engine.luksClose(container)
self.verify_container(params)
class IOErrorReLUKSIPCTest(LUKSIPCTest):
def run(self):
params = self.prepare_luksdevice()
container = self._engine.luksOpen()
try:
# Now reluksify the opened container
self._engine.cleanup_files()
returncode = self._engine.luksify(unlockedcontainer = container, additional_params = [ "--development-ioerrors" ], success_codes = [ 0, 2 ])
self._engine.verify_hdrbackup_file(params.backup_header_hash)
while returncode == 2:
returncode = self._engine.luksify(unlockedcontainer = container, resume = True, additional_params = [ "--development-ioerrors" ], success_codes = [ 0, 2 ])
self._engine.verify_hdrbackup_file(params.backup_header_hash)
finally:
self._engine.luksClose(container)
self.verify_container(params)
luksipc-0.04/tests/SimpleTests.py 0000664 0000000 0000000 00000002227 12531634264 0017110 0 ustar 00root root 0000000 0000000 import random
from TestEngine import LUKSIPCTest
class SimpleLUKSIPCTest(LUKSIPCTest):
def run(self):
params = self.prepare_device()
self._assert(self._engine.luksify() == 0, "LUKSification failed")
self.verify_container(params)
class AbortedLUKSIPCTest(LUKSIPCTest):
def run(self):
params = self.prepare_device()
returncode = self._engine.luksify(abort = 20)
self._engine.verify_hdrbackup_file(params.backup_header_hash)
while returncode == 2:
returncode = self._engine.luksify(abort = random.randint(10, 60), resume = True)
self._engine.verify_hdrbackup_file(params.backup_header_hash)
self.verify_container(params)
class IOErrorLUKSIPCTest(LUKSIPCTest):
def run(self):
params = self.prepare_device()
returncode = self._engine.luksify(additional_params = [ "--development-ioerrors" ], success_codes = [ 0, 2 ])
self._engine.verify_hdrbackup_file(params.backup_header_hash)
while returncode == 2:
returncode = self._engine.luksify(resume = True, additional_params = [ "--development-ioerrors" ], success_codes = [ 0, 2 ])
self._engine.verify_hdrbackup_file(params.backup_header_hash)
self.verify_container(params)
luksipc-0.04/tests/TestEngine.py 0000664 0000000 0000000 00000035516 12531634264 0016710 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import os
import subprocess
import hashlib
import collections
import random
import string
import signal
import time
import sys
import datetime
_DEFAULTS = {
"hdrbackup_file": "data/backup.img",
"resume_file": "data/resume.bin",
"key_file": "data/keyfile.bin",
}
class LUKSIPCTest(object):
_PreTestParameters = collections.namedtuple("PreTestParameters", [ "seed", "plain_data_hash", "backup_header_hash", "source", "expected_sizediff", "devsize_pre", "devsize_post" ])
def __init__(self, testengine, assumptions):
self._engine = testengine
self._assumptions = assumptions
def __getitem__(self, key):
return self._assumptions[key]
def run(self):
raise Exception(NotImplemented)
def prepare_device(self, expected_sizediff = None):
"""Prepare a plain device (no LUKS) with a PRNG pattern. Hash the
device excluding the trailing part that is going to be cut away by
LUKSification and also hash the part that is going to be in the header
backup (128 MiB). Typically called to test LUKSification."""
if expected_sizediff is None:
expected_sizediff = -self["default_luks_hdr_size"]
devsize_pre = self._engine.rawdevsize
devsize_post = devsize_pre + expected_sizediff
seed = random.randint(0, 0xffffffff)
plain_data_hash = self._engine.patternize_rawdev(exclude_bytes, seed)
backup_header_hash = self._engine.hash_rawdev(total_size = self["default_backup_hdr_size"])
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)
def prepare_luksdevice(self, luksformat_params = None, expected_sizediff = 0):
"""Prepare a LUKS device and fill the plain part of the device with a
PRNG pattern. Hash the whole plain data of the LUKS device container
(unlocked) and hash the part of the raw device that is going to end up
in the header backup (128 MiB). Typically called to test
reLUKSification."""
if luksformat_params is None:
luksformat_params = [ ]
seed = random.randint(0, 0xffffffff)
self._engine.luksFormat(luksformat_params)
try:
container = self._engine.luksOpen()
devsize_pre = self._engine._getsizeof(container.unlockedblkdev)
plain_data_hash = self._engine.patternize_device(container.unlockedblkdev, seed = seed)
finally:
self._engine.luksClose(container)
devsize_post = devsize_pre + expected_sizediff
backup_header_hash = self._engine.hash_rawdev(total_size = self["default_backup_hdr_size"])
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)
def verify_container(self, pretestparams):
"""Verify the container integrity against the parameters that were
determined at generation from the prepare_xyz() function by checking
the MD5SUM of the (unlocked) device."""
self._engine.verify_file(_DEFAULTS["hdrbackup_file"], pretestparams.backup_header_hash)
# Verify initial luksification worked by decrypting and verifying hash
container = self._engine.luksOpen()
try:
self._engine.verify_device(container.unlockedblkdev, pretestparams.plain_data_hash)
finally:
self._engine.luksClose(container)
def _assert(self, cond, msg):
if not cond:
raise Exception("Assertion failed: %s" % (msg))
class TestEngine(object):
_OpenLUKSContainer = collections.namedtuple("OpenLUKSContainer", [ "rawdatablkdev", "unlockedblkdev", "keyfile", "dmname" ])
def __init__(self, destroy_data_dev, luksipc_binary, logdir, additional_params):
self._destroy_dev = destroy_data_dev
self._luksipc_bin = luksipc_binary
self._logdir = logdir
if not self._logdir.endswith("/"):
self._logdir += "/"
try:
os.makedirs(self._logdir)
except FileExistsError:
pass
try:
os.makedirs("data/")
except FileExistsError:
pass
self._patternizer_bin = "prng/prng_crc64"
self._rawdevsize = self._getsizeof(self._destroy_dev)
self._total_log = open(self._logdir + "summary.txt", "a")
self._lastlogfile = self._get_lastlogfile()
self._additional_params = additional_params
self._kill_list = set()
try:
for line in open("kill_list.txt"):
line = line.rstrip("\r\n").strip()
if line.startswith("#") or line.startswith(";"):
continue
if line == "":
continue
self._kill_list.add(line)
except FileNotFoundError:
print("Warning: no kill list found.")
if self._destroy_dev not in self._kill_list:
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.")
def _log(self, msg):
msg = "%s: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), msg)
print(msg)
print(msg, file = self._total_log)
self._total_log.flush()
def _get_lastlogfile(self):
lastlog = 0
for filename in os.listdir(self._logdir):
if not filename.endswith(".log"):
continue
lastlog = max(int(filename[:-4]), lastlog)
return lastlog
@property
def rawdevsize(self):
return self._rawdevsize
@staticmethod
def _randstr(length):
return "".join(random.choice(string.ascii_lowercase) for i in range(length))
@staticmethod
def _getsizeof(blkdev):
f = open(blkdev, "rb")
f.seek(0, os.SEEK_END)
devsize = f.tell()
f.close()
return devsize
def _get_log_file(self, purpose):
self._lastlogfile += 1
filename = "%s%04d.log" % (self._logdir, self._lastlogfile)
f = open(filename, "w")
print("%s" % (purpose), file = f)
print("=" * 120, file = f)
self._log("Execute: %s -> %s" % (purpose, filename))
f.flush()
return f
def hash_device(self, blkdevname, exclude_bytes = 0, total_size = None):
if total_size is not None:
hash_length = total_size
else:
hash_length = self._getsizeof(blkdevname) - exclude_bytes
assert(hash_length >= 0)
f = open(blkdevname, "rb")
datahash = hashlib.md5()
remaining = hash_length
while remaining > 0:
if remaining > 1024 * 1024:
data = f.read(1024 * 1024)
else:
data = f.read(remaining)
datahash.update(data)
if len(data) == 0:
break
remaining -= len(data)
datahash = datahash.hexdigest()
self._log("Hash device %s (length %d): %s" % (blkdevname, hash_length, datahash))
f.close()
return datahash
def hash_rawdev(self, exclude_bytes = 0, total_size = None):
return self.hash_device(self._destroy_dev, exclude_bytes, total_size)
def verify_device(self, blkdevname, expect_hash, exclude_bytes = 0, total_size = None):
self._log("Verification of hash of block device %s" % (blkdevname))
calc_hash = self.hash_device(blkdevname, exclude_bytes, total_size)
if calc_hash == expect_hash:
self._log("PASS: '%s' has the correct hash value (%s)." % (blkdevname, expect_hash))
else:
msg = "FAIL: %s is supposed to have hash %s, but had hash %s." % (blkdevname, expect_hash, calc_hash)
self._log(msg)
raise Exception(msg)
def verify_file(self, filename, expect_hash):
self._log("Verification of hash of file %s" % (filename))
f = open(filename, "rb")
datahash = hashlib.md5()
while True:
data = f.read(1024 * 1024)
if len(data) == 0:
break
datahash.update(data)
f.close()
calc_hash = datahash.hexdigest()
if calc_hash == expect_hash:
self._log("PASS: '%s' has the correct hash value (%s)." % (filename, expect_hash))
else:
msg = "FAIL: %s is supposed to have hash %s, but had hash %s." % (filename, expect_hash, calc_hash)
self._log(msg)
raise Exception(msg)
def verify_hdrbackup_file(self, expect_hash):
return self.verify_file(_DEFAULTS["hdrbackup_file"], expect_hash)
def scrub_device(self):
self._log("Scrubbing raw device")
self._execute_sync([ "dd", "if=/dev/zero", "of=" + self._destroy_dev, "bs=1M" ], success_codes = [ 1 ])
def scrub_device_hdr(self):
self._log("Scrubbing raw device header")
self._execute_sync([ "dd", "if=/dev/zero", "of=" + self._destroy_dev, "bs=1M", "count=10" ])
def patternize_device(self, device, exclude_bytes = 0, seed = 0):
pattern_size = self._getsizeof(device) - exclude_bytes
self._log("Patternizing %s with seed %d for %d bytes (%.1f MiB)" % (device, seed, pattern_size, pattern_size / 1024 / 1024))
assert(pattern_size > 0)
proc = subprocess.Popen([ self._patternizer_bin, str(pattern_size), str(seed) ], stdout = subprocess.PIPE)
datahash = hashlib.md5()
outfile = open(device, "wb")
while True:
data = proc.stdout.read(1024 * 1024)
datahash.update(data)
outfile.write(data)
if len(data) == 0:
break
outfile.close()
datahash = datahash.hexdigest()
self._log("Patternized %s (excluded %d): %s" % (device, exclude_bytes, datahash))
return datahash
def patternize_rawdev(self, exclude_bytes = 0, seed = 0):
return self.patternize_device(self._destroy_dev, exclude_bytes = exclude_bytes, seed = seed)
def _execute_sync(self, cmd, **kwargs):
success_codes = kwargs.get("success_codes", [ 0 ])
cmd_str = " ".join(cmd)
logfile = self._get_log_file(cmd_str)
proc = subprocess.Popen(cmd, stdout = logfile, stderr = logfile)
if "abort" in kwargs:
time.sleep(kwargs["abort"])
os.kill(proc.pid, signal.SIGHUP)
proc.wait()
logfile.flush()
print("=" * 120, file = logfile)
print("Process returned with returncode %d" % (proc.returncode), file = logfile)
returncode = proc.returncode
if proc.returncode not in success_codes:
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) ))
self._log(failmsg)
raise Exception(failmsg)
return returncode
def cleanup_files(self):
self._log("Cleanup all files")
for filename in [ _DEFAULTS["hdrbackup_file"], _DEFAULTS["key_file"], _DEFAULTS["resume_file"] ]:
try:
os.unlink(filename)
except FileNotFoundError:
pass
def luksify(self, **kwargs):
self._log("Luksification (parameters: %s)" % (str(kwargs)))
cmd = [ self._luksipc_bin ]
cmd += [ "-d", self._destroy_dev ]
cmd += [ "-l", "4", ]
cmd += [ "--i-know-what-im-doing" ]
cmd += [ "--keyfile", _DEFAULTS["key_file"] ]
cmd += [ "--backupfile", _DEFAULTS["hdrbackup_file"] ]
cmd += [ "--resume-file", _DEFAULTS["resume_file"] ]
if "resume" in kwargs:
cmd += [ "--resume" ]
if "unlockedcontainer" in kwargs:
cmd += [ "--readdev", kwargs["unlockedcontainer"].unlockedblkdev ]
cmd += self._additional_params
if "additional_params" in kwargs:
cmd += kwargs["additional_params"]
if "success_codes" in kwargs:
success_codes = kwargs["success_codes"]
else:
if "abort" not in kwargs:
success_codes = [ 0 ]
else:
success_codes = [ 0, 2 ]
if "abort" not in kwargs:
return self._execute_sync(cmd, success_codes = success_codes)
else:
return self._execute_sync(cmd, abort = kwargs["abort"], success_codes = success_codes)
def luksOpen(self):
dmname = self._randstr(8)
cmd = [ "cryptsetup", "luksOpen", self._destroy_dev, dmname, "-d", _DEFAULTS["key_file"] ]
self._execute_sync(cmd)
return self._OpenLUKSContainer(rawdatablkdev = self._destroy_dev, dmname = dmname, keyfile = _DEFAULTS["key_file"], unlockedblkdev = "/dev/mapper/" + dmname)
def luksClose(self, openlukscontainer):
self._execute_sync([ "cryptsetup", "luksClose", openlukscontainer.dmname ])
def luksFormat(self, params = None):
if params is None:
params = [ ]
open(_DEFAULTS["key_file"], "w").write(self._randstr(32))
self._execute_sync([ "cryptsetup", "luksFormat", "-q", "--key-file", _DEFAULTS["key_file"] ] + params + [ self._destroy_dev ])
def new_testcase(self, tcname):
self._log(("=" * 60) + " " + tcname + " " + ("=" * 60))
def finished_testcase(self, tcname, verdict):
self._log(("=" * 60) + " " + tcname + " " + verdict + " " + ("=" * 60))
def setup_loopdev(self, ldsize):
assert(self._destroy_dev.startswith("/dev/loop"))
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))
ldbase = "/dev/shm/loopy"
fullmegs = (ldsize + (1024 * 1024) - 1) // (1024 * 1024)
self._execute_sync([ "losetup", "-d", self._destroy_dev ], success_codes = [ 0, 1 ])
self._execute_sync([ "dd", "if=/dev/zero", "of=%s" % (ldbase), "bs=1M", "count=%d" % (fullmegs) ])
# Then truncate loopy file
f = open(ldbase, "r+")
f.truncate(ldsize)
f.close()
# Then attach loop device again
self._execute_sync([ "losetup", self._destroy_dev, ldbase ])
self._rawdevsize = self._getsizeof(self._destroy_dev)
if __name__ == "__main__":
print("Please check code first!")
sys.exit(1)
# teng = TestEngine(destroy_data_dev = "/dev/loop0", luksipc_binary = "../luksipc", logdir = "logs/")
# teng.setup_loopdev(543 * 1024 * 1024)
teng = TestEngine(destroy_data_dev = "/dev/sdh1", luksipc_binary = "../luksipc", logdir = "logs/")
expected_lukshdr_len = 4096 * 512
conversion_parameters = {
"filltype": ("prng_rnd", ),
# "filltype": ("prng_constant", 123456),
# "filltype": ("zero", ),
}
for iteration in range(10):
teng.new_testcase("basic")
teng.cleanup_files()
teng.scrub_device_hdr()
if conversion_parameters["filltype"][0] == "prng_rnd":
seed = random.randint(0, 0xffffffff)
plain_datahash = teng.patternize_rawdev(expected_lukshdr_len, seed)
elif conversion_parameters["filltype"][0] == "prng_constant":
seed = conversion_parameters["filltype"][1]
plain_datahash = teng.patternize_rawdev(expected_lukshdr_len, seed)
else:
teng.scrub_device()
plain_datahash = teng.hash_rawdev(expected_lukshdr_len)
header_hash = teng.hash_rawdev(total_size = 128 * 1024 * 1024)
# Luksify with abort
returncode = teng.luksify(abort = 15)
teng.verify_file(_DEFAULTS["hdrbackup_file"], header_hash)
while returncode == 2:
# Resume luksification
returncode = teng.luksify(resume = _DEFAULTS["resume_file"], abort = random.randint(20, 50))
teng.verify_file(_DEFAULTS["hdrbackup_file"], header_hash)
# Verify initial luksification worked
container = teng.luksOpen()
try:
teng.verify_device(container.unlockedblkdev, plain_datahash)
finally:
teng.luksClose(container)
# Reluksify
header_hash = teng.hash_rawdev(total_size = 128 * 1024 * 1024)
container = teng.luksOpen()
try:
# Now reluksify
teng.cleanup_files()
returncode = teng.luksify(unlockedcontainer = container, abort = 15)
teng.verify_file(_DEFAULTS["hdrbackup_file"], header_hash)
while returncode == 2:
# Resume reluksification
returncode = teng.luksify(unlockedcontainer = container, resume = _DEFAULTS["resume_file"], abort = random.randint(20, 50))
teng.verify_file(_DEFAULTS["hdrbackup_file"], header_hash)
finally:
teng.luksClose(container)
# And verify again
container = teng.luksOpen()
try:
teng.verify_device(container.unlockedblkdev, plain_datahash)
finally:
teng.luksClose(container)
luksipc-0.04/tests/kill_list.txt 0000664 0000000 0000000 00000000211 12531634264 0017000 0 ustar 00root root 0000000 0000000 # This list contains all devices that may be used during testing (and which
# will be overwritten in the process)
#/dev/loop0
#/dev/sdh1
luksipc-0.04/tests/mkflakey 0000775 0000000 0000000 00000002450 12531634264 0016011 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import os
import sys
import subprocess
import random
if len(sys.argv) == 1:
print("%s [Blockdevice]" % (sys.argv[0]))
print()
print("Create a flakey device mapper alias for given block device as /dev/mapper/flakey.")
sys.exit(1)
def getdevsize(devname):
f = open(devname, "rb")
f.seek(0, os.SEEK_END)
devsize = f.tell()
f.close()
return devsize
devname = sys.argv[1]
subprocess.call([ "dmsetup", "remove", "flakey" ], stdout = subprocess.PIPE, stderr = subprocess.PIPE)
devsize = getdevsize(devname)
devsize_sects = devsize // 512
error_begin_sect = random.randint(0, devsize_sects - 1) // 4 * 4
error_sect_length = random.randint(1, 10) * 4
print("Error region: %d len %d" % (error_begin_sect, error_sect_length))
after_err_begin = error_begin_sect + error_sect_length
after_err_length = devsize_sects - after_err_begin
tblfile = open("tmp_table.txt", "w")
print("0 %d linear %s 0" % (error_begin_sect, devname), file = tblfile)
print("%d %d error" % (error_begin_sect, error_sect_length), file = tblfile)
print("%d %d linear %s %d" % (after_err_begin, after_err_length, devname, after_err_begin), file = tblfile)
tblfile.close()
subprocess.check_call([ "dmsetup", "create", "flakey", "tmp_table.txt" ], stdout = subprocess.PIPE, stderr = subprocess.PIPE)
os.unlink("tmp_table.txt")
luksipc-0.04/tests/prng/ 0000775 0000000 0000000 00000000000 12531634264 0015225 5 ustar 00root root 0000000 0000000 luksipc-0.04/tests/prng/Makefile 0000664 0000000 0000000 00000000652 12531634264 0016670 0 ustar 00root root 0000000 0000000 .PHONY: all clean
CC := gcc
CFLAGS := -Wall -Wextra -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -std=c11 -Wall -O3
LDFLAGS :=
OBJS := prng_crc64.o
all: prng_crc64
clean:
rm -f $(OBJS) prng_crc64
test: all
./prng_crc64 123456789
valgrind: all
valgrind --leak-check=yes ./prng_crc64
prng_crc64: $(OBJS)
$(CC) $(CFLAGS) $(LDFLAGS) -o $(@) $(OBJS)
.c.o:
$(CC) $(CFLAGS) -c -o $@ $<
luksipc-0.04/tests/prng/prng_crc64.c 0000664 0000000 0000000 00000003050 12531634264 0017336 0 ustar 00root root 0000000 0000000 #include
#include
#include
#include
#define staticassert(cond) _Static_assert(cond, #cond)
#define BLOCK_WORDCNT 32768
#define BLOCK_BYTECNT (BLOCK_WORDCNT * (int)sizeof(uint64_t))
const uint64_t polynomial = 0xc96c5795d7870f42; // ECMA-182
uint64_t intState = 0xb55dd361fcaa9779;
staticassert(sizeof(long) == 8);
static uint64_t nextValue(void) {
for (int i = 0; i < 2; i++) {
if (intState & 1) {
intState = (intState >> 1) ^ polynomial;
} else {
intState = (intState >> 1);
}
}
return intState;
}
int main(int argc, char **argv) {
if (argc < 2) {
fprintf(stderr, "%s [Bytecount] [(Seed)]\n", argv[0]);
exit(EXIT_FAILURE);
}
int64_t byteCount = atol(argv[1]);
if (byteCount < 0) {
fprintf(stderr, "Bytecount must be nonnegative.\n");
exit(EXIT_FAILURE);
}
if (byteCount == 0) {
byteCount = ((int64_t)1 << 62);
}
if (argc >= 3) {
intState ^= atol(argv[2]);
}
/* Complete blocks first */
{
uint64_t bufferBlock[BLOCK_WORDCNT];
for (int64_t i = 0; i < byteCount / BLOCK_BYTECNT; i++) {
for (int j = 0; j < BLOCK_WORDCNT; j++) {
bufferBlock[j] = nextValue();
}
fwrite(bufferBlock, BLOCK_BYTECNT, 1, stdout);
}
byteCount %= BLOCK_BYTECNT;
}
/* Complete words afterwards */
for (int64_t i = 0; i < byteCount / 8; i++) {
uint64_t state = nextValue();
(void)fwrite(&state, 8, 1, stdout);
}
/* Then last bytes */
uint64_t state = nextValue();
for (int i = 0; i < byteCount % 8; i++) {
(void)fwrite(&state, 1, 1, stdout);
state >>= 8;
}
return 0;
}
luksipc-0.04/tests/rmdm 0000775 0000000 0000000 00000000446 12531634264 0015150 0 ustar 00root root 0000000 0000000 #!/bin/bash
#
#
remove_all() {
ANY_SUCCESS="0"
for name in /dev/mapper/*; do
dmsetup remove "$name" >/dev/null 2>&1
if [ "$?" == "0" ]; then
ANY_SUCCESS="1"
fi
done
return $ANY_SUCCESS
}
while true; do
remove_all
success="$?"
if [ "$success" == "0" ]; then
break
fi
done
luksipc-0.04/tests/runtests 0000775 0000000 0000000 00000002710 12531634264 0016074 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import traceback
from SimpleTests import SimpleLUKSIPCTest, AbortedLUKSIPCTest, IOErrorLUKSIPCTest
from ReLUKSTests import SimpleReLUKSIPCTest1, SimpleReLUKSIPCTest2, AbortedReLUKSIPCTest, IOErrorReLUKSIPCTest
from CornercaseTests import LargeHeaderLUKSIPCTest
from TestEngine import TestEngine
test_classes = [
# SimpleLUKSIPCTest,
# AbortedLUKSIPCTest,
# IOErrorLUKSIPCTest,
# SimpleReLUKSIPCTest1,
# SimpleReLUKSIPCTest2,
# AbortedReLUKSIPCTest,
# IOErrorReLUKSIPCTest,
LargeHeaderLUKSIPCTest,
]
assumptions = {
"default_luks_hdr_size": 2048 * 1024,
"default_backup_hdr_size": 128 * 1024 * 1024,
}
#device = "/dev/sdh1"
device = "/dev/loop0"
#additional_params = [ "--development-slowdown" ]
additional_params = [ ]
engine = TestEngine(destroy_data_dev = device, luksipc_binary = "../luksipc", logdir = "logs/", additional_params = additional_params)
pass_cnt = 0
fail_cnt = 0
for test_class in test_classes:
test_name = test_class.__name__
engine.new_testcase(test_name)
test_passed = True
try:
engine.cleanup_files()
engine.scrub_device_hdr()
test_instance = test_class(testengine = engine, assumptions = assumptions)
test_instance.run()
except Exception as e:
test_passed = False
traceback.print_exc()
if test_passed:
pass_cnt += 1
engine.finished_testcase(test_name, "PASSED")
else:
fail_cnt += 1
engine.finished_testcase(test_name, "FAILED")
engine._log("Finished testcases: %d PASS, %d FAIL" % (pass_cnt, fail_cnt))
luksipc-0.04/utils.c 0000664 0000000 0000000 00000004312 12531634264 0014421 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "utils.h"
#include "logging.h"
bool safestrcpy(char *aDest, const char *aSrc, size_t aDestArraySize) {
bool success = true;
size_t srcLen = strlen(aSrc);
if ((srcLen + 1) > aDestArraySize) {
/* String does not fit, copy best effort */
memcpy(aDest, aSrc, aDestArraySize - 1);
success = false;
} else {
/* String does fit, simply copy */
strcpy(aDest, aSrc);
}
return success;
}
uint64_t getDiskSizeOfFd(int aFd) {
uint64_t result;
if (ioctl(aFd, BLKGETSIZE64, &result) == -1) {
perror("ioctl BLKGETSIZE64");
result = 0;
}
return result;
}
uint64_t getDiskSizeOfPath(const char *aPath) {
uint64_t diskSize;
int fd = open(aPath, O_RDONLY);
if (fd == -1) {
perror("open getDiskSizeOfPath");
diskSize = 0;
}
diskSize = getDiskSizeOfFd(fd);
close(fd);
return diskSize;
}
double getTime(void) {
struct timeval tv;
gettimeofday(&tv, NULL);
return (double)tv.tv_sec + (1e-6 * tv.tv_usec);
}
bool doesFileExist(const char *aFilename) {
struct stat statBuf;
int statResult = stat(aFilename, &statBuf);
return statResult == 0;
}
luksipc-0.04/utils.h 0000664 0000000 0000000 00000002450 12531634264 0014427 0 ustar 00root root 0000000 0000000 /*
luksipc - Tool to convert block devices to LUKS in-place.
Copyright (C) 2011-2015 Johannes Bauer
This file is part of luksipc.
luksipc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; this program is ONLY licensed under
version 3 of the License, later versions are explicitly excluded.
luksipc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luksipc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Johannes Bauer
*/
#ifndef __UTILS_H__
#define __UTILS_H__
#include
#include
/*************** AUTO GENERATED SECTION FOLLOWS ***************/
bool safestrcpy(char *aDest, const char *aSrc, size_t aDestArraySize);
uint64_t getDiskSizeOfFd(int aFd);
uint64_t getDiskSizeOfPath(const char *aPath);
double getTime(void);
bool doesFileExist(const char *aFilename);
/*************** AUTO GENERATED SECTION ENDS ***************/
#endif