Ubuntu installation setting up an SSH server. Installing and configuring SSH - Ubuntu Removing ssh ubuntu

In this article you will learn how to install, enable and configure SSH on Ubuntu Linux.

OpenSSH is a freely available version of the Secure Shell (SSH) family of protocols for remote control or file transfer between computers.

Traditional tools used to perform functions such as telnet or rcp are insecure and transmit the user's password in plain text when used. OpenSSH provides server daemon and client tools to enable secure, encrypted remote control and file transfer operations, effectively replacing legacy tools.

The OpenSSH server component, sshd, constantly listens for client connections from any of the client tools. When a connection request occurs, sshd establishes the correct connection depending on the client tool's connection type. For example, if a remote computer connects to an ssh client application, the OpenSSH server establishes a remote control session after authentication. If a remote user connects to the OpenSSH server using scp, the OpenSSH server daemon initiates a secure copy of files between the server and the client after authentication. OpenSSH can use a variety of authentication methods, including simple password and public key.

How to install OpenSSH

To install OpenSSH, open a terminal and enter the following commands

Sudo apt-get update sudo apt-get install openssh-server -y

Once the installation is complete, the SSH service will start automatically. To verify that the SSH service completed successfully, run the following command:

Sudo systemctl status ssh

You should see something like Active: active (running): This means SSH is installed and running on your Ubuntu system.

Configuration

You can change the default OpenSSH server behavior configuration by editing the /etc/ssh/sshd_config.

But before editing the configuration file, you should make a copy of the original file and write-protect it so that you have the original settings as a reference so that you can reuse this file if necessary.

Copy the /etc/ssh/sshd_config file and write-protect it using the following commands:

Sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.original sudo chmod a-w /etc/ssh/sshd_config.original

Now open the file for editing

Sudo apt-get install nano -y sudo nano /etc/ssh/sshd_config

For information about the configuration directives used in this file, you can view the corresponding man page using the following command:

Man sshd_config

Below are examples of configuration directives that you can change:

To configure OpenSSH to listen on port 2222 instead of the default TCP port 22, for example, change the port directive to: Port 2222

To have sshd resolve login credentials based on public key, simply add or change the line: PubkeyAuthentication yes– If the line is already present, make sure it is not commented out.

To have your OpenSSH server display the contents of the /etc/issue.net file as a banner before logging in, simply add or change the line: Banner /etc/issue.net. In the file /etc/ssh/sshd_config.

After making changes to the /etc/ssh/sshd_config file, save the file and restart the sshd server application to implement the changes, use the following command in the terminal:

Sudo systemctl restart sshd.service

The OpenSSH suite consists of the following tools:

  • Remote operations are performed using ssh, scp and sftp.
  • Key management - ssh-add, ssh-keysign, ssh-keyscan and ssh-keygen.
  • The services consist of sshd, sftp-server and ssh-agent.

And for example, to connect to a remote server, use the following command:

Ssh user@serverip

This command connects you to your server, which has its own IP address serverip and username user.

You will be prompted to enter a password, after entering which you will be successfully connected to your server.


To install the ssh server, run in the terminal:

Ubuntu/Debian/Linux Mint

Then edit the ssh server settings in the /etc/ssh/sshd_config file
To do this, in the terminal run:


Also, in order for OpenSSH to listen only to certain IP addresses, for example 192.168.0.50, 192.168.0.51 on port 777, then simply add the following lines:

Restrict access via SSH for users: test test2 test3

The OpenSSH server can use the Rlogin protocol for authorization and can simulate the behavior of the legacy rsh command, so disable reading the user files ~/.rhosts and ~/.shosts:

Enable the warning banner by editing the following line and creating the following. file:

Save logs, make sure the LogLevel directive is set to INFO or DEBUG

To restart OpenSSH on CentOS, Fedora or RHEL:

In some cases, you can start the server only in this way:


To check the server status use the following command


Now you can log into a computer with OpenSSH-server installed like this:

Ssh [-p port]

For example:

CentOS / RHEL / Fedora Linux - you can disable or remove OpenSSH like this:

$ chkconfig sshd off
$ yum erase openssh-server

Main SSH files and folders:
~/.ssh/ - user configuration directories
~/.ssh/authorized_keys and ~/.ssh/authorized_keys2 - lists of public keys (RSA or DSA) that can be used to authorize a user account
~/.ssh/known_hosts - server keys
/etc/ssh/sshd_config - OpenSSH server configuration file
/etc/ssh/ssh_config - OpenSSH client configuration file
/etc/nologin - if this file exists, the system will refuse to allow anyone other than the root user. It is better to remove and not use.
/etc/hosts.allow and /etc/hosts.deny - access control lists (ACLs)

When encryption algorithms began to be widely used when transmitting data over the network, one of the first tasks was organizing a secure shell.

When encryption algorithms began to be widely used when transmitting data over the network, one of the first tasks was organizing a secure shell. Before this, there was a system called rsh, which allowed certain users from certain machines (there had to be a trust relationship between them) to work on the server with its shell. This is practically the same as telnet access. But with the development of networks, glaring rsh holes became visible:

  • data transmitted through the network is not encrypted in any way, including passwords;
  • data transmitted through the network can be easily received or modified by a third party;
  • an attacker could easily replace the client’s IP and, using the previously obtained password hash, pass authentication on the server with all the ensuing consequences.

