Error loading key dev fd 63 invalid format

Here is my code giltlab-ci.yml : before_script: ## ## Install ssh-agent if not already installed, it is required by Docker. ## (change apt-get to yum if you use an RPM-based image) ## - '

Here is my code giltlab-ci.yml :

 before_script:
  ##
  ## Install ssh-agent if not already installed, it is required by Docker.
  ## (change apt-get to yum if you use an RPM-based image)
  ##
  - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'

  ##
  ## Run ssh-agent (inside the build environment)
  ##
  - eval $(ssh-agent -s)
  ##
  ## Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store
  ## We're using tr to fix line endings which makes ed25519 keys work
  ## without extra base64 encoding.
  ## https://gitlab.com/gitlab-examples/ssh-private-key/issues/1#note_48526556
  ##
  - mkdir -p ~/.ssh
  #- echo -n "$PROJECT_SSH_KEY" | ssh-add - >/dev/null
  - echo "$PROJECT_SSH_KEY"
  - ssh-add <(echo "$PROJECT_SSH_KEY")
  - '[[ -f /.dockerenv ]] && echo -e "Host *ntStrictHostKeyChecking nonn" > ~/.ssh/config'
      ##
  ## Create the SSH directory and give it the right permissions
  ##
  - mkdir -p ~/.ssh
  - chmod 700 ~/.ssh

  ##
  ## Optionally, if you will be using any Git commands, set the user name and
  ## and email.
  ##
  #- git config --global user.email "user@example.com"
  #- git config --global user.name "User name"

I get this out put

Running with gitlab-runner 11.8.0 (4745a6f3)
on Allence-Tunisie-docker-runner sH47eTgb
Using Docker executor with image ntfactory/ci-tool:0.0.2 …
Pulling docker image ntfactory/ci-tool:0.0.2 …
Using docker image sha256:7fe7b170806f6846271eec23b41c4f79202777f62c0d7a32165dc41722900979
for ntfactory/ci-tool:0.0.2 …
Running on runner-sH47eTgb-project-11060727-concurrent-0 via a732493b4b94…
Cloning repository…
Cloning into ‘/builds/allence-tunisie/e-formation’…
Checking out 0a6b48ef as feat/gitlab-ci…
Skipping Git submodules setup
Checking cache for default…
No URL provided, cache will not be downloaded from shared cache server. Instead a local version of cache will be extracted.
Successfully extracted cache
$ which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )
/usr/bin/ssh-agent
$ eval $(ssh-agent -s)
Agent pid 12
$ mkdir -p ~/.ssh
$ echo «$SSH_PRIVATE_KEY» | tr -d ‘r’ | ssh-add — > /dev/null
Error loading key «(stdin)»: invalid format
ERROR: Job failed: exit code 1

even though i tried — echo «$SSH_PRIVATE_KEY» | tr -d ‘r’ | ssh-add
— > /dev/null i get this error

Error loading key «(stdin)»: invalid format

asked Mar 18, 2019 at 14:25

Montassar Bouajina's user avatar

2

This error happens when the private key in $SSH_PRIVATE_KEY is malformed, you can easily test it locally if you add some random characters in it. In particular, it happens on Travis-CI when you just copy & paste the private key into the SSH_PRIVATE_KEY variable in the online form. It has to do with the new line characters after and before the ——BEGIN RSA PRIVATE KEY——, ——END RSA PRIVATE KEY—— blocks. For this reason, I use base64 encoding to make sure the key is formatted properly.

try this:

  • Encode your private RSA key

    cat my_private_key | base64 -w0

  • Add the base64 string to your project variables.

  • Use it in your .gitlab-ci.yml

ssh-add <(echo «$SSH_PRIVATE_KEY» | base64 -d)

https://gitlab.com/gitlab-examples/ssh-private-key/issues/1#note_15038961

answered Apr 4, 2019 at 18:56

Brian's user avatar

BrianBrian

1,26514 silver badges25 bronze badges

2

If you have protected the variable then you need to have a protected branch. As mentioned in the variables settings — «They can be protected by only exposing them to protected branches or tags.»

answered May 29, 2020 at 14:26

Salil Dhawan's user avatar

4

As mentioned in this thread on GitLab’s bug tracker, the issue can arise when carriage return characters (r) are added to the variable (a.k.a. «secret»). This can be worked around by piping to tr -d "r" to delete these characters, leaving the SSH key correctly formed.

An example in your CI would be:

ssh-add <(echo "${SSH_priv_key_b64}" | base64 --decode | tr -d "r")

Note that base 64 encoding is necessary to use an SSH key with the «masked» and «protected» properties.

answered Nov 1, 2021 at 16:18

Louis Maddox's user avatar

Louis MaddoxLouis Maddox

5,0275 gold badges34 silver badges64 bronze badges

The documentation says that they have fixed the error. This is the new way to do it.

  ##
  ## Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store
  ## We're using tr to fix line endings which makes ed25519 keys work
  ## without extra base64 encoding.
  ## https://gitlab.com/gitlab-examples/ssh-private-key/issues/1#note_48526556
  ##

  - echo "$SSH_PRIVATE_KEY" | tr -d 'r' | ssh-add -

answered Apr 7, 2022 at 19:06

X 2's user avatar

X 2X 2

3132 silver badges10 bronze badges

The error I got was similar as above ones. However none of above works on my case. After I tried several times, I noticed the file is empty when my pipeline was running. Considering that I made my secrets only exposed to protected branches or protected tags, I went /-/settings/repository and added my target branches. Everything works now.

answered May 16, 2022 at 0:58

Jack Liu Shurui's user avatar

Jack Liu ShuruiJack Liu Shurui

5191 gold badge5 silver badges13 bronze badges

I got this error from a silly mistake!- in my GitLab project settings, the Type for my variable was set to File instead of Variable.

And so, changing the Type from File to Variable fixed this for me.

answered Aug 26, 2022 at 4:53

sping's user avatar

spingsping

359 bronze badges

Step by step:

  1. Generate ssh key info about generation
ssh-keygen -t ed25519 -C "<comment>"
  1. Encode PRIVATE_KEY
cat /root/.ssh/id_rsa | base64 -w0
# OR
echo "-----BEGIN OPENSSH..." | base64 -w0
  1. On gitlab, go to your repository > settings > CI/CD > Variables and add your variable with encoded value (also you can switch «protected variable flag»)

  2. In you .gitlab-ci.yml add decoding pipe

- ssh-add <(echo "$SSH_KEY" | base64 -d)
  1. That’s all.

But if you will have «Permission denied, please try again.» error after all — try my answer here

answered Oct 29, 2022 at 22:51

job.js.org's user avatar

job.js.orgjob.js.org

2,3972 gold badges18 silver badges29 bronze badges

You must gen RSA key not OPENSSH Key. Use param «-m PEM» (ssh-keygen -m PEM) to generate RSA Key will start with ——BEGIN RSA PRIVATE KEY—— and end with ——END RSA PRIVATE KEY——

answered May 31, 2021 at 10:26

Doan Thai's user avatar

Doan ThaiDoan Thai

3292 silver badges8 bronze badges

1

For me I protected branch and tags , and then I finally did it without any errors.

Jean-François Fabre's user avatar

answered Nov 29, 2021 at 10:21

IAM Re3v3s's user avatar

1

Перейти к содержанию

На чтение 2 мин Опубликовано 18.02.2021

Содержание

  1. Тестовая схема:
  2. Необходимые шаги
  3. Решение ошибки Error loading key “/dev/fd/63”: invalid format

Тестовая схема:

  • Gitlab Runner с запущенным и запущенным Docker исполнителем (может быть локально)
  • Cервер для развертывания (тоже может быть локально, он должен быть доступен для раннера).
  • У вас есть сервер Gitlab, и вы уже создали репозиторий своего проекта с файлом .gitlab-ci.yml.

Необходимые шаги

Подключитесь по ssh к раннеру:

ssh root@runner-ip

Создайте пару ключей SSH:

Получите закрытый ключ раннера:

 cat ~/.ssh/id_rsa

Добавьте этот закрытый ключ в качестве переменной в свой проект на Gitlab:

Перейдите: Settings > CI/CD > Variables

Выполните вход по SSH к серверу:

ssh root@server-ip

Скопируйте открытый ключ раннера( cat id_rsa.pub ) внутрь ~/.ssh/authorized_keys сервера.

Измените свой .gitlab-ci.yml. согласно следующему примеру.

Предполагается образ на основе ubuntu.

Отредактируйте CI скрипт свои задачи:

"SSH DEPLOY":
  stage: deploy
  image: ubuntu-cd:0.0.2 
  before_script:
    - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
    - mkdir -p ~/.ssh
    - eval $(ssh-agent -s)
    - '[[ -f /.dockerenv ]] && echo -e "Host *ntStrictHostKeyChecking nonn" > ~/.ssh/config'
    - chmod 700 ~/.ssh
  artifacts:
    when: always
    paths:
      - ./src/file.txt
    expire_in: 1 day
  script:
    - pwd
    - ls -a
    - ssh-add <(echo "$SSH_PRIVATE_KEY" | base64 --decode)
    - scp ./src/file.txt root@172.2.16.50:/tmp/

Сделайте коммит .gitlab-ci.yml, запустится пайплайн и отправит по ssh на ваш сервер необходимых файл!


Пожалуйста, не спамьте и никого не оскорбляйте.

Это поле для комментариев, а не спамбокс.

Рекламные ссылки не индексируются!

Содержание

  1. [gitlab] ‘Error loading key «/dev/fd/63»: invalid format’ error #756
  2. Comments
  3. 🔥 Как настроить Gitlab-CI для автоматического развертывания (CD) вашего приложения через SSH
  4. Тестовая схема:
  5. Необходимые шаги
  6. Решение ошибки Error loading key “/dev/fd/63”: invalid format
  7. Не удалось открыть файл конфигурации ‘/ dev / fd / 63’, ошибка: нет такого файла или каталога для wpa_supplicant
  8. «/dev/fd/63 Нет такого файла или каталога»
  9. 4 ответа

[gitlab] ‘Error loading key «/dev/fd/63»: invalid format’ error #756

On a private repo I keep getting this error (which has prevented me from switching to industrial_ci on Gitlab)

  • Got a hint stackoverflow.com#55523151. But I get the same result
  • gitlab.com
  • SSH_PRIVATE_KEY is supplied by using the repo’s feature (Settings —> CI/CD —> Variables)

