Load key bad permissions windows

Решение проблемы «WARNING: UNPROTECTED PRIVATE KEY FILE!»

SSH позволяет подключаться к удалённым серверам, компьютерам и выполнять на них команды, будто бы вы открыли консоль этого компьютера. Соединение SSH очень надёжно зашифровано. Поэтому SSH имеет очень большую популярность среди системных администраторов, веб-мастеров, которым нужно управлять своими сайтами на VPS и вообще среди всех пользователей, если нужно выполнить команду или скачать файл с удалённой системы.

SSH поддерживает вход по паролю, а также аутентификацию с помощью ключей, которые представляют собой два файла: приватный и публичный ключ. Публичный ключ размещается на удалённой системе, а приватный на компьютере с которого производится подключение.

Такой способ подключения, используя ключи, очень удобен (не нужно каждый раз вводить пароли) и очень безопасен (подобрать соответствующий ключ методом полного перебора намного сложнее, чем брут-форс учётных данных «логин-пароль»).

При подключении по SSH используя ключи, вы можете столкнуться с примерно следующей ошибкой:

Ошибка возникла из-за того, что права доступа к файлу с секретным ключом слишком открытые. По этой причине приватный ключ игнорируется в текущую сессию и служба SSH запрашивает пароль для подключения.

Как показано в сообщении, файл размещён по пути /home/mial/.ssh/id_rsa и имеет разрешения 0644.

Разберёмся, что означает набор цифр 0644. Самый первый символ (ноль) в данном случае нас не интересует. В оставшихся трёх цифрах (644) зашифрованы права доступа к файлу.

Самая первая цифра содержит в себе данные о правах доступа к файлу владельца. Вторая цифра устанавливает разрешение для группы, а третья цифра — права доступа для всех остальных.

Эти цифры могут быть в диапазоне 0-7. Они складываются из суммы разрешений, которые также обозначаются цифрами 4, 2, и 1. Цифры означают следующее:

  • 4 — чтение
  • 2 — запись
  • 1 — выполнение
  • 0 — отсутствие каких-либо прав доступа на фай

В нашем случае у владельца права доступа обозначаются цифрой 6, её можно получить только из суммы цифр 4 и 2. 4 — это право на чтение, а 2 — это право на запись. Итак, у владельца есть право на чтение и запись.

У группы и у всех остальных пользователей права 4 — то есть только право на чтение.

Наличие всех прав (чтение, запись, выполнение) обозначается цифрой 7.

Программе SSH не нравится, что файл с приватным ключом доступен для чтения другим пользователям. Если несколько людей являются пользователями операционной системы, то с такими правами доступа они могут просмотреть файл приватного ключа, который им не принадлежит. То есть это нарушает безопасность.

Чтобы исправить эту проблему, достаточно установить такие права доступа для файла с приватным ключом, чтобы его не могли просматривать посторонние.

Приватный ключ подключения по SSH обычно храниться в файле

/.ssh/id_rsa. Поэтому для исправления ошибки «It is required that your private key files are NOT accessible by others. This private key will be ignored.» достаточно выполнить команду:

После этого у файла id_rsa будут другие разрешения (чтение и запись для владельца, и полный запрет для всех остальных) и SSH сможет выполнить подключение.

Windows SSH: разрешения для «закрытого ключа» слишком открыты

Я установил OpenSSH 7.6 в Windows 7 для целей тестирования. Клиент и сервер SSH работают нормально, пока я не попытался получить доступ к одной из своих коробок AWS EC2 из этого окна.

Кажется, мне нужно изменить разрешение на файл закрытого ключа. Это можно легко сделать в Unix / Linux с помощью chmod команды.

А как насчет окон?

private-key.ppm скопирован непосредственно из AWS, и я думаю, что разрешение тоже.

Вы находите файл в проводнике Windows, щелкните его правой кнопкой мыши и выберите «Свойства». Перейдите на вкладку «Безопасность» и нажмите «Дополнительно».

Смените владельца на вас, отключите наследование и удалите все разрешения. Затем предоставьте себе «Полный контроль» и сохраните разрешения. Теперь SSH больше не будет жаловаться на разрешение файла, слишком открытое.

Это должно выглядеть так:

Ключи должны быть доступны только тому пользователю, для которого они предназначены, и никаким другим аккаунтам, сервисам или группам.

  • GUI:
    • Свойства [Файл] — Безопасность — Дополнительно
      1. Установите владельца на пользователя ключа
      2. Удалите всех пользователей, группы и службы, кроме пользователя ключа , в разделе « Записи разрешений».
      3. Установите для пользователя ключа полный доступ

CLI:

В дополнение к ответу, предоставленному ibug. Так как я использовал систему Ubuntu внутри Windows, чтобы запустить команду SSH. Это все еще не работало. Так я и сделал

и тогда это сработало

У меня была такая же проблема, и, похоже, она связана с версией SSH, которую вы используете.

Когда я бегу ssh -V в обоих местах, я получаю

Итак, когда я запускаю ssh из каталога git / bin, он работает нормально и не жалуется на разрешения, но, запустив ту же командную строку, используя прежнюю установку SSH, он возвращается с этим.

Читайте также:  Steam ��� mac os

пс. права доступа к файлу — это полный доступ для себя и больше ничего.

Вам нужны только 2 вещи:

1) Отключить наследование

2) Преобразовать унаследованные разрешения в явные разрешения

3) Удалить группу пользователей

4) В итоге пользователи не смогут получить доступ к личным файлам, этого должно быть достаточно для добавления id_rsa.

У меня была похожая проблема, но я был на работе, и у меня нет возможности изменять права доступа к файлам на моем рабочем компьютере. Что вам нужно сделать, это установить WSL и скопировать ключ в скрытый каталог ssh в WSL:

Теперь вы сможете нормально изменять разрешения.

Затем SSH с использованием WSL:

используйте команду ниже на вашем ключе, она работает на Windows

Вы можете использовать icacls в окнах вместо chmod для настройки прав доступа к файлам. Чтобы дать текущему пользователю разрешение на чтение и удалить все остальное,

Это всего лишь скриптовая версия ответа CLI @ JW0914, так что в первую очередь оповестите его. Кроме того, это мой первый скрипт PowerShell, поэтому предложения приветствуются.

Одна строка в CMD может помочь (как описано здесь: https://serverfault.com/a/883338/550334 ), то есть добавление ключа из stdin вместо изменения разрешений:

Чтобы проверить, был ли добавлен ключ:

Скачать с Git для Windows или напрямую.

Он также имеет другие полезные команды Linux, такие как tar и gzip .

Я пользователь Windows, использую bash для Windows и выполнил все шаги, чтобы установить разрешение с помощью графического интерфейса Windows, но он все еще не работает и жалуется:

Я добавил sudo в начале команды ssh, и это просто работает. Надеюсь, что это полезно для других.

Ответ от iBug работает отлично! Вы можете следить за этим и избавиться от этой проблемы.

Но есть несколько вещей, которые необходимо очистить, так как я столкнулся с проблемами при настройке разрешений, и мне понадобилось несколько минут, чтобы выяснить проблему!

После ответа iBug вы удалите все разрешения, но как вы установите для себя разрешение «Полный доступ»? вот где я сначала застрял, так как не знал, как это сделать.

После отключения наследования вы сможете удалить всех разрешенных пользователей или групп.

Как только закончите с этим,

Нажмите на Add затем нажмите Set a Principal затем введите System и и Administrators и your email addredd в поле внизу, затем нажмите check names .

Он загрузит имя, если пользователь существует. Затем нажмите OK > Тип Allow > Основные разрешения Full Control > Okay

Это установит разрешение «Полный доступ» для СИСТЕМЫ, Администраторов и Вашего Пользователя.

После этого попробуйте ssh, используя этот ключ. Это должно быть решено сейчас.

У меня была та же проблема, и я решил, что с помощью этого метода. Если есть какой-либо пользователь или группа с таким именем, он будет загружен.

OpenSSH using private key on Windows (“Unprotected private key file” error)

I am attempting to do a simple connection to a SSH server using OpenSSH for Windows using a private key, and am met with this:

On Linux, this is fixed with a simple chmod 600 on the private key file, however Windows does not have an equivalent method.

This sounds like something that should be pretty easy, but I am completely unable to find any reasonable solution to it. Is there a way to either add the private key directly without going through a file, or to skip this privacy check? Or am I missing something else entierly?

5 Answers 5

You can use icacls in Windows instead of chmod to adjust file permission. To give the current user read permission and remove everything else (Which will allow openssh to work), this works nicely:

In PowerShell, you can get icacls to work by wrapping the command in a call to cmd.exe

You locate the file in Windows Explorer, right-click on it then select «Properties». Navigate to the «Security» tab and click «Advanced».

Change the owner to you, disable inheritance and delete all permissions. Then grant yourself «Full control» and save the permissions. Now SSH won’t complain about file permission too open anymore.

If we are still looking the solution of the SSH problem:

  1. Go to your private key and add the root user(make sure you are adding the owner of the computer) of your computer and provide full rights.
  2. Remove the other users.

If we are not able to remove the users

  1. Go to the security tab in Properties tab and click on Advanced
  2. In next screen there will be a Disable Inheritance button click on that.
  3. It will open a popup and select the first option(Convert inherited permissions..) and then try removing.

In my issue, I was trying to connect ec2.prem file which is a private key to AWS and after following above steps, I was able to resolve it.

Читайте также:  Windows 10 упорядочивание значков

I did it on Windows 10 and it fixed the issue as you can see in the image as well.

You should change the owner of the file(which contains the private key)to your username with full access. and then remove the other usernames that have access to that file.

right-click on the file which contains the private key and clicks on properties and then Security tab> Advanced by clicking on the change button you can change the owner to your username. (if you don’t know the name of your username run: «echo %USERNAME%» in command prompt.) Change>Advanced. >Find Now

remove all Permission entries except the one you just added

click on Disable inheritance> Convert inherited permissions. then remove all Permission entries except the one you just added.

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

Recently I’ve been unable to clone or push to github, and I’m trying to find the root cause.

This is on windows

I have cygwin + git as well as msysgit.

Msysgit was installed with the following options:

  • OpenSSH
  • Use Git from Windows Command Prompt

That gives me 4 environments to try to use git in:

  • Windows cmd prompt
  • Powershell
  • Git Bash
  • Cygwin

Somehow I’ve managed to get myself into a position where when I try to clone a repository using msysgit, cmd.exe, or Powershell, I get the following error:

This is using the .ssh folder in my c:\users\ben\ folder, which is what is used by msysgit. I suspect cygwin works because the .ssh folder is located elsewhere, but I’m not sure why

In Git Bash, I check the permissions:

These permissions are apparently too relaxed. How they got this way, I have no idea.

I can try to change them.

But it seems to have no effect. I still get the same error, and doing

yields the same permissions as before.

UPDATE:

I tried to fix the permissions to those files in cygwin, and cygwin reports their permissions correctly, gitbash does not: alt text http://cdn.cloudfiles.mosso.com/c54102/app7962031255448924.jpg

Any ideas on how I can really fix these permissions?

rc/help/faq/permissions.html for more detailed explanations. – Mark Embling Oct 12 ’09 at 19:35

25 Answers 25

You changed the permissions on the whole directory, which I agree with Splash is a bad idea. If you can remember what the original permissions for the directory are, I would try to set them back to that and then do the following

inside the .ssh folder. That will set the id_rsa file to rwx (read, write, execute) for the owner (you) only, and zero access for everyone else.

If you can’t remember what the original settings are, add a new user and create a set of SSH keys for that user, thus creating a new .ssh folder which will have default permissions. You can use that new .ssh folder as the reference for permissions to reset your .ssh folder and files to.

If that doesn’t work, I would try doing an uninstall of msysgit, deleting ALL .ssh folders on the computer (just for safe measure), then reinstalling msysgit with your desired settings and try starting over completely (though I think you told me you tried this already).

Edited: Also just found this link via Google — Fixing «WARNING: UNPROTECTED PRIVATE KEY FILE!» on Linux While it’s targeted at linux, it might help since we’re talking liunx permissions and such.

Windows SSH: Permissions for ‘private-key’ are too open

I’ve OpenSSH 7.6 installed in Windows 7 for testing purposes. SSH client & server work just fine till I tried to access one of my AWS EC2 box from this windows.

It seems like I need to change the permission on the private key file. This can be easily done on unix/linux with chmod command.

What about windows?

private-key.ppm is copied directly from AWS and I guess the permission too.

18 Answers 18

You locate the file in Windows Explorer, right-click on it then select «Properties». Navigate to the «Security» tab and click «Advanced».

Change the owner to you, disable inheritance and delete all permissions. Then grant yourself «Full control» and save the permissions. Now SSH won’t complain about file permission too open anymore.

It should end up looking like this:

Keys must only be accessible to the user they’re intended for and no other account, service, or group.

  • GUI:
    • [File] Properties — Security — Advanced
      1. Set Owner to the key’s user
      2. Remove all users, groups, and services, except for the key’s user, under Permission Entries
      3. Set key’s user to Full Control

    CLI:

    In addition to the answer provided by ibug. Since i was using the ubuntu system inside windows to to run the ssh command. It still was not working. So i did

    and then it worked

    I had a similar issue but I was at work and don’t have the ability to change file permissions on my work computer. What you need to do is install WSL then copy the your key to the hidden ssh directory in WSL:

    Now you should be able to modify the permissions normally.

    Then ssh using WSL:

    You just need to do two things:

    Convert inherited permissions to explicit permissions

    Remove Users group

    You will end up with no Users can access private files, this should be enough to add id_rsa.

    use below command on your key it works on windows

    This seems to be related to the version of OpenSSH you’re running:

    • where ssh returns: ssh -V returns:

    When running ..\Git\usr\bin\ssh.exe , it works fine and doesn’t complain about the permissions, but running ..\OpenSSH\ssh.exe comes back with the following, even though key ACLs are Full Access for myself and nothing else:

    You can use icacls in Windows instead of chmod to adjust file permission. To give the current user read permission and remove everything else:

    A single line in CMD might do the trick; as described here, adding the key from stdin instead of changing the permissions:

    To check key has been added:

    This is just a scripted version of @JW0914’s CLI answer, so upvote him first and foremost:

    I couldn’t get any of these answers working for me due to permission issues, so I’ll share my solution:

    1. Go to %UserProfile%\.ssh
    2. Copy and paste id_rsa , rename it to something else [ example ]
    3. Open the renamed file [ example ] and replace the key with your own private key
    4. cd to that directory
    5. Enter your passphrase after issuing: ssh -i example example@127.0.0.1
    1. Copy the public and private keys to %userprofile%\.ssh
    2. Use the batch script below after finding your keys from the cmd prompt with where *.pub :
    3. Right-click each file → Properties → Security:
      Remove everyone except the user, setting the permissions for the user to Read
    1. Download and unzip OpenSSH-Win64.zip(or Win32, depending on your system)
    2. Execute FixUserFilePermissions.ps1 in PowerShell with administrator privilege

    Here’s the way to do it using Microsoft’s tooling, avoiding the problem from the get-go. But it should also fix the issue, meaning you can follow these instructions with existing keys.

    Start PowerShell/Terminal as Administrator and run the following:

    Anonymous cowards press down to go down on me.

    Download with Git for Windows, or directly.

    It also has other useful Linux commands like tar and gzip .

    I’m a Window user, using the Windows’s bash and followed all the steps to set permission using Windows GUI, and it still doesn’t work and it complains:

    The I added sudo at the front of the ssh command and it just works. Hope this is helpful to others.

    I had the same problem on Windows 10, and it arouse when I created a second user account on my machine.

    Since that new user was also an administrator and It had access to my user folder, I did these steps to limit the access on my .ssh folder and it worked!

    1. Navigate to your user folder at C:\Users\YOU
    2. Right click on .ssh/ folder to open context menu
    3. Under Give access to. sub-menu, select Remove access
    4. Done!

    Now try to log back in to your remote computer using ssh!

    Hope it helps someone!

    Answer by iBug works fine! You can follow that and get rid of this issue.

    But there are few things which are needed to be cleared as I faced issues during setting up permissions and it took few minutes for me to figure out the problem!

    Following iBug’s answer, you’ll remove all the permissions but how do you set Full Control permission to yourself? that’s where I got stuck at first as I didn’t knew how to do that.

    After Disabling Inheritance, you’ll be able to delete all allowed users or groups.

    Once Done with that,

    Click on Add then click on Set a Principal then enter System and Administrators and your email addredd in the field at bottom then click on check names .

    It’ll load the name if user exists. Then, Click on OK > Type Allow > Basic Permisisons Full Control > Okay

    This will setup Full Control permission to SYSTEM, Administrators and Your User.

    After that try to ssh using that key. It should be solved now.

    I had same issue and I solved that using this method. If there’s any user or group with that name then it’ll load that.

    Читайте также:  Как откатить ядро linux mint
Оцените статью