Поддержка ssh-ключей пользователя в облаке

Шаг 1 — Создание пары ключей RSA

Сперва создадим пару ключей на клиентской машине (обычно, это ваш компьютер):

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

После ввода этой команды вы должны увидеть следующий вывод:

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

Если ранее вы уже генерировали пару SSH ключей, вы можете увидеть следующий вывод:

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

Вы должны увидеть следующий вывод:

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

Вы должны увидеть следующий вывод:

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

Our solutions to SSH key management

The role of SSH.COM in SSH key mnanagement projects is typically to provide best-of-breed software, best subject matter expertise, and help to structure and manage the project and define SSH-related policies. We typically provide 1-2 subject matter experts for larger projects to work with the customer’s engineers or outsourcing partners.

SSH Risk Assessment

We usually start with an assessment of SSH and SSH key usage, even before any formal project starts. Our Risk Assessment software, process and reporting helps understand the severity of the issue and evaluate risk and priority. Our SSH Risk Assessment service is designed to be fast and non-invasive.

Universal SSH Key Manager

Universal SSH Key Manager is our flagship product for managing SSH keys. It has been used by numerous large and mid-sized organizations for solving their key management problems. It handles the entire lifecycle for key-based access, and integrates to leading identity and access management systems, privileged access and privilege elevation systems, as well as SIEM (Security Information and Event Management) and configuration management.

Together with consulting services, Universal SSH Key Manager makes it easy for customers to solve their key management issues. We also can run the whole project for you, working with your application teams and identity & access management, cryptography, security engineering, operations, and/or IT transformation groups as needed, globally. We’ve run SSH key management projects in the US, UK, Germany, and Singapore, among others.

PrivX cloud access manager

We also recommend looking at PrivX On-Demand Access Manager. It is a lean privileged access management solution that helps eliminate risk from passwords, vaults and unmanaged SSH keys.

Шаг 2 — Копирование открытого ключа на сервер Ubuntu

Самый быстрый способ скопировать открытый ключ на хост Ubuntu — использовать утилиту . Это самый простой способ, поэтому его рекомендуется использовать, если он доступен. Если на клиентском компьютере нет утилиты , вы можете использовать один из двух альтернативных методов, описанных в этом разделе (копирование через SSH на базе пароля или копирование ключа вручную).

Копирование открытого ключа с помощью утилиты

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

Для использования этой утилиты вам нужно только указать удаленный хост, к которому вы хотите подключиться, и учетную запись пользователя, к которой у вас есть доступ через SSH с использованием пароля. Ваш открытый ключ SSH будет скопирован в эту учетную запись.

Синтаксис выглядит следующим образом:

Вы можете увидеть следующее сообщение:

Это означает, что ваш локальный компьютер не распознает удаленный хост. Это произойдет при первом подключении к новому хосту. Введите «yes» и нажмите , чтобы продолжить.

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

Введите пароль (для безопасности вводимый текст не будет отображаться) и нажмите . Утилита подключится к учетной записи на удаленном хосте, используя указанный вами пароль. Затем содержимое ключа будет скопировано в основной каталог удаленной учетной записи в файл с именем .

Вы должны увидеть следующий результат:

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

Копирование открытого ключа с помощью SSH

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

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

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

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

Полная команда выглядит следующим образом:

Вы можете увидеть следующее сообщение:

Это означает, что ваш локальный компьютер не распознает удаленный хост. Это произойдет при первом подключении к новому хосту. Введите «yes» и нажмите , чтобы продолжить.

После этого вам нужно будет ввести пароль учетной записи удаленного пользователя:

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

Копирование открытого ключа вручную

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

Мы вручную добавим содержимое вашего файла в файл на удаленном компьютере.

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

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

Получите доступ к удаленному хосту с использованием любого доступного метода.

После получения доступа к учетной записи на удаленном сервере убедитесь, что каталог существует. При необходимости эта команда создаст каталог, а если каталог уже существует, команда ничего не сделает.

Теперь вы можете создать или изменить файл в этом каталоге. Вы можете добавить содержимое файла в конец файла и при необходимости создать его с помощью этой команды:

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

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

При этом будут рекурсивно удалены все разрешения «group» и «other» для каталога .

Если вы используете учетную запись для настройки ключей учетной записи пользователя, важно учитывать, что каталог принадлежит пользователю, а не пользователю :

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

Теперь мы можем попробовать настроить аутентификацию без пароля на нашем сервере Ubuntu.

SSH Academy

IAM

IAM Zero Trust Framework
Gartner CARTA
Standing Privileges
Zero Standing Privileges (ZSP)
Ephemeral access
PrivX lean PAM
Identity management
Active Directory
Administrators
Domain administrators
Local administrators
Jump server
IAM Just in time
Just-in-time security tokens
Multi-Factor Authentication (MFA)
OpenID Connect (OIDC)
PAM (Privileged Access Management)
Legacy PAM
Password generator
Password strength
Password vaults
Privileged accounts
PASM
Privilege Elevation and Delegation Management
Privileged session management
Radius
Root accounts
Service accounts
System accounts
Sudo
Users
User IDs
Superuser

Vagrant

Cloud

Cloud applications
Cloud computing
Cloud computing characteristics
Cloud computing companies
Cloud computing definition
Cloud computing models
Cloud computing pros and cons
Cloud computing security
Cloud storage
Cloud technology
IaaS
PaaS
SaaS
SaaS companies
SaaS security

Secure Shell

Secure Shell
Secure Shell protocol
SSH software downloads
SSH certificate authentication
Ipsec
Network monitoring
Port 22
RCP
rlogin
RSH
SCP
Session key
Automated connections
SSH command
SSH configuration
SSHFS SSH File System
SSH for Windows
SSH servers
Tectia SSH Server
SSH server configuration
SSO using SSH agent
Telnet
WinSCP

SSH keys

CAC and PIV smartcards
OpenSSH key authorization
Passphrases
Passphrase generator
Copy ID
Host key
Authorized key
Authorized key file
SSH key basics
SSH key identities
SSH key management
Universal SSH Key Manager
SSH key proliferation
SSH keygen
SSH keys for SSO
Public key authentication

SSH compliance

SSH key compliance
Basel III
COBIT
Cybersecurity framework
Fips 140
Fips 199
Fips 200
GDPR
HIPAA
ISACA
ISACA SSH guide
ISO 27001
NERC-CIP
NIS directive
NIST 7966
NIST 7966 download
NIST 800-53
PCI-DSS
Sans Top 20
Sarbanes Oxley

sshd OpenSSH server process

PuTTY

PuTTY download
PuTTY manuals
PuTTY for Windows
PuTTY for Mac
PuTTY for Windows
PuTTY for Windows installation
PuTTY public keys
PuTTYgen for Linux
PuTTYgen for Windows

SSH tunneling example

SSH Keys and Public Key Authentication

The SSH protocol uses public key cryptography for authenticating hosts and users. The authentication keys, called SSH keys, are created using the program.

SSH introduced public key authentication as a more secure alternative to the older authentication. It improved security by avoiding the need to have password stored in files, and eliminated the possibility of a compromised server stealing the user’s password.

However, SSH keys are authentication credentials just like passwords. Thus, they must be managed somewhat analogously to user names and passwords. They should have a proper termination process so that keys are removed when no longer needed.

Step 3 — Authenticate to Ubuntu Server Using SSH Keys

If you have successfully completed one of the procedures above, you should be able to log into the remote host without the remote account’s password.

The basic process is the same:

If this is your first time connecting to this host (if you used the last method above), you may see something like this:

This means that your local computer does not recognize the remote host. Type “yes” and then press to continue.

If you did not supply a passphrase for your private key, you will be logged in immediately. If you supplied a passphrase for the private key when you created the key, you will be prompted to enter it now (note that your keystrokes will not display in the terminal session for security). After authenticating, a new shell session should open for you with the configured account on the Ubuntu server.

If key-based authentication was successful, continue on to learn how to further secure your system by disabling password authentication.

Step 1 — Create the RSA Key Pair

The first step is to create a key pair on the client machine (usually your computer):

By default will create a 2048-bit RSA key pair, which is secure enough for most use cases (you may optionally pass in the flag to create a larger 4096-bit key).

After entering the command, you should see the following output:

Press to save the key pair into the subdirectory in your home directory, or specify an alternate path.

If you had previously generated an SSH key pair, you may see the following prompt:

If you choose to overwrite the key on disk, you will not be able to authenticate using the previous key anymore. Be very careful when selecting yes, as this is a destructive process that cannot be reversed.