Therefore, now rsh is used in extremely rare cases, for example, when transferring data between two pairwise connected machines (I had to work with two machines in different rooms). Basically, ssh has become the de facto standard. The first letter “s” stands for secure, which means that all data transmitted via ssh is encrypted and therefore protected from viewing. There are several versions of the ssh protocol, differing in the encryption algorithms used and general operating schemes. Currently, the ssh protocol version two is widely used. The minor versions of the protocol are insecure by modern standards (there are several very dangerous holes there). In fact, ssh is now a commercial product (which in itself contradicts security requirements - everyone should know the source code of the information security system to make sure there are no backdoors), but nevertheless, a free implementation of ssh is available - OpenSSH, which can be found at www.openssh.com. The best document on ssh, in my opinion, is the banal man ssh, so in some places I will not hesitate to simply translate it.

So, let's start, as usual, with theory. SSH provides 3 methods of client authentication: by the client's IP address (not secure), by the client's public key, and the standard password method. Here's how ssh version 2 works: when a client makes a request, the server tells it which authentication methods it supports (this is defined in the PreferredAuthentications option of sshd.conf) and the client tries to verify them in turn. By default, the client first tries to authenticate with its address, then with the public key, and, if all else fails, transmits the password entered from the keyboard (the password is encrypted with asymmetric encryption). After authentication using one of the methods, a symmetric encryption key is generated from the key pairs available to the client and server, which, as I described in the introduction, is generated based on its secret and remote public keys. After that, all subsequent data transmitted via ssh is encrypted with this key (usually the aes algorithm is used with a key length of 128 bits). I note that the ssh protocol version 1 had some bugs in the encryption of transmitted traffic and was essentially a secure authentication method, so by modern standards this protocol is considered unsafe. Protocol version 2 supports more modern methods of encrypting traffic; checksums in sha or md5 format are also sent along with the data, which excludes substitution or other modification of the transmitted traffic (which was not the case with ssh version 1).

