# HOWTO: Encrypt a filesystem in a loopback file via dm_crypt

## samx

HOWTO: Encrypt a filesystem in a loopback file via dm_crypt

Note: Thanks to the dm_crypt tutorial: https://forums.gentoo.org/viewtopic.php?t=143301 (sorry if I copy some things from there)

But it took me a while to figure out how to setup a loopback file (okay, I'm still n00b) so I thought it would be a good idea to write this short tutorial

The Goal:

Having an encrypted file system which is stored in one file

Introduction

I didn't like the idea of storing all my private files in my home-directory, because you might forget to lock your screen, go away and somebody can take a quick look at them... Beside that, they are stored clearly on the harddisk, so if someone has your harddrive, he has all your private files. 

I stumbled over dm_crypt and yeah - that's it! I didn't like cryptoloop, because it seams that it will be replaced soon (http://kerneltrap.org/node/view/2433)

Also I didn't find it useful to encrypt my whole root filesystem - it's quite dangerous and 99% of my system are public available - so why encrypt them? If I have a small (say perhaps 200 MB) file, I can store all my private files and can backup them easily and savely (just burn the encrypted file and even the CIA won't recover your files without the passphrase  :Smile:  )

Let's start

At first, you need at least a 2.6.4 kernel for device mapping and dm_crypt support. Make sure you have these options enabled:

Device Drivers->Multi-device support (RAID and LVM)->

```
[*] Multiple devices driver support (RAID and LVM)

<M>   Device mapper support

<M>     Crypt target support
```

Device Drivers->Block-devices->

```
<M> Loopback device support
```

Cryptographic options->

```
<M>   AES cipher algorithms
```

Of course you can use a different algorithm, but I chose aes because it's said to be quite safe. I recommend to compile these things as modules.

After that, you have to create a loopback file. (This will create a 100 MB file at the location /home/secret)

```
dd if=/dev/zero of=/home/secret bs=1M count=100
```

Setup this as a loop device:

```
losetup /dev/loop0 /home/secret
```

Install cryptsetup

You'll need dev-libs/popt, sys-libs/device-mapper, >=dev-libs/libgcrypt-1.1.42 (you'll need an ACCEPT_KEYWORDS="~arch"!) to compile it

Setup the crypt-device: 

```
modprobe dm_crypt

cryptsetup -c aes -y create secret /dev/loop0
```

(You might add dm_crypt and dm_mod to /etc/modules.autoload.d/kernel-2.6)

So... now your encrypted device is available at /dev/mapper/secret, so let's create a filesystem (I chose ext3):

```
mke2fs -j /dev/mapper/secret
```

Mount it:

```
mount /dev/mapper/secret /mnt/secret
```

You might add a line to your /etc/fstab:

```
#/etc/fstab

/dev/mapper/secret     /mnt/secret    ext3           noauto,noatime           0 0
```

That's it!

Now you can store your data there and after that just 

```
umount /mnt/secret

cryptsetup remove secret
```

If you don't call cryptsetup remove, everybody can remount it without typing the passphrase!

Next time, you'll only have to type:

```
losetup /dev/loop0 /home/secret

cryptsetup create secret /dev/loop0

mount /mnt/secret
```

Remarks

You might encrypt your whole /home/user directory, but that has disadvantages: You'll have mounted it all time when you sit in front of your computer, so if you leave it without locking it... then the best encryption is useless!

So I have a separate directory which I mount only when I need it, copy my files there and when I don't need it anymore, I unmount it.

For questions about dm_crypt, look at: http://www.saout.de/misc/dm-crypt/

Hope this tutorial is useful, if I'm wrong somewhere please correct me.

----------

## icywolf

Thank I was searching for something like that for my usb key

----------

## Redeeman

ehrm... well.. i thought you didnt need the losetup with dm-crypt, you can do all this without dm-crypt, and just mount /dev/loop0 directly  :Neutral: 

----------

## samx

Hm... I don't really know how you mean that (I'm a n00b happy about having an encrypted filesystem  :Wink:  )

But if you want to do it without dm-crypt, than you mean using cryptoloop??? It was one goal to do it with dm-crypt because this seams to be the future of linux encryption!

And before you can mount /dev/loop0, you must setup /dev/loop0 (because you can't mount the /home/secret file directly) and this is being done by losetup, isn't it?

I'm not familiar with cryptoloop, but I think the main difference in mounting an encrypted file are (of course the system internals are quite different!):

With cryptoloop you would type something like this:

```
losetup -e aes /dev/loop0 /home/secret

mount /dev/loop0 /mnt/secret
```

With dm_crypt you have to type this:

```
losetup /dev/loop0 /home/secret

cryptsetup create secret /dev/loop0

mount /dev/mapper/secret /mnt/secret
```

With dm_crypt, the /dev/loop0 device is the raw access to your file - it's quite useless, because it's the same like you open your file with an editor - only encrypted Hexdata. The de-/encryption is handled between /dev/loop0 and the device mapping (only a mapping!) /dev/mapper/secret.

Okay, if you do this with dm_crypt, you have one more line to type, but hopefully this will change with future versions of cryptsetup, which will handle this for you. 

It's possible that future versions of mount will do all this for you, so that you only have to type one line, but right now, you have to type these three lines or write a script.

I hope this was right?

----------

## nero

I'd like to see a script for this that would monitor IO on that file and then automatically unmount it and destroy the loop device. I have a terrible history of forgetting to do things like this.

/me leaves to figure out how to monitor the file IO...

--sean

----------

## nero

I have given it a shot, but for some reason when a file is accessed through a loopback device, none of its stats are updated. You can create a file on the loopback partition, then ls -l the encrypted filesystem image, and the modification data will not have changed at all!!

So I guess an auto unmount feature is impossible without a kernel mod   :Sad: 

----------

## samx

I think this is not very elegant, but I think it could work (I haven't tried it yet):

You could write a cronjob, that tries to

```
umount /mnt/secret

cryptsetup remove secret
```

every ten minutes. If it's not mounted, nothing will happen and if you have mounted it, but it's still busy, nothing will happen, too.

And when you don't need it anymore (if you haven't any open files), it will be unmounted in the next ten minutes.

The alternative would be to write a special daemon, but I think that's not worth it...

----------

## nero

You could, but that way you could not justify using forced unmount. Like if you were to have a shell or something that is currently in that directory. Without being able to tell if it active or not, a forced unmount could result in the loss of critical data.

----------

## S_aIN_t

Looks pretty interesting.. thanks.. i'll give it a shot. :)

----------

## davidc

Thanks for this tutorial, it is very useful.  However, if I make a reiserfs file using mkreiserfs it has 33M used even before I've written anything to it.  Is there any specific reason for this?

----------

## Nate_S

reiserfs is a journeled filesystem.  I'm guessing that the 33MB is the journel.  If it's a very small filesystem, you might go with ext2, as journeling doesn't make as much sense (though can't hurt other than taking extra space) on smaller filesystems, as the whole thing can be checked fairly quickly anyways.  I use it on /boot myself, and I'm thinking I'm going to put it on my usb stick as well.

----------

## jkcunningham

I followed the instructions in this thread and it works like a charm - so long as I'm root. How do you mount this encrypted filesystem as a user?  I tried adding ",users" to the fstab options, and chown on both the /home/secret file, the /mnt/secret directory, and /dev/mapper/secret. When I try to mount it as a user, it says "only root can do that". 

EDIT: I succeeded in mounting it as a user with the fstab line:

```
/dev/mapper/secret   /mnt/private   ext3   noauto,noatime,user   0 0
```

But when mounted, anyone else logged in can read it also. It seems like it should have the additional option ",usmask=077" but it won't mount when I try that. 

It doesn't seem like a good idea to have your secret encrypted directory mounted with standard read privileges for other users. Any idea how to get around this?

-Jeff

----------

## soulwarrior

Thanks for this tutorial   :Very Happy:  Have been using loop-aes on our server for quite some time (seems to be very stable for us) but I am now planing to convert to dm-crypt. I am right now testing dm-crypt on my development computer.

Has anyone had till now any problems with dm-crypt?

Maybe you could submit your tutorial also to the dm-crypt wiki?

----------

## samx

 *jkcunningham wrote:*   

> But when mounted, anyone else logged in can read it also. It seems like it should have the additional option ",usmask=077" but it won't mount when I try that. 

 

The option umask is only for fat filesystems (on other fs types mount will ignore it, read man mount) which can't store the owner and rights information (it's no Unix filesystem...) So you can set the default rights for mounted fat partitions with umask, uid and gid. 

But ext3 does save owner and rights information - all you have to do is to change the permissions in the mounted partition for example with 

```
chmod -R g-rwx,o-rwx /path/to/mountpoint/
```

so that nobody else can read the data.

If other users still can list the files in your mounted folder, just change the owner for the mountpoint:

```
chown yourusername:root /path/to/mountpoint

chmod o-rwx /path/to/mountpoint
```

Now nobody (except root...) should be able to read files or even list the files in this folder.

Here are just two little scripts I wrote to make things a little easier, but of course you'll need to sudo these scripts.

secretup

```
# !/bin/bash

/sbin/losetup /dev/loop0 /home/secret

/sbin/modprobe dm_crypt

/usr/bin/cryptsetup create secret /dev/loop0

/bin/mount /mnt/secret
```

secretdown

```
# !/bin/bash

/bin/umount /mnt/secret

/usr/bin/cryptsetup remove secret

/sbin/losetup -d /dev/loop0
```

Another advantage: you'll never forget the cryptsetup remove  :Wink: 

----------

## jkcunningham

 *samx wrote:*   

> The option umask is only for fat filesystems (on other fs types mount will ignore it, read man mount) which can't store the owner and rights information (it's no Unix filesystem...) So you can set the default rights for mounted fat partitions with umask, uid and gid. 

 

Actually, umask applies to most filesystems. Go back and check man mount and read a little further. Unfortunately, it doesn't work with loopback filesystems apparently.  

I have tried the approach of changing the permissions. The problem with that is it only acts on existing files. Any new files you create have the default permissions (644) that come with the default umask. That's why I was hoping to be able to override it with the mount command - it would have solved the problem. 

Your script approach may be the best one can do - but I think this is a weak point in the encrypted loopback filesystem approach. At work (a MS Windows environment) everyone is setup with an encrypted directory for proprietary work, using some third party software. All they have to do is drop files in that directory and they are encrypted.  

Thanks. 

-Jeff

----------

## samx

Sorry, but I think you muddled something here... I hope I can explain it right...

The single and only purpose of the umask= option is to control the default permissions when mounting a fs that doesn't know file permissions (for example fat)

 *man mount wrote:*   

> umask=value
> 
> Set the umask (the bitmask of the permissions that are not present). The default is  the umask of the current process.  The value is given in octal.

 

Because the FAT filesystem doesn't have file permissions, the kernel has to assign some. You can only set the permissions for all files on the partition at once. The only thing you can do is to set different permissions for all directories (dmask=) and files (fmask=). Per default it uses 0777 with the umask of the current process. With umask=0022 (a common one), all files have the permission rwxr-xr-x 

You can't change file permissions for only some files or directories on fat fs later because fat isn't capble of storing them - the permissions will remain the same until you unmount the partition. 

That's different to the umask command, which sets the umask for the current process. That umask specifies what permissions new files created by that process will have. Therefore, you can't specify different umasks for different partitions or something like that, only for different processes. That's why mount will fail if you try to mount a fs like ext,reiser,... with -o umask=

I'm quite sure that mounting a loop file doesn't make any difference to mounting a "real" partition (only some different kernel drivers)

 *jkcunningham wrote:*   

> All they have to do is drop files in that directory and they are encrypted.

 

That's exactly the same with an encrypted loopback file! The data is never stored unencrypted on the harddisk. As long as you keep it mounted, you can access your data (the kernel does the "magic" for you)

I can't see any weeknesses - the only weekness is that you might forget to unmount it when you leave the computer, but that's the same when you use some proprietary software with windows!

The only weekness is the human being in front  :Wink: 

----------

## jkcunningham

You are in error. There is a default umask value in /etc/profile that is used when files and directories are created.  You can change it with the umask command. You can use the umask option to mount a file system with a different default (if it supports it, and obviously the loopback and some others don't).  

Check out these links if you don't believe me:

http://www.linuxsecurity.com/HOWTO/Security-HOWTO-5.html#umask

http://rootprompt.org/article.php3?article=6874

http://www.mkssoftware.com/docs/man1/umask.1.asp

http://www.sun.com/bigadmin/content/submitted/umask_permissions.html?biga=15

I agree about the human error part. 

-Jeff

----------

## bld

Really interesting paper, I'll do something like this right away.. but I was thinking that the best thing is to make impossible for users:

(a) To read "mount" output and see that root has /dev/loop0 mounted

(b) To make the file /home/secret visible to others.

I use reiserfs, I dont know if it has some option to hide files from normal users, or possibly hide the file from the users and the root too.. 

to explain this.. If someone boots with a liveCD he is "root" on your system, but if the file cannot be listed (ls) by the root either.. then you're much more secure.

----------

## linux_girl

i hope some one make an ebuild for cryptsetup

----------

## makuk66

linux_girl: There is an ebuild for cryptsetup in bugzilla: Bug 44347.

----------

## afabco

How would one set this up for a production environment, given an arbitrary number of users with arbitrary usernames that may or may not be logged in at any given time?

----------

## zimzum

hey..I did a few things differently...I'm using the slightly newer SHA512 hash algorithm with AES-256 and I decided to try it using a live partition instead so there is no loopback device:

```

cryptsetup -c aes -h sha512 -y create vault /dev/sda2

mount -t ext3 /dev/mapper/vault /vault

```

and the kernel messages are like this:

```

Aug  9 16:30:16 gargoyle kjournald starting.  Commit interval 5 seconds

Aug  9 16:30:16 gargoyle EXT3 FS on dm-0, internal journal

Aug  9 16:30:16 gargoyle EXT3-fs: mounted filesystem with ordered data mode.

```

so far so good with this.  Badass howto!  Too bad you can't configure dm_crypt into fstab like with loopback crypto tho ;(

pz

zim

----------

## alwin

snipLast edited by alwin on Tue Feb 28, 2006 8:06 pm; edited 2 times in total

----------

## michaelkuijn

People, if you are going to use it, please please don't forget to unmount the encrypted filesystem when you are not using it! When the system freezes/crashes/behaves mysteriously disastrous (like what happened with me) YOU'RE SCREWED REAL BAD!

I lost 800 mb of emotionally very important data. I know what you're thinking... I should have made a backup.

HOMO SAPIENS NON URINAT IN VENTUM

----------

## asiobob

 *zimzum wrote:*   

> hey..I did a few things differently...I'm using the slightly newer SHA512 hash algorithm with AES-256 and I decided to try it using a live partition instead so there is no loopback device:
> 
> ```
> 
> cryptsetup -c aes -h sha512 -y create vault /dev/sda2
> ...

 

is this working well?

----------

## golloza

 *nero wrote:*   

> I'd like to see a script for this that would monitor IO on that file and then automatically unmount it and destroy the loop device. I have a terrible history of forgetting to do things like this.
> 
> /me leaves to figure out how to monitor the file IO...
> 
> --sean

 

This script checks if any process is using the mountpoint and unmounts the fs and removes the mapper if no one is using it:

```
#!/bin/sh

fuser -m /mnt/secure > /dev/null || (umount /mnt/secure/; cryptsetup remove secure)
```

Of course you have to change the mounpoint and the name of the mapper to match your setup.

You can have cron execute it every 10 minutes or so.

----------

## GentooBox

 *golloza wrote:*   

>  *nero wrote:*   I'd like to see a script for this that would monitor IO on that file and then automatically unmount it and destroy the loop device. I have a terrible history of forgetting to do things like this.
> 
> /me leaves to figure out how to monitor the file IO...
> 
> --sean 
> ...

 

thats nice, but i have 500 Gb RAID0 reiserfs partition encrypted with SHA256 and it takes 1 minutes to mount.  :Very Happy: 

does anyone know if reiser4 mounts faster than reiserfs 3.6 ?

----------

## golloza

I've also noticed that mounted the encrypted device takes longer than a normal partition (about 1-2 secs, 5GB reiserv3, aes 256 bit).

Updated version of the unmounter:

```
#!/bin/sh

                                                                                                                                                             

mappername="secure"

mpoint="/mnt/secure"

                                                                                                                                                             

if grep $mpoint /etc/mtab > /dev/null; then

        fuser -m $mpoint > /dev/null || (umount /mnt/secure/; cryptsetup remove $mappername)

else

        echo $mpoint is not mounted!

        if [ -e /dev/mapper/$mappername ]; then

                echo "Removing the mapper " $mappername

                cryptsetup remove $mappername

        fi

fi

```

----------

## ultraViolet

Thanks for this tutorial !

I would like to traduce it in french for the french gentoo forums, if you agree of course.

I am migrating from cryptoloop and I have followed your how to, but I don't use losetup, because I can't see the difference using it or not.

```

cryptsetup -c twofish -s 128 -y create test /dev/vg/test

mount /dev/mapper/test /mnt/crypto

```

is working fine for me. I found many web sites indicating that dm-crypt was superior to cryptoloop because it don't use loopback devices... But if you use a /dev/loop0, what is the advantage of using dm-crypt   :Question: 

----------

## alwin

snipLast edited by alwin on Tue Feb 28, 2006 8:07 pm; edited 1 time in total

----------

## ultraViolet

I think I have understand the problem :

It seems that losetup is necessary only if you want to create an encrypted filesystem in a file.

 *Quote:*   

> 
> 
> http://www.saout.de/misc/dm-crypt/
> 
> [...]
> ...

 Last edited by ultraViolet on Tue Sep 28, 2004 2:41 pm; edited 1 time in total

----------

## ultraViolet

I have a really stupid question : if I want the encrypted HD being automounted, I know that I can I write a sh script for doing so. But how can I launch it automatically when I start my computer ?

----------

## alwin

snipLast edited by alwin on Tue Feb 28, 2006 8:07 pm; edited 3 times in total

----------

## golloza

Write a script and add it to /etc/conf.d/local.start.

Btw: baselayout 1.11.0 has support for dm-crypt (and WLAN  :Smile: ), but it's still hard-masked.

----------

## absinthe

I made a patch for baselayout-1.11.7 to support the mounting and unmounting of dm-crypt loops via conf.d/cryptfs.  Works for me, but some testing and feedback on it by others would be appreciated.

Please refer to:

https://bugs.gentoo.org/show_bug.cgi?id=73598

----------

## JazzSax006

Is it only worth switching to dm-crypt if you're using block disk encryption on a physical partition, or is it still worth the upgrade even if you're mounting files as virtual encrypted disks?

----------

## absinthe

Yes, mainly because cryptoloop support is being dropped in 2.6 it seems (it appears to be broken in 2.6.8 and 2.6.9)... also in situations where a system can't be sliced up to create block device maps, loops make a nice alternative.  THere are some upsides to using loopback filesystems, namely it's a nice way to back up filesystem snapshots, and move them around as you need to.

I don't think the mount behavior is limited versus block devices in any way... the only drawback I can see is a performance penalty.

dm-crypt loops are not supported in the current baselayout.  My patch attempts to address that (see link in previous post.)

----------

## JazzSax006

Thanks for the info!  I guess I'll be converting to dm-crypt this weekend.  I just hope it is as stable as cryptoloop has been for me.

----------

## Helper_Monkey

does anyone know how to use this in conjunction with pam-mount so that you can encrypt your home directory and have it automount when you login and unmount when you log out?

I have seen some docs on how to do this, but for the life of me I can't get everything to work correctly together.

----------

## tuxophil

 *Helper_Monkey wrote:*   

> does anyone know how to use this in conjunction with pam-mount so that you can encrypt your home directory and have it automount when you login and unmount when you log out?

 

Maybe this HOWTO could help you.

 *Helper_Monkey wrote:*   

> I have seen some docs on how to do this, but for the life of me I can't get everything to work correctly together.

 

I just hope you're not talking about my doc  :Wink: . If you've got problems with it I'd be glad to help out.

----------

## CodAv

I would like to add that it is more secure to shred the /home/secret once with random data, since a file containing just zeroes is potentially unsecure in cryptographic means. Create the file with these commands:

```
dd if=/dev/zero of=/home/secret bs=1M count=100

shred -n 1 /home/secret
```

----------

## nyk

I use the command "/usr/bin/cryptsetup create secret /dev/loop0" to activate my passphrase protected, encrypted storage device stored in a file.

I've got the command from this howto.

It worked for a year, but now I get: "Command failed: Invalid argument". 

What do I have to change? 

Something with cryptsetup seems to have changed, but I don't even find a manpage...

----------

## tagwar

does anyone have an idea if it is possible to use dm-crypt together with squashfs? I would like to copy some stuff from my main machine to my laptop, the two things i need are encryption and packing, since it's around 10GB of data... wouldn't want to fill up the small laptop harddisk with that...

----------

## crubb

 *nyk wrote:*   

> I use the command "/usr/bin/cryptsetup create secret /dev/loop0" to activate my passphrase protected, encrypted storage device stored in a file.
> 
> I've got the command from this howto.
> 
> It worked for a year, but now I get: "Command failed: Invalid argument". 
> ...

 

At the moment, cryptsetup needs to be linked against libdevmapper.so.1.01, therefore you need to:

```
# echo '>=sys-fs/device-mapper-1.02.02' >> /etc/portage/package.mask && emerge device-mapper cryptsetup
```

Or install the latest cryptsetup snapshot, see: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=344313

I filed a bug on bugzilla as well: https://bugs.gentoo.org/show_bug.cgi?id=120802

mfg,

crubb

----------

## Massimo B.

To open my encrypted firewire drive I do:

```
cryptsetup create _dev_sda1 /dev/sda1
```

..as you do also with the loop file. But I am wondering, it just ask once for a passphrase. If tha passphrase is correct, I can access my data, if not, my data is lost and a new mapper-device is created with the new passphrase?? What about typo's :Smile: 

----------

## crubb

When you mistype your passphrase your data isn't lost, it's just not accessible.

The filesystem on the crypted device cannot be mounted, therefore no writing operations should occur on this device and your data is still intact.

You'll just need to remove the mapper device and recreate it with the correct passphrase.

----------

