Skip to content

RFC: systemd-repart: support encrypting partitions with existing data - #29731

Draft
berrange wants to merge 1 commit into
systemd:mainfrom
berrange:reencrypt
Draft

berrange wants to merge 1 commit into
systemd:mainfrom
berrange:reencrypt

Conversation

@berrange

Copy link
Copy Markdown
Contributor

This adds support for a new "EncryptDataShift=" option in systemd-repart config files, causing the pre-existing partition content to be shifted to make room for a LUKS header. See the commit message for further details.

My goal is to create a self-encrypting cloud disk image root FS for a traditional general purpose OS install. I'm aware that image based OS installs with immutable rootfs are conceptually nicer, but most cloud VM usage is still the traditional approach of fully writable root FS. I want to bring better protection to that legacy world and system-repart has 95% of the logic needed already.

This is intended to be run from the initrd before ANY partitions are mounted, and indeed before anything at all touches the root FS partition, even before fsck of root.

One problem is that if "EncryptDataShift=yes" is set, and systemd-repart is invoked while the partition in question is mounted (or otherwise in use, eg fsck), it happily runs the encryption process and the mounted (or otherwise used) FS gets very unhappy & crashy :-) I'm not sure what the best way to protect against this danger is ?

For testing I've modified the systemd-repart.service file in this nasty hacky way which is definitely not right:

[Unit]
Description=Repartition Root Disk
Documentation=man:systemd-repart.service(8)

ConditionVirtualization=!container
ConditionDirectoryNotEmpty=|/usr/lib/repart.d
ConditionDirectoryNotEmpty=|/usr/local/lib/repart.d
ConditionDirectoryNotEmpty=|/etc/repart.d
ConditionDirectoryNotEmpty=|/run/repart.d
ConditionDirectoryNotEmpty=|/sysusr/usr/lib/repart.d
ConditionDirectoryNotEmpty=|/sysusr/usr/local/lib/repart.d

DefaultDependencies=no
[email protected] modprobe@dm_mod.service
After=dev-gpt\x2dauto\x2droot.device [email protected] modprobe@dm_mod.service
Before=systemd-fsck-root.service
Conflicts=shutdown.target initrd-switch-root.target
Before=shutdown.target initrd-switch-root.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/systemd-repart --dry-run=no --root=/ /dev/vda
ExecStartPost=sleep 3

# The tool returns 77 if there's no existing GPT partition table
SuccessExitStatus=77

I don't want to hardcode the device path, but I'm not sure how to otherwise identify the device path that contains the EFI boot device. systemd-repart can't detect the device directly because in initrd phase where re-encryption has to run, nothing is mounted, so it can't detect the blockdev from the /sysroot mount point.

Since this re-encryption adds a LUKS format, it caused dev-gpt\x2dauto\x2droot.device to be stopped and renamed to dev-gpt\x2dauto\x2droot\x2dluks.device which is then unlocked to create a new dev-gpt\x2dauto\x2droot.device. This caused a race with the following systemd-fsck-root.service running before LUKS had been unlocked, hence the 'sleep 3'. This is all because I'm really running this too later. I think the right thing is to get this run before the systemd-gpt-auto-generator runs but not sure how to express a dependency on a generator ?

More generally I'm not sure if its possible to have a single 'systemd-repart.service' unit file definition that will work correctly inside an initrd and also be able to run on the live root fs later, or whether a second 'initrd-systemd-repart.service' is a better bet.

As an illustration of this working in a real Fedora cloud image

