It is required that your private key files are not accessible by others windows

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:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions for 'private' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "private": bad permissions

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?

asked Feb 20, 2018 at 15:12

Excludos's user avatar

ExcludosExcludos

1,4201 gold badge13 silver badges24 bronze badges

2

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:

Command Prompt:

icacls .\private.key /inheritance:r
icacls .\private.key /grant:r "%username%":"(R)"

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

icacls .\private.key /inheritance:r
start-process "icacls.exe" -ArgumentList '.\private.key /grant:r "$env:USERNAME":"(R)"'

Aamnah's user avatar

Aamnah

5696 silver badges9 bronze badges

answered Feb 22, 2018 at 9:32

Excludos's user avatar

ExcludosExcludos

1,4201 gold badge13 silver badges24 bronze badges

11

FYI: Rename the «test.pem» to your original pem file name.

  1. Setting path variable

    $path = ".\test.pem"

  2. Reset to remove explicit permissions

    icacls.exe $path /reset

  3. Give current user explicit read-permission

    icacls.exe $path /GRANT:R "$($env:USERNAME):(R)"

  4. Disable inheritance and remove inherited permissions

    icacls.exe $path /inheritance:r

Note:

  • You can replace the file name as per your file name. In this case it is test.pem.
  • You must be in the same directory where your file is located.
  • You must open power shell as administrator.

ouflak's user avatar

ouflak

2,45810 gold badges44 silver badges49 bronze badges

answered Nov 25, 2021 at 7:21

Himanshu Jain's user avatar

1

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.

  1. 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

  2. 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.

enter image description here

answered Dec 10, 2020 at 7:17

pedram's user avatar

pedrampedram

7458 silver badges6 bronze badges

For windows 10
store the key file in User
Ex: C:\Users\MANNEM.ssh

Make sure permission of private key file will be as shown in the image
permissions

permissions

answered Mar 24, 2021 at 6:09

mannem srinivas's user avatar

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.

answered Oct 21, 2020 at 8:16

Shraddha J's user avatar

Shraddha JShraddha J

7149 silver badges17 bronze badges

i had the same error on windows, but after moving the private key file to «C:\Users\Administrator.ssh» it works fine
enter image description here

answered Sep 3, 2021 at 15:44

MedMahmoud's user avatar

MedMahmoudMedMahmoud

1171 gold badge2 silver badges15 bronze badges

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.

Tomerikoo's user avatar

Tomerikoo

18.4k16 gold badges47 silver badges61 bronze badges

answered Jul 12, 2020 at 2:18

sobby01's user avatar

sobby01sobby01

1,9161 gold badge13 silver badges22 bronze badges

Save the following script and run it for the keys you need to reset the permission for.

This is based on the commands given in the answer above

# ResetKeyPermssions.ps1 <keyfile>
# Resets windows permissions for private key file, such that ssh-add doesn't complain about permissions being too open

$path = $args[0]
#icacls.exe $path /reset #not required as :R replaces permissions
# replace all permissions, give full control to currently logged in user
icacls.exe $path /GRANT:R "$($env:USERNAME):(F)"
# Remove all inheritances
icacls.exe $path /inheritance:r

answered Jun 7, 2022 at 8:01

Vijay's user avatar

VijayVijay

8913 gold badges19 silver badges35 bronze badges

I tried changing permission but that didn’t work.
What worked for me was changing the ownership to current user, as the key was created by other Admin user

answered May 4, 2022 at 12:16

PatrickBateman92's user avatar

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.

-Screenshots-

Permission Entries
Select a Principal/ Select User or Groups


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

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

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

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

C:\>ssh -V
OpenSSH_7.6p1, LibreSSL 2.5.3

C:\>ver

Microsoft Windows [Version 6.1.7601]

C:\>


C:\>ssh ubuntu@192.168.0.1 -i private-key.ppk
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions for 'private-key.ppk' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "private-key.ppk": bad permissions
ubuntu@192.168.0.1: Permission denied (publickey).

C:\>
C:\>
C:\>ssh ubuntu@192.168.0.1 -i private-key.ppm
Warning: Identity file private-key.ppm not accessible: No such file or directory.
ubuntu@192.168.0.1: Permission denied (publickey).

C:\>






Ответы:


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

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

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

введите описание изображения здесь







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

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

    :: Set Variable ::
    set key="C:\Path\to\key"
    
    :: Remove Inheritance ::
    cmd /c icacls %key% /c /t /inheritance:d
    
    :: Set Ownership to Owner ::
    cmd /c icacls %key% /c /t /grant %username%:F
    
    :: Remove All Users, except for Owner ::
    cmd /c icacls %key%  /c /t /remove Administrator "Authenticated Users" BUILTIN\Administrators BUILTIN Everyone System Users
    
    :: Verify ::
    cmd /c icacls %key%






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

sudo ssh ...

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





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

Если я наберу

where ssh

Я получил…

C:\Windows\System32\OpenSSH\ssh.exe
C:\Program Files\Git\usr\bin\ssh.exe

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

OpenSSH_7.5p1, without OpenSSL
OpenSSH_7.3p1, OpenSSL 1.0.2k  26 Jan 2017

…соответственно

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

Load key "t:\\mykeys\\rich-private.ppk": invalid format
banana@127.0.0.127: Permission denied (publickey).

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






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

1) Отключить наследование
введите описание изображения здесь

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

3) Удалить группу пользователей
введите описание изображения здесь

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


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

cp <path to your key> ~/.ssh/<name of your key>

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

sudo chmod 600 ~/.ssh/<your key's name>

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

ssh -i ~/.ssh/<name of your key> <username>@<ip address>


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

icacls .\private.key /inheritance:r
icacls .\private.key /grant:r "%username%":"(R)"


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

icacls <file name> /inheritance:r
icacls <file name> /grant:r "%username%":"(R)"


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

# DO the following in powerhsell if not already done:
# Set-ExecutionPolicy RemoteSigned


# NOTE: edit the path in this command if needed
$sshFiles=Get-ChildItem -Path C:\DevContainerHome\.ssh -Force

$sshFiles | % {
  $key = $_
  & icacls $key /c /t /inheritance:d
  & icacls $key /c /t /grant %username%:F
  & icacls $key  /c /t /remove Administrator "Authenticated Users" BUILTIN\Administrators BUILTIN Everyone System Users
}

# Verify:
$sshFiles | % {
  icacls $_
}


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

cat /path/to/permission_file | ssh-add -k 

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

ssh-add -l



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

Permissions 0555 for 'my_ssh.pem' are too open.
It is required that your private key files are NOT accessible by others.

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




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

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

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

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

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

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

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

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

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

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

-Screenshots-

Записи разрешений
Выберите принципала / выберите пользователя или группы

Установил xfce вместо unity на ubuntu. После чего git fetch начал отдавать такую штуку:

$ git fetch
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for '/home/username/.ssh/id_rsa' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "/home/username/.ssh/id_rsa": bad permissions
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Permissions 0644 for ‘~/.ssh/id_rsa’ are too open — т.е. файл ключа id_rsa имеет слишком много прав. 

Смотрим текущие права:

$ ls -la ~/.ssh/
total 24
drwx------  2 eugeney eugeney 4096 Jun  6 16:42 .
drwxr-xr-x 33 eugeney eugeney 4096 Jun 13 12:10 ..
-rw-r--r--  1 eugeney eugeney 1679 Mar 11  2013 id_rsa
-rw-r--r--  1 eugeney eugeney  398 Mar 11  2013 id_rsa.pub
-rw-r--r--  1 eugeney eugeney 5534 Jun 13 10:35 known_hosts

Основная проблема в том, что с такими правами наш ключ могут читать и другие пользователи. Поэтому система обязывает нас изменить права. Запретим другим пользователям читать наш id_rsa, выставив права только для нашего пользователя с помощью команды chmod.

Задаём права 700 либо 600 на приватный ключ ~/.ssh/id_rsa

chmod 700 ~/.ssh/id_rsa

Теперь у текущего пользователя будут права на запись, чтение и выполнение (цифра 7). А у остальных пользователей не будет никаких прав на этот файл (цифра 0).

600 и 700 оба варианта подходят.

После этого ssh авторизация по ключу должна проходить без ошибок.

Дата добавления:
7 лет назад

Lately, I have been working a lot with SSH and Windows 10, for one transitioning away from WMI for certain things, hopefully, a blog post coming on that front soon. Setting up SSH on Windows 10 is fairly simple to do, but it is one of those processes that can be wrought with missteps and misinformation from various places. As a case in point, you may receive permissions issues on a private key connecting to Windows 10. Why is this? Let’s take a look at bad owner or permissions on SSH config Windows 10 and see what this relates to.

Public key authentication with Windows 10

First of all, if you see this error mentioned in the title of the blog post, it means you are most likely attempting to configure public key authentication to access your OpenSSH installed and configured in Windows 10. Why do you want to configure public key authentication?

First of all, if you want to know how to configure Windows 10 SSH, take a look at my blog post here:

  • OpenSSH Server Windows 10 Install with Public Key authentication

Also, learn about OpenSSH in general here:

Spinbackup

  • OpenSSH

Public key authentication is noted as a more secure way to authenticate to an OpenSSH server. Why is this? With public-key authentication, you have two parts of a cryptographic key that grants access. It includes both a private key and a public key. The SSH server possesses the public key of the key pair, while you as the user possess the private key. In addition to passing the physical private key file, you can also secure the private key with a password.

So, it is easy to understand how this type of authentication is much more secure. As far as the cryptographic key is concerned, an attacker can’t simply brute force the server to guess a weak, guessable, or cracked password to gain access. They have to have possession of the key and know the password if the private key is secured with one.

SSH clients have also come a long way in recognizing when there may be bad ideas in play when it comes to private key files. If the permissions contain other security permissions on the private key file other than the user that should possess those permissions, the key can be more easily compromised.

Many SSH clients check for the permissions configured on the SSH private key and if these are too permissive, it will not be allowed for use to make the SSH connection. Note the following error seen when trying to SSH into a remote Windows 10 machine with wide-open permissions on the private key file:

Unprotected private key file error

Unprotected private key file error

The error above states the issue: Permissions for the key file are too open. It is required that your private key files are NOT accessible by others. This private key will be ignored.

To get past the Bad Owner or Permissions on SSH Config Windows 10 error, you need to configure three things:

  • Permissions on the authorized_keys file
  • Permissions on your private key file
  • sshd_config file changes

Part of the process to properly configure your Windows 10 SSH session for public-key authentication is ensuring the permissions are set correctly, both on the authorized_keys file (holds public key) and the private key file that holds the private key side of your key pair. Let’s take a look at both.

When you enable OpenSSH on your Windows 10 machine, you need to create the .ssh directory in the user profile of the user you will be logging in with. This is the location OpenSSH looks to find the authorized public keys, and by extension, the paired private keys that are allowed to access the machine.

By default, when you create the directory and the authorized_keys file, it will have too many permissions assigned. As you can see, it will have the local Administrators group added to the file. Click Advanced.

Permissions set by default on the authorized keys file
Permissions set by default on the authorized keys file

Here, we need to disable inheritance. This breaks inheritance on the folder and allows you to set explicit permissions.

Disable permissions inheritance
Disable permissions inheritance

Choose the option Convert inherited permissions into explicit permissions on this object.

Convert inherited permissions to explicit permissions
Convert inherited permissions to explicit permissions

Adjust your permissions so that you only have SYSTEM and your username displayed as having permissions on the authorized_keys file.

Remove all permissions except SYSTEM and your user
Remove all permissions except SYSTEM and your user

Permissions on your private key file

Now, on your private key, you need to ensure the same thing is set. The user that you are logged in with and SYSTEM are the only permissions that need to be enumerated on the private key file.

Setting permissions on the SSH private key
Setting permissions on the SSH private key

sshd_config file changes

Now that we have the permissions set correctly on the authorized_keys file and the private key, we need to make sure the sshd_config file is configured correctly. We need to make three changes for this to work correctly:

Below, I have uncommented the PubeyAuthentication yes stanza. Then, we have commented out the PasswordAuthentication yes and Match Group administrators configuration.

PubkeyAuthentication yes
#PasswordAuthentication yes
#Match Group administrators
#       AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys

Be sure to restart your OpenSSH SSH Server service on your Windows 10 machine after making these changes to the sshd_config file. Once the changes are in place, you should be able to connect to the machine via SSH.

Restart the OpenSSH Server service
Restart the OpenSSH Server service

Wrapping Up

Connecting to Windows 10 via SSH is a great way to make secure connections to Windows 10 when public-key authentication is used. It can also be a great way to use solutions like Ansible to connect to your Windows 10 boxes remotely.

  • It is getting a bit cold i the windows
  • Isunshare windows password genius standard
  • Ista bmw скачать на русском для windows 7
  • Isunshare windows password genius advanced full version
  • Isumsoft windows password refixer скачать