git remote repository SSH setup

The following is combined from this and this.

Generate an SSH key

On the local machine:

1
2
cd ~/.ssh
ssh-keygen

Follow the prompts. This will generate two files:

  • id_rsa
  • id_rsa.pub

You’ll need to send id_rsa.pub to the remote machine later.

Create the git user

Log on to the remote git-hosting machine as a sudo user:

1
2
sudo adduser git
su - git

Set up the SSH directory

1
2
mkdir .ssh && chmod 700 .ssh
touch .ssh/authorized_keys && chmod 600 .ssh/authorized_keys

Restrict the git user

This sets the shell to git-shell so that the git user can only do git stuff.

Create the git-shell directory:

1
mkdir git-shell-commands

Log out as git user (back to sudo user account):

1
exit

Is git-shell already installed?

1
cat /etc/shells

If not, make sure git-shell is installed and get its path:

1
which git-shell

This will look something like this:

1
/usr/bin/git-shell

Copy the path (assuming it is already installed) and paste it to the end of this file:

1
sudo vim /etc/shells

Then change the shell:

1
sudo chsh -s /usr/bin/git-shell git

Create a bare repository

1
2
3
4
5
6
sudo mkdir -p /opt/git
cd /opt/git
sudo mkdir my-project.git
cd my-project.git
sudo git init --bare
sudo chown -R git:git .

Transfer the public key

Back on the local machine:

1
2
cd ~/.ssh
scp id_rsa.pub user@example.com:~

This will put the public key in the user‘s home directory.

Append the public key to authorized_keys

The git user is restricted to doing git stuff, so this must be executed as root on the remote machine:

1
2
3
4
su
cd /home/user
cat id_rsa.pub >> /home/git/.ssh/authorized_keys
exit

Initialize the project locally

On the local machine:

1
2
3
4
5
6
7
mkdir my-project
cd my-project
git init
git add .
git commit -m "Hello, my-project"
git remote add origin git@example.com:/opt/git/my-project.git
git push origin master

Clone

Now, anyone with a key appended to git‘s authorized_keys (as above) can clone, push, and pull to that repository.

1
git clone git@example.com:/opt/git/my-project.git