You should then see the following prompt:

Here you optionally may enter a secure passphrase, which is highly recommended. A passphrase adds an additional layer of security to prevent unauthorized users from logging in. To learn more about security, consult our tutorial on How To Configure SSH Key-Based Authentication on a Linux Server.

You should then see the following output:

You now have a public and private key that you can use to authenticate. The next step is to place the public key on your server so that you can use SSH-key-based authentication to log in.

Creating an SSH Key Pair for User Authentication

The simplest way to generate a key pair is to run without arguments. In this case, it will prompt for the file in which to store keys. Here’s an example:

First, the tool asked where to save the file. SSH keys for user authentication are usually stored in the user’s directory under the home directory. However, in enterprise environments, the location is often different. The default key file name depends on the algorithm, in this case when using the default RSA algorithm. It could also be, for example, or .

Then it asks to enter a passphrase. The passphrase is used for encrypting the key, so that it cannot be used even if someone obtains the private key file. The passphrase should be cryptographically strong. Our online random password generator is one possible tool for generating strong passphrases.

Choosing an Algorithm and Key Size

SSH supports several public key algorithms for authentication keys. These include:

  • — an old algorithm based on the difficulty of factoring large numbers. A key size of at least 2048 bits is recommended for RSA; 4096 bits is better. RSA is getting old and significant advances are being made in factoring. Choosing a different algorithm may be advisable. It is quite possible the RSA algorithm will become practically breakable in the foreseeable future. All SSH clients support this algorithm.

  • — an old US government Digital Signature Algorithm. It is based on the difficulty of computing discrete logarithms. A key size of 1024 would normally be used with it. DSA in its original form is no longer recommended.

  • — a new Digital Signature Algorithm standarized by the US government, using elliptic curves. This is probably a good algorithm for current applications. Only three key sizes are supported: 256, 384, and 521 (sic!) bits. We would recommend always using it with 521 bits, since the keys are still small and probably more secure than the smaller keys (even though they should be safe as well). Most SSH clients now support this algorithm.

  • — this is a new algorithm added in OpenSSH. Support for it in clients is not yet universal. Thus its use in general purpose applications may not yet be advisable.

The algorithm is selected using the option and key size using the option. The following commands illustrate:

Specifying the File Name

Normally, the tool prompts for the file in which to store the key. However, it can also be specified on the command line using the option.

Troubleshooting

Key ignored by the server

If it appears that the SSH server is ignoring your keys, ensure that you have the proper permissions set on all relevant files.

For the local machine:
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/key
For the remote machine:
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys

If that does not solve the problem you may try temporarily setting StrictModes to no in /etc/ssh/sshd_config. If authentication with StrictModes off is successful, it is likely an issue with file permissions persists.

  • Make sure keys in are entered correctly and only use one single line.
  • Make sure the remote machine supports the type of keys you are using: some servers do not support ECDSA keys, try using RSA or DSA keys instead, see .
  • You may want to use debug mode and monitor the output while connecting:
# /usr/bin/sshd -d

How To Create SSH Keys

The first step to configure SSH key authentication to your server is to generate an SSH key pair on your local computer.

To do this, we can use a special utility called , which is included with the standard OpenSSH suite of tools. By default, this will create a 2048 bit RSA key pair, which is fine for most uses.

On your local computer, generate a SSH key pair by typing:

The utility will prompt you to select a location for the keys that will be generated. By default, the keys will be stored in the directory within your user’s home directory. The private key will be called and the associated public key will be called .

Usually, it is best to stick with the default location at this stage. Doing so will allow your SSH client to automatically find your SSH keys when attempting to authenticate. If you would like to choose a non-standard path, type that in now, otherwise, press ENTER to accept the default.

If you had previously generated an SSH key pair, you may see a prompt that looks like this:

If you choose to overwrite the key on disk, you will not be able to authenticate using the previous key anymore. Be very careful when selecting yes, as this is a destructive process that cannot be reversed.

Next, you will be prompted to enter a passphrase for the key. This is an optional passphrase that can be used to encrypt the private key file on disk.

