How to Remotely Access the Initial Ramdisk of an Encrypted Linux System

If you use cryptsetup to encrypt your Linux root file system, the default setup requires console access to enter the password and boot up the system. If your system is remote or doesn’t have console access, you will need to find a way to get remote access to the console.

If you cannot install a remote console or if your system doesn’t allow one, for example, instances in Amazon Web Services (AWS), you can still obtain remote access to enter the password by installing an ssh server in the initial ramdisk. Once you can login by ssh into the initrd, you can then supply the password to decrypt and boot up the system.

Below is a step-by-step guide on how to install an ssh server in the initial ramdisk, login to it, and enter the password to boot up your encrypted Linux system. The guide is created for Ubuntu and Debian systems and using DHCP to establish network access. The idea can be easily applied to other distributions like CentOS or RHEL.

The guide shows both a manual process and a script to automate the steps. It is recommended to try the manual steps first so that you will have an understanding of the underlying process. This can help in troubleshooting the script in case you encounter problems.

You will need access to GitHub to download the scripts.

Install dropbear

apt-get install dropbear

Get your public ssh-key and copy it to this file on your remote system:


If you don’t have an ssh-key pair, you can create one using the ssh-keygen command


This command will generate two files:


The file is the public key where you will need to copy to the remote system as described in #2 above.

The id_rsa file is the private key where you will need to copy to the client that will login by ssh.

If you are using an AWS instance, copy the public-key of your instance into this authorized_keys file.

Update the initial ramdisk image

Run this command to update the initial ramdisk file:

update-initramfs -u

Boot up the system

When the system boots up, connect to the system using ssh and the private key you created above.

ssh -i ~/.ssh/id_rsa root@ip-address

You don’t actually need to supply the -i option for that key-file since that is the default. This is just to illustrate that you need to use the matching key-file to login by ssh.

Enter password remotely

Once you gained access to the system by ssh, execute the following steps in sequence:

  1. Kill the cryptroot process.Sample run:
    # pidof cryptroot
    # kill -9 161
  2. For Ubuntu systems, wait for the cryptsetup process to terminate. You can monitor this process by running this command:
    # pidof cryptsetup

    This could take about a minute to complete.

  3. For Debian systems, wait for the /bin/sh -i process to come up. This is also applicable for Ubuntu.

    # ps | grep '/bin/sh -i' | grep -v grep
      214 root      4620 S    /bin/sh -i

    This could take about a minute to complete. Take note of the ID of this process when it comes up.

  4. Once cryptsetup has terminated (for Ubuntu only) or the /bin/sh -i process has come up, run the cryptroot command:

    This command will prompt for the password to decrypt the system.

    Sample run:

    # /scripts/local-top/cryptroot
    /scripts/local-top/cryptroot: line 1: modprobe: not found
    Unlocking the disk /dev/disk/by-uuid/b1aa9e88-c344-4922-a0a6-d3f7c52f947a (sda5_crypt)
    Enter passphrase:
       Reading all physical volumes.  This may take a while...
      Found volume group "ubuntu-vg" using metadata type lvm2
      2 logical volume(s) in volume group "ubuntu-vg" now active
    cryptsetup: sda5_crypt set up successfully
  5. After entering the password, kill the process-id of the /bin/sh -i you saw earlier.Important Note: At this point, your terminal is kind of screwed up. You won’t be able to see what you are typing. So carefully, type the kill command using the /bin/sh -i process-id you got earlier and hit the enter key.
    # kill -9 214
  6. Type ctrl-d to disconnect from your ssh access. At this point, the system should be on the way up booting the system. If you have access to the console, you can observe how long it takes for your system to boot up. You can use this to estimate the time it takes for your system to fully come up after you enter the password remotely and start accessing the system.

Automating the remote password process

The remote password process above seems to be a lot of work just to enter the password and boot up the system. If this doesn’t sound fun to you, I wrote a couple of scripts to automate the steps.

  1. Download these two scripts from GitHub:
  2. Save the files at this location:

    Make them executable:

    chmod +x /root/
    chmod +x /etc/initramfs-tools/hooks/my_initrd_hook
  3. Update the initial ramdisk image
    update-initramfs -u
  4. Boot up the system and login remotely by ssh
  5. At the shell prompt, run this command and enter the password when you get the prompt:

    Sample run:

    # /root/
    cryptroot has terminated.
    Waiting for /bin/sh -i to start...
      277 root      4620 S    /bin/sh -i
    sh -i has started.
    Unlocking the disk /dev/disk/by-uuid/b1aa9e88-c344-4922-a0a6-d3f7c52f947a (sda5_crypt)
    Enter passphrase:   
    Reading all physical volumes.  This may take a while...
      Found volume group "ubuntu-vg" using metadata type lvm2
      2 logical volume(s) in volume group "ubuntu-vg" now active
    cryptsetup: sda5_crypt set up successfully
    Terminating sh -i process...
    Press ctrl-d or type exit to disconnect from initrd dropbear.