Oct 26 16:29:43 fedora systemd[1]: Starting systemd-repart.service - Repartition Root Disk...
Oct 26 16:29:43 fedora systemd-repart[363]: TYPE        LABEL                UUID                                 PARTNO FILE                      RAW SIZE        SIZE PADDING
Oct 26 16:29:43 fedora systemd-repart[363]: root-x86-64 root-x86-64          47a8d1f6-e285-4ec4-8c6a-a7385f6172ee 1      initrd-root-repart.conf 4286558208 3.0G → 3.9G 1000.9M → 0B
Oct 26 16:29:43 fedora systemd-repart[363]: esp         EFI System Partition a55fd2c3-ab52-4f6a-a31f-8ff8f6c8ab27 0                              1055916032     1007.0M 0B
Oct 26 16:29:43 fedora systemd-repart[363]:                                                                                                                    Σ = 4.9G Σ = 0B
Oct 26 16:29:43 fedora systemd-repart[363]:  ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
Oct 26 16:29:43 fedora systemd-repart[363]:  └─ EFI System Partition
Oct 26 16:29:43 fedora systemd-repart[363]:                 └─ initrd-root-repart.conf
Oct 26 16:29:43 fedora systemd-repart[363]: Applying changes.
Oct 26 16:29:43 fedora systemd-repart[363]: Successfully discarded gap at beginning of disk.
Oct 26 16:29:43 fedora systemd-repart[363]: Encrypting future partition 1...
Oct 26 16:30:17 fedora systemd-repart[363]: Successfully encrypted future partition 1.
Oct 26 16:30:17 fedora systemd-repart[363]: Growing existing partition 1.
Oct 26 16:30:17 fedora systemd-repart[363]: Setting partition label of existing partition 1.
Oct 26 16:30:17 fedora systemd-repart[363]: Writing new partition table.
Oct 26 16:30:17 fedora systemd-repart[363]: Telling kernel to reread partition table.
Oct 26 16:30:17 fedora systemd-repart[363]: All done.
Oct 26 16:30:20 fedora systemd[1]: Finished systemd-repart.service - Repartition Root Disk.

The "Encrypt" option is currently a no-op if the partition already
exists. IOW it is only possible to apply encryption to newly created
partitions. This is an unhelpful restriction when dealing with cloud
images.

It is undesirable to pre-encrypt the cloud image as at the time it
is created there is no TPM to seal against, so it would have to be
encrypted with a well known password. The image would then have to
be re-encrypted on deployment to ensure every instance has a unique
master key.

It is simpler to distribute the cloud images with plain text root
FS partition and then apply encryption to them at time of deployment.
This halves the overhead, as there's no decrypt of existing data
needed. There is of course still a risk that the cloud host has
modified the original plain text image before the first-boot
encryption runs, but even with this, guest owners will still
benefit from having their image encrypted.

To avoid changing the semantics of the existing "Encrypt" option,
a new "EncryptDataShift" option is added, which is a boolean
indicating whether existing partitions will be encrypted with a
datashift operation applied to their contents

For an existing partition to be encrypted, its size must grow by
at least the LUKS2 header reservation size (32MB). Thus if the
GrowFS=on option is set, we validate the growth is at least
32MB, treating it as a non-recoverable error if smaller. If
GrowFS=off is set, however, we expect the image creator has
adjusted the size of content in the partition such that the
trailing 32MB are empty. This could be achieved by shrinking the
filesystem after creation.

Signed-off-by: Daniel P. Berrangé <[email protected]>
@github-actions github-actions Bot added documentation repart please-review PR is ready for (re-)review by a maintainer labels Oct 26, 2023
@berrange
berrange marked this pull request as draft October 27, 2023 10:23
@poettering

Copy link
Copy Markdown
Member

Hmm, let's take a step back:

  1. @ddstreet's model, which I am very sympathetic to, is based on the idea that the TPM is deployed with a pre-installed SRK (or other key), which we the image is then enrolled against?

  2. how does this relate to cryptsetup's "reencryption" stuff, shouldn't you use that?

  3. wouldn't it make more sense to create the partition fresh, but use CopyFiles= to populate it with some defaults shipped in /usr/ somewhere? i.e. like /etc/skel for the roofs or so?

@poettering

Copy link
Copy Markdown
Member

note that right now repart is written in a style that makes it very robust towards abnormal termination: any new partitions it creates it only registers in the partition table as very last step, which means if the system is aborted in between, the next reboot will just start afresh.

What you are proposing here is a lot more problematic, as it abnormal termination of the process will leave a half moved/converted partition around, which means the system is fucked.

@poettering

Copy link
Copy Markdown
Member

modern file systems such as btrfs leave space at the beginning (64k for btrfs), couldn't that be used for this? (would require some trickery to make sure the 64K of nothingness are prefixed again virtually on activation)

@berrange

Copy link
Copy Markdown
Contributor Author

Hmm, let's take a step back:

  1. @ddstreet's model, which I am very sympathetic to, is based on the idea that the TPM is deployed with a pre-installed SRK (or other key), which we the image is then enrolled against?

Yes, that is a useful model and one I'm interested in supporting for Linux KVM hosts in future too.

In particular if a guest owner requires an image to be encrypted from the very moment it leaves their local client, and wants to use TPM sealing, then pre-encrypting against an SRK that will be pre-enrolled with the future VM's TPM is probably the only usable and secure game in town. Without it, you're left having to use a plain passphrase on first boot and re-seal to the TPM afterwards which is tedious.

This pre-sealing to the SRK though has downsides too though.

The biggest is that this approach only works in Azure cloud today AFAIK.

The second problem is that if you want to deploy the image many times, you don't want all the instances sharing the same LUKS master key and also don't want to upload many copies of the same template either. So something needs to do unique encryption per instance, and this needs to be completed either before booting the VM, or very early in boot before any unique data for the VM is stored, especially any secrets like SSH host keys.

If a cloud supports pre-sealing against a future VM's TPM SRK that is certainly nice to have & use, but I'm looking for a more general solution that can be implemented in a guest disk image, that will work on /any/ cloud that provides a TPM and SecureBoot. This requires that it be self-contained within the guest, so there's no mandatory dependency on the cloud host to do re-encryption or TPM sealing.

I could do this as an entirely standalone tool, but systemd-repart already has alot of relevant functionality so it made sense to see if it could be extended to cope with this use case.

  1. how does this relate to cryptsetup's "reencryption" stuff, shouldn't you use that?

systemd-repart uses libcryptsetup's API to implement its encryption facility. The code I've leveraged for encryption in this patch already exists in systemd-repart, and is calling the same libcryptsetup APIs that the cryptsetup reencrypt tool would be using. The way CopyBlocks= is implemented involves copying the content into a plain text partition and then running the re-encryption process with a data-shift to add LUKS after the fact.

Using cryptsetup reencrypt is certainly possible, but it probably still requires some wrapper tool to co-ordinate what to encrypt - systemd-repart is nice in that its config file facility provides a good way to control the what happens already.

  1. wouldn't it make more sense to create the partition fresh, but use CopyFiles= to populate it with some defaults shipped in /usr/ somewhere? i.e. like /etc/skel for the roofs or so?

That is possible, but at the cost of having double the storage requirement for the running image. If the source of the files is before the encrypted root fs, deleting the partition just leaves a gap. If the source of thte files is after the encrypted root fs, then deleting the partition leaves space, but encrypting and growing would have to be done in two separate steps.

note that right now repart is written in a style that makes it very robust towards abnormal termination: any new partitions it creates it only registers in the partition table as very last step, which means if the system is aborted in between, the next reboot will just start afresh.

What you are proposing here is a lot more problematic, as it abnormal termination of the process will leave a half moved/converted partition around, which means the system is fucked.

Actually with LUKS2 it should be possible to turn a plain text partition into an encrypted partition with minimal risk, because it keeps a journal tracking encryption progress for later resume from failure. This doesn't work with the code I've got in this MR, but IIUC it could be made to work. Essentially on later boots a check would be needed to see it re-encryption was marked as "in progress" and if so tell cryptsetup to resume from where it left off.

Since this logic is intended to run on first-boot of a guest, the consequences of abnormal termination are not severe anyway, as the guest won't have yet stored any important data. It can be thrown away and re-instantiated once more.
The critical thing from a safety POV is to ensure it is a no-op on the second (and later) boots.

modern file systems such as btrfs leave space at the beginning (64k for btrfs), couldn't that be used for this? (would require some trickery to make sure the 64K of nothingness are prefixed again virtually on activation)

LUKS2 wants rather more than this - 32 MB is recommended for its re-encryption process, and what systemd-repart already uses for this purpose.

@berrange

Copy link
Copy Markdown
Contributor Author
  1. wouldn't it make more sense to create the partition fresh, but use CopyFiles= to populate it with some defaults shipped in /usr/ somewhere? i.e. like /etc/skel for the roofs or so?

That is possible, but at the cost of having double the storage requirement for the running image. If the source of the files is before the encrypted root fs, deleting the partition just leaves a gap. If the source of thte files is after the encrypted root fs, then deleting the partition leaves space, but encrypting and growing would have to be done in two separate steps.

I should mention one further thing I'm interested in doing is proving integrity of the resulting encrypted FS, via some kind of signature that covers the original plain text content.

If the plain text were a partition covered by dm-verity and a signature, then if either a block level copy + encrypt or in-replace re-encrypt is done, then the dm-verity should be able to validate the LUKS volume when first opened, before it is mounted / fscked. Obviously as soon as you start changing the block dev the dm-verity validation will no longer pass, but even a one-time only proof of the encrypted root FS partition is valuable. Thereafter, authenticated encryption of the LUKS volume is sufficient. CopyFiles wouldn't work in this scheme, but using CopyBlocks could.

@poettering

Copy link
Copy Markdown
Member

So if we can make this robust towards abnormal termination I think this might be OK to do.

Hmm, the shifting problem, isn't that irrelevant? I mean, we could simply require that either:

  1. people leave the right amount of space empty before the partition to encrypt, i.e. if they build the original image with repart, then require them to use PaddingMinBytes=/PaddingMaxBytes= on the preceeding partition, with enough space. Then, when we apply the reencryption we simply extend to the front as needed, and refuse if we can't.

  2. alternatively, just put the unencrypted version of the data into the partition at an offset. if people build the original image with repart, we could add a CopyBlocksOffset= value so that they can configure this. Then, when we reencrypt we'd not have to resize any partition, but would just stick the LUKS header in front, and initiate the reencryption.

if you pick 2 then the partition table doesn't have to be changed at all, and instead this would become a job for cryptsetup or so. i.e. we'd add a new option "auto-encrypt" or so to crypttab. And it would take the offset as argument maybe. it would then check if the volume already has a lUKS header. If yes, it would just mount it as usual. If not, it would add it, and then initiate the reencryption.

I am not sure how reencryption actually works though, never played around with it.

Kinda leaning towards option 2, i.e. making this a systemd-cryptsetup problem rather than a repart problem.

@berrange

berrange commented Nov 1, 2023

Copy link
Copy Markdown
Contributor Author

Kinda leaning towards option 2, i.e. making this a systemd-cryptsetup problem rather than a repart problem.

I think this could work, so I'm going to have a crack at a PoC for systemd-cryptsetup.

@ddstreet

Copy link
Copy Markdown
Contributor

Sorry it took me so long to comment here. It does sound like a good idea to me, but I have 2 thoughts:

Hmm, the shifting problem, isn't that irrelevant? I mean, we could simply require that either:

We shouldn't need to do any shifting; cryptsetup's reencryption operation will handle that. If systemd-cryptsetup just resizes the filesystem down so it's $LUKS_HEADER_SIZE smaller than the partition size, the reencryption handles everything else. So really, the 'source' image just needs to make sure the filesystem has at least $LUKS_HEADER_SIZE bytes free. Then the same 'source' image can be used for both unencrypted VM instances as well as encrypted VM instances (from this perspective, at least). This is assuming, of course, that the block device/partition to be encrypted contains only a single filesystem; encrypting an entire block device with e.g. a partition table or lvm data or raid member would definitely require increasing the partition size.

Actually with LUKS2 it should be possible to turn a plain text partition into an encrypted partition with minimal risk, because it keeps a journal tracking encryption progress for later resume from failure

