Friday, February 25, 2011: Serving Mercurial Over SSH, with Passwords « from the old blog archive »

I'm doing a website project and I want to put them in a central repository on my server. I prefer to use password authentication on the server. The trick is to tell SSH to always execute hg instead of the shell.

Note: These command are to be executed as root.

Preparing for the environment

I created a /hg directory to hold the repositories.

mkdir /hg
cd /hg

Setting up a skeleton

mkdir skel
mkdir skel/.ssh
mkdir skel/repo
echo > skel/.ssh/authorized_keys
chmod 600 skel/.ssh/authorized_keys

This creates a skeleton directory.

Creating A New User

I do this by copying the skeleton, well, actually, I like doing this manually:

cp -Rp skel hg-rwb
chown -R hg-username:hg hg-username/

Add the new user to /etc/passwd

hg-username:x:3001:3000::/hg/hg-username:/bin/sh

Take note of the group ID 3000, we'll add it in /etc/group

hg:x:3000:hg-username

Add the password:

passwd hg-username

Tell the SSH server to allow only Mercurial

Edit /etc/ssh/sshd_config and add these lines:

Match Group hg
    ForceCommand hg -R ~/repo serve --stdio
    AllowAgentForwarding no
    AllowTcpForwarding no
    X11Forwarding no

Initialize the repository

su hg-username
cd ~/repo
exec hg init

Use it!

hg init
hg add
hg commit
echo '[paths]' >> .hg/hgrc
echo 'default-push=ssh://hg-username@my.secret.server/' >> .hg/hgrc
hg push