Configure the SSH service to log on to the Linux server using the certificate

Source: Internet
Author: User
Tags filezilla ssh server ed25519

Configure the SSH service to log on to the Linux server using the certificate

Common authentication methods for logging on to a Linux server through SSH (Secure Shell) include passwords and certificates. From the security perspective, we recommend that you log on with a certificate. It takes a lot of effort to configure SSH login using a certificate on the server for the first time, and create a certificate and then log on successfully. It is complicated to configure the certificate to log on to SSH.

Record the SSH certificate configuration and use PuTTY and FileZilla to log on to Windows for the next time.

0. Configure the SSH certificate Logon Process
  1. Configure SSH on the server as the certificate logon mode.
  2. The client generates the certificate: private key and public key ).
    Keep the private key on the client and save it securely: a password is usually set and the key file may need to be encrypted. If a password is set, you need to enter the password to unlock the private key every time you log on to the server using this private key.
    The Public Key is uploaded and added to the file specified by the SSH configuration on the server to be trusted.

Tip: although the same private key/public key can be used to log on to different servers repeatedly, the private key/public key must be generated separately for different servers based on security considerations.

Personally, using SSH to log on to the server in Windows involves two types of special software: PuTTY and FileZilla.

If you want to use FileZilla's sftp to log on to the server, because FileZilla uses putty to connect to the sftp server, therefore, you need to add the required private key in default settings-> ssh-> Auth of putty and save it.

If you use PuTTY to log on to the server, you must add and save the required private key in default settings-> ssh-> Auth of putty, and then log on to the server.

1. The client generates the private key/Public Key

When using the private key/Public Key (key pairs are paired), you need to consider the security of the Key itself. In addition to proper storage, there is also the reliability of encryption and verification. According to the introduction here (Secure Shell), you can choose the ed25519 and rsa encryption systems safely at present. Of course, the two key exchange systems must be configured for the corresponding SSH server.

The public key/private key is generated on the client (the user's computer that needs to log on to the server). This ensures that the generated private key is not transmitted over the network. Therefore, on the client, if it is a Linux system, run any of the following commands,

# ssh-keygen -t ed25519 -o -a 100 -C "Your comment here"# ssh-keygen -t rsa -b 4096 -o -a 100 -C "Your comment here"

To generate a certificate in the corresponding format. Follow the prompts.

Passphrase is the password used to protect the private key. You need to use a password that contains special characters and has a certain length. Remember it, or you will not be able to use it.

The generated key is saved in the. ssh/directory of the current user directory. Two files: id_rsa is the private key, and id_rsa.pub is the public key.

In Windows, you can use PuTTYgen () related to PuTTY to generate a key pair. The latest PuTTY version is version 0.65 (or Beta ). Double-click PuTTYgen to open the window.

The following can choose the encryption method, the default is the SSH-2 RSA is rsa; next to the number of digits can be selected, the default is 2048 bits (now we have started to use 4096 bits ). Click Generate on the right in the middle, and then shake the mouse in the upper half of the window. The certificate is generated based on these random points. After the progress bar is completed, the key pair is generated, the following interface is displayed.

Use PuTTYgen to generate the key/Public Key

In the figure, click Save public key to Save the public key as a file (it is best to copy the text file in the box to a text file before saving, which will be used later ). Of course, the saved public key file can also be opened using a text editor such as NotePad or NotePad ++ in Windows. The content of the file saved above is as follows,

---- BEGIN SSH2 PUBLIC KEY ----Comment: "rsa-key-20151019"AAAAB3NzaC1yc2EAAAABJQAAAQEAmmEZDOTuPdrARNCZjWyZfZcDRHm4oRjZN6fLWG8eNh1KhNJu1pPtFvhACaWVE0vBfPS/6UzDeClNk1DScMmYVsqgsqwrjazcS4eeNFT1A9B4MeppI2N7pa5Gsvq/iD3cQpzAmGv8IZl6Aqoujz0429+dCoeUW6L2Mu490+0A6MWhEh/GQWV/VpYwf/J1KxAWgGuNpeMONN9el2+BiCwJdhmKwQaXNcmdqVvZWdm+A//+1GWJqydDWmFgYj8yXOGIHNlS0bNtw0Mrq+GrXCGiJuPWEXNDIlVA5Pgnw+6Xd0zv1qgeGe1CpjZzV2e/bTlG9AHLumJ/uWhp7ZuMwsBq6Q==---- END SSH2 PUBLIC KEY ----

The public key copied above should look like this (this is the actual public key, and the following is the character to be used later, not the above ),

ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAmmEZDOTuPdrARNCZjWyZfZcDRHm4oRjZN6fLWG8eNh1KhNJu1pPtFvhACaWVE0vBfPS/6UzDeClNk1DScMmYVsqgsqwrjazcS4eeNFT1A9B4MeppI2N7pa5Gsvq/iD3cQpzAmGv8IZl6Aqoujz0429+dCoeUW6L2Mu490+0A6MWhEh/GQWV/VpYwf/J1KxAWgGuNpeMONN9el2+BiCwJdhmKwQaXNcmdqVvZWdm+A//+1GWJqydDWmFgYj8yXOGIHNlS0bNtw0Mrq+GrXCGiJuPWEXNDIlVA5Pgnw+6Xd0zv1qgeGe1CpjZzV2e/bTlG9AHLumJ/uWhp7ZuMwsBq6Q== rsa-key-20151019

Therefore, if it is not copied, you need to open the saved public key and combine it yourself.

The Key comment is used to annotate the public Key, for example, the above rsa-key-20151019 is. This is not part of the public key. You can modify it as needed, for example, replace it with your own email address.

You can enter or do not enter a key passphrase before saving the private Key ). Of course, security is used. Key passphrase and the Confirm passphrase below it are the aforementioned cryptographic phrase used to protect the private Key. It is better to mix uppercase and lowercase letters with numbers and add special characters such! " £ $ % ^. If you save the private key without entering the password phrase, a confirmation prompt will be prompted. Note that the phrase is a long string. However, existing text may be cracked by brute force attempts.

2. SSH Server Configuration

OpenSSH is generally used on the server to provide the SSH login service. The server configuration files on CentOS (Other Linux releases may be different) are stored in,

/etc/ssh/sshd_config

Modify this file,

# vim /etc/ssh/sshd_config

Configuration example (Here we describe how to split rows or blocks ):

Note: many lines in the default configuration file of SSH are commented out (that is, it does not work. The mark is that there is a # sign at the beginning of the Line). To make it work, delete.

Port. The default value is 22. We recommend that you customize the port,

Port 2222

If there is no special reason, do not use Protocol 1,

Protocol 2

Prohibit Root Account Login,

PermitRootLogin no

Logon with a blank password is not allowed. The default value is no,

PermitEmptyPasswords no

User name/user group that allows SSH login.

#AllowUsers user1 user2AllowGroups ssh-users

The benefit of using a user group is that you need to maintain this configuration when changing users and adding/Deleting Users. Therefore, we recommend that you use user groups for management. A new user is generated and can be added directly to this additional user group.

Add a user to an additional user group. Simply put,

# groupadd ssh-user# usermod -a -G ssh-user <username>

Sshd is not allowed to check the permission data of User Directories Or important files. This is to prevent users from setting the permissions of some important files wrong. For example, the user's ~. When the ssh/permission is set incorrectly, users are not allowed to log on in some special circumstances.

StrictModes no

Allow users to log on to the server using a pair of key systems. Here, only Protocol Version 2 is used. The public key data generated by the user is stored in the corresponding user directory (such as/home/luser1 on the server).ssh/authorized_keysFile,

RSAAuthentication yesPubkeyAuthentication yesAuthorizedKeysFile %h/.ssh/authorized_keys

Save the server's own KEY corresponding to protocol version 2, and save different types of keys to different files (only the two mentioned above are enabled here ),

KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256HostKey /etc/ssh/ssh_host_ed25519_keyHostKey /etc/ssh/ssh_host_rsa_key

Because the Key Exchange Algorithm diffie-hellman-group-exchange-sha256 is enabled, you also need to modify/etc/ssh/moduli to enhance its security. If this file is available (usually available during installation), delete all rows with a value less than 5th in the 2000 column of this file. Because there are many lines, it is easier to use the awk command to automatically delete them,

# Awk '$5> 100'/etc/ssh/moduli> "$ {HOME}/moduli" # wc-l "$ {HOME}/moduli" # Make sure file contains content, the number output by this command is greater than 0 # mv "$ {HOME}/moduli"/etc/ssh/moduli

If this file is not available, a file is generated,

# ssh-keygen -G /etc/ssh/moduli.all -b 4096# ssh-keygen -T /etc/ssh/moduli.safe -f /etc/ssh/moduli.all# mv /etc/ssh/moduli.safe /etc/ssh/moduli# rm /etc/ssh/moduli.all

This may take a long time to generate.

Disable Password Logon (you can also use a certificate to log on without disabling Password Logon; you can disable Password Logon to prevent yourself from shutting yourself out of the server ),

PasswordAuthentication noChallengeResponseAuthentication no

Disable graphic interface forwarding and TCP forwarding,

#AllowTcpForwarding no#X11Forwarding no

Detailed logs must be recorded,

LogLevel VERBOSE

SFTP subsystem is allowed (FileZilla uses this ),

Subsystem sftp /usr/local/ssh/libexec/sftp-server
3. Add the user's public key to the server

The user's public key generated in 1. Needs to be imported to the SSH trusted Certificate list on the server by the system administrator. The SSH server will automatically search for the Public Key in the. ssh/authorized_keys file in the corresponding user directory on the server based on the username used by the user to log on to the server.

For example, you need to save the rsa public key (save it as id_rsa.save) (note that it is different from the id_rsa.pub saved by PuTTYgen. If it is wrongServer refused our keyError prompt, because the pubkey is incorrect) put in the certificate list of the user luser1, yes,

# mkdir /home/luser1/.ssh# touch /home/luser1/.ssh/authorized_keys# cat id_rsa.save >> /home/luser1/.ssh/authorized_keys#

Then you can delete the id_rsa.pub file.

Modify the file access permission (if StrictModes is set to yes in sshd_config, this is required, otherwise it cannot work ),

# chmod 700 /home/luser1/.ssh# chmod 600 /home/luser1/.ssh/authorized_keys

Restart the SSH service,

# systemctl restart sshd

Then the user can log on with the certificate.

4. log on with a certificate

On Linux,

ssh -i /path/to/private_key/id_rsa luser1@<ssh_server_ip>

In Windows, if PuTTY is used (refer to here ),

  • Double-click to open putty;
  • Enter the IP address and Port under Basic options for you PuTTY session on the right, click SSH, and enter a name, such as ssh-to-server, and Save;
  • Under "Category" on the left, click "Connection", "SSH", "Auth", and then "Browse" on the right, select the generated private key id_rsa, and click "Open" to Open the logon process;
  • Enter the username to Log On As prompted;
  • Enter the Key passphrase to log on.

If you use FileZilla (refer to here): You can use Pagent (see the putty download page) or directly use it to provide private key management settings, which is simpler than putty. The following describes how to use FileZilla's built-in private key manager:

  • Open FileZilla, click Edit in the toolbar, and set to open the Settings manager;
  • Select SFTP from the list on the left, and the private key management interface is displayed on the right;
  • Click Add key file... (Add a private key file), select the private key to use, and open it;
  • Complete (Click OK on the left );
  • Return to FileZilla and configure the SFTP Server:
    • IP, Port (Port)
    • Protocol: Select SFTP-SSH File Transfer Protocol
    • Select Normal for Logon Type (LOGIN Mode)
    • Enter the User name
    • Leave Password Blank
    • Connect
    • If you are prompted to enter a password phrase after you click Connect (Connect), it is the private key's protected password.
5. Appendix 5.1 SSH configuration parameters
#1. The overall settings of the SSH Server include the port used, and the password calculation method Port 22 # SSH uses 22 by default. You can also use multiple ports! # That Is, You can reuse the port setting item! Protocol # The selected SSH Protocol version can be 1 or 2. # If you want to support both versions, you must use! # ListenAddress 0.0.0.0 # host adapter for listening! For example, if you have two IP addresses: #192.168.0.100 and 192.168.2.20, you can write them in the following format if you only want to # enable 192.168.0.100: listenAddress 192.168.0.100 # only listen to SSH connections from the IP address 192.168.0.100. # If you do not use the settings, all the default interfaces will accept SSHPidFile/var/run/sshd. pid # You can put the sshd pid file! The left column is the default LoginGraceTime 600 # After the user connects to the SSH server, a password input screen appears. # In this screen, how long does the user fail to connect to the SSH server? # disconnected! The time is second! Compression yes # Can Compression commands be used? Of course ?! #2. Describe the files placed by the Private Key of the host. You can use the following files by default! HostKey/etc/ssh/ssh_host_key # Private Key HostKey/etc/SSH/ssh_host_rsa_key # RSA private key used by ssh version 2/etc/SSH/ssh_host_dsa_key # ssh version 2 uses the DSA Private Key #2.1 some settings about version 1! KeyRegenerationInterval 3600 # It can be seen from the previous online instructions that version 1 will use the Public Key of # server. If this Public # Key is stolen, won't it be finished? So we need to rebuild it at intervals of time! The time here is second! ServerKeyBits 768 # yes! This is the length of the Server key! #3. Information about the logon file is stored with the daemon name! SyslogFacility AUTH # when someone uses SSH to log on to the system, SSH will record the information # message. What daemon name should this information be recorded under? # The default value is set by AUTH, that is,/var/log/secure! What? Forgot! Go back to the basics of Linux. # other available daemon names: DAEMON, USER, AUTH, # LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, logLevel INFO # logon record level! Hey! Any message! # Similarly, if you forget it, go back to the reference! #4. Security Settings! Very important! #4.1 set PermitRootLogin no # allow root login! The default value is allowed, but it is recommended to set it to no! UserLogin no # login to the login program is not accepted under SSH! StrictModes yes # When the user's host key changes, the Server will not accept online, # It can withstand some Trojans! # RSAAuthentication yes # Do you want to use RSA Authentication !? Only for version 1! PubkeyAuthentication yes # Are Public keys allowed? Of course! Only version 2 AuthorizedKeysFile. ssh/authorized_keys # The name of the file where the account stores the file if you want to use an account that does not need a password to log in! #4.2 authentication part RhostsAuthentication no # the local system does not only use. rhosts, because only. rhosts is used too # It is not safe, so it must be set to no here! IgnoreRhosts yes # whether to cancel use ~ /. Ssh/. rhosts for authentication! Of course! RhostsRSAAuthentication no # This option is specially used for version 1. The rhosts file is used for authentication in #/etc/hosts. equiv with the RSA algorithm! Do not use HostbasedAuthentication no # This project is similar to the above project, but it is used for version 2! IgnoreUserKnownHosts no # Whether to ignore ~ in the Home Directory ~ /. Ssh/known_hosts what is recorded in this file # What is the host content? Of course, do not ignore it, so here is no! PasswordAuthentication yes # password verification is required! So write yes here ?! PermitEmptyPasswords no # If the above item is set to yes, it is best to set it to # no. Whether the project allows logging in with an empty password! Of course not! ChallengeResponseAuthentication yes # challenge any password authentication! Therefore, any authentication method specified by login. conf # can be applied! # PAMAuthenticationViaKbdInt yes # Whether to enable other PAM modules! Enabling this module will cause the PasswordAuthentication setting to become invalid! #4.3 Kerberos-related parameter settings! Because we do not have a Kerberos host, we do not need to set it below! # Define custom uthentication no # define osorlocalpasswd yes # define osticketcleanup yes # define ostgtpassing no #4.4 the settings for use under X-Window are described below! X11Forwarding yes # X11DisplayOffset 10 # X11UseLocalhost yes #4.5 project after Logon: PrintMotd no # Is there any information displayed after logon? For example, for the time and location of the Last login, the default value is yes. However, you can change it to no for security reasons! PrintLastLog yes # display the Last login information! Yes! Yes, too! KeepAlive yes # In general, if this project is set, the SSH Server will send the # KeepAlive message to the Client to ensure that the connection between the two is normal! # In this case, SSH can immediately know when any end is dead! No # botnets happen! UsePrivilegeSeparation yes # user permission setting project! Set it to yes! MaxStartups 10 # How many online images are allowed at the same time? When we connect to SSH, # But haven't entered the password, this is what we call online! # In this online screen, you need to set the maximum value to protect the host. # A maximum of 10 online images can be preset, those that have already been established online do not count in these 10 cases #4.6 set items for user resistance: DenyUsers * # Set names of users who are blocked. If they are all users, that's all # block! For some users, enter this account! For example! DenyUsers testDenyGroups test # Same as DenyUsers! Only a few groups are supported! #5. SFTP service configuration items! Subsystem sftp/usr/lib/ssh/sftp-server
5.2 OTP

It is also possible to use OTP authentication to reduce the consequences of lost passwords. google Authenticator is a nice implementation of TOTP, or Timebased One Time Password. you can also use a printed list of one time passwords or any other PAM module, really, if you enable ChallengeResponseAuthentication.

You may also like the following SSH-related articles. For details, refer:

Complete SSH service configuration and troubleshooting in Ubuntu

How to install Samba and SSH server in Ubuntu 14.04

SSH service remote access to Linux Server login is slow

How to Improve the SSH login authentication speed of Ubuntu

Enable the SSH service to allow Android phones to remotely access Ubuntu 14.04

How to add dual authentication for SSH in Linux

Configure the SFTP environment for non-SSH users in Linux

Configure and manage the SSH service on Linux

This article permanently updates the link address:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.