The text was updated successfully, but these errors were encountered:

I believe it’s the same issue as https://gitlab.com/gitlab-examples/ssh-private-key/-/issues/1#note_48526556
And there they suggest echo «$SSH_PRIVATE_KEY» | tr -d ‘r’ | ssh-add

Thanks. I stopped seeing the exact error message above but I still see the following with plusone-robotics/industrial_ci/fix-gitlab-sshkey.

So there might be as well something with actual key data.
Without a public test cases, it hard to tell what’s going wrong.

Tested on a private repo on my personal org (which I don’t mind giving an acecss), unlike the OP that is on a corporate org, I can’t repro this issue. So I assume there’s a difference b/w personal org and corporate org that ICI’s Gitlab tool isn’t yet handling.

Same as OP, SSH_PRIVATE_KEY is supplied by using the repo’s feature (Settings —> CI/CD —> Variables).

Interestingly, btw, I tested deleting SSH_PRIVATE_KEY on Gitlab from the same repo, which I’d expect ICI to fail with the same/similar error in this ticket as ssh key is now unavailable, but the job still went on and passed.

Источник

🔥 Как настроить Gitlab-CI для автоматического развертывания (CD) вашего приложения через SSH

Тестовая схема:

  • Gitlab Runner с запущенным и запущенным Docker исполнителем (может быть локально)
  • Cервер для развертывания (тоже может быть локально, он должен быть доступен для раннера).
  • У вас есть сервер Gitlab, и вы уже создали репозиторий своего проекта с файлом .gitlab-ci.yml.

Необходимые шаги

Подключитесь по ssh к раннеру:

ssh-keygen -t rsa -N ‘’ -f

Получите закрытый ключ раннера:

Добавьте этот закрытый ключ в качестве переменной в свой проект на Gitlab:

Перейдите: Settings > CI/CD > Variables

Решение ошибки Error loading key “/dev/fd/63”: invalid format

Если при выполнении CI/CD возникает ошибка вида:

/.ssh/id_rsa | base64 -w0

Спасибо за гайд, мне помогло!

Но мне пришлось изменить image, вместо “ubuntu-cd:0.0.2 ” я оставил значение “ubuntu-cd:0.0.2 “

Ошибка в прошлом комментарии :
* я оставил значение “ubuntu“

Спасибо за гайд, мне помогло!
Но мне пришлось изменить image, вместо “ubuntu-cd:0.0.2 ” я оставил значение “ubuntu “

Ну образа меняются, это нормально! Рад, что помогло!

Для выполнения команд по SSH мне помогла только такая конфигурация:

“SSH DEPLOY”:
stage: deploy
image: tetraweb/php
before_script:
– ‘which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )’
– mkdir -p

/.ssh
– eval $(ssh-agent -s)
– ssh-add Ответить

  • Аудит ИБ (49)
  • Вакансии (12)
  • Закрытие уязвимостей (105)
  • Книги (27)
  • Мануал (2 234)
  • Медиа (66)
  • Мероприятия (39)
  • Мошенники (23)
  • Обзоры (800)
  • Обход запретов (34)
  • Опросы (3)
  • Скрипты (109)
  • Статьи (336)
  • Философия (99)
  • Юмор (18)

Anything in here will be replaced on browsers that support the canvas element

Источник

Не удалось открыть файл конфигурации ‘/ dev / fd / 63’, ошибка: нет такого файла или каталога для wpa_supplicant

Когда я делаю это:

Примечание: из-за подстановки процесса вы не можете запустить эту команду с помощью sudo — вам потребуется корневая оболочка.

Вы должны быть в состоянии использовать su -c под sudo так:

Подстановка процесса создает канал, использует /dev/fd для указания пути, эквивалентного дескриптору файла, в котором находится канал, и передает имя файла в качестве аргумента программе. Здесь есть программа sudo , и она передает этот аргумент (который является просто строкой) wpa_supplicant , который обрабатывает его как имя файла.

Проблема в том, что sudo закрывает все файловые дескрипторы, кроме стандартных (stdin = 0, stdout = 1 и stderr = 2). Канал подстановки процесса находится в другом дескрипторе, который закрывается, поэтому при wpa_supplicant попытке открыть его он находит файл, который не существует.

Если ваша политика sudo это позволяет ( closefrom_override опция включена), вы можете запретить закрывать дескрипторы файлов. Но обычно это не так.

Кроме того, поскольку вы не используете стандартный ввод, передайте данные туда.

В качестве альтернативы, запустите оболочку из sudo и поместите подстановку процесса туда. Будьте осторожны с кавычками, если команда содержит специальные символы.

Для тех, кто приходит с веб-поисковой системы: убедитесь, что ваш /dev подключен. Легкая ошибка, которую можно совершить при chrooting, которая может привести к таким ошибкам, как эта.

Источник

«/dev/fd/63 Нет такого файла или каталога»

Я пытался запустить команду в chroot (довольно новый для этого), и я получаю следующий вывод.

4 ответа

TL;DR: скопировать /root папка вне chroot в каталог chroot

Оператор известен как подстановка процесса и является способом запуска команды, вывод которой идет в анонимный канал. Вот что такое /dev/fd/63. Идея состоит в том, чтобы разрешить внешнюю команду (здесь это bash ) обрабатывать вывод других команд, как если бы это был файл. Как правило, форма будет использовать перенаправить этот объект псевдо-файла в bash входной поток.

Это обычно ничем не отличается от wget https://stuff.com/blah | bash , В обоих случаях, как правило, не рекомендуется использовать такие команды, если вы не уверены на сто процентов, что загружаемый скрипт не из поверхностного источника и не является вредоносным.

Тем не менее, так как вы упомянули запуск команды в chroot и сценарий выводит No such file or directory root и потому что bash позволяет запускать сценарии как bash script.sh здесь ваш скрипт выполняется, но нет каталога с именем root в твоей chroot. Вы можете просто исправить это через sudo cp -R /root chrootdir , Для лучших результатов я бы предложил сначала просто прочитать сценарий, посмотреть, что ему нужно, скопировать его в папку chroot и только потом запускать сценарий локально в папке. Не нужно запускать Wget несколько раз

Так что скрипт работает. Ошибки в сценариях оболочки, как правило, в форме : : error message поэтому скрипт временно сохраняется как /dev/fd/63 и запускается, он просто не находит то, что ему нужно.

Источник

Comments

@130s

130s

added a commit
to plusone-robotics/industrial_ci
that referenced
this issue

Nov 6, 2021

@130s

130s

added a commit
to plusone-robotics/industrial_ci
that referenced
this issue

Nov 18, 2021

@130s

130s

added a commit
to plusone-robotics/industrial_ci
that referenced
this issue

Mar 18, 2022

@130s

130s

added a commit
to plusone-robotics/industrial_ci
that referenced
this issue

Sep 14, 2022

@130s

130s

added a commit
to plusone-robotics/industrial_ci
that referenced
this issue

Sep 14, 2022

@130s

130s

added a commit
to plusone-robotics/industrial_ci
that referenced
this issue

Dec 30, 2022

@130s

130s

added a commit
to plusone-robotics/industrial_ci
that referenced
this issue

Dec 30, 2022

@130s

@130s
130s

mentioned this issue

Jan 4, 2023

Тестовая схема:

  • Gitlab Runner с запу­щен­ным и запу­щен­ным Docekr испол­ни­те­лем (может быть локально)
  • Cер­вер для раз­вер­ты­ва­ния (тоже может быть локаль­но, он дол­жен быть досту­пен для раннера).
  • У вас есть сер­вер Gitlab, и вы уже созда­ли репо­зи­то­рий сво­е­го про­ек­та с фай­лом .gitlab-ci.yml.

Необходимые шаги

Под­клю­чи­тесь по ssh к раннеру:

Создай­те пару клю­чей SSH:

Полу­чи­те закры­тый ключ раннера:

 cat ~/.ssh/id_rsa

Добавь­те этот закры­тый ключ в каче­стве пере­мен­ной в свой про­ект на Gitlab:

Перей­ди­те: Settings > CI/CD > Variables

Выпол­ни­те вход по SSH к серверу:

Ско­пи­руй­те откры­тый ключ ран­не­ра( cat id_rsa.pub ) внутрь ~/.ssh/authorized_keys сервера.

Изме­ни­те свой .gitlab-ci.yml. соглас­но сле­ду­ю­ще­му примеру.

Пред­по­ла­га­ет­ся образ на осно­ве ubuntu.

Отре­дак­ти­руй­те CI скрипт свои задачи:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

«SSH DEPLOY«:

  stage: deploy

  image: ubuntu-cd:0.0.2

  before_script:

     ‘which ssh-agent || ( apt-get update -y &amp;&amp; apt-get install openssh-client -y )’

     mkdir -p ~/.ssh

     eval $(ssh-agent -s)

     ‘[[ -f /.dockerenv ]] &amp;&amp; echo -e «Host *ntStrictHostKeyChecking nonn» &gt; ~/.ssh/config’

     chmod 700 ~/.ssh

  artifacts:

    when: always

    paths:

       ./src/file.txt

    expire_in: 1 day

  script:

     pwd

     ls -a

     ssh-add &lt;(echo «$SSH_PRIVATE_KEY« | base64 —decode)

     scp ./src/file.txt root@172.2.16.50:/tmp/

Сде­лай­те ком­мит .gitlab-ci.yml, запу­стит­ся пай­плайн и отпра­вит по ssh на ваш сер­вер необ­хо­ди­мых файл!

https://github.com/midnight47/

So a while ago I set up a server on AWS, and used their generated SSH key. I saved the key to Lastpass, and have successfully retrieved it from there before, and got it working. However, after trying that again today, I can’t get it to work.

-rw------- 1 itsgreg users 1674 Jun 6 12:51 key_name

I’ve tried ssh -i key_name, ssh-keygen -f key_name, but nothing works, I always get this error message:

Load key "key_name": invalid format

Is there any way to fix this?

asked Jun 6, 2017 at 12:06

Gregor Menih's user avatar

1

Check the contents of key_name, if the agent says invalid format, then there’s something wrong with the key — like .. are you sure that’s the correct key? Even if it’s not the private key you need, the ssh agent won’t return invalid format if the key is working, you simply won’t be able to connect. You might have placed your public key in there, for some reason. Check it!

