# AMD64 Encrypted Filesystem with dm-crypt howto

## dreamshadow

#HOWTO build an encrypted filesystem

#my howto

I wrote this as a reminder of how i set up my system, im posting it for a friend and those who would like

to try this.  You can comment all you want and send me replies and i will try to answer as i get time.

If any of this is confusing dont try it. And if you loose any data its your own fault. Dont blame me.

#im running a amd64 dual core linux, with sda as my primary partition

Use the latest knoppix boot using or use gentoo amd64 install disk but youll need to

download a cryptsetup static binary from somewhere if your using the gentoo amd64 boot disk

```
knoppix 2 no swap
```

```
for i in dm-crypt dm-mod serpent sha256 blowfish aes; do modprobe $i; done
```

Now lets prepare the harddisk for install (testing badblocks and shredding)

```
/sbin/badblocks -c 10240 -s -w -t random -v /dev/hda

shred -v /dev/sda
```

Decide how you are going to partition your harddrive

```
cfdisk /dev/sda
```

now create encrypted swap:

```
cryptsetup -c blowfish -h sha256 -d /dev/urandom create swap /dev/sda2

mkswap /dev/mapper/swap

swapon /dev/mapper/swap
```

configure your network and such as needed and set passwd for root

```
passwd

ifconfig eth0 192.168.x.x

route add default gw 192.168.x.x

nano /etc/resolv.conf

start /etc/init.d/ssh

mkdir /gentoo
```

make sure uuencode (emerge sharutils) is installed

```
emerge sharutils
```

now lets create a gpg encryption key for the main partition and copy it to the usb key

mine is located as sdc, yours will probably be different, also im using sda3 and my primary partition

```
mount /dev/sdc1 /mnt/sdc1

head -c 45 /dev/random | uuencode -m - | head -n 2 | tail -n 1 | gpg --symmetric -a > /mnt/sdc1 mykey.gpg

mkdir /gentoo

cd /mnt/sdc1

gpg -d mykey.gpg | cryptsetup -v --cipher serpent-cbc-essiv:sha256 --key-size 256 luksFormat /dev/sda3

gpg -d mykey.gpg | cryptsetup luksOpen /dev/sda3 myroot

mkfs.ext3 -j -m1 -O dir_index,filetype,sparse_super /dev/mapper/myroot

mount /dev/mapper/myroot /gentoo
```

Mount a boot partition, modify this part if you are using a usb/other place for your boot, if your boot partition is going to be sda1 it cannot be encrypted.

```
mkdir /gentoo/boot

mke2fs /dev/sda1

mount /dev/sda1 /gentoo/boot
```

The next part is if you want multiple encrypted partitions....

if you have multiple partions and keys for different partitions do the following

NOTE: if sensitive data is going to be on the partition that will need to be shredded (example: /tmp)

      it must be an ext2 filesystem, not a journaling fs as ext3/ext4 data cant be permanely delete because of journling.

```
mkdir /root/.keys/

mkdir /gentoo/<partition>

head -c 45 /dev/random | uuencode -m - | head -n 2 | tail -n 1 > /root/.keys/<partition>.key
```

example:  head -c 45 /dev/random | uuencode -m - | head -n 2 | tail -n 1 > /root/.keys/portage.key

now for each partition that you just made a key we need to mount the filesystem

```
cat /root/.keys/<partition>.key | cryptsetup -h plain -c serpent -s 256 create <partition> /dev/sda?
```

for example, my portage directory is on sda7 so i would do the following

>> cat /root/.keys/portage.key | cryptsetup -h plain -c serpent -s 256 create portage /dev/sda7

decide what type of fs you want on that partition and create it

NOTE: if sensitive data is going to be on the partition that will need to be shredded (example: /tmp)

      it must be an ext2 filesystem, not a journaling fs

```
mke2fs /dev/mapper/<partition>

mount /dev/mapper/<partition> /gentoo/<partition>
```

repeat as needed for each partition (portage,tmp,dvds,etc)

now to get the base files  (www.gentoo.org/main/en/mirrors.xml)

find a gentoo mirror and get the latest "stage3" for your distro and save it to /gentoo (make sure its i686 or x86_64)

find a gentoo mirror and get the latest "portage" for your distro and save it to /gentoo

dont forget the md5sums, dont want some hacker spoiling your new install

```
cd /gentoo

tar -xjpvf stage3-XXXXXXXXX.tar.bz2
```

now extract the portage stuff

```
cd /gentoo

tar -xjpf /gentoo/portage-XXXXXXXX.tar.bz2 -C /gentoo/usr
```

now lets get things setup for the new root

```
cp /etc/resolv.conf /gentoo/etc/

mkdir /gentoo/usr/local/portage

mkdir /gentoo/var/log/portage

mount -t proc none /gentoo/proc

mount -o bind /dev /gentoo/dev

cp /proc/mounts /gentoo/etc/mtab
```

now lets change to the new filesystem and get going =)

```
chroot /gentoo /bin/bash

env-update

source /etc/profile
```

now lets set the date so were good ( MMDDHHMMYYYY )

```
date 113018292008
```

now fix the timezone files

```
rm /etc/localtime

ln -s /usr/share/zoneinfo/America/Denver /etc/localtime
```

edit your /etc/make.conf to fit your desire (See Appendix A)

edit the files in /etc/portage:

 *Quote:*   

> /etc/portage/package.keywords

 

```
sys-devel/gcc ~amd64

sys-devel/gcc-config ~amd64

sys-libs/libstdc++-v3 ~amd64

sys-libs/glibc ~amd64

app-emulation/vmware-workstation ~amd64

app-emulation/vmware-modules ~amd64

dev-cpp/libsexymm ~amd64

x11-libs/libview ~amd64
```

 *Quote:*   

> /etc/portage/package.use

 

```
sys-libs/glibc userlocales

sys-devel/libperl ithreads

dev-lang/perl ithreads
```

 *Quote:*   

> /etc/locale.gen

 

```
en_US ISO-8859-1

en_US.UTF-8 UTF-8
```

Sync the portage with the latest sync

```
emerge --sync
```

install the latest linux-headers

```
emerge -v linux-headers
```

build the toolchain

```
emerge sandbox portage binutils gcc-config

USE="nocxx" emerge gmp

emerge mpfr gcc
```

Change to the new compiler:

```
gcc-config -l

gcc-config 2

env-update && source /etc/profile
```

Prune out the old compiler

```
emerge -P gcc
```

Reemerge the new compiler and stuff again

```
emerge glibc binutils gcc portage sandbox
```

Now emerge the empty system:

```
USE="-X" emerge hal

emerge -e system
```

Wait forever..and debug any problems One tip is to

>> emerge -vp system >> system.out

that way you can do an emerge -vp system | less and see whats already install and what still needs to be installed

Onces that finishes lets put in a few daemons and get to some other fun stuff

```
emerge syslog-ng grub vixie-cron sysfsutils gentoolkit
```

Now configure your kernel'=

## AMD64 notes  

#with amd64 you must include

#	Executable file formats/Emulation -->

#		[*]	IA32 Emulation

#	Processor type and features -->

#		[*]	Symmetric multi-processing support

```
cd /usr/src/linux

make clear mrproper

make menuconfig

make ; make modules_install ; make install
```

ok, i noticed at this point there are a few files that need to be relinked, you may need to delete these files

first

```
ln -s /lib64/rc/sh/gendepends.sh /etc/init.d/depshan.sh

ln -s /lib64/rc/sh/runscript.sh /etc/init.d/runscript.sh

ln -s /sbin/udevadm /sbin/udevinfo
```

Ok now that the kernel is made and installed lets create an initramfs to boot this bitch

```
cd /root

mkdir new_ramfs

cd new_ramfs

mkdir ./{bin,dev,lib,mnt,new,proc}

touch init
```

Now we need to build some busybox programs to use

```
ROOT="/tmp/bb" USE="static -readline" emerge --nodeps busybox

cd /root/new_ramfs/bin

cp /tmp/bb/bin/busybox ./

for i in cat clear echo mkdir mknod mount sed sh sleep stty switch_root test touch umount; do

ln busybox $i

done
```

We now need to install a STATIC cryptsetup from:  http://luks.endorphin.org/dm-crypt

```
cd /root/new_ramfs/bin/

wget http://luks.endorphin.org/precompiled/cryptsetup-1.0.3-i686-pc-linux-gnu-static.bz2

bzip2 -d cryptsetup-1.0.3-i686-pc-linux-gnu-static.bz2

mv cryptsetup* ./cryptsetup

chmod 0755 cryptsetup
```

Now we need to install a STATIC version of gpg

```
ROOT="/root/tmp" USE="static" emerge -av =gnupg-1.4.9

cp /root/tmp/gpg /root/new_ramfs/bin/
```

We now need to get e2fsck and its libraries moved over

```
cp /sbin/e2fsck /root/new_ramfs/bin/

ldd /sbin/e2fsck
```

For each lib listed copy it to the new_ramfs/lib folder

```
cp /lib/linux-gate.so.1 /root/new_ramfs/lib/
```

We now need to create the device files for our initramfs

```
cd /root/new_ramfs/dev

mknod -m600 console c 5 1

mknod -m660 hda3 b 3 3

mknod -m660 null c 1 3

mknod -m660 ram0 b 1 0

mknod -m666 tty c 5 0
```

Now we need to create the following script in /root/new_ramfs called devmap_mknod.sh

```
#!/bin/sh

DM_DIR="mapper"

DM_NAME="device-mapper"

set -e

DIR="/dev/$DM_DIR"

CONTROL="$DIR/control"

if test -e /dev/.devfsd ; then

 echo "devfsd detected: devmap_mknod.sh script ending."

 exit

fi

if test ! -e /proc/devices ; then

 echo "procfs not found; please create /dev/mapper/control manually."

 exit 1

fi

MAJOR=`awk '/misc$/ {print $1}' /proc/devices`

MINOR=`awk '/'"$DM_NAME"'$/ {print $1}' /proc/misc`

if test -z "$MAJOR" -o -z "$MINOR" ; then

 echo "device-mapper kernel module not loaded; cant create /dev/mapper/control"

 exit 1

fi

mkdir -p -m755 /dev/mapper

test -e /dev/mapper/control && rm -f /dev/mapper/control

echo "Creating $CONTROL character device with major: $MAJOR minor: $MINOR"

mknod -m600 $CONTROL c $MAJOR $MINOR

```

Now we need to create the /root/new_ramfs/linuxrc file,  Please change the following script to

match your setup replacing the /mnt/gpgkey.gpg and luksOpen settings

#note replace sdc1 with whatever device your usb key will show up as!!!!!

```

#!/bin/sh

export PATH=/bin:/sbin

#the following die() is for debugging, once you have things working it can be removed

die()

 {

  err_msg="$1"

  echo "Error: $err_msg, dropping to a shell"

  echo

  exec /bin/sh

 }

/bin/busybox mount -t proc proc /proc

CMDLINE=`cat /proc/cmdline`

sh devmap_mknod.sh

sleep 3

/bin/cat /lib/eyes2   #this is just an ascii file with cool ascii in it

if [ ! -e "/mnt/thepgpkey.gpg" ]; then

 echo

 echo "Please insert Key Device and press Enter"

 echo

 read x

 sleep 2                        

 echo "Checking key device..."  

 /bin/e2fsck -y /dev/sdc1      #replace with your usb device from the start

 /bin/busybox mount -n /dev/sdc1 /mnt

 if [ ! -e "/mnt/thepgpkey.gpg" ]; then

  die "Either mount failed or cant find Cryptkey"

 fi                             

fi                              

                                

rm /dev/tty                     

ln -s /dev/console /dev/tty     

cd /mnt                         

echo                            

/bin/gpg -d /mnt/thepgpkey.gpg 2>/dev/null | cryptsetup luksOpen /dev/hda3 cypher

                                

if [ ! -e "/dev/mapper/cypher" ]; then

 die "Cryptsetup or GPG"        

else                            

 /bin/e2fsck -y /dev/mapper/cypher

 /bin/busybox mount -n -r /dev/mapper/cypher /new

fi

cd /                            

/bin/busybox umount /mnt        

                                

clear                           

echo "Entering......"   

echo                            

sleep 2                         

/bin/busybox umount /proc       

exec /bin/busybox switch_root /new /sbin/init ${CMDLINE}

```

Now we need to compress this and copy it to /boot

```
cd /root/new_ramfs

chmod 0755 devmap_mknod.sh

chmod 0755 linuxrc

cd /root/new_ramfs/bin

chmod 0755 *

cd /root/new_ramfs/lib/
```

Option is to create a funny little ascii file in here to be called by linuxrc

```
echo "Funny little ascii file" >> funny.asc

chmod 0755 *

cd /root/new_ramfs

find . | cpio -o -H newc | gzip -9 > /root/initramfs-crypt

cp /root/initramfs-crypt /boot

cd /boot/

chmod 0755 initramfs-crypt
```

Were going to edit the grub files now, given is just and example of how one looks

```
cd /boot/grub

nano menu.lst

timeout 30

default 0

fallback 1

color light-green/black blink-red/blue

title Cypher-0.10

root (hd1,0)

kernel /boot/vmlinuz-2.6.26-gentoo-r1dual-cypher.10 root=/dev/ram0 rdinit=/linuxrc \

ramdisk=8192 real_root=/dev/mapper/cypher vga=0x318 video=vesafb:mtrr:3,ywrap

initrd /boot/initramfs-crypt

```

Now were going to set up grub

```
grub

root (hd1,0)

setup (hd1)

quit
```

Now that thats done its time to get a few things configured

First set a passwd for root

```
passwd
```

Now edit /etc/fstab, given is an example fstab file

```

/dev/sda1               /boot           ext2            noauto,noatime  1 2

/dev/mapper/cypher      /               ext3            noatime         0 0

/dev/mapper/swamp       none            swap            sw              0 0

/dev/mapper/wasteland   /tmp            ext2            noatime,noexec  0 0

/dev/mapper/matrix      /home           ext3            defaults        0 2

/dev/mapper/portage     /usr/portage    ext3            noatime,noexec  0 0

/dev/mapper/ramfs       /ramfs          ext3            defaults        0 2

/dev/mapper/junkyard    /junkyard       ext3            defaults        0 2
```

Now edit /etc/conf.d/dmcrypt, given is and example file

When running dmcrypt for the first reboot, uncomment all thre pre_mout and post_mount commands

so that dmcrypt can reformat the drives as encrypted, then on the next boot, comment them out again.

Does that make sense?

note these are just examples not my real layout, youll need to change things to match your layout

NOTE: if you encrypted your /var directory make sure you do the following

```
tar -cjf /root/var.tar.bz2 /var/
```

then on next reboot after your new var has been reformatted untar your backed up var to your new encrypted /var

that way your portage files and cache are saved and everything. make sure you add a fstab for your /var section.

if that doesnt make sense then this document is probably above your head.

```

# /etc/conf.d/dmcryt

swap=swamp

source='/dev/sda2'

target=matrix

source='/dev/sda9'

key='/root/.keys/matrix.key'

#pre_mount='/sbin/mkfs.ext3 -j -m 1 -O dir_index,filetype,sparse_super ${dev}'

#post_mount='chown cypher:deckers /home'

target=wasteland

source='/dev/hda6'

key='/root/.keys/tmp.key'

pre_mount='/sbin/mke2fs ${dev}'

post_mount='chown root:root /tmp; chmod 1777 /tmp; chmod +t /tmp'

target=ramfs

source='/dev/hda7'

key='/root/.keys/ramfs.key'

#pre_mount='/sbin/mkfs.ext3 -j -m 1 -O dir_index,filetype,sparse_super ${dev}'

#post_mount='chown cypher:deckers /ramfs'

target=junkyard

source='/dev/hda8'

key='/root/.keys/junkyard.key'

#pre_mount='/sbin/mkfs.ext3 -j -m 1 -O dir_index,filetype,sparse_super ${dev}'

#post_mount='chown cypher:deckers /junkyard'

```

Now edit the other files in /etc/conf.d to meet your needs

Once you are completely satisfied you have a running base its time to test it out

Exit and unmount all the mounted partitions

```
exit

umount /gentoo/{boot,proc,dev,etc,etc,etc}

cryptsetup remove <encrypted parition>   (for example portage,tmp,etc}

cryptsetup luksClose <something>

sync

reboot
```

Goodluck!!!

Appendix A

```

/etc/make.conf

CFLAGS="-O2 -pipe -march=k8 -mtune=k8 -mfpmath=sse  -fomit-frame-pointer"

CXXFLAGS="-O2 -pipe"

#LDFLAGS="-W1,-O1"

CHOST="x86_64-pc-linux-gnu"

ACCEPT_KEYWORDS="~amd64"

PORTAGE_OVERLAY="/usr/local/portage"

PORTDIR_OVERLAY="${PORTAGE_OVERLAY}"

PORT_LOGDIR="/var/log/portage"

MAKEOPTS="-j4"

PORTAGE_NICENESS=5

AUTOCLEAN="yes"

FEATURES="distlocks nodoc sandbox"

ALSA_CARDS="snd-hda-intel"

VIDEO_CARDS="nvidia vesa nv"

INPUT_DEVICE="keyboard mouse"

LIRC_DEVICES="all"

JAVA_HOME="/etc/java-config-2/current-system-vm"

CONFIG_PROTECT="/etc/conf.d /etc/X11/gdm"

PORTAGE_RSYNC_EXTRA_OPTS="--exclude-from=/etc/portage/rsync_excludes --recursive --links --safe-links --perms --times --compress --force --whole-file --delete --stats --timeout=180 --exclude=/distfiles --exclude=/local --exclude=/packages"

USE="3dnow 3dnowext X a52 aac aalib accessibility acpi aim alsa amarok -apache apache2

     -cups -arts audacious avi bash-completion bluetooth cairo cdaudio cdda cddb cdio

     cdparanoia chroot clamav cpio css curl curlwrappers cxx dba dbus device-mapper

     dga divx divx4linux dlloader -doc dts dv dvb dvd dvdnav dvdr dvdread dvdwrite dvi 

     eap-tls encode escreen ethereal evolution fame threads

     fbcon ffmpeg firefox firefox3 flac fortune gcrypt gd gif gimp gkrellm

     glade glib glibc-compat20 gmp gnome gnome-keyring gnutella gnutls gpg

     gpgme grub gsm gstreamer gtk gtk2 gtkhtml hal hash html http httpd id3tag idea

     imagemagick imap imlib injection inotify ipod iproute2 ipsec irc ithreads

     jabber java javascript jpeg jpeg2k lame ldap libgcrypt libssh2 libwww

     lm_sensors loop-aes mad maildir md5sum mhash mime mjpeg mmx mmxext mng

     mono mozdevelop mozilla mp3 mp4 mpeg mpeg2 mplayer multilib nsplugin

     nvidia offensive ogg oggvorbis opengl openssl opensslcrypt -oss pcap php pidgin png

     prelude quicktime samba sdl sha512 sockets socks5 sqlite sse sse2 ssh svga 

     subtitles tcl tcltk tcpd tiff udev usb userlocales vorbis wifi wireshark win32codecs 

     x264 xinerama xmms xscreensaver xine xv xvid xvmc -fortran -kde -nls -qt3 -qt4

     xml xml2 ldappam unicode innodb imlib2 xulrunner v4l vcd vidix"
```

----------

## avx

 *Quote:*   

> cryptsetup -v --cipher serpent-cbc-essiv:sha256

 Any reason your not using the much better xts-mode?

 *Quote:*   

> I cant stress this enought...The boot partition cannot be encrypted!!!!

 Sure it can, if your booting from usb/sd/mcc/dvd/... that is.

For readability, please edit your post and place code-tags around what the user is supposed to enter, thx.

----------

## jamario

 *dreamshadow wrote:*   

> #cypher@futilesystems.net
> 
> dont forget the md5sums, dont want some hacker spoiling your new install
> 
> >> cd /gentoo
> ...

 

If the hacker has half a brain he will just replace the md5 in the HTTP stream with a hash of his infected image. Not to mention MD5 and SHA1 are weak in the first place..

----------

## Evildad

One side note I found out:

You have to use app-crypt/gnupg-1.4.9 in your initramfs. 

The newer app-crypt/gnupg-2.0.11 needs pinentry as a dependency which segfaulted for me...

----------

