dockersshopensslgitlab-ci

Gilab CI: load ssh key from environment variable


I've spent the day trying to add a keypair to a docker image in Gitlab CI

I always get theses errors : "error in libcrypto" or "Invalid format" (depending on the docker image used), when loading the key in ssh-keygen to generate a pub key or in ssh-add when loading the private key :

Load key "/root/.ssh/id_rsa": error in libcrypto

the code looks like :

job_deploy:
  image: ubuntu:kinetic
  stage: deploy
  rules:
    - if: $CI_PIPELINE_SOURCE == "push"
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH == "master"

  environment: "staging"
  before_script:
    - 'command -v ssh-agent >/dev/null || ( apt-get update -y && apt-get install openssh-client openssl libssl-dev -y )'
    - eval $(ssh-agent -s)
    # - echo -n "${SSH_PRIVATE_KEY}" | tr -d '\r' | ssh-add - > /dev/null
    - mkdir -p ~/.ssh
    - echo "${SSH_PRIVATE_KEY}" > ~/.ssh/id_rsa
    - chmod -R 400 ~/.ssh
    - ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub # < error here
    # - ssh-add ~/.ssh/id_rsa

  script:
    - ssh root@00.00.00.00 "ls"

The variable of the ssh key looks like this :

SSH_PRIVATE_KEY: "-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAuNk4L4Cf4oDaDjXdjNydM6g5hg5/wGzxoqzENx2Xxq1QminyrZpB
...
Eo6Re1Rp+K3vifSALr2QbOfhd2yVy27oM8FuFQQpOppOJQPuWuwmSyHbT6AhIlAbo8E2v1
mrCMIVawQXSytHAAAAFmN5cHJpZW5AY3lwcmllbi11YnVudHUBAgME
-----END OPENSSH PRIVATE KEY-----"

I've tried adding a new line at the end of the variable

I've tried changing the docker image to a newer or older image of debian and ubuntu and the error remains

error in libcrypto

There is this issue in openssl for this error: https://github.com/openssl/openssl/issues/13443

but it's been solved in openssl-3.0.0-alpha16 and the error is present with openssl 3.0.3


Solution

  • Here is the solution I found :

      before_script:
        - 'command -v ssh-agent >/dev/null || ( apt-get update -y && apt-get install openssh-client wget gnupg -y )'
        - wget -qO- https://get.docker.com/gpg | apt-key add -
        - eval $(ssh-agent -s)
        - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
        - mkdir -p ~/.ssh
        - touch ~/.ssh/config
        - touch ~/.ssh/known_hosts
        - chmod -R 400 ~/.ssh
        - ssh-keyscan <ip> >> ~/.ssh/known_hosts
        - '[[ -f /.dockerinit ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
    

    create a variable SSH_PRIVATE_KEY with the content of your key (add an empty line at the end)

    That being said, I could'nt make it work with a runner running on my development machine.