Now a few words about ways to authenticate users via ssh:

  1. To the client's address. With this authentication method, the following happens: each client and server have their own RSA key pairs, which are called host keys. However, there are several methods for verifying a client's address. The server looks at the files $HOME/.rhosts, $HOME/.shosts, /etc/hosts.equiv or /etc/ssh/shosts.equiv, if the server is configured to check client keys (and this is necessary for security reasons, because . otherwise the attacker can replace the client’s IP with his own), then he additionally checks /etc/ssh/ssh_known_hosts and $HOME/.ssh/known_hosts. Naturally, files located in the server's home directories affect the user in whose directory they are located, and files located in /etc have a global effect.

    First, I’ll tell you about the syntax of the above files: - .rhosts - determines the address of the machine and user name from which this user has access (the file is located in the user’s home directory); - .shosts* - similar to .rhosts, but intended exclusively for ssh, so it is better to use this particular file; - /etc/hosts.equiv - also contains hostname/username pairs, but has an effect on all users; - /etc/shosts.equiv** - analogous to hosts.equiv, but only ssh is used, which is also more preferable. - /etc/ssh/ssh_known_hosts and $HOME/.ssh/known_hosts*** - these files contain a list of addresses and their corresponding public keys. When a client requests, the server generates a random string and encrypts it with the public key of the remote host. The client, having received this string, decrypts it with his secret key (which only he has) and encrypts the received string with the server key. The server receives the encrypted message, decrypts it with its secret key and compares it with the original one. If the lines match, then the client has a valid secret key, which gives him the right to access this server. But first, the client must have the correct address, which corresponds to the public key on the server in the ssh_known_hosts file. The file consists of 3 fields: address (or addresses separated by a comma), the public key for it in one (!) line and an additional comment field (optional);

    * Example.shhosts:

    User1.test.ru user1 userstend.test.ru user1 null.test.ru user1

    ** Example file /etc/shhosts.equiv:

    User1.test.ru user1 - server.test.ru xakep The “+” sign means allowing the user to work with the server from this address, the “-” sign prohibits such an action.

    *** Example known_hosts file: user1.test.ru (SOME_VERY_LONG_PUBLIC_KEY) The client address must be in full format (name.domain), otherwise there may be problems. In addition, the patterns * and ? can be used in the address. Public keys are inserted into this file by the administrator himself from the public keys generated by the ssh (identity.pub) client. In general, creating ssh_known_hosts is the prerogative of the administrator (aka root).

    And I’ll also add: when authenticating by host, it is better to use ssh_known_hosts, because this method is quite secure if the clients' public keys were obtained from a trusted source. Other authentication methods do not prevent address spoofing and are therefore considered unsafe.

  2. User authentication using his public key.

    Authenticating a remote user by key is identical to checking the host key (with a random string sent), except that it is not the client machine address that is checked, but the client key and user name. A given user on the server can correspond to his public key, then the client, having a secret key, will be able to log into the server without a password. I just described the working mechanism, so I’ll immediately tell you how to authenticate users using a key (assuming that an openssh client and server are used):

    To generate a key pair, use the ssh-keygen program. To specify the key type, specify ssh-keygen -t (RSA DSA), for example, ssh-keygen -t rsa will create a 1024-bit RSA key pair. To specify the file in which the keys should be saved, you can use the -f option (traditionally the files $HOME/.ssh/id_rsa and $HOME/.ssh/id_dsa are used for the rsa and dsa keys, respectively), to specify the length of the key in bits, use the option -b:

    Ssh-keygen -t rsa -b 2048 -f $HOME/.ssh/id_rsa

    As a result of the work, the program will ask you to enter a password to encrypt the secret key in order to prevent its use if it gets into the hands of unauthorized persons who do not know the password (it is advisable to choose a password no shorter than 10 characters). After this, you will be required to enter this password every time you use the secret key (later I will tell you how to avoid this using the ssh-agent program). After running ssh-keygen, a pair of keys is created: one is secret (encrypted with the entered password), and the other is public with the .pub extension (id_rsa.pub). You will need to copy the public key to the server's home directory $HOME/.ssh/authorized_keys. The server will then know the user's key and will be able to authenticate you without a password. The authorized_keys file can contain multiple public keys that are valid for a given user: just place them in this file in order. After these operations, you will be able to log in, having a secret key, to the server where your public key is located, and under the user in whose home directory this key is located. A remote user password is not required, you only need to know the secret key decryption password. To transfer your public key to the server, you must use only secure sources, otherwise your key may be replaced. To transfer the client's public key, use the ssh-copy-id program. To get started, you need to do the following:

    # ssh-copy-id -i public_key_file user@machine

    After connecting to the machine server and passing the user name user (must be specified if the remote name is different from the local one), password authentication of the specified user (or current) on the remote machine occurs, then the key public_key_file (or $HOME/.ssh/identity.pub) is copied , if the file name is not specified) to the server in $HOME/.ssh/authorized_keys. After this, you can log into the server without using the user password. When performing this operation, keep in mind that you must copy the PUBLIC key to the remote machine, otherwise everything will be very sad (I think it’s clear why).

  3. Basic password authentication.

    Only one thing can be noted here: in any case, asymmetric keys are exchanged first, and the password hash is transmitted in encrypted form. Password authentication is the most commonly used, but to be honest, ssh offers more convenient authentication methods, and IMHO you can use them if you have all the patches for ssh. And, of course, protocol version 1 must be disabled altogether. So, let's start setting up... I noticed that most administrators simply leave the client and server configs as default so as not to get their hands dirty. But this is wrong: in different systems these configs differ very significantly, and this leads to confusion and misunderstanding of the server’s operation, which creates an additional security threat (your own server is in the dark). To do this, I decided to describe the ssh configuration files using the examples ssh_config and sshd.conf for the client and server, respectively. For client configuration, use the file $HOME/.ssh/config or /etc/ssh/ssh_config (for the entire system). The file has the following format: definition of the host address and parameters for it. You can use the usual * and? patterns in the address; all parameter names and their values ​​must be typed in the same case as in the example (otherwise the parameter will not be accepted). Here is an example of ssh_config, which contains the most useful options (in fact, it makes no sense to describe some ssh configuration parameters, since they are used very rarely):

    # Host definition, in this case includes all hosts of the test.ru domain, you can # use a single * character to specify access parameters to any host Host *.test.ru # This option determines whether ssh will use data transfer from a remote # X server through your secure channel. The following will describe how # secure tunnels are established via ssh. This feature allows you to protect # supposedly insecure protocols (X, pop, smtp, ftp) with ssh encryption. # By default this option is no ForwardX11 yes # List of preferred authentication methods via ssh version 2. The first # is the most preferred protocol, I think the meaning of this parameter is clear PreferredAuthentications hostbased,publickey,keyboard-interactive # This parameter determines whether standard password verification will be performed # Default yes PasswordAuthentication yes # Number of password attempts before the client disconnects from the server. By # default, the password can be entered three times NumberOfPasswordPrompts 3 # List of allowed users for this server. Two # formats can be used: a space-separated list of users, and a space-separated list of users and # hosts (USER@HOST - allows this user access # only from this address). You can use the expressions * and?. The AllowGroups, DenyUsers and DenyGroups options have a similar # purpose (for groups you cannot # specify the client address) AllowUsers *@*.test.ru DenyUsers xakep lamer DenyGroups x* # Using ssh (version 2) authentication via rhosts and RSA keys. #Default is no. HostbasedAuthentication yes # Will the client try to work via rsh if ssh is unavailable or is not working correctly for some # reasons. Default no FallBackToRsh no # Whether to use rsh. Default no UseRsh no # Script mode when passwords are not asked from the terminal. By default no BatchMode no # Additionally, the host key of the remote machine is checked in # known_hosts, which prevents ip substitution. Default is yes. CheckHostIP yes # This parameter indicates whether the client will trust keys received from # servers. The parameter can take the following values: yes - keys are never # automatically placed in known_hosts, ask - a key can be placed in # known_hosts only after user confirmation, no - all keys # are automatically placed in known_hosts (not secure). By default ask. StrictHostKeyChecking ask # The following parameters define ssh secret keys of various formats: # rsa and dsa IdentityFile $HOME/.ssh/id_rsa IdentityFile $HOME/.ssh/id_dsa # The port on the remote machine used by ssh. Default 22 Port 22 # Protocol versions used by the client in descending order of priority. Protocol 2 # Encryption protocol for version 1 of the ssh protocol Cipher 3des # Possible encryption protocols in descending order of priority for protocol # version 2 Ciphers aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256- cbc # The value of the escape character, signaling that the characters following it # must be treated in a special way (for example, ~. will cause the client to immediately # disconnect from the server) when transmitting binary data, this parameter must # be set to none, which turns off escape sequences. # Default ~ EscapeChar ~ # Controls the operation of compression of encrypted traffic. Useful parameter for # slow networks, because... encrypted data typically increases in size due to the # fixed key length. Compression allows you to reduce the amount of # data transmitted over the network, but will increase the operating time of the protocol itself. # So it is advisable to enable this option on slow connections. #Default is no. Compression yes # Controls the sending of client availability messages to the server, which allows # the connection to be closed normally if there is a network or other problem that # leads to the connection being lost. If the connection is bad, it is better to # disable this option so that disconnection does not occur after every network error. Default # to yes. KeepAlive yes I think that in this example everything is explained in sufficient detail and I will only say this: in most cases the default options work well, you just need to disable support for ssh version 1 and configure the necessary authentication methods (except password) and specify the access paths to the keys . This is where we finish setting up the client and configure the server. The sshd server configuration file is located in /etc/ssh/sshd_config, and many of its settings are the same as those in ssh_config, but there are no host definitions like there were in ssh_config. I will still give an example of sshd_config so that further questions do not arise: # Port number and protocol version Port 22 Protocol 2
    # The addresses on which the server listens can also be specified # by port (server.test.ru:2022), but assigning a non-standard ssh port # is impractical, because will be of interest to potential hackers (“What are they hiding there?”) ListenAddress server.test.ru
    # Server key for protocol version 1 HostKey /etc/ssh/ssh_host_key # Rsa and dsa keys for ssh version 2 HostKey /etc/ssh/ssh_host_rsa_key HostKey /etc/ssh/ssh_host_dsa_key
    # These values ​​determine the length of the server key and its lifetime for # using ssh version 1 (this key will be regenerated after # the specified time) #KeyRegenerationInterval 3600 #ServerKeyBits 768
    # Next, we define authentication methods for this server and its parameters
    # The server disconnects after this time in seconds if the client # does not pass authentication LoginGraceTime 600 # Allow logging in via ssh root. This topic was discussed on the forum for a long time, # but I still think that the root can also log in via ssh from the internal network (for # this you need to configure iptables properly). You can also prevent the root # from logging in using a password: without-password, allowing login only using the public key PermitRootLogin yes # Checking sshd access rights and owners of home directories. Useful for those # users who give rights to everything 0777. Although it is better to keep such idiots at a # distance from the server (it is best to do this with a log suspended # from the ceiling in the server room to give the unwanted guest the proper acceleration, and do not forget # to beat the end of the log some kind of piece of hardware, otherwise the logs will have to be changed # too often;) StrictModes yes
    # RSA authentication (version 1) RSAAuthentication yes # User key authentication (version 2) PubkeyAuthentication yes # Defines the user's public key for key authentication. You can # use templates: %u - username, %h - user's home directory. AuthorizedKeysFile .ssh/authorized_keys
    # Don't use rhosts authentication RhostsAuthentication no # You can also ignore rhosts and shosts in hostbased authentication, # using only the known_hosts file. #IgnoreRhosts yes # Whether we use known_hosts authentication in conjunction with .rhosts or # .shosts. The option is valid only for protocol version 1. RhostsRSAAuthentication no # Same as the previous one only for version 2 HostbasedAuthentication yes # If there is no trust in known_hosts, then they can not be used with hostbased # authentication. Default no IgnoreUserKnownHosts no
    # To prevent password hashes from being sent through the ssh tunnel, set this # option to no. By default, password authentication is allowed PasswordAuthentication yes # You can also allow empty passwords, but that sucks because... This is a huge # hole in the server through which you can do a lot of nasty things! Therefore should # be no (default) PermitEmptyPasswords no
    # Authentication via PAM mechanism. PAMAuthenticationViaKbdInt no
    # Transferring the X protocol through the ssh tunnel X11Forwarding yes # We use this one as an x-server, i.e. the client, running the x-client # will actually use our server, but all data from the server to the client # will be encrypted, which is good! X11UseLocalhost yes # When the user logs in, we display /etc/motd: in some systems this is canceled for # security purposes PrintMotd yes # We inform the user the time and place of the last login, the situation is similar # to the previous one PrintLastLog yes # Send availability messages to the client KeepAlive yes # Maximum number possible connections where authentication did not occur. If # there are more clients who have not passed authentication, then new connections will not # be processed MaxStartups 10 # Path to the file that will be displayed when the client logs in BEFORE authentication Banner /etc/ssh_message # Check the correspondence between the client's IP address and its symbolic name in the backzone, # then compare the name with the IP address again. This way (in a twisted way) # the authenticity of the ip is verified, but this method is quite slow and by default # it is disabled VerifyReverseMapping no
    # New systems running via ssh. This example defines # a "secure" ftp server - sftp, similar to user access, but with # the ability to transfer files (i.e. the user gets access to all of his # files and there is no ability to configure permissions and virtual users, # as in, for example, proftpd). In fact, ssh subsystems can allow other protocols # to pass over the network, but under the ssh umbrella. For example, for the # sftp server there is an sftp client of the same name. Its interface is completely identical # to the original ftp, but with one difference: the same # user authentication occurs on the remote server (using ssh methods), but instead of a shell, a # subsystem interacts with the user, in this case sftp. Subsystem sftp /usr/lib/ssh/sftp-server

    Well, everything seems to be set! Now I would like to talk about some features that work in ssh. First, I would like to talk about tunnels. SSH has the built-in ability to transfer data from a local port to a remote port using a network tunnel, and the data transferred through this tunnel will be encrypted. That is, authentication occurs on the remote system, and then traffic redirection through the tunnel begins. Thus, any traffic can be redirected, and the X protocol can work in interactive mode; to do this, you need to enable the appropriate options in the server and client configuration files (this was described earlier). For other ports, you need to call ssh with the parameter -L(LOCAL_PORT):(LOCAL_ADDRESS):(REMOTE_PORT):

    # ssh -L10101:localhost:101 server.test.ru

    Such a tunnel dies quite quickly, because... the server automatically kills "lazy" clients. Therefore, you can use a method that allows you to set an arbitrary tunnel hold time: execute sleep on the remote server:

    # ssh -f -L10101:loclahost:101 server.test.ru sleep 100

    This command holds the tunnel for 100 seconds, which is enough for any connection. And one more thing: when data is transmitted through the tunnel, it is not destroyed, which is good for implementing secure ftp, smtp and pop3 protocols (however, the sftp server is already included in the openssh package, using it should not cause any difficulties sftp hostname, because in fact this is a special implementation of the ssh protocol and the sftp mechanism is absolutely identical to the ssh mechanism). To disable port forwarding, you must set the sshd AllowTcpForwarding option to no. Using a long ssh tunnel delay reduces security somewhat, because... while waiting, the attacker has a greater chance of attacking (but the ssh version 2 mechanism allows you to avoid this situation by signing the transmitted messages).

    Here's what I would do for secure ssh. To begin with, I would create an RSA key with a length of 4096 bits:

    # ssh-keygen -t rsa -b 4096

    Then I would copy this key using a flash drive or ssh-copy-id to the remote server(s):

    # ssh-copy-id -i $HOME/.ssh/id_rsa remote_host

    After that, I would disable password and all host-based authentication in sshd_config:

    IgnoreHosts yes RhostsAuthentication no RhostsRSAAuthentication no RSAAuthentication yes HostbasedAutentification no PasswordAuthentication no PermitEmptyPasswords no UseLogin no PermitRootLogin without-password

    And disable protocol version 1 (by default Protocol 2.1 and the server falls to ssh 1, if ssh 2 fails):

    Protocol 2 Well, now, in order to log into the server via ssh, you need to enter a strong (and it should be strong!) password for the secret key. A little inconvenient, isn't it? You can store the password for the private key in memory during the operation of some program (for example, bash) and retrieve it from memory when the ssh client requests it. The ssh-agent program (ssh authentication agent) is used for this purpose. The agent starts the necessary program and waits for new secret keys to be added (ssh-agent stores the decrypted secret keys). For this purpose, there is another program - ssh-add, which adds the $HOME/.ssh/id_rsa, id_dsa, identity keys to the agent. If you need to add other keys, you need to run ssh-add with the file name: ssh-add filename. Please note that when adding a key to the ssh-add agent, you still need to enter a password to decrypt it, but while the agent is in memory (until the program it called has completed), you do not need to enter the secret key password: the key is taken from ssh-agent. Moreover, only the program launched by it (and all its child processes) can establish contact with the ssh-agent, because environment variables are set. The usual method for starting ssh-agent is: # ssh-agent bash # ssh-add Enter passphrase for ".ssh/id_rsa": Enter passphrase for ".ssh/id_dsa": .ssh/identity: No such file or directory

    Once the shell exits, ssh-agent exits and the keys are removed from memory. Well, finally, you can allow access for certain users from certain machines. This is done by the AllowUsers field in sshd_config or by iptables rules. I think this is enough for normal and safe work on a remote server via ssh. Particularly suspicious people can deny root access via ssh (PermitRootLogin no) and delegate some of its rights using sudo. Well, use protocol version 2 (advantages such as the algorithm for calculating a symmetric key based on a pair of asymmetric ones, and signing messages transmitted over the network, as well as version 2 of the ssh protocol is faster than the first). There are many ssh clients running on different OSes. For Windows I will highlight

S secure Sh ell, i.e. SSH is a protocol that provides secure connections and data transfer between two remote computers. Initially created to replace systems such as rlogin and rcp. As the full name of the protocol implies, the SSH system allows you to connect and manage a remote host (computer, router, etc.), while protecting all transmitted traffic using highly secure encryption.
SSH is widely used by server administrators to configure and manage them, and ordinary advanced users - owners, for example, of websites or virtual servers - actively use SSH to connect to their hosting account and use the server command shell.
Immediately after development was completed, the SSH system began to actively transform into a closed commercial product in the form of version SSH2. But thanks to the GNU community, versions of the SSH1 and SSH2 protocols have been implemented as open and free software openSSH. Linux systems use this metapackage.
The SSH metapackage basically includes an SSH server (sshd) as a daemon program, as well as several utilities: ssh for remote logging and command execution, scp for file transfer, and ssh-keygen for generating SSH key pairs.

Installing SSH packages

As already mentioned, the ssh system on Linux systems is distributed as a composite metapackage, so to install all the required ssh utilities you need to run just one command:
In Ubuntu

$ sudo apt-get install ssh

$ yum -y install openssh-server openssh-clients

After which the installation process will begin

As you can see, the package manager itself will recognize all dependent and related packages and install them. Also, upon completion of the installation, the SSH server will be automatically launched in daemon mode. This can be checked with the command:
$ systemctl status sshd
or:
$service sshd status will give the same output. Now the server is running with basic default settings.

Setting up SSH

The SSH server operating mode with default settings, although quite functional for small private networks, still needs to set some important parameters for use on highly reliable public servers. The daemon settings are stored in the /etc/ssh/sshd_config file. You can view it with the command

Cat /etc/ssh/sshd_config

First of all, you should pay attention to the following parameters: Port, AddressFamily, ListenAddress. The first globally sets the port number through which the connection will work, and if you leave it standard, i.e. 22, then there is a high probability that it will be scanned by robots too often.
Note: to set the activation of a parameter, you need to uncomment the corresponding line - remove the “#” symbol at the beginning.
The second parameter specifies the family of IP addresses used - IPv4 and IPv6. If, for example, only IPv4 addresses are used, then it is highly recommended to set the parameter

AddressFamily inet value: AddressFamily inet

For IPv6 family addresses, the value is inet6.
The ListenAddress parameter allows you to set ports for individual network interfaces:

ListenAddress 10.24.205.75:2123 ListenAddress 10.24.205.76:2124

Since the openSSH implementation allows you to work with the SSH1 and SSH2 protocols, it is reasonable to disable the use of SSH1, since this version is outdated. Working via SSH1 is highly discouraged: Protocol 2
A very useful option is that allows you to authorize and encrypt traffic using special SSH keys:

PubkeyAuthentication yes

