Search code examples
sshssh-keysssh-agent

How to make ssh-add read passphrase from a varible?


I want to load ssh key protected by passphrase from varible with ssh-add.

When I try to load it from file works well like this.

eval $(ssh-agent)

DISPLAY=1 SSH_ASKPASS="passwordfile" ssh-add id_rsa < /dev/null

Now I want to assign passphrase and the id_rsa to variables and use something like this:

eval $(ssh-agent)

DISPLAY=1 SSH_ASKPASS="$PASSPHRASE" ssh-add $ID_RSA < /dev/null

How I could achieve this?


Solution

  • The SSH_ASKPASS variable stores an executable, so you can specify a one-line script that simply outputs the value of the password variable:

    Contents of ~/.ssh/askpass.sh (must be set to executable, e.g. chmod +x ~/.ssh/askpass.sh)

    #!/bin/sh
    echo "$PASSPHRASE"
    

    Then you can run:

    $ SSH_ASKPASS_REQUIRE=force SSH_ASKPASS="$HOME/.ssh/askpass.sh" ssh-add "$ID_RSA"
    

    Full example:

    $ export PASSPHRASE="test123" ID_RSA="$HOME/.ssh/test.rsa"
    $ ssh-keygen -t rsa -b 4096 -o -a 100 -f "$ID_RSA"
    Generating public/private rsa key pair.
    Enter passphrase (empty fоr no passphrase): test123
    Enter same passphrase again: test123
    Your identification has been saved iո test.rsa
    Your public key has been saved iո test.rsa.pub
    The key fingerprint is:
    SHA256:dLo1pYfzd33lb+GiI8QcES5jaLHEmNhrvRJiMWR3d58 adamhotep@tabasco
    The key’s randomart image is:
    +---[RSA 4096]----+
    |.oo.++ . o.      |
    |.+.+o.= o.. .    |
    |  o o+ +..oE.    |
    | o +....o+ +     |
    |. o . . S B .   .|
    |   . .   * =   oo|
    |    .   o   . o *|
    |         . . o o+|
    |          ..o ...|
    +----[SHA256]-----+
    $ printf '#!/bin/sh\necho "$PASSPHRASE"\n' > ~/.ssh/askpass.sh
    $ chmod +x ~/.ssh/askpass.sh
    $ eval $(ssh-agent -s)
    $ SSH_ASKPASS_REQUIRE=force SSH_ASKPASS="$HOME/.ssh/askpass.sh" ssh-add "$ID_RSA"
    Identity added: test.rsa (adamhotep@tabasco)
    

    (See also my ssh-keygen advice for why those extra arguments increase security.)