answered Jun 6, 2017 at 12:23

13dimitar's user avatar

13dimitar13dimitar

2,4081 gold badge13 silver badges15 bronze badges

11

Starting openssh 7.6, it defaults to a new more secure format. You can force it to convert to that format using the commands below to change your key password. In case you don’t have and/or don’t want a password, you can simply press enter and it will still rewrite the key in the new format

ssh-keygen -f ~/.ssh/id_rsa -p

answered Jul 16, 2020 at 10:03

kim0's user avatar

kim0kim0

1,1507 silver badges7 bronze badges

6

I had the same issue, and it turns out I had Windows-style (CRLF) line separators in the file for some reason.

In addition, the file must end with a single LF.

Fixing those made things dandy again.

answered Mar 29, 2019 at 15:23

AKX's user avatar

AKXAKX

7635 silver badges7 bronze badges

9

I fixed this issue in Windows by converting the private key to OpenSSH format using the PuTTY Key Generator.

  1. Start Menu | All apps | PuTTY | PuTTYgen
  2. Load my.ppk
  3. Conversions | Export OpenSSH key
  4. Save my_openssh.ppk

Start Menu, All apps, PuTTY section, PuTTYgen

PuTTYgen, Conversions, Export OpenSSH

Now this works:

ssh -i "my_openssh.ppk" user@example.com

Mac conversion: (thanks @ChrisGillatt)

brew install putty 
puttygen ~/.ssh/my.ppk -O private-openssh -o ~/.ssh/my_openssh.ppk

Bob Stein's user avatar

Bob Stein

1,0421 gold badge7 silver badges9 bronze badges

answered Jul 21, 2018 at 3:44

Ras's user avatar

RasRas

4214 silver badges3 bronze badges

2

If you get a warning about an invalid public key format but the command still works then it may be because you only have a private key file and are using OpenSSH 8.3.

OpenSSH 8.3 includes a change to the ssh client where it looks for the private key’s corresponding public key file and outputs this load pubkey "/home/user/.ssh/id.rsa": invalid format warning but continues to connect successfully. Tools using ssh, such as scp or git may show key_load_public: invalid format.

The client does not need the public key when connecting, only the private key. So this check is pointless and it has already been removed by an upstream commit but isn’t in a relase (yet).

There’s a discussion about this on the ArchLinux forum.

answered Jul 28, 2020 at 12:31

starfry's user avatar

starfrystarfry

5811 gold badge7 silver badges13 bronze badges

3

In my case, it turned out that I had newlines between the start/end «headers» and the key data:

-----BEGIN RSA PRIVATE KEY-----

- Key data here -

-----END RSA PRIVATE KEY-----

Removing the extra new lines, so it became

-----BEGIN RSA PRIVATE KEY-----
- Key data here -
-----END RSA PRIVATE KEY-----

solved my problem.

answered Sep 13, 2019 at 13:59

user50849's user avatar

user50849user50849

3232 silver badges7 bronze badges

2

I just ran into this today when was writing some git tagging utils for my CI pipeline.

Here was the difference between my two keys:

$ diff ~/.ssh/gitlab ~/.ssh/git_ssh_key
27c27
< -----END OPENSSH PRIVATE KEY-----
---
> -----END OPENSSH PRIVATE KEY-----
 No newline at end of file

I changed my code like so:

     with open(ssh_key_file, 'w') as skf:
-        skf.write(ssh_key)
+        skf.write(ssh_key + 'n')

And now my ssh key works.

TL;DR — I guess you have to have a newline at the end of your private key.

answered Aug 4, 2019 at 16:38

Robert J's user avatar

Robert JRobert J

2412 silver badges4 bronze badges

2

After a recent update in Fedora 32 I started to get this warnings when connecting to remote hosts.

I solved the problem adding pkcs11: to the IdentityFile parameter in my .ssh/config like this:

IdentityFile pkcs11:~/.ssh/my_key.pem 

For reference, excerpt from ssh_config man page:

The authentication identity can be also specified in a form of PKCS#11 URI starting with a string pkcs11:.

answered Jun 2, 2020 at 9:08

Vicente Quintans's user avatar

5

I was asking openssh to use a particular identity file by specifying it in .ssh/config file.

The original working configuration had

IdentityFile = <path to public key file> 

This stopped working without any changes. On a little thinking I replaced the «path to public key file» above with «path to private key file» . That worked. The reasoning is that both public and private key files have large peudoprime related numbers as per the RSA algorithm. If you replace the private key file by public key file, these cryptographic numbers would not be extracted correctly from the base64 block saved within the key files. It seems some versions of ssh can figure out the .pub extension and use it to identify the correct private key file — and other versions dont do that. This is another way this error can happen. Hope it helps someone.

answered Apr 17, 2018 at 12:41

vpathak's user avatar

vpathakvpathak

1911 silver badge1 bronze badge

3

In my case, this was happening because I was missing a blank line between DEK-Info and the actual key data. I had:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,6E6F6E65206F6620796F757220627573
VGhpcyBpcyBub3QgbXkgYWN0dWFsIGtleSBzb3JyeSB0byBkaXNhcHBvaW50IHlv
...

But it needed to be:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,6E6F6E65206F6620796F757220627573

VGhpcyBpcyBub3QgbXkgYWN0dWFsIGtleSBzb3JyeSB0byBkaXNhcHBvaW50IHlv
...

answered Jan 7, 2021 at 18:23

Joshua Davies's user avatar

1

You should convert your .ppk key to OpenSSH key

Here is how you do it:

  1. Download PuttyGen and generate your keypair (if you don’t have keypair ready). Save private key to your folder (.ppk)
  2. If you are already had the private key, load the private key file (.ppk) by pressing the «Load» Button. Otherwise, skip this step
  3. Under menu «Conversions», choose Export OpenSSH key then save it to your folder
  4. Now you are ready to use the key to login your server without typing the password (I assume you already put the public key under /root/.ssh/authorized_keys, chmod 600 /root/.ssh/authorized_keys, And Restarted SSH demon )

answered Apr 20, 2019 at 9:31

Dylan B's user avatar

Dylan BDylan B

1611 silver badge3 bronze badges

1

Use your private key instead of the public key.

answered Apr 3, 2018 at 12:11

Richard's user avatar

2

I’ve faced with the compatibility issue in Win32-OpenSSH 8.1.

None of the answers here worked for me so I found my own way: convert key to the new format using PuTTYgen utility.

  1. Run fresh version of puttygen
  2. Open the key (Conversions > Import key). Enter passphrase.
  3. Save key in new OpenSSH format (Conversions > Export OpenSSH key (force new file format))

enter image description here

answered Nov 18, 2020 at 18:17

Ilya Serbis's user avatar

I started seeing this problem when I upgraded to Ubuntu 20.10. It uses OpenSSH_8.3p1.

I fixed it using:

ssh-keygen -y -f mykey.pem > mykey.pem.pub

Andrew Schulman's user avatar

answered Jan 6, 2021 at 16:05

mark amos's user avatar

Confusingly, the error says «pubkey» while pointing to a private key file.

A missing public key file (or other problems with it) causes this error — see this answer for details.

answered Oct 3, 2020 at 9:47

uvsmtid's user avatar

uvsmtiduvsmtid

8771 gold badge6 silver badges13 bronze badges

You are logging with the wrong user

In my case, I was trying to connect to an Amazon AWS EC2 instance, but getting the error

load pubkey "MyPrivateKey.pem": invalid format

This was because I was trying to log with the wrong user (ec2-user)

I was using an Ubuntu machine, with user ubuntu instead of ec2-user (as is stated on the official Amazon Linux server OS).

But why that error?

It turns out Amazon uses an old format (puttygen says upon loading «openssh ssh-2 private key (old pem format)») that openssh doesn’t like very much, so it is really a warning and not an error.

The real error (there is no such user on that server) is hidden by the server (otherwise you could brute force login names), but instead a «Connection closed» is shown.


You can find the name you use to connect to your machine on AWS under Actions>Connect.


How to fix the warning?

Just follow the answer of «Ras», which is, use PuTTYgen to convert to the OpenSSH format.

kenlukas's user avatar

kenlukas

2,9862 gold badges14 silver badges25 bronze badges

answered Jun 11, 2020 at 16:35

F. Alessandro's user avatar

I got this error when I use my public key with ssh-add. I should have used the private key. The public key can cause this error.

ssh-add rsakey.pub
Error loading key "rsakey.pub": invalid format

However, this is fine:

ssh-add rsakey

answered Jan 13, 2021 at 18:35

thebiggestlebowski's user avatar

In my case the problem was that the private key was in the following format:

-----BEGIN OPENSSH PRIVATE KEY-----
...
-----END OPENSSH PRIVATE KEY-----

whereas the SSH server expected the following format:

-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----

answered Feb 1, 2021 at 14:48

syntagma's user avatar

I was having this problem with Mac OSX 11.4 and ssh version OpenSSH_8.1p1, LibreSSL 2.7.3. I tried all of the other solutions and nothing worked (i.e., I regenerated keys, tried newlines etc.).

Then I read this on the GitHub docs and by adding the following to my ~/.ssh/config I no longer got the error

Host *
    AddKeysToAgent yes
    UseKeychain yes
    IdentityFile ~/.ssh/id_rsa

answered Aug 1, 2021 at 0:07

Michael Hall's user avatar

I had this issue because I had a key in ~/.ssh that actually was an invalid format and I had a lot of keys, which meant SSH was trying them all, even though I specified my identity file in the command. It just happens to fail because it can only try 5 keys I think, and then left me with that error, which was legit, just for the wrong identity file. The solution was to just use IdentitiesOnly yes in my ~/.ssh/config.

answered Feb 12, 2019 at 8:51

Elijah Lynn's user avatar

Elijah LynnElijah Lynn

1393 silver badges17 bronze badges

I had this error because there was a blank line at the beginning of the key file. Easy to miss if you are cating it out.

answered Feb 15, 2019 at 3:01

Elijah Lynn's user avatar

Elijah LynnElijah Lynn

1393 silver badges17 bronze badges

This is also the error ssh (at least some versions) emits if you have a passphrase on your private key, and enter the passphrase wrong when you attempt to connect.

(In particular, this happened to me with:
OpenSSH_7.6p1, LibreSSL 2.6.2,
which is the built-in SSH for Mac OS X 10.13.6 .)

So double-check that you’re using the right passphrase, and that CAPS LOCK is off.

answered Feb 15, 2019 at 3:31

ssh user on os x's user avatar

My issue was due to encoding. Looking in VSCode the encoding of the file (which I had created using Out-File in PowerShell) was UTF-16LE. When I switched to UTF-8, the key was valid.

answered Mar 24, 2020 at 13:02

john's user avatar

johnjohn

1,9951 gold badge17 silver badges30 bronze badges

For anyone who has tried sudo puttygen ~/.ssh/your-key.pem -O private-openssh -o ~/.ssh/your-key-new.pem and got an error message saying puttygen: this command would perform no useful action there is an even newer format so you need to amend the command as follows:

sudo puttygen ~/.ssh/your-key.pem -O private-openssh-new -o ~/.ssh/your-key-new.pem

I was using a key generated by AWS on Manjaro which is a bit more bleeding edge than most other distros, still worked but the warning message was annoying.

For more info you can use man puttygen but the relevent section is below:

  -O output-type
    Specify the type of output you want puttygen to produce. Acceptable options are:

    private
      Save the private key in a format usable by PuTTY. This will either be the standard SSH-1 key format, or PuTTY's own SSH-2 key format.

    public Save  the  public key only. For SSH-1 keys, the standard public key format will be used (`1024 37 5698745...'). For SSH-2 keys, the public key will be output in the format specified by
      RFC 4716, which is a multi-line text file beginning with the line `---- BEGIN SSH2 PUBLIC KEY ----'.

    public-openssh
      Save the public key only, in a format usable by OpenSSH. For SSH-1 keys, this output format behaves identically to public. For SSH-2 keys, the public key will be output in the  OpenSSH
      format, which is a single line (`ssh-rsa AAAAB3NzaC1yc2...').

    fingerprint
      Print the fingerprint of the public key. All fingerprinting algorithms are believed compatible with OpenSSH.

    private-openssh
      Save an SSH-2 private key in OpenSSH's format, using the oldest format available to maximise backward compatibility. This option is not permitted for SSH-1 keys.

    private-openssh-new
      As private-openssh, except that it forces the use of OpenSSH's newer format even for RSA, DSA, and ECDSA keys.

    private-sshcom
      Save an SSH-2 private key in ssh.com's format. This option is not permitted for SSH-1 keys.

    If no output type is specified, the default is private.

answered Aug 9, 2020 at 13:20

Bob's user avatar

I did something like the information here
https://github.com/marketplace/actions/webfactory-ssh-agent

SSH Private Key Format
If the private key is not in the PEM format, you will see an Error loading key «(stdin)»: invalid format message.

Use ssh-keygen -p -f path/to/your/key -m pem to convert your key file to PEM, but be sure to make a backup of the file first 😉.

It solved my issue.

answered Aug 17, 2021 at 4:24

Dicky Macias's user avatar

If you are on windows using Cygwin, Gitbash, MSYS or similar tools, try to start your command in elevated mode (run as administrator).

I had to do this to re-export the public key file.
If you are using .ssh/config file, make sure that the private key file is referenced there IdentityFile ~/.ssh/id_rsa.

Creating your private key file using puttygen will lead to similar error messages too, use OpenSSH to generate your private-public key-pair.

Using the public key file (~/.ssh/id_rsa.pub) as your identity file (IdentityFile in .ssh/config) will cause misleading error messages like

  • invalid format
  • connection timeout

answered Oct 11, 2021 at 12:33

linux64kb's user avatar

TL;DR

FWIW, I ran into this problem today.

I never figured out what the new install of Win32 «portable openssh» 8.0.p1 didn’t like about the key files — I just created new keys and added them to github and gitlab:

ssh-keygen -o -t rsa -b 4096 -C "New format OpenSSH for github" -f C:Usersmburr.sshgithub.mburr-precor.key-2.id_rsa

Details

I had a working install of OpenSSH from the https://github.com/PowerShell/openssh-portable project (as installed by Chocolatey). But a few days ago I had to perform a «repair install» of Windows and therefore had to reinstall OpenSSH.

After that my keys used to authenticate to github and gitlab would no longer work giving the «invalid format» error. These were the identical key files that had been on the system before (the Repair Reinstall didn’t remove those files).

I found no problems with line endings (all LF and an LF at the end of the file). The keys worked on a Linux system — and I later found that they worked with the OpenSSH included with Git for Windows v2.33.1.

 using the Win32 "portable OpenSSH" (from https://github.com/PowerShell/openssh-portable as installed by Chocolatey)
# Private key file error: "invalid format"
#

C:devtrees>"c:Program FilesOpenSSH-Win64ssh.exe" -V
OpenSSH_for_Windows_8.0p1, LibreSSL 2.6.5

C:devtrees>"c:Program FilesOpenSSH-Win64ssh.exe" -F c:utilemptyfile -i c:usersmburr.sshgithub.mburr.id_rsa -T git@github.com
Load key "c:\users\mburr\.ssh\github.mburr.id_rsa": invalid format
git@github.com: Permission denied (publickey).


#-------------------------------------------------------
# using the OpenSSH that comes with Git for Windows v2.33.1
# No problem with the private key
#

C:devtrees>c:gitusrbinssh.exe -V
OpenSSH_8.8p1, OpenSSL 1.1.1l  24 Aug 2021

C:devtrees>c:gitusrbinssh.exe -F c:utilemptyfile -i c:usersmburr.sshgithub.mburr.id_rsa -T git@github.com
Enter passphrase for key 'c:usersmburr.sshgithub.mburr.id_rsa':
Hi mburr! You've successfully authenticated, but GitHub does not provide shell access.

(emptyfile is just that. I specified it as the config file with -F to force ssh to ignore ~/.ssh/config)

I never figured out what the Win32 «portable openssh» 8.0.p1 didn’t like about the key files — I just created new keys and added them to github and gitlab:

ssh-keygen -o -t rsa -b 4096 -C "New format OpenSSH for github" -f C:Usersmburr.sshgithub.mburr-precor.key-2.id_rsa

Problem solved.

answered Oct 28, 2021 at 1:01

Michael Burr's user avatar

In my case the private key must have been added to the agent with:

ssh-add ~/.ssh/private_id_rsa

answered Mar 4, 2022 at 6:46

0x416e746f6e's user avatar

0x416e746f6e0x416e746f6e

1511 gold badge1 silver badge6 bronze badges

I encountered this problem because the key file did not end with a newline character.

answered Apr 17, 2022 at 5:21

david.barkhuizen's user avatar

This error happens when the private key in $SSH_PRIVATE_KEY is malformed, you can easily test it locally if you add some random characters in it. In particular, it happens on Travis-CI when you just copy & paste the private key into the SSH_PRIVATE_KEY variable in the online form. It has to do with the new line characters after and before the ——BEGIN RSA PRIVATE KEY——, ——END RSA PRIVATE KEY—— blocks. For this reason, I use base64 encoding to make sure the key is formatted properly.

try this:

  • Encode your private RSA key

    cat my_private_key | base64 -w0

  • Add the base64 string to your project variables.

  • Use it in your .gitlab-ci.yml

ssh-add <(echo «$SSH_PRIVATE_KEY» | base64 -d)

https://gitlab.com/gitlab-examples/ssh-private-key/issues/1#note_15038961

If you have protected the variable then you need to have a protected branch. As mentioned in the variables settings — «They can be protected by only exposing them to protected branches or tags.»

Tags:

Gitlab Ci

Related

;
Date: Thu Jun 30 2016

Tags:
Gitlab »»»» SSH Key »»»» Security

If you’re a Gitlab user you’re probably hoping to use Gitlab CI to automate builds and deployments. You probably want to deploy something using rsync, using an SSH key for security. Unfortunately (in my opinion) the official Gitlab documentation is confusing. While the Gitlab team does provide example .gitlab-ci.yml files that are supposed to work, the actual specifics of what to do are sketchy, and I found myself puzzling over a curious error message: «Enter passphrase for /dev/fd/63» … WTF?

The official example for using an SSH key in a .gitlab-ci.yml file is here:-
(gitlab.com)
gitlab.com gitlab-examples ssh-private-key blob master .gitlab-ci.yml

The instructions are to ensure ssh-agent is installed, then to run

eval $(ssh-agent -s)
ssh-add <(echo "$SSH_PRIVATE_KEY")

The Enter passphrase for /dev/fd/63 message occurred right after that last command. The message is cryptic, however the ssh-add command for some reason thinks it must ask for a passphrase. For example, is it an ssh key which requires a secondary password?

What we have to do is revisit the process of attaching an SSH key to a Gitlab CI configuration.

The first step is to generate an SSH key that you’ll use for this Gitlab CI job. On your laptop you do have OpenSSH tools installed, and have access to the ssh-keygen command, right?

Simply run:

$ ssh-keygen -f ~/Downloads/hmp.key

Just hit return for all the prompts. Give whatever filename you wish — that was simply the one I used. It generates the private key in the named file, then generates a second file containing the public key. In my case that file name was /Users/david/Downloads/hmp.key.pub.

It’s important that this ssh key not have a passphrase associated with it. That’s why it’s important to just hit return for all the prompts. It’s important that, for this key, that SSH tools not prompt for a passphrase.

In Gitlab, go to the Variables section of the project configuration. Add a new Variable, named SSH_PRIVATE_KEY, whose contents is the text in the private key file just generated.

Then, on any server this Gitlab CI job needs to access, add the public key. For example, add it to ~/.ssh/authorized_keys on the server.

Once you’ve done these steps, the ssh-add shown above will execute properly.

About the Author(s)


(davidherron.com)
David Herron
:
David Herron is a writer and software engineer focusing on the wise use of technology. He is especially interested in clean energy technologies like solar power, wind power, and electric cars. David worked for nearly 30 years in Silicon Valley on software ranging from electronic mail systems, to video streaming, to the Java programming language, and has published several books on Node.js programming and electric vehicles.

Ezoic

Понравилась статья? Поделить с друзьями:
  • Error loading kernel cache 0x9 хакинтош что делать
  • Error loading kernel cache 0x7 хакинтош
  • Error loading kernel cache 0x1
  • Error loading jvm at odis
  • Error loading java agent in