It should be noted that in this case the server must explicitly indicate where the users' public keys are stored. This can be either one common file for storing the keys of all users (usually the etc/.ssh/authorized_keys file), or separate keys for each user. The second option is preferable due to ease of administration and increased security:
AuthorizedKeysFile etc/ssh/authorized_keys # For a shared file
AuthorizedKeysFile %h/.ssh/authorized_keys # File -> user
In the second option, thanks to the autosubstitution pattern with the “%h” mask, the user’s home directory will be used.
It is also important to disable password access:

PasswordAuthentication no

Or, if you still need to use password access, you must disable authorization using an empty password:

PermitEmptyPasswords no

To specify allowed or prohibited users and groups, use the DenyUsers, AllowUsers, DenyGroups, and AllowGroups directives. The values ​​for these are lists of names separated by spaces, for example:

DenyUsers fred john AllowGroups root clients administrators

You should also disable root access:

PermitRootLogin no

Sometimes, when you need to set up a multi-server configuration, it is very convenient to use Aliases, which allows you to configure several access modes at once (with different hosts, ports, etc.) and use them, while specifying a specific alias:

$ssh alias_name

Settings for aliases are stored either globally in /etc/ssh/ssh_config, or separately for users in ~/.ssh/config. This should not be confused with ssh_config! Example:

Host your_alias Port your_ssh_port HostName 0.0.0.0 # IP or hostname User your_user_name

To apply the settings you have made, you must restart the SSH server:

$ systemctl restart sshd

$ service sshd restart

Setting up and using an SSH client
To connect to the server use the command:

$ ssh user_name@host_name

where user_name is the user name in the system, host_name is the name of the host to which the connection is made, for example:

$ ssh fred@fredwebserver

In this case, the ssh utility will request (depending on the server settings) a login, password or passphrase to unlock the user’s private key.
In the case of authorization by key, a pair of SSH keys must first be generated - an open one, which is stored on the server side, usually in the .ssh/authorized_keys file in the user's home directory, and a private one, which is used to authorize the client and is usually stored in the directory .ssh/ user's home directory. The public key is a “digital copy” of the private key thanks to which the server “knows” who is “its own” and who is “strangers”.
To generate keys, use the ssh-keygen utility:

$ssh-keygen

The utility will prompt you to select the location of the keys (it is better to leave everything as default), usually this is the ~/.ssh/ directory, enter the passphrase for the private key. After which the public key id_rsa.pub and the private key id_rsa will be generated. Now you need to copy the public key, i.e., a “snapshot” of the private key, to the server. The easiest way to achieve this is with the command:

Ssh-copy-id -i ~/.ssh/id_rsa.pub user_name@host_name

Now you can connect using the ssh command and start a secure remote control session.
It is important to note that the use of generated openSSH keys is incompatible with the PPK format used by default in complexes such as PuTTY. Therefore, it is necessary to convert existing openSSH keys to PPK format. The most convenient way to do this is with the PuTTY utility – puttygen.exe.

If you find an error, please highlight a piece of text and click Ctrl+Enter.

What is SSH and why do you need it?

Secure Shell (SSH) is a network protocol that provides shell functions to a remote machine through a secure channel. SSH comes with various security enhancements, including user/host authentication, data encryption, and data integrity, making popular attacks like eavesdropping, DNS/IP spoofing, data forgery, and connection hijacking impossible. etc. Ftp, telnet or rlogin users who use a protocol that transfers data in clear text are highly recommended to switch to SSH.

OpenSSH is an open source implementation of the SSH protocol that allows you to encrypt your network connection through a set of programs. If you want to have SSH on Linux, you can install OpenSSH, which consists of an OpenSSH server and client packages.

OpenSSH server/client packages come with the following utilities:

  • OpenSSH server: sshd (SSH daemon)
  • OpenSSH client: scp (secure remote copy), sftp (secure file transfer), slogin/ssh (secure remote login), ssh-add (private key completion), ssh-agent (authentication agent), ssh-keygen (authentication key management ).
Installing OpenSSH server and client on Linux

If you want to install the OpenSSH server/client and configure the OpenSSH server to start automatically, follow the following instructions, which vary depending on the distribution.

Debian, Ubuntu or Linux Mint

$ sudo apt-get install openssh-server openssh-client

On Debian based systems, once installed, OpenSSH will start automatically on boot. If for some reason the OpenSSH server does not start automatically at system startup, you can run the following command to explicitly add ssh to the boot at system startup.

$ sudo update-rc.d ssh defaults

Fedora or CentOS/RHEL 7

$ sudo yum -y install openssh-server openssh-clients $ sudo systemctl start sshd service $ sudo systemctl enable sshd.service

CentOS/RHEL 6

$ sudo yum -y install openssh-server openssh-clients $ sudo service sshd start $ sudo chkconfig sshd on

Arch Linux

$ sudo pacman -Sy openssh $ sudo systemctl start sshd service $ sudo systemctl enable sshd.service

Setting up an OpenSSH server

If you want to configure the OpenSSH server, you can edit the system-wide configuration file located in /etc/ssh/sshd_config.

There are a couple of OpenSSH options that may be of interest:
By default, sshd listens on port 22 and listens for incoming ssh connections. By changing the default port for ssh, you can prevent various automated hacker attacks.
If your machine has more than one physical network interface, you may want to check which one is associated with sshd, for this you can use the ListenAddress option. This option helps improve security by limiting incoming SSH to only a specific interface.

HostKey /etc/ssh/ssh_host_key

The HostKey option determines where the personal host key is located.

PermitRootLogin no

PermitRootLogin option – whether root can log into the system via ssh.

AllowUsers alice bob

Using the AllowUsers option you can selectively disable the ssh service for certain Linux users. You can specify multiple users, separated by spaces.

After /etc/ssh/sshd_config has been changed, make sure to restart the ssh service.

To restart OpenSSH on Debian, Ubuntu or Linux Mint:

$ sudo /etc/init.d/ssh restart

To restart OpenSSH on Fedora, CentOS/RHEL 7 or Arch Linux:

$ sudo systemctl restart sshd.service

To restart OpenSSH on CentOS/RHEL 6:

$ sudo service sshd restart

How to connect to SSH

Connecting to SSH from Linux

Linux users do not need to install additional programs.

Connecting to SSH from Windows

Hidden from guests

.

Cygwin is more than just an SSH client. It is a powerful combiner that supports many Linux commands. For example, Cygwin makes it very easy to create SSL certificates (just like Linux). In Windows, to create self-signed certificates you need to dance with a tambourine. Cygwin is very convenient to use cURL (no need to install anything separately), etc. Those who lack the command line and Linux programs on Windows will find an outlet in Cygwin.

Installing Cygwin is easy. Let's go to

Hidden from guests

And download

Hidden from guests

Hidden from guests

A tiny file will download - this is the installer. Graphical installer. Although it contains a large number of options, they are all quite simple and many are familiar from other graphical installers. If something is not clear, just click “Next”. Perhaps only the following window can lead to confusion:

All elements available for installation are presented here. We don't need to understand them right now. Because the most popular ones are already marked for installation. And if something is missing in the future, you can easily install what you need.

SSH connection (common to Linux and Windows)

Linux users open the console, Windows users type in Cygwin.

SSH needs the following information to connect:

  • IP or hostname
  • port number
  • Username
  • user password
Two of these parameters SSH can guess: username and port number. If a port is not specified, the default port is assumed. If a user is not specified, then the same name is used as on the system from which the connection is made. For example, the host address for the connection is 192.168.1.36. If I dial

Ssh 192.168.1.36

I see the following

Alex@mial-PC ~ $ ssh 192.168.1.36 The authenticity of Host "192.168.1.36 (192.168.1.36)" Can "t be estable. Ecdsa key finterprint is SHA256: Sixzesusuiivoeqaqh XYLXUEA8SC5R/YPHL8WFP8S. yes/no)?

Since I am connecting to the host for the first time, it is an unfamiliar host. They ask me if I want to continue. I'm dialing yes:

Warning: Permanently added "192.168.1.36" (ECDSA) to the list of known hosts. [email protected]"s password:

Okay, host 192.168.1.36 has been added to the list of familiar hosts. I am being asked for a password for user Alex. Since there is no such user on the server with SSH, but I click Ctrl+C(to break) and enter the command along with the username of the remote system. The user is entered before the address of the remote machine and is separated from the address by the @ symbol. The @ symbol in English is read as at and can be translated as “in”. Those. record [email protected] can be interpreted as "mial user on machine 192.168.1.36".

Ssh [email protected]

The Alex@MiAl-PC invitation was replaced by the mial@mint invitation. This means that we are already on the remote machine, i.e. we have already made a connection. If you need to specify a port (if it differs from the standard one), then the port must be specified after the -p switch. For example like this:

Ssh [email protected]-p 10456

After connecting, we are greeted with something like this:

Linux mint 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1 (2015-05-24) x86_64 The programs included with the Debian GNU/Linux system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. Last login: Tue Jun 16 15:32:25 2015 from 192.168.1.35

It follows that the remote machine is Linux Mint, with kernel 3.16, 64-bit version. Also important information is the time of the last login and the IP address from which the connection originated. If the time and IP are unfamiliar to you and you are the only user, then your system is compromised and you need to take appropriate action.

Let's type a few commands to make sure where we are and who we are: pwd, [B]uname -a etc.:

To end the session (log out), dial

Or click Ctrl+D.

Login to SSH without entering a password

Firstly, it's just more convenient. Secondly, it's safer.

First, we need to create rsa keys. If you are a Linux user, then you are fine. If you are a Windows user, but you did not listen to my advice and chose PuTTY, then you have a problem and think for yourself how to solve it. If you have Cygwin, then everything is also in order.

If you managed to log in to the remote system, log out. After that, dial

Ssh-keygen -t rsa

We are asked for a file name, we do not need to enter anything, the default name will be used. It also asks for a password. I don't enter the password.

Now on the remote machine we need to create a .ssh directory. Executing the command on a remote machine will be discussed below. For now, just copy the command, not forgetting to change the IP address and username to your own:

Ssh [email protected] mkdir.ssh

Now we need to copy the contents of the id_rsa.pub file to the remote machine. This is very easy to do (don’t forget to change the data to your own):

Cat .ssh/id_rsa.pub | ssh [email protected]"cat >> .ssh/authorized_keys"

Now we just log in and they don’t ask us for any password anymore. And it will always be like this now.

Executing commands on a remote server without creating a shell session

In addition to opening a shell session on a remote system, ssh also allows you to execute individual commands on the remote system. For example, to run the tree command on a remote host named remote-sys and display the results on the local system, you would do this:

Ssh remote-sys tree

My real example:

Ssh [email protected] tree

Using this technique you can do interesting things, like running an ls command on a remote system and redirecting the output to a file on the local system:

Ssh remote-sys "ls *" > dirlist.txt

Real example:

Ssh [email protected]"ls *" > dirlist.txt cat dirlist.txt

Note the single quotes in the above command. This is because we don't want path expansion to be done on the local machine; because we need this execution on a remote system. Also, if we want to redirect standard output to a file on the remote machine, we can put the redirection statement and the file name inside single quotes:

Ssh remote-sys "ls * > dirlist.txt"

Transferring standard output from local machine to remote machine via ssh

An equally interesting option for executing commands is given a little higher:

Cat .ssh/id_rsa.pub | ssh [email protected]"cat >> .ssh/authorized_keys"

  • The cat command reads and displays the contents of the .ssh/id_rsa.pub file, located on the local machine, line by line.
  • | (pipe) passes what would appear on standard output to another command.
  • Instead of a command that would process the strings passed to it, a connection is made to the remote system (ssh [email protected]).
  • The remote system receives lines for which the cat >> .ssh/authorized_keys command is provided. Those. the contents of the standard output are written line by line to the .ssh/authorized_keys file located on the remote machine.
Opening a graphics program located on a remote computer

The next trick requires two Linux computers. Unfortunately, even Cygwin can't handle this trick. Moreover, both Linux systems must have a graphical user interface.

Tunneling with SSH

Among other things that happens when a connection is established with a remote host via SSH is the creation of an encrypted tunnel that is formed between the local and remote systems. Typically, this tunnel is used to ensure that commands typed on the local machine are securely transmitted to a remote machine, and the result is also securely sent back.

In addition to this basic functionality, the SSH protocol allows most types of traffic to be sent over an encrypted tunnel, creating a kind of VPN (virtual private network) between the local and remote systems.

Perhaps the most commonly used of these features is the ability to broadcast X Window systems traffic. On a system running an X server (these are machines that have a graphical user interface), it is possible to run an X client program (a graphical application) on a remote system and see the results of its operation on the local system. It's easy to do. For example, I want to connect to the remote host remote-sys and on it I want to run the xload program. At the same time, I will be able to see the graphical output of this program on the local computer. This is done like this:

Ssh -X remote-sys xload

Real example:

Ssh -X [email protected] gedit

Those. SSH starts with the -X switch. And then the program simply starts. Look at the screenshot.

I'm on Kali Linux. I successfully log in to a remote computer via SSH. After that I ran the gedit program. This program may not even be on Kali Linux, but it definitely is on Linux Mint, which is what I connected to. I can see the result of this program on the screen as if the program were running locally. But again, I want you to understand this, there is no gedit program running on the local computer. If I want to save the result of gedit (or any other program opened in this way), it turns out that it works in the environment of the remote computer, sees its file system, etc. This is convenient when you want to configure the remote computer using a graphical interface .

You will learn how to transfer an image from the entire desktop in the same article later, in the section “How to configure VNC via SSH”.

On some systems, this trick requires using the -Y option instead of the -X option.

Copying from/to a remote computer (scp and sftp)

scp

The OpenSSH package also includes two programs that use an encrypted SSH tunnel to copy files over the network. First program - scp(“secure copy”) - used more often, like the similar cp program for copying files. The most noticeable difference is that the source of the file can be the remote host followed by a colon and the location of the file. For example, if we wanted to copy a document called document.txt from our home directory to remote-sys in the current working directory on our local system, we could do this:

Scp remote-sys:document.txt . document.txt 100% 177 0.2KB/s 00:00

Real example:

# delete the file on the local machine if it exists rm dirlist.txt # create a file on the remote machine ssh [email protected]"ls * > dirlist.txt" # check for its presence ssh [email protected]"ls -l" # copy it to the local machine scp [email protected]:dirlist.txt. # check its contents cat dirlist.txt

  • [email protected]- username and remote host,
  • . (dot) means that the file needs to be copied to the current working directory on the remote server, but the file name will remain the same, i.e. nfile.txt
  • Memo:

    To copy a file from B to A when logged in to B:
    scp /path/to/file username@a:/path/to/destination
    Copying a file from B to A when logged in to A:
    scp username@b:/path/to/file /path/to/destination

    sftp

    The second program to copy files over SSH is sftp. As its name suggests, it is a secure ftp program replacement. sftp works like the original ftp program. However, instead of sending in clear text, it uses an encrypted SSH tunnel. An important advantage of sftp over ftp is that it does not require a running FTP server on a remote host. It only requires an SSH server. This means that any remote machine that is connected via an SSH client can also be used as an FTP-like server. Here's an example session:

    Alex@MiAl-PC ~ $ sftp [email protected] Connected to 192.168.1.36. sftp> ls dirlist.txt newfile.txt nfile.txt temp Videos Documents Downloads Images Music Public Desktop Templates sftp> lls dirlist.txt nfile.txt sftp> ls temp temp/TakeMeHome sftp> cd temp/ sftp> get TakeMeHome Fetching /home /mial/temp/TakeMeHome to TakeMeHome sftp> bye

    The SFTP protocol is supported by many graphical file managers that can be found in Linux distributions. Using both Nautilus (GNOME) and Konqueror (KDE), we can enter URIs (links) starting with sftp:// in the jump bar and work with files located on a remote system running an SSH server.

     

    It might be useful to read: