After creating a compute instance on the cloud, logging in through the SSH protocol is the primary way of accessing the instance. The SSH protocol uses a key pair for authentication, where the public key is installed in the remote instance and the private key is installed on your local machine. Red Hat Enterprise Linux 6 uses SSH Protocol 2 and RSA keys by default (see Section 14.1.3, “Protocol Versions” for more information). Important Do not generate key pairs as root, as only root would be able to use those keys. Apr 12, 2018 SSH-key-based authentication provides a more secure alternative to password-based authentication. In this tutorial we'll learn how to set up SSH-key-based authentication on a CentOS 7 installation.
Introduction
Secure Shell (SSH) is an encrypted protocol used by Linux users to connect to their remote servers.
Generally, there are two ways for clients to access their servers – using password based authentication or public key based authentication.
Using SSH keys for authentication is highly recommended, as a safer alternative to passwords.
This tutorial will guide you through the steps on how to generate and set up SSH keys on CentOS 7. We also cover connecting to a remote server using the keys and disabling password authentication.
1. Check for Existing Keys
Prior to any installation, it is wise to check whether there are any existing keys on the client machines.
Open the terminal and list all public keys stored with the following command:
The output informs you about any generated keys currently on the system. If there aren’t any, the message tells you it cannot access /.ssh/id_*.pub
, as there is no such file or directory.
2. Verify SSH is Installed
To check if thw package is installed, run the command: Linux generate ssh key pem windows 10.
If you already have SSH, the output tells you which version it is running. Currently, the latest version is OpenSSH 8.0/8.0p1.
Note: Refer to our guide If you need to install and enable SSH on your CentOS system.
1. Start by logging into the source machine (local server) and creating a 2048-bit RSA key pair using the command:
If you want to tighten up security measures, you can create a 4096-bit key by adding the -b 4096 flag:
2. After entering the command, you should see the following prompt:
3. To save the file in the suggested directory, press Enter. Alternatively, you can specify another location.
Note: If you already have a key pair in the proposed location, it is advisable to pick another directory. Otherwise it will overwrite existing SSH keys.
4. Next, the prompt will continue with:
Although creating a passphrase isn’t mandatory, it is highly advisable.
5. Finally, the output will end by specifying the following information:
Now you need to add the public key to the remote CentOS server.
You can copy the public SSH key on the remote server using several different methods:
The fastest and easiest method is by utilizing ssh-copy-id
. If the option is available, we recommend using it. Otherwise, try any of the other two noted.
1. Start by typing the following command, specifying the SSH user account, and the IP address of the remote host:
If it is the first time your local computer is accessing this specific remote server you will receive the following output:
2. Confirm the connection – type yes and hit Enter.
3. Once it locates the id_rsa.pub key
created on the local machine, it will ask you to provide the password for the remote account. Type in the password and hit Enter.
4. Once the connection has been established, it adds the public key on the remote server. This is done by copying the ~/.ssh/id_rsa.pub
file to the remote server’s ~/.ssh
directory. You can locate it under the name authorized_keys
.
5. Lastly, the output tells you the number of keys added, along with clear instructions on what to do next:
1. First, set up an SSH connection with the remote user:
2. Next, create the ~/.ssh
directory as well as the authorized_keys
file:
3. Use the chmod command to change the file permission:
chmod 700
makes the file executable, while chmod 600
allows the user to read and write the file.
4. Now, open a new terminal session, on the local computer.
5. Copy the content from id_rsa.pub
(the SSH public key) to the previously created authorized_keys
file on the remote CentOS server by typing the command:
With this, the public key has been safely stored on the remote account.
1. To manually add the public SSH key to the remote machine, you first need to open the content from the ~/.ssh/id_rsa.pub
file:
2. As in the image below, the key starts with ssh-rsa and ends with the username of the local computer and hostname of the remote machine:
3. Copy the content of the file, as you will need later.
4. Then, in the terminal window, connect to the remote server on which you wish to copy the public key. Use the following command to establish the connection:
5. Create a ~/.ssh directory and authorized_keys file on the CentOS server with the following command:
6. Change their file permission by typing:
7. Next, open the authorized_keys
file with an editor of your preference. For example, to open it with Nano, type:
8. Add the public key, previously copied in step 2 of this section, in a new line in (under the existing content).
9. Save the changes and close the file.
10. Finally, log into the server to verify that everything is set up correctly.
Once you have completed the previous steps (creating an RSA Key Pair and copying the Public Key to the CentOS server), you will be able to connect to the remote host without typing the password for the remote account.
All you need to do is type in the following command:
If you didn’t specify a passphrase while creating the SSH key pair, you will automatically log in the remote server.
Otherwise, type in the passphrase you supplied in the initial steps and press Enter.
Once the shell confirms the key match, it will open a new session for direct communication with the server.
Although you managed to access the CentOS server without having to provide a password, it still has a password-based authentication system running on the machine. This makes it a potential target for brute force attacks.
You should disable password authentication entirely by following the outlined steps.
Note: Consider performing the following steps through a non-root account with sudo privileges, as an additional safety layer.
1. Using the SSH keys, log into the remote CentOS server which has administrative privileges:
2. Next, open the SSH daemon configuration file using a text editor of your choice:
3. Look for the following line in the file:
4. Edit the configuration by changing the yes
value to no
. Thus, the directive should be as following:
5. Save the file and exit the text editor.
6. To enable the changes, restart the sshdservice using the command:
7. Verify the SSH connection to the server is still functioning correctly. Open a new terminal window and type in the command:
In this article, you learned how to generate SSH key pairs and set up an SSH key-based authentication. We also covered copying keys to your remote CentOS server, and disabling SSH password authentication.
Next, You Should Read:
A colleague and I were recently discussing how he preps his RHEL template VMs for use with Puppet. It inspired me to share how I prepare my Linux VMs to become a template within vSphere 6.5. A point to note is that I don’t prepare my template images for a particular configuration management system like Puppet, but instead bootstrap them once they’re deployed. Why? I use my templates for a variety of things, and sometimes the people who end up with the VMs don’t want my management systems on them. It also means I have to handle manually some of what is done scriptwise via the configuration management system, but that’s just fine. I’d actually rather do it that way because it helps me guarantee the state of the system.
You can perform these steps in full multiuser — runlevel 3 — or in single-user by issuing an “init 1” and waiting for all the processes to stop. I wouldn’t do any of this in runlevel 5, with full X Windows running. In fact, I really don’t suggest installing X Windows at all on Linux VMs unless you really, really need it for some reason… but that’s a whole different topic. I’d also suggest taking a snapshot of your template prior to trying any of this out. As Lenin said, “Trust, but verify.”
This write up assumes you have a fresh RHEL/CentOS install running that has been updated and has your required packages installed. You must also ensure that open-vm-tools is installed before proceeding.
Points to note on the install:
- Don't create a local user (use a root account only)
- Make sure the disk is thin provisioned
- Ensure that the network is enabled and leave it set as DHCP for now
I like to use the --skip-broken flag when running yum update. It's a great feature for skipping packages that have dependency problems or that may introduce problems to the already installed packages.
i.e: yum update --skip-broken -y
You’re going to all this trouble to create a clean deployable template, so you might as well stop writing new data. Otherwise all your deployed VMs will have a log of you shutting the VM down.
Issue the following commands to stop the logging services:
/sbin/service rsyslog stop
/sbin/service auditd stop
You need yum-utils installed to get package-cleanup. This has to go before the yum cleanup in the next step as it needs your channel data. I usually let the post-deployment configuration management take care of this, but this is nice when we create a new template for a intermediate/point release, or just to cover a security hole.
Issue the following command to remove the old kernels (if there are any):
package-cleanup --oldkernels --count=1
Yum keeps a cache in /var/cache/yum that can grow quite large, especially after applying patches to the template. For example, my lab host currently has 360 MB of stuff in yum’s cache right now, just from a few months of incremental patching. In the interest of keeping my template as small as possible I wipe this.
Issue the following command to clean the cache:
yum clean all
Starting fresh with the logs is nice. It means that you don’t have old, irrelevant log data on all your cloned VMs. It also means that your template image is smaller. Change out the “rm” command for one that matches whatever your logrotate renames files as. As an aside, because people usually neglect this step, if you get really, really bored it’s fun to look at the old log data people leave on virtual appliances in cloud templates. Lots of leaked information there ;)
Issue the following commands to clear the logs:
/usr/sbin/logrotate –f /etc/logrotate.conf
/bin/rm –f /var/log/*-???????? /var/log/*.gz
/bin/rm -f /var/log/dmesg.old
/bin/rm -rf /var/log/anaconda
This whole /dev/null business is a neat function that lets you clear a file without restarting the process associated with it, useful in many more situations than just template-building.
Issue the following commands to truncate the audit logs:
/bin/cat /dev/null > /var/log/audit/audit.log
/bin/cat /dev/null > /var/log/wtmp
/bin/cat /dev/null > /var/log/lastlog
/bin/cat /dev/null > /var/log/grubby
Have you ever noticed that if you clone/deploy a Linux VM that won't bring up it single network interface and renames the interface to something like eth1? Yep, well that's the udev persistent network interface rules coming back to haunt you. This is how I've decided to deal with the problem.
This generally affects CentOS /RHEL 6 and you shouldn't have to do it in v7 but it won't hurt anything.
Issue the following command to remove the udev persistent rules:
/bin/rm -f /etc/udev/rules.d/70*
This is a corollary to step 5, just removing unique identifiers from the template so the cloned VM gets its own. You can also change the “-i” to “-i.bak” if you want to keep a backup copy of the file.
Issue the following command to clear the identifiers:
/bin/sed -i ‘/^(HWADDR UUID)=/d’ /etc/sysconfig/network-scripts/ifcfg-e*
Under normal, non-template circumstances you really don’t ever want to run rm on /tmp like this. Use tmpwatch or any other manner of safer ways to do this, since there are attacks people can use by leaving symlinks and what-not in /tmp that rm might traverse (“whoops, I don’t have an /etc/passwd anymore!”). Plus, users and processes might actually be using /tmp, and it’s impolite to delete their files. However, this is your template image, and if there are people attacking your template you should reconsider how you’re doing business really.
/bin/rm –rf /tmp/*
/bin/rm –rf /var/tmp/*
If you don’t do this all your VMs will have all the same keys, which has negative security implications. It’s also annoying to fix later when you’ve realised that you’ve deployed a couple of years worth of VMs and forgot to do this in your prep script. Not that I would know anything about that. Nope.
/bin/rm –f /etc/ssh/*key*
No sense in keeping this history around, it’s irrelevant to the cloned VM.
/bin/rm -f ~root/.bash_history
unset HISTFILE
You might choose to just remove ~root/.ssh/known_hosts if you have SSH keys you want to keep around.
/bin/rm -rf ~root/.ssh/
/bin/rm -f ~root/anaconda-ks.cfg
Time to clear the history of everything you've just done and shutdown the server in a clean state for converting to a VM:
history –c
sys-unconfig
The server will automatically now shutdown.
So that’s my prep routine. It relies heavily on keeping the rest of the VM clean, and only cleans up what we can’t avoid sullying. Once the server shuts down as a result of the sys-unconfig command you can convert to a sanitized template in vSphere and add any customization specs required to the Linux deployments.
Hey Liam,
Awesome How To article! It really helped me out with a project I'm working on! If it's alright, I do have one question about doing the deployments from a template. I'm currently working with SUSE Enterprise Linux 12 and I noticed that when I deploy off a template, the /sda1 and /sda2 UUIDs are the same in every clone. Is this something that I need to change? Or can several servers with the same device UUIDs exist? If I need to change them, how should I go about it?
Thank you in advance for any and all help you may be able to provide!!!
MC, I blieve you will want to place this in your cleanup script:
echo '> Remove the traces of the template MAC address and UUIDs'
sudo sed -i '/^(HWADDR UUID)=/d' /etc/sysconfig/network-scripts/ifcfg-e*
Hope this helps..
Great guide. Step 6 was specially interesting for me . That udev trick is very neat. Will be using it from now on.