Простота не предшествует сложности, а вытекает из нее. (Алан.Дж.Перлис)
Главное меню » Microsoft » OS Windows » Как устранить ошибку «Unprotected Private Key File (Незащищённый файл закрытого ключа)» в SSH в Windows
При работе с SSH, особенно при попытке подключиться к удалённым серверам (например, инстансам AWS EC2), вы обычно используете файл закрытого ключа для безопасной аутентификации. Однако иногда вы можете столкнуться с ошибкой, связанной с разрешениями файла закрытого ключа. Эта ошибка часто выглядит следующим образом:
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: UNPROTECTED PRIVATE KEY FILE! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Permissions for 'ec2-key.pem' are too open. It is required that your private key files are NOT accessible by others. This private key will be ignored.
Эта ошибка возникает из-за того, что права доступа к файлу закрытого ключа (ec2-key.pem) слишком открыты. SSH обеспечивает строгие права доступа, чтобы файлы закрытых ключей были доступны только их владельцу. Если файл ключа доступен другим пользователям системы, SSH откажется его использовать из соображений безопасности.
В этой статье мы расскажем, как решить эту проблему, настроив права доступа к файлам в Windows.
Шаги по исправлению ошибки “Незащищенный файл закрытого ключа” в Windows
Выполните следующие действия, чтобы исправить права доступа к файлам и устранить проблему:
Откройте PowerShell от имени администратора
- Нажмите Win + X и выберите Windows PowerShell (администратор)
- Кроме того, найдите «PowerShell» в меню «Пуск», щёлкните по нему правой кнопкой мыши и выберите «Запуск от имени администратора»
Перейдите в каталог, содержащий закрытый ключ
Вам нужно будет перейти к местоположению вашего закрытого ключа (ec2-key.pem). Выполните следующую команду в PowerShell, заменив путь на фактическое местоположение файла ключа:
cd C:/Users/iFran/Desktop
Удалить разрешения для других пользователей
Используйте следующие команды PowerShell, чтобы удалить унаследованные разрешения и ограничить доступ к файлу закрытого ключа, чтобы только ваша учётная запись могла получить к нему доступ:
icacls ec2-key.pem /inheritance:r icacls ec2-key.pem /remove "BUILTIN\Users" icacls ec2-key.pem /grant:r "%username%":F
Давайте разберем, что делают эти команды:
- icacls ec2-key.pem /inheritance:r: удаляет унаследованные разрешения из файла.
- icacls ec2-key.pem /remove “BUILTIN\Users”: удаляет доступ для группы “Users”, которая представляет всех пользователей вашей системы.
- icacls ec2-key.pem /grant:r “%username%”:F: предоставляет полный контроль над файлом только вашей учётной записи.
Проверьте разрешения
После выполнения команд убедитесь, что только ваша учётная запись имеет доступ к файлу, выполнив:
icacls ec2-key.pem
Вы должны увидеть вывод, подобный следующему:
ec2-key.pem: <your_username>:(F)
Это означает, что только ваш пользователь (<your_username>) имеет полный доступ ((F)) к файлу, что решает проблему безопасности.
Исправление прав доступа к файлам в Linux/macOS
Если вы столкнулись с той же проблемой в Linux или macOS, вы можете решить её, изменив разрешения с помощью одной команды:
chmod 600 ec2-key.pem
Эта команда гарантирует, что только владелец файла имеет права на чтение и запись файла закрытого ключа.
Заключение
Ошибка «UNPROTECTED PRIVATE KEY FILE» возникает, когда права доступа к файлу приватного ключа SSH слишком открыты и он доступен другим пользователям вашей системы. Следуя инструкциям, приведённым в этом руководстве, вы сможете ограничить права доступа к файлу и безопасно использовать приватный ключ с SSH.
Обеспечение безопасности файлов с закрытыми ключами имеет решающее значение для предотвращения несанкционированного доступа, и эти шаги помогают усилить защиту как в Windows, так и в Linux/macOS.
Выполнив эти действия, вы сможете устранить ошибку с разрешениями и продолжить безопасно использовать свой SSH-ключ. Не стесняйтесь делиться своими мыслями или задавать дополнительные вопросы в комментариях ниже!
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Просмотров поста: 287
Если статья понравилась, то поделитесь ей в социальных сетях:
When working with SSH, especially while trying to connect to remote servers (like AWS EC2 instances), you typically use a private key file to authenticate securely. However, sometimes you may encounter an error related to the permissions of your private key file. This error often looks like the following:
Bash
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: UNPROTECTED PRIVATE KEY FILE! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions for 'ec2-key.pem' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
This error occurs because the permissions on your private key file (ec2-key.pem) are too open. SSH enforces strict permissions to ensure that private key files are accessible only to their owner. If the key file is accessible by others on the system, SSH will refuse to use it for security reasons.
In this article, I’ll explain how to fix this issue by adjusting the file permissions on Windows.
Follow these steps to correct the file permissions and resolve the issue:
Open PowerShell as Administrator
- Press Win + X and choose Windows PowerShell (Admin)
- Alternatively, search for “PowerShell” in the Start menu, right-click on it, and select Run as administrator
Navigate to the Directory Containing the Private Key
You’ll need to navigate to the location of your private key (ec2-key.pem). Run the following command in PowerShell, replacing the path with the actual location of your key file:
Bash
cd C:/Users/iFran/Desktop
Remove Permissions for Other Users
Use the following PowerShell commands to remove inherited permissions and restrict access to the private key file so that only your user account can access it:
Bash
icacls ec2-key.pem /inheritance:r
icacls ec2-key.pem /remove "BUILTIN\Users"
icacls ec2-key.pem /grant:r "%username%":F
Let’s break down what these commands do:
- icacls ec2-key.pem /inheritance:r: Removes inherited permissions from the file.
- icacls ec2-key.pem /remove “BUILTIN\Users”: Removes access for the “Users” group, which represents all users on your system.
- icacls ec2-key.pem /grant:r “%username%”:F: Grants full control over the file to your user account only.
Verify the Permissions
After running the commands, verify that only your user account has access to the file by running:
You should see output similar to the following:
Bash
ec2-key.pem: <your_username>:(F)
This means that only your user (<your_username>) has full access ((F)) to the file, resolving the security issue.
Fixing File Permissions on Linux/macOS
If you encounter the same issue on Linux or macOS, you can resolve it by changing the permissions with a single command:
Bash
chmod 600 ec2-key.pem
This command ensures that only the file owner has read and write permissions for the private key file.
Conclusion
The UNPROTECTED PRIVATE KEY FILE error occurs when the permissions on your SSH private key file are too open, making it accessible to others on your system. By following the steps outlined in this guide, you can restrict the file permissions and securely use your private key with SSH.
Ensuring the security of private key files is crucial for preventing unauthorized access, and these steps help enforce those protections on both Windows and Linux/macOS.
By following these steps, you’ll be able to resolve the permissions error and continue using your SSH key securely. Feel free to share your thoughts or any additional questions in the comments below!
When using SSH to connect to a server, you may encounter a warning about an “unprotected private key file.” This warning indicates that the private key file has permissions that are too open, making it accessible to other users. As a security measure, SSH enforces strict permission settings on private keys to prevent unauthorized access.
debug1: Authentications that can continue: publickey debug1: Next authentication method: publickey debug1: Trying private key: /Users/shakir/.ssh/simplified-guide.pem @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: UNPROTECTED PRIVATE KEY FILE! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Permissions 0755 for '/Users/shakir/.ssh/simplified-guide.pem' are too open. It is required that your private key files are NOT accessible by others. This private key will be ignored. Load key "/Users/shakir/.ssh/simplified-guide.pem": bad permissions
The issue often arises when a private key is copied or transferred, altering its original permissions. This can happen if the tool used to copy the key does not preserve the original file permissions, leading to a more permissive setting. The default system umask value might also contribute to this problem, causing the private key file to become accessible by others.
To resolve this issue, the file permissions of the private key must be restricted. The correct permissions ensure that the private key is only accessible by the file owner. Once the permissions are set properly, SSH will allow the private key to be used for authentication without triggering the warning.
Steps to change SSH private key permission in Linux:
-
Locate the private SSH key file on your system.
-
Open a terminal window.
-
Verify the current permissions of the private key file (optional).
$ ls -l ~/.ssh/simplified-guide.pem -rwxr-xr-x@ 1 shakir staff 1700 May 12 2021 .ssh/simplified-guide.pem
-
Modify the permissions of the private key to restrict access.
$ chmod 600 ~/.ssh/simplified-guide.pem
The file must be owned by the user where the user has read and execute access, and is set to allow no access at all to user’s group or other users.
-
Verify the new permissions of the private key file.
$ ls -l .ssh/simplified-guide.pem -rw------- 1 user group 1700 May 12 2021 .ssh/simplified-guide.pem
-
Attempt to connect to the server again using the public key authentication method.
Discuss the article:
Comment
anonymously. Login not required.
Установил 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 авторизация по ключу должна проходить без ошибок.
Дата добавления:
9 лет назад
Уточнение, не удается зайти именно с использованием ключа, с паролем нормально захожу.
Решил посмотреть что такое vagrant, параллельно поиграться с windows subsystem for linux, но пока не получается зайти на виртуальную машину по ssh (который для меня тоже темный лес).
Вот что пишет:
root@NEIKIST-DESKTOP:/mnt/c/Users/neikist/test-vagrant# ssh-add .vagrant/machines/default/virtualbox/private_key
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: UNPROTECTED PRIVATE KEY FILE! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0777 for '.vagrant/machines/default/virtualbox/private_key' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
С помощью chmod права на файл изменить не удалось.
Подскажите пожалуйста, можно ли заставить ssh игнорировать права на файл ключа или изменить их как то на удовлетворяющие ssh?