I think the encryption needs to be done offline, and boot needs to be delayed until it's complete. Or, at minimum, there should be an option for the encryption to delay boot (that defaults to true). This is because if the end user wants an encrypted device/filesystem, they almost certainly expect it to be fully encrypted as soon as the instance first boots up. Otherwise, there is a window of time where part of their filesystem is not encrypted, and they shouldn't actually be using the system for sensitive operations.

This will of course add a (probably significant) delay to first boot, which is why the pre-encryption (where possible) option is more attractive.

@yuwata yuwata removed the please-review PR is ready for (re-)review by a maintainer label Jan 11, 2024
@aplanas

aplanas commented Jul 11, 2024

Copy link
Copy Markdown
Contributor

This will of course add a (probably significant) delay to first boot, which is why the pre-encryption (where possible) option is more attractive.

But pre-encryption will not fix the delay issue, right? If you deploy a pre-encrypted image you need to change the master key, and for that you need a re-encryption, investing almost the same time.

@vittyvk

vittyvk commented May 22, 2025

Copy link
Copy Markdown
Contributor

This seems to got stale so I wanted to revive the discussion. I believe that main goal of this PR and #29824 request is to be able to do self-encrypting CVMs. This may come handy when there's no support in the infrastructure for doing pre-encryption or to improve the scalability as a dedicated pre-encryption service may actually be a bottleneck as each VM needs to be passed through it.

In addition to the encryption or re-encryption on the first boot, CVMs also require some sort of a verity protection. If we want to use the existing systemd-veritysetup, then the partition must me either / or /usr and the data must stay verity protected all the time before reencryption (or encryption) is over. I don't think it is easily achievable if we want to create a new LUKS container by re-using the data in the partition so I was picturing the following scheme:

  • The image has root on LUKS with a publicly known key to it.
  • The image has dm-verity for the contents of the LUKS container.
  • Upon the first boot LUKS gets fully re-encrypted with a new master key (this doesn't break verity) and the integrity of the data is checked against dm-verity after reencryption is complete.
  • Verity partition can now be discarded (along with e.g. corresponding UKI addon with has the expected hash)
  • Ideally, the instance keeps booting with the root volume in r/w and no additional reboot is needed.

Alternatively, we can go with 'copy': the image has a verity protected 'source' partition and verity for it (both dm-verity or fs-verity could do the job I guess) and enough space before it where systemd-repart can create a new root. This may be easier to implement, the only hurdle is to make sure verity information for the source is actually used.

One additional CVM implication is that we probably want to preserve some knowledge about the source (e.g. verity hash) and the environment which did re-encryption (e.g. TPM quote) to the newly create (or reencrypted) target to protect against an attack when e.g. the host launches the image in a non-CVM environment and steals the new LUKS key from memory post-enctyption/re-encryption.

@cgwalters

Copy link
Copy Markdown
Contributor

What you are proposing here is a lot more problematic, as it abnormal termination of the process will leave a half moved/converted partition around, which means the system is fucked.

Yeah this is an important concern. Today for e.g. Ignition, it's just not transactional in the general case of reprovisioning the rootfs.

I think we could design something for this though at least for the simple case where all we're doing is adding a LUKS header.

Another option is to just to always have the LUKS header but make it null cipher but sadly today that always adds a devmapper layer which adds nontrivial I/O overhead.

@Conan-Kudo

Copy link
Copy Markdown
Contributor

Another option is to just to always have the LUKS header but make it null cipher but sadly today that always adds a devmapper layer which adds nontrivial I/O overhead.

This is also a security issue, as if anyone has a copy of that header, they can decrypt your volume even if you set a password later.

@cgwalters

Copy link
Copy Markdown
Contributor

This is because if the end user wants an encrypted device/filesystem, they almost certainly expect it to be fully encrypted as soon as the instance first boots up.

(Replying to an old message here) We're talking about the rootfs here and since we're mounting that in the initramfs, we can initialize LUKS at the block device level before even mounting the filesystem - hence before any writes can be performed. Any writes that happen will be encrypted - we don't need to pause to wait for everything to be encrypted. For generic cloud images I think it's OK to have the "generic data" that's part of the OS remain unencrypted while the boot proceeds.

This is also a security issue, as if anyone has a copy of that header, they can decrypt your volume even if you set a password later.

Hmm you seriously worried me here, this is a very important concern to look at. But as far as I can tell, cryptsetup-reencrypt always changes the volume key unless --keep-key is passed. So as long as one doesn't do that (and it's not the default, why would you?) things are safe.

