Skip to content

Instantly share code, notes, and snippets.

@SuwakoMmh
Last active May 14, 2023 14:30
Show Gist options
  • Save SuwakoMmh/0b53f081d17c51189900f809e25dcc62 to your computer and use it in GitHub Desktop.
Save SuwakoMmh/0b53f081d17c51189900f809e25dcc62 to your computer and use it in GitHub Desktop.
Using the same SSH key for multiple Github (& co) accounts

Using the same SSH key for multiple Github (& co) accounts

The most known hack is to edit ~/.ssh/config and use a different hostname in place of github.com for each account. (ref this gist)

However, one might still want to use github.com as a hostname for various reasons. Hence this hack idea I had.

1. Creating a bridge user

This may vary depending on the distribution, but for ubuntu or any given useradd :

# useradd -r -m -d /opt/git git
  • -m – Create the user’s home directory
  • -r – Create a system user
  • -d /opt/git – Set /opt/git as home directory of the new account

2. Setting up the bridge

First, connect as the newly created user :

# sudo -iu git

or

# su - git

Create the ssh directory and create authorized_keys, we'll add the keys later. :

$ mkdir .ssh
$ touch .ssh/authorized_keys

Then let's make a directory for our ssh keys

$ mkdir keys

and add the /opt/git/bridge script using your prefered editor :

#!/usr/bin/env python3
import sys
import os
import subprocess
import shlex

def printe(*args, file=sys.stderr, flush=True, **kwargs):
    print(*args, **kwargs, file=file, flush=flush)

printe("\n~~Connecting via git Bridge...~~")
for keyname in map(os.fsdecode, os.listdir('/opt/git/keys')):
    printe(f"\nConnecting using {keyname}")
    proc = subprocess.Popen(["ssh", '-o', 'StrictHostKeyChecking=no', '-i', '/opt/git/keys/'+keyname, '[email protected]'] + shlex.split(os.environ['SSH_ORIGINAL_COMMAND']), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    payloads=[]
    while True:
        # printe("Waiting...")
        data = proc.stdout.read(4)
        if data == b'':
            break
        length = int(data, base=16)
        if length != 0:
            payload = proc.stdout.read(length - 4)
            payloads.append(payload)
            # printe('S : ', payload)
        else:
            proc.terminate()
    stderr = proc.stderr.read()
    if stderr != b'ERROR: Repository not found.\n':
        printe("Successfuly connected.")
        pid = subprocess.call(['ssh', '-o', 'StrictHostKeyChecking=no', '-i', '/opt/git/keys/'+keyname, '[email protected]']+ shlex.split(os.environ['SSH_ORIGINAL_COMMAND']), stdout=sys.stdout, stderr=sys.stderr, stdin=sys.stdin)
        break
    else:
        printe(stderr.decode())
        printe(f"Failed to connect using {keyname}.\n\n")

and make sure the script is executable :

$ chmod +x /opt/git/bridge

3. Setting up the ssh server

Refer to your distribution manual to install sshd, You might want to disable password authentification or external connections. Log in as root and add your main user's public key to /opt/git/.ssh/authorized_keys

Warning : Make sure to add the options that make our script run before the public key

Here's an example with a dummy public key :

command="/opt/git/bridge",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCtCk3+PdiWcDKbQud7ICxeMkisfxpA6uSXohfoCF42krvorTiXFRxqOxlws+BUM6zIBWxtt7y1mFTuhBhqqG07R5IPfA3KV+wv16Y4G1lOsWPFQA2oQY9u1TrOu02yc8XSdSOWGPfMYwO8rb3+ApSa5T8lKDmuB6MSpE8jGOVrLXGU/K9vSxTaZImEtQJQlT3gdegi+YZNygk7mP3ZCYpaXzfYipIjBEkooCft+/1fTx9jzMowzrx+D5Gea+R8sqKMsKYpAEQL2shzSa+fljND2Z8KOrcyDAoeoYFbOyLz3xuzzdesk5us+f4Iz0RVtCt8dhs6Z6PABfkubjTIJmG3MwDVPyo0pT6IOvbzcgGNgGwdlM/jVLdx8fpeIRRyEeUc3Sr4xBzWtACGLXuGcRi3pPZ4Hrb1nX6Fpjcwpxxs/oa/PjzGRohAOxXRVTupgu7V+6DDZKU4oBQetzjPf62HgiIBJvlJHmg8uM61u3f8AUHBHEntvTOeZ9Mf9YmbXOU= git@moriya-shrine

Finally, add your github private keys in /opt/git/keys, then make sure to chown and chgrp the keys to git.

# cp /home/larry/.ssh/id_rsa /opt/git/keys
# chown git /opt/git/keys/id_rsa
# chgrp git /opt/git/keys/id_rsa

4. Redirect github.com to localhost

As the user you're going to use git with,

If it doesn't exist, create ~/.ssh/config

$ touch ~/.ssh/config

open it in your prefered editor and add the following :

Host github.com
	HostName localhost
	User git
	IdentityFile ~/.ssh/id_rsa

You may add a Port <port> directive if your ssh server is running on a non default port.

Now make sure sshd is running, and try to use git !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment