Search code examples
gitsshssh-keys

How does ssh server know which public key to match the ssh private key?


The server's authorized_keys contains tens of thousands keys, how does the server know which public key to match the current user's private key?

For example, normally the username is always git, how does the server know current user's identity?

enter image description here

Detail questions:

  • When I use ssh to pull the code by git pull, how does the server know that git pull is from which user?

  • And then how does the server get the public key associated with the user?


Solution

  • Because the public key is registered to the GitHub user account settings

    https://github-images.s3.amazonaws.com/github-ae/assets/images/help/settings/ssh-key-paste.png

    Usually, this kind of repository hosting service will populate its ~git/.ssh/authorized_keys with a SSH forced command:

    command="/path/to/script userID",\
     no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty \
     ssh-rsa <yourPublicKey>
    

    instead of:

     ssh-rsa <yourPublicKey>
    

    It calls a script with your userId, associated to your public key.

    That is how GitHub will associate git@github.com with your account.
    Registering a public key in your account modifies the ~git/.ssh/authorized_keys with a command and the userID, not just the public key.

    • When I use ssh to pull the code by git pull, how does the server know that git pull is from which user?
    • And then how does the server get the public key associated with the user?

    Actually GitHub gets your public key as part of the SSH transaction between you and GitHub: it then fetches your userID from its ~git/.ssh/authorized_keys

    Finally, it checks if that user is authorized to clone/fetch/pull from the remote repository (which could be private, for instance, in which case the user better be the owner or a declared collaborator on that repository).