That said, the more I think about this the more I feel it's misleading to have a LUKS header that isn't actually encrypting. I think what would be a lot cleaner here is a special "uninitialized LUKS" header. If that's detected, (probably in cryptsetup) then it's actually just mounted via dm-linear or so. But if the system provides credentials/config, we want to be able to initialize the LUKS setup for real (tpm2, passphrase, NBDE whatever).

Involving repartitioning by default (especially this report discussion with CopyBlocks) feels like a lot of unnecessary overhead - in the optimal case where the user is happy with the default filesystem we don't want to copy the whole thing at boot.

@berrange

Copy link
Copy Markdown
Contributor Author

I think what would be a lot cleaner here is a special "uninitialized LUKS" header.

Would a detached LUKS header help ? Start off with a plain volume, and when you want to encrypt, create a detached header with null-cipher and immediately trigger re-encrypt with a real cipher ? Downside is that you need to associate the detached header and corresponding volume in some manner, forever more.

@aplanas

aplanas commented Mar 25, 2026

Copy link
Copy Markdown
Contributor

(Replying to an old message here) We're talking about the rootfs here and since we're mounting that in the initramfs, we can initialize LUKS at the block device level before even mounting the filesystem - hence before any writes can be performed. Any writes that happen will be encrypted - we don't need to pause to wait for everything to be encrypted.

Uhm ... in disk-encryption-tool we are encrypting the rootfs device in the initrd, as commented here. Basically we move the file system a bit, to allocate the 32Kb required for the LUKS2 header, resize the filesystem to its minimal size, encrypt, and resize back to its full extend.

I guess that for systemd-repart can be a problem the allocation of 32Kb unless uses libraries for specific file systems, but this is resolving all the issues mentioned here (pre allocation of LUKS2, speed of re-encryption, detached LUKS2 header, risk of re-use of volume key, etc)

@cgwalters

Copy link
Copy Markdown
Contributor

Would a detached LUKS header help ? Start off with a plain volume, and when you want to encrypt, create a detached header with null-cipher and immediately trigger re-encrypt with a real cipher ? Downside is that you need to associate the detached header and corresponding volume in some manner, forever more.

Clearly no matter what, some mechanism has to be defined to find and mount the rootfs.

So far a somewhat implicit constraint/goal in some of these discussions is supporting the discoverable partition spec. It'd need to be changed for something like that AFAICS - like would we actually move the root type UUID from the original partition to the LUKS header or so? And we'd need to also define a mechanism to find the partition it covers since I don't think the header includes that (by design).

One advantage of the "dynamic header" approach is we're not allocating any wasted space. AFAICS though most of the implementation work in that path would be on systemd (and uapi work on DDI spec changes), not cryptsetup. But Lennart's previous comment here seemed to lean towards making this something to solve in cryptsetup (closer to the "null header" proposal).

Either way worth noting AFAICS such a disk image wouldn't be mountable with older tooling. I don't think that's a big deal though.

I personally lean towards the cryptsetup side solution; it's relatively self-contained and the disk space overhead is negligible for most general purpose use cases.

@cgwalters

Copy link
Copy Markdown
Contributor

Uhm ... in disk-encryption-tool we are encrypting the rootfs device in the initrd, as commented here. Basically we move the file system a bit, to allocate the 32Kb required for the LUKS2 header, resize the filesystem to its minimal size, encrypt, and resize back to its full extend.

I don't want to move the rootfs by default just for LUKS, it's an unnecessary very large latency hit on first boot.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

8 participants