Posted in Uncategorized | Leave a comment

Show the History of CVS Commits Similar to Git or SVN

I wrote a simple script that will display the history of CVS commits similar to the way Git or SVN do. You can download the script from Github:

Basic usage [-b BRANCH] module or files

For more options, see:


If you use the “cvs history” command to display the history of commits in CVS, you will get an output that is not sorted chronologically.

Here’s a sample run:

$ cvs history -a -c hello_cvs/
M 2015-02-28 23:52 +0000 alice 1.6 hello_cvs == ~/main/hello_cvs
M 2015-02-28 23:48 +0000 alice 1.3 hello_cvs == ~/main/hello_cvs
M 2015-03-01 17:05 +0000 alice hello_cvs == ~/workspace/hello_cvs
A 2015-03-01 00:38 +0000 alice hello_cvs == ~/feature_branch/hello_cvs
M 2015-03-01 00:42 +0000 alice hello_cvs == ~/workspace/hello_cvs
M 2015-02-28 23:10 +0000 alvin 1.2 hello_cvs == ~/src/hello_cvs
M 2015-02-28 23:13 +0000 alvin 1.3 hello_cvs == ~/src/hello_cvs
M 2015-02-28 23:18 +0000 alvin 1.4 hello_cvs == ~/src/hello_cvs
M 2015-02-28 23:23 +0000 alvin 1.5 hello_cvs == ~/src/hello_cvs
M 2015-03-01 00:37 +0000 alvin 1.7 hello_cvs == ~/src/hello_cvs
A 2015-02-28 23:20 +0000 alvin 1.1 hello_cvs == ~/src/hello_cvs
M 2015-02-28 23:23 +0000 alvin 1.2 hello_cvs == ~/src/hello_cvs
M 2015-03-01 00:44 +0000 alvin 1.4 hello_cvs == ~/src/hello_cvs

As you can see from the output above, it is hard to figure out the order when the changes happened. The output gets worse if you have many branches. The output displays all the history of commits in all branches and mixed altogether.

Posted in Uncategorized | Tagged | Leave a comment

A Simple Option Parser in Bash

There is a builtin command in bash named getopts that can process command-line options of a shell script. It works pretty well except that it can only handle single-letter options like -a, -b, -c, etc. It cannot handle long option names like --version, --verbose, and --force. For long option names, there is an external command named getopt, however for me, it is one command that is not easy to use.

Single-letter options in a command is fine until you run out of letters or you require more user-friendly usage. For example, if you need both version and verbose options, which one should you assign -v for? If you need options like --force and --file, which one should use -f for? When this happens, you’re left with no choice but to use a different character for the other option. And most of the time, you end up with a character that doesn’t make sense with the option it pertains to.

So, I decided to just implement my own parsing. It can handle both short and long option names. Below is an example.


while true
  case $1 in
    --version)  # get version
        shift; shift
    -v) # use verbose mode
        echo "Unknown option: $1"
        exit 1

echo $*

The bash code above handles the options --version and -v. The idea is simple. All it has to do is loop through all the command line arguments using the while and case commands. For each argument it encounters, it checks if it’s one of the options it is expecting. If the option requires a parameter, which is usually the case for long option names, it gets the value in $2 which is the next parameter since $1 contains the name of the option itself. Before proceeding to the next option, it performs a double shift command in order to set $1 as the next option name. If the option does not require a parameter, it only executes a single shift command. You can also use long option names that does not require a parameter by simply using a single shift command.

Once the script encounters a non-option argument, it breaks out of the while-loop and the rest of the arguments get assigned to $*.

For non-expected options, you search for the -* string (after exhausting all expected options) and then generate an error. If you prefer, you may just ignore it or simply pass it to the rest of the arguments as a non-option.

The code above is short and simple. It’s also easy to read for anyone who wants to know how to run your script since it’s almost self-documenting. You don’t need to write an elaborate usage documentation on what options to use.

One limitation to this parser is that all options must be specified before the non-option arguments. It’s a small price to pay for the ease of use it offers.

Posted in Linux | Leave a comment

Setting up a Raspberry Pi

This little beauty is a lot of fun.

The Raspberry Pi

Image linked from –

For only $35, you can set up a small Linux server. I’ve documented the steps below on how to set it up. This assumes a MAC OSx environment.

1. Download the Raspbian image.

The download page is located here:

Locate the latest wheezy-raspbian zip file and run wget to download:

$ wget

$ unzip

inflating: 2013-02-09-wheezy-raspbian.img

2. Load an SD card of at least 2GB in size into your MAC.

Identify the device the sd card is connected to using the diskutil command

$ diskutil list
0: FDisk_partition_scheme *4.0 GB disk4
1: DOS_FAT_32 NO NAME 4.0 GB disk4s1

3. Unmount the sd card

$ diskutil unmountDisk /dev/disk4
Unmount of all volumes on disk4 was successful

4. Save the raspbian image into the SD card. Grab a coffee. This takes several minutes. In my case, it took almost 15 minutes.

$ sudo dd bs=1m if=2013-02-09-wheezy-raspbian.img of=/dev/disk4
1850+0 records in
1850+0 records out
1939865600 bytes transferred in 865.345934 secs (2241723 bytes/sec)

5. Unmount and eject the sd card

$ diskutil list /dev/disk4
0: *4.0 GB disk4

$ diskutil unmountDisk /dev/disk4
Unmount of all volumes on disk4 was successful

$ diskutil eject /dev/disk4
Disk /dev/disk4 ejected

6. Load the sd card into the Raspberry Pi and power it up.

I used a serial connection to the raspberry pi so that I can cut-and-paste the bootup information below.

Debian GNU/Linux 7.0 raspberrypi ttyAMA0

raspberrypi login: pi
Linux raspberrypi 3.6.11+ #371 PREEMPT Thu Feb 7 16:31:35 GMT 2013 armv6lThe programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.

NOTICE: the software on this Raspberry Pi has not been fully configured. Please run ‘sudo raspi-config’

7. Set initial configuration.

pi@raspberrypi:~$ sudo raspi-config

8. Change passwords

# sudo passwd root
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully

# sudo passwd pi
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully

9. Run update and upgrade

To run the update and upgrade commands below, you will need to have Internet connection. Connect your pi to your ethernet network that has dhcp. With dhcp, the pi is preconfigured to connect automatically and establish network connection.

If you are using the model A Raspberry Pi, it doesn’t have an ethernet connection. You will need to use a wifi usb adapter to obtain Internet connectivity. Follow step #11 below to setup wifi access.

$ sudo apt-get update
$ sudo apt-get upgrade

10. Configure time zone and reboot.

$ sudo dpkg-reconfigure tzdata
$ sudo reboot

11. Configure Wireless LAN

I recommend the Edimax-EW-7811Un wireless USB adapter for the Raspberry pi. This device is plug-and-play on the raspberry pi. You don’t need to download any drivers. The drivers are already available with the image. This device also offers a very simple configuration. I’ve seen configurations out there for other adapters that are too complex. As you’ll see below. you only need to update one file to get this working.

First, check if the raspberry pi has detected the device. The ifconfig command should show the device wlan0.

# ifconfig -a
eth0 Link encap:Ethernet HWaddr b8:27:eb:01:b6:8a
inet addr: Bcast: Mask:
RX packets:130 errors:0 dropped:0 overruns:0 frame:0
TX packets:95 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:12743 (12.4 KiB) TX bytes:14501 (14.1 KiB)

lo Link encap:Local Loopback
inet addr: Mask:
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)

wlan0 Link encap:Ethernet HWaddr 80:1f:02:9b:f0:3b
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)

Update /etc/network/interfaces file

# cat /etc/network/interfaces
auto lo
iface lo inet loopback
iface eth0 inet dhcpauto wlan0
allow-hotplug wlan0
iface wlan0 inet dhcp

# WPA type
wpa-ssid “MYSSID”
wpa-psk “secret”

### WEP type
#wireless-essid MYSSID
#wireless-key secret

iface default inet dhcp

Run ifdown/ifup or simply reboot for changes to take effect.

# ifdown wlan0
# ifup wlan0

That’s it. It’s just one file to update to enable wifi access.

Run iwconfig to check the status of your wifi connection.

# iwconfig wlan0
wlan0 IEEE 802.11bgn ESSID:”MYSSID” Nickname:””
Mode:Managed Frequency:2.462 GHz Access Point: 90:E6:BA:D3:C8:68
Bit Rate:150 Mb/s Sensitivity:0/0
Retry:off RTS thr:off Fragment thr:off
Encryption key:****-****-****-****-****-****-****-**** Security mode:open
Power Management:off
Link Quality=100/100 Signal level=73/100 Noise level=0/100
Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0
Tx excessive retries:0 Invalid misc:0 Missed beacon:0

12. Prevent your wifi adapter from sleeping

Some wifi adapters are set to sleep when there is no activity. You may want to disable this feature if you want your wifi access to be on at all times. This would be useful if you use your pi as a headless server and you only connect to it through its wifi.

Update or create the file below (or equivalent) to prevent your wifi device from sleeping. The filename may be different with your wifi adapter.

# cat /etc/modprobe.d/8192cu.conf
options 8192cu rtw_power_mgnt=0 rtw_enusbss=0 rtw_ips_mode=1

Posted in Linux | 3 Comments

Some Debian and Ubuntu Quirks


I’m not sure why Debian and Ubuntu decided to make the EDITOR default to nano instead of vi. It is annoying whenever I run the visudo command the sudoers file gets opened up by nano instead of vi. Isn’t it why it was called visudo and not nanosudo? :)

Arrow keys in VI

The vi in Debian doesn’t allow the arrow keys in edit mode. Why? An easy fix would be to do :set nocompatible in vi. But still, would it be nice if this would be the default like in other distros (Ubuntu, Redhat, and CentOS)? VI in MacOSX also allows the arrow keys in edit mode.

Posted in Unix | Leave a comment

How to specify an ssh-key file with the Git command

If you want to use an ssh-key file whenever you run the ssh command, one convenient way to do this is to use the -i option.

ssh -i ~/.ssh/thatuserkey.pem

This is pretty neat. It’s simple, elegant, and highly intuitive. I want to do the same thing with the Git command like this:

git -i ~/.ssh/thatuserkey.pem clone

Unfortunately, there is no such -i option in the git command. Bummer.

I’ve looked around but I can’t find a solution like this. There are two options I can think of: 1) use GIT_SSH and 2) use a wrapper script.

Option 1: Use the GIT_SSH environment variable

The GIT_SSH option will allow you to specify a key file with the Git command like this:

PKEY=~/.ssh/thatuserkey.pem git clone

where ~/.ssh/thatuserkey.pem is the keyfile you want to use.

To make this work, it needs some pre-configuration. The first step is to create a shell script that contains the following.


if [ -z "$PKEY" ]; then
# if PKEY is not specified, run ssh using default keyfile
ssh "$@"
ssh -i "$PKEY" "$@"

The script needs to be executable so do a chmod +x on it.

Next step is to set the value of the GIT_SSH variable to the path of the script above. The variable will need to be exported to the shell environment.

export GIT_SSH=~/

Now every time you run the git command, the keyfile you set to the PKEY variable is passed to the shell script GIT_SSH is pointing to. This will then allow Git to connect using that key file.

PKEY=~/.ssh/thatuserkey.pem git clone

From hereon, every time you run the Git command, you can freely choose any key file you want to use by setting the PKEY variable.[1]

If you run the git command without the PKEY line, the GIT_SSH script will still run since this is exported to the shell environment. The script has a fail safe to avoid using the -i option if there was no keyfile set so that it can still run using the default keyfile.

Be careful when exporting PKEY to the shell environment because GIT_SSH will use whatever value it is set to even if you don’t specify it with the git command. This brings another problem with GIT_SSH exported to the environment since Git will always use this when it runs. So you need to be constantly conscious that you have this set. You can always chain the GIT_SSH setting with the git command to avoid exporting it to the environment, but at the expense making the entire command longer.

The PKEY-line usage works well except that the setting of PKEY together with the git command is somehow unconventional.[2]

If you find this unintuitive, there is another option.

Option 2: Use a wrapper script

The -i option with ssh is pretty neat and elegant. You supply the -i option to choose the key file you want to use. If you don’t use the option, ssh will fall back to use the default ssh-key file.

To use the -i option with the Git command, we need to write a wrapper script. The wrapper script will then allow us to set the usage we like and that is to mimic the -i option in ssh.

The usage will be something like this: -i ~/.ssh/thatuserkey.pem clone

where is the wrapper script.

The only thing you need to do is create that script, put it in your PATH, and you’re all set.

To get the code, you can download it from here or cut-and-paste that below.


# The MIT License (MIT)
# Copyright (c) 2013 Alvin Abad

if [ $# -eq 0 ]; then
    echo "Git wrapper script that can specify an ssh-key file
Usage: -i ssh-key-file git-command
    exit 1

# remove temporary file on exit
trap 'rm -f /tmp/.git_ssh.$$' 0

if [ "$1" = "-i" ]; then
    SSH_KEY=$2; shift; shift
    echo "ssh -i $SSH_KEY \$@" > /tmp/.git_ssh.$$
    chmod +x /tmp/.git_ssh.$$
    export GIT_SSH=/tmp/.git_ssh.$$

# in case the git command is repeated
[ "$1" = "git" ] && shift

# Run the git command
git "$@"

The wrapper script can fail gracefully. If you don’t specify the -i option, it will run git using your default key-file.

This wrapper script uses the same principle of the GIT_SSH environment variable. But instead of pre-setting this up manually, the wrapper script sets this up on the fly every time it runs the actual git command.

Other options

There are other ways to use different ssh-keys with the Git command. There is this $HOME/.ssh/config file where you can map different keys to hosts you want to connect to. But this method doesn’t allow you to choose any key file at will when you need to run the git command. The keys need to be pre-defined in the config file.

You can also use ssh-agent to programmatically add the key you want to use. I also wrote a wrapper script that uses ssh-agent to allow the -i option. But it turned out to be more complex than GIT_SSH way. I’ll probably post that to show how it can be done that way.

With all the different methods available, none is necessarily better than the other. It will all depend on the circumstances and of course your personal taste.


[1] I prefer this kind of control in my workflow because I use different keys for different servers I use. I have a different key for my servers at work and different keys for my personal servers and public sites (like Github). It works the same with passwords. You don’t use the same password on your Facebook and bank accounts.

[2] Personally, I find this all right since I am used to this usage. I run a lot of scripts and make commands that require environment settings. But I don’t like the idea of exporting all of them to the shell environment and leaking them everywhere so I only specify them with the command.

Posted in Git, Unix | Tagged | 15 Comments

How to Use LUKS to Encrypt a Disk Partition

You can use LUKS to encrypt a partition of a disk drive or USB. If you store sensitive information in portable drives it’s more compelling than ever to protect them using encryption since they carry a high risk of getting lost or stolen.

LUKS/dm-crypt is a good choice for encrypting Linux devices. It’s usually pre-installed in most Linux distros and if not, it’s easy to install using YUM or APT.

Here are seven easy steps to encrypt a disk partition:

Step 1. Create the disk partition you wish to encrypt. For example, let’s say you have a USB drive and it’s connected to /dev/sdb. The partition you’d want to create would be /dev/sdb1.

# fdisk -l /dev/sdb
Disk /dev/sdb: 512 MB, 512483328 bytes
255 heads, 63 sectors/track, 62 cylinders, total 1000944 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1              63     1000943      500440+  83  Linux

Step 2. Encrypt the partition

# cryptsetup -q -y luksFormat /dev/sdb1
Enter LUKS passphrase: 
Verify passphrase: 

Step 3. Map a logical partition

# cryptsetup luksOpen /dev/sdb1 sdb1_crypt
Enter passphrase for /dev/sdb1:

This will create a device mapper:

# ls -al /dev/mapper/sdb1_crypt
brw-rw---- 1 root disk 253, 5 Sep 23 11:53 /dev/mapper/sdb1_crypt

Step 5. Format the encrypted partition

# mkfs.ext3 /dev/mapper/sdb1_crypt 
mke2fs 1.42.5 (29-Jul-2012)
Filesystem label=
OS type: Linux
Block size=1024 (log=0)
Fragment size=1024 (log=0)
Stride=0 blocks, Stripe width=0 blocks
124928 inodes, 498392 blocks
24919 blocks (5.00%) reserved for the super user
First data block=1
Maximum filesystem blocks=67633152
61 block groups
8192 blocks per group, 8192 fragments per group
2048 inodes per group
Superblock backups stored on blocks: 
	8193, 24577, 40961, 57345, 73729, 204801, 221185, 401409

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (8192 blocks): done
Writing superblocks and filesystem accounting information: done 

Step 6. Mount the encrypted partition:

# mkdir /mnt/sdb1
# mount /dev/mapper/sdb1_crypt /mnt/sdb1

Step 7. When done unmount the logical partition and close (unlock) the encrypted partition

# unmount /mnt
# cryptsetup luksClose sdb1_crypt
Posted in Uncategorized | Leave a comment