Secure access to remote servers is a fundamental concern for maintaining the integrity of sensitive data and ensuring the overall security of your systems. One of the most effective ways to achieve this is by utilizing SSH key-based authentication.
In this guide, we will explore how to add ssh key to ubuntu vps server. By the end of this guide, you will have a clear understanding of how to generate SSH keys on an Ubuntu system and effectively add these keys to your Ubuntu server for robust and secure access.
Let’s delve into the details of this process and empower you to bolster the security of your remote server connections.
What is SSH or Secure Shell?
SSH keys function as a digital handshake between two systems. A key pair is generated, consisting of a public key and a private key. The public key is freely distributable, while the private key is kept confidential and never shared. When connecting to a server via SSH, the client system presents its public key. The server verifies this key against a list of authorized keys, granting access if there’s a match. This eliminates the need for passwords, offering several advantages:
- Enhanced Security: Public keys cannot be brute-forced or guessed like passwords. Even if intercepted, they cannot be used to gain access without the corresponding private key.
- Convenience: Passwordless login expedites the workflow, eliminating the need to repeatedly enter credentials.
- Automation: SSH keys are ideal for scripting automated tasks and server management, streamlining administrative processes.
Prerequisites
Before we embark on adding SSH keys, ensure you have the following:
- An Ubuntu Server: This guide focuses on adding SSH keys to Ubuntu systems. The process might differ slightly for other Linux distributions.
- Terminal Access: You’ll interact with the system using the terminal application.
- Administrative Privileges: Certain steps require root or sudo permissions to modify system configurations.
7 usages of generating ssh key on ubuntu servers
“Ubuntu get ssh key” typically refers to the process of generating SSH key pairs on an Ubuntu operating system. SSH keys consist of a public key and a private key, and they are used for secure authentication when connecting to remote servers or systems.
The usages of generate ssh key ubuntu servers are:
-
Secure Remote Access
SSH keys provide a more secure alternative to password-based authentication. They allow users to log in to remote servers or systems without exposing their passwords over the network.
-
Enhanced Security
SSH keys use strong encryption algorithms, making them resistant to brute-force attacks and other unauthorized access attempts.
-
Passwordless Logins
Once SSH keys are set up, users can log in to remote servers without typing passwords. This improves convenience while maintaining a high level of security.
-
Automation and Scripting
SSH keys are used in automation and scripting tasks that require remote access. They enable these processes to run without manual intervention.
-
Secure File Transfers
SSH keys are also used for secure file transfers using tools like SCP (Secure Copy Protocol) and SFTP (Secure File Transfer Protocol).
-
Git and Version Control
SSH keys are commonly used to authenticate with Git repositories and other version control systems, allowing secure interaction with code repositories.
-
Server Administration
Server administrators often use SSH keys for secure remote administration and maintenance tasks.
For the purpose of “Ubuntu create ssh key” you would typically generate a key pair using the `ssh-keygen` command on your Ubuntu system. The public key can then be placed on the servers or systems you want to access, while the private key remains on your local machine.
This process enhances security, simplifies authentication, and enables secure remote interactions on Ubuntu systems. Stay with us for more detailed information. Click on the link to learn about linux vps.
How to add ssh key to ubuntu server
In order to add the ssh key to the ubuntu server, do the following steps in order:
Step 1: Generating a key pair
To initiate the process, begin by generating a key pair on your client machine, typically your computer, using the command
ssh-keygen
By default, modern versions of ssh-keygen will create a secure 3072-bit RSA key pair; you can opt for a larger 4096-bit key with the “-b 4096” flag.
ssh-keygen -t rsa -b 4096
After executing the command, the following output will prompt you to save the key pair either in the “.ssh/” subdirectory within your home directory or to specify an alternate path.
Output Generating public/private rsa key pair. Enter file in which to save the key (/your_home/.ssh/id_rsa):
Press Enter and save the key pair into .ssh/ subdirectory in your Home directory. Do this to specify an alternate path.
In case you had previously generated an SSH key pair, you might encounter a query about overwriting the existing key.
If you have already generated a key pair, You may see a message like this:
Output /home/your_home/.ssh/id_rsa already exists. Overwrite (y/n)?
take caution if you want to choose “y” as “yes” since this action is irreversible and replaces the previous key.
Following this, you’ll have the option to input an additional layer of security by creating a passphrase, which is strongly recommended.
Once this is done, the system will provide output detailing the saved paths for your identification and public key, along with their associated key fingerprints and randomart images.
With this process complete, you’ll possess both a public and private key ready for authentication, enabling you to proceed to the subsequent step of placing the public key on your server for SSH-key-based access.
You should then see an output prompt similar to this:
Output Your identification has been saved in /your_home/.ssh/id_rsa Your public key has been saved in /your_home/.ssh/id_rsa.pub The key fingerprint is: SHA256:/hk7MJ5n5aiqdfTVUZr+2Qt+qCiS7BIm5Iv0dxrc3ks user@host The key's randomart image is: +---[RSA 3072]----+ | .| | + | | + | | . o . | |o S . o | | + o. .oo. .. .o| |o = oooooEo+ ...o| |.. o *o+=.*+o....| | =+=ooB=o.... | +----[SHA256]-----+
Step 2: Copy your public key to your Ubuntu server
There are two primary methods to transfer your public key to the Ubuntu server:
Method 1: Using ssh-copy-id
Establish an SSH Connection (if possible): If you can already connect to the Ubuntu server using a password, this method is the most convenient. Execute the following command, replacing <username> with your username on the server and <server_ip> with the server’s IP address:
ssh-copy-id -i ~/.ssh/id_rsa.pub <username>@<server_ip>
Enter Password: You’ll be prompted to enter the password for your Ubuntu server user account. Once entered, the ssh-copy-id tool will automatically add your public key to the authorized_keys file on the server.
-
Copying the public key using SSH
If you lack access to the ssh-copy-id utility but possess password-based SSH access to a server account, you can upload your public key using conventional SSH methods.
The process entails utilizing the cat command to read the contents of your local public SSH key file. This output is then piped through an established SSH connection to the remote server.
On the server-side, a script verifies the existence and permission settings of the ~/.ssh directory for the designated user account.
Finally, the piped content, containing your public key, is appended to the authorized_keys file within this directory. The >> redirection operator is employed to achieve this, ensuring previously added keys remain intact and facilitating the seamless addition of multiple keys.
The full command looks like this:
$ cat ~/.ssh/id_rsa.pub | ssh username@remote_host "mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys && chmod -R go= ~/.ssh && cat >> ~/.ssh/authorized_keys"
You will then see the following output:
Output The authenticity of host '203.0.113.1 (203.0.113.1)' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes
In the scenario where an SSH connection is established for the first time to a particular host, your local machine will not possess a record of the remote server’s identification. This is an expected behavior during the initial connection attempt.
To acknowledge the legitimacy of the remote host and proceed with the connection, respond in the affirmative (“yes”) and press the “ENTER” key.
Following this step, you will likely be prompted to enter the password associated with the designated user account on the remote server.
Output username@203.0.113.1's password:
Upon successful password authentication, the contents of your local id_rsa.pub key file will be appended to the authorized_keys file within the remote user’s account. This signifies the establishment of key-based authentication for subsequent connections.
Assuming this key upload process finishes without errors, you may proceed to Step 3.
-
Copying the public key manually
In case password-based SSH access isn’t an option, you can manually complete the process by displaying your local id_rsa.pub content using “cat” command, creating the ~/.ssh directory on the remote server, appending the key content to the authorized_keys file using the “echo” command, and ensuring proper permissions using the “chmod” and “chown” commands.
To display the content of your id_rsa.pub key, type this into your local pc:
$ cat ~/.ssh/id_rsa.pub
Then You will see the key content. It should look like this:
Output ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCqql6MzstZYh1TmWWv11q5O3pISj2ZFl9HgH1JLknLLx44+tXfJ7mIrKNxOOwxIxvcBF8PXSYvobFYEZjGIVCEAjrUzLiIxbyCoxVyle7Q+bqgZ8SeeM8wzytsY+dVGcBxF6N4JS+zVk5eMcV385gG3Y6ON3EG112n6d+SMXY0OEBIcO6x+PnUSGHrSgpBgX7Ks1r7xqFa7heJLLt2wWwkARptX7udSq05paBhcpB0pHtA1Rfz3K2B+ZVIpSDfki9UVKzT8JUmwW6NNzSgxUfQHGwnW7kj4jp4AT0VZk3ADw497M2G/12N0PPB5CnhHf7ovgy6nL1ikrygTKRFmNZISvAcywB9GVqNAVE+ZHDSCuURNsAInVzgYo9xgJDW8wUw2o8U77+xiFxgI5QSZX3Iq7YLMgeksaO4rBJEa54k8m5wEiEE1nUhLuJ0X/vh2xPff6SQ1BL/zkOhvJCACK6Vb15mDOeCSq54Cr7kvS46itMosi/uS66+PujOO+xt/2FWYepz6ZlN70bRly57Q06J+ZJoc9FfBCbCyYH7U/ASsmY095ywPsBo1XQ9PqhnN1/YOorJ068foQDNVpm146mUpILVxmq41Cj55YKHEazXGsdBIbXWhcrRf4G2fJLRcGUr9q8/lERo9oxRm5JFX6TCmj6kmiFqv+Ow9gI0x8GvaQ== demo@test
Establish a secure connection to your designated remote host utilizing your preferred authentication method.
Upon successful authentication and access to your designated user account on the remote server, verify the existence of the directory denoted by the path ~/.ssh
. The following command will create the aforementioned directory if it is absent; otherwise, no action will be taken.
$ mkdir -p ~/.ssh
Having established the presence of the ~/.ssh directory, we can now proceed to manage the authorized_keys file within it. This file plays a crucial role in SSH key-based authentication.
To grant access to a specific user via SSH key authentication, you can append the contents of their id_rsa.pub file (which holds the public key) to the authorized_keys file on the remote server. The following command facilitates this process, creating the authorized_keys file if it doesn’t already exist:
$ echo public_key_string >> ~/.ssh/authorized_keys
Within the above command, a placeholder named public_key_string is present. To replace this placeholder effectively, you should utilize the output generated by executing the cat ~/.ssh/id_rsa.pub command on your local machine. This output, typically beginning with the identifier ssh-rsa AAAA…, represents the public key that will grant access.
Following this step, we will undertake a final measure to solidify security. We will verify and, if necessary, adjust the permission settings associated with both the ~/.ssh directory and the authorized_keys file on the remote server.
$ chmod -R go= ~/.ssh
The following command executes a recursive operation, effectively eradicating all permissions granted to groups and “other” users for the ~/.ssh directory. This action strengthens security by restricting access to authorized individuals.
It is imperative to note that if you are currently utilizing the root account to configure SSH keys for a designated user account, an additional security measure is necessary. You must verify ownership of the ~/.ssh directory. In an ideal scenario, ownership should be assigned to the target user account, and not retained by the root account.
$ chown -R sammy:sammy ~/.ssh
Whichever method you choose, successfully completing this step will pave the way for passwordless authentication on your Ubuntu server.
Step 3: Authenticating to your Ubuntu server using SSH keys
Following the successful execution of either above methods, subsequent login attempts to the remote host should no longer necessitate the remote account’s password.
If you got through one of those methods, you should be able to log in to the remote server without typing that password every time. The basic process is the same:
$ ssh username@remote_host
If this is your first time connecting to this server (especially if you used the key upload method), you might see something like this:
Output The authenticity of host '203.0.113.1 (203.0.113.1)' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes
The message indicates that your local machine has not encountered this remote host beforehand. To proceed with the connection and establish trust, entering “yes” followed by the ENTER key is required.
Assuming you did not configure a passphrase for your private key, you will be granted access automatically. However, if a passphrase was implemented during key creation, the system will prompt you to enter it now. For security reasons, the characters you type will not be displayed on the terminal screen. Upon successful authentication, a new shell session with the designated account on the Ubuntu server will be initiated.
If key-based authentication was successful, you have the option to explore further security measures by disabling password authentication. This step is covered in subsequent guidance.
Step 4: Disabling Password Authentication on your server
If you were able to log in to your account using SSH without providing a password, congratulations! This indicates that you have effectively configured SSH key-based authentication for your account. However, it is essential to note that password-based authentication remains active on your server. This vulnerability exposes your system to potential brute-force attacks.
Before proceeding with the following steps, it is imperative to ensure that you have established SSH key-based authentication. This can be achieved in two ways:
Root Account: Configure SSH key-based authentication for the root account on the server.
Non-Root Account with sudo (Preferred): Preferably, configure SSH key-based authentication for a non-root user account that possesses sudo privileges.
Disabling password-based logins is a crucial step in this process. Verifying an alternative method for administrative access is paramount to avoid locking yourself out.
Once you have confirmed that your remote account possesses administrative access (either root or a sudo-enabled user), utilize SSH keys to log in to your server. Following a successful login, proceed to open the configuration file for the SSH daemon.
$ sudo nano /etc/ssh/sshd_config
Within the opened SSH daemon configuration file, locate a directive labeled “PasswordAuthentication.” This specific line might be commented out, indicated by a “#” symbol placed at the beginning of the line. You can uncomment the line by removing the # symbol, and set the value to “no”. This modification will disable your ability to log in via SSH using account passwords:
. . . PasswordAuthentication no . . .
Once you have completed the modifications within the SSH daemon configuration file, proceed with saving and closing the file. Here’s how to achieve this using the nano text editor:
Save: Press the keyboard shortcut CTRL+X. This action initiates the exit process from nano.
Confirmation: A prompt will appear asking for confirmation to save the changes. Press the Y key to confirm saving.
Exit: Finally, press the ENTER key to fully exit the nano text editor.
To actually activate these changes, we need to restart the sshd service:
$ sudo systemctl restart ssh
As a precautionary measure, it is recommended to open a new terminal window and test that the SSH service is functioning correctly before closing your current session.
$ ssh username@remote_host
This test will help ensure you haven’t inadvertently locked yourself out by disabling password-based logins.
Once you have successfully verified that the SSH service is functioning as expected, you can safely close all existing server sessions. This signifies that the SSH daemon on your Ubuntu server is now configured to exclusively respond to SSH key-based authentication. Consequently, password-based login attempts will be disabled.
Conclusion
With SSH-key-based authentication now set up on your server, you can log in without the need to input an account password. If you have any questions about adding an ssh key in ubuntu server, ask in the comments section.