You may be wondering what advantages an SSH key provides if you still need to enter a passphrase. Some of the advantages are:

  • The private SSH key (the part that can be passphrase protected), is never exposed on the network. The passphrase is only used to decrypt the key on the local machine. This means that network-based brute forcing will not be possible against the passphrase.
  • The private key is kept within a restricted directory. The SSH client will not recognize private keys that are not kept in restricted directories. The key itself must also have restricted permissions (read and write only available for the owner). This means that other users on the system cannot snoop.
  • Any attacker hoping to crack the private SSH key passphrase must already have access to the system. This means that they will already have access to your user account or the root account. If you are in this position, the passphrase can prevent the attacker from immediately logging into your other servers. This will hopefully give you time to create and implement a new SSH key pair and remove access from the compromised key.

Since the private key is never exposed to the network and is protected through file permissions, this file should never be accessible to anyone other than you (and the root user). The passphrase serves as an additional layer of protection in case these conditions are compromised.

A passphrase is an optional addition. If you enter one, you will have to provide it every time you use this key (unless you are running SSH agent software that stores the decrypted key). We recommend using a passphrase, but if you do not want to set a passphrase, you can simply press ENTER to bypass this prompt.

You now have a public and private key that you can use to authenticate. The next step is to place the public key on your server so that you can use SSH key authentication to log in.

How common are SSH keys and what is the risk

SSH keys turn out to be extremely common and widely used. Many large organizations have accumulated them for twenty years without any controls. A typical Fortune 500 enterprise has several million keys granting access to their servers. In one customer case, we examined 500 applications and 15,000 servers, and found 3,000,000 authorized keys and 750,000 unique key pairs. This organization also had over five million daily logins using keys. The keys were used for executing financial transactions, updating configurations, moving log data, file transfers, interactive logins by system administrators, and many other purposes.

It is turning out that most large enterprises have hundreds of thousands or even millions of keys. These keys are access that is unaccounted for, and may risk the entire enterprise.

SSH keys are a critical access management problem

SSH keys provide the same access as user names and passwords. Furthermore, they often grant access to privileged accounts on the operating system level, giving a command line. Yet, in many cases, SSH keys have been completely overlooked in identity and access management planning, implementation, and audits. Users have been able to create and install keys without oversight and controls. This has led to violations of corporate access policies and dangerous backdoors.

Over the last few years, it has turned out that most large organizations have massive numbers of SSH keys in their environment. These keys are like passwords. They grant access to resources — production servers, databases, routers, firewalls, disaster recovery systems, financial data, payment systems, intellectual property, and patient information.

Information security starts from controlling who is given access to systems and data. If there is no control over access, there is no security, no confidentiality, no integrity, and no guarantees of continued operation.

Intro into SSH keys and SSH key management

Link to SSH Risk Assessment

Insight from real customer cases

We have worked with many companies, including several global top-10 banks, leading retailers, and other large Fortune 500 companies. Based on our findings, most organizations:

  • Have extremely large numbers of SSH keys — even several million — and their use is grossly underestimated

  • Have no provisioning and termination processes in place for key based access

  • Have no records of who provisioned each key and for what purpose

  • Allow their system administrators to self-provision permanent key-based access — without policies, processes, or oversight.

In the case of one representative customer, we went through a quarter of their IT environment as part of a major SSH key management project. They had five million daily logins using SSH, most of them using SSH keys for automation. We analyzed 500 business applications, 15000 servers, and found three million SSH keys that granted access to live production servers. Of those, 90% were no longer used. Root access was granted by 10% of the keys.

NIST issues guidance on SSH key management

US National Instute of Standards and Technology (NIST) as issued guidance on SSH key management as NIST IR 7966. It is a good starting point for understanding how to manage access using SSH. We wrote most of the NIST guidelines, and have expanded upon them in our internal processes. We also invented SSH (Secure Shell). We are the best subject matter experts in the field.

Regulatory compliance requires SSH key management

Typical requirements for compliance include:

  • Managing identities and credentials — SSH keys are access credentials

  • Provisioning and termination process for access — including access based on SSH keys

  • Segregation of duties — elimination of key-based access from test and development systems into production

  • Disaster recovery — limiting attack spread from primary systems to disaster recovery sites and backup systems

  • Privileged access controls — SSH keys are often used to bypass jump servers

  • Boundary definition and documentation of connections for payment systems, financial data environments, patient data environments, or between government information systems

  • Incident response and recovery — being able to change compromised SSH keys.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector