SSH in Ubuntu
Installation openssh-server
You can connect to a host over ssh if an ssh server is installed on it.
In Ubuntu the standard variant of the ssh server is called openssh-server
You can install it with the command
sudo apt install -y openssh-server
Reading package lists... Done Building dependency tree Reading state information... Done The following additional packages will be installed: ncurses-term openssh-sftp-server ssh-import-id Suggested packages: molly-guard monkeysphere ssh-askpass The following NEW packages will be installed: ncurses-term openssh-server openssh-sftp-server ssh-import-id 0 upgraded, 4 newly installed, 0 to remove and 2 not upgraded. Need to get 688 kB of archives. After this operation, 6 010 kB of additional disk space will be used. Get:1 http://fi.archive.ubuntu.com/ubuntu focal/main amd64 ncurses-term all 6.2-0ubuntu2 [249 kB] Get:2 http://fi.archive.ubuntu.com/ubuntu focal-updates/main amd64 openssh-sftp-server amd64 1:8.2p1-4ubuntu0.3 [51,5 kB] Get:3 http://fi.archive.ubuntu.com/ubuntu focal-updates/main amd64 openssh-server amd64 1:8.2p1-4ubuntu0.3 [377 kB] Get:4 http://fi.archive.ubuntu.com/ubuntu focal/main amd64 ssh-import-id all 5.10-0ubuntu1 [10,0 kB] Fetched 688 kB in 2s (399 kB/s) Preconfiguring packages ... Selecting previously unselected package ncurses-term. (Reading database ... 145758 files and directories currently installed.) Preparing to unpack .../ncurses-term_6.2-0ubuntu2_all.deb ... Unpacking ncurses-term (6.2-0ubuntu2) ... Selecting previously unselected package openssh-sftp-server. Preparing to unpack .../openssh-sftp-server_1%3a8.2p1-4ubuntu0.3_amd64.deb ... Unpacking openssh-sftp-server (1:8.2p1-4ubuntu0.3) ... Selecting previously unselected package openssh-server. Preparing to unpack .../openssh-server_1%3a8.2p1-4ubuntu0.3_amd64.deb ... Unpacking openssh-server (1:8.2p1-4ubuntu0.3) ... Selecting previously unselected package ssh-import-id. Preparing to unpack .../ssh-import-id_5.10-0ubuntu1_all.deb ... Unpacking ssh-import-id (5.10-0ubuntu1) ... Setting up openssh-sftp-server (1:8.2p1-4ubuntu0.3) ... Setting up openssh-server (1:8.2p1-4ubuntu0.3) ... Creating config file /etc/ssh/sshd_config with new version Creating SSH2 RSA key; this may take some time ... 3072 SHA256:9++2jX5qWUOvh/GgxzZ45hX1jnictvNdKOBTy1zWXLI root@andrei-VirtualBox (RSA) Creating SSH2 ECDSA key; this may take some time ... 256 SHA256:E0jgFvpa5eFuVVhjViXDsHjE1R0kY5GI86bB4WtaSLo root@andrei-VirtualBox ( ECDSA) Creating SSH2 ED25519 key; this may take some time ... 256 SHA256:zO8nJicXCUwGo74Usj3u5MZ41mCoRfpb0Jmn5q38Z4w root@andrei-VirtualBox ( ED25519) Created symlink /etc/systemd/system/sshd.service → /lib/systemd/system/ssh.serv ice. Created symlink /etc/systemd/system/multi-user.target.wants/ssh.service → /lib/ systemd/system/ssh.service. rescue-ssh.target is a disabled or a static unit, not starting it. Setting up ssh-import-id (5.10-0ubuntu1) ... Attempting to convert /etc/ssh/ssh_import_id Setting up ncurses-term (6.2-0ubuntu2) ... Processing triggers for systemd (245.4-4ubuntu3.11) ... Processing triggers for man-db (2.9.1-1) ... Processing triggers for ufw (0.36-6) ...
Connecting over SSH
The connection is made with the command ssh + user_name + hostFor example
ssh andrei@192.168.0.2
If you are connecting to the host for the first time, a warning appears
The authenticity of host '192.168.56.101 (192.168.56.101)' can't be established. ECDSA key fingerprint is SHA256:db8az/qbrWOJWvNRv2d9UHaDBnnUHanJ9Svca9vFx7c. Are you sure you want to continue connecting (yes/no/[fingerprint])?
If you choose yes, you will see a message in the terminal
Welcome to Ubuntu 20.04.3 LTS (GNU/Linux 5.11.0-27-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage 0 updates can be applied immediately. Your Hardware Enablement Stack (HWE) is supported until April 2025. The programs included with the Ubuntu system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law.
And at the same time, without you noticing, into the file ~/.ssh/known_hosts a similar line will be added:
|1|abcdef+abcdefghijklmnopqrst=|abcdefghijklmnopqrstuvwxyz1= ssh-rsa abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrst/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz12345/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzB1234567
Usually the file known_hosts has the following format (the entries are separated by spaces)
{server-id} ssh-rsa {public-key-string} {comment}
Thus
abcdef+abcdefghijklmnopqrst=|abcdefghijklmnopqrstuvwxyz1=
This is a hash of the server name.
Here three elements are written separated by spaces: a hash of the server name, the name of the asymmetric algorithm used and the server's public key. Let us go through them one by one.
Generating a key pair
The first step is generating a key pair. Usually this is done on the client machine.
For example, on your laptop.
The basic command ssh-keygen will create a 2048-bit RSA key pair. For
greater security you can add the -b 4096 flag
Run
ssh-keygen -b 4096
To generate the key in /home/$(whoami)/.ssh
or
sudo ssh-keygen -b 4096
To generate the key in /home/root/.ssh
Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa):
You need to come up with a key name.
I will name the key
andrei-key101
and I will save it to the current directory.
Enter file in which to save the key (/root/.ssh/id_rsa): andrei-key101 Enter passphrase (empty for no passphrase): Enter same passphrase again:
You need to enter the password twice. If you need one. Usually you do not.
Your identification has been saved in andrei-key101 Your public key has been saved in andrei-key101.pub The key fingerprint is: SHA256:abcd/abcdefghijklmnopqrstuvwxyz1234567890ab root@urn-su The key's randomart image is: +---[RSA 4096]----+ |=o oo++ | |= oo o. = o | |+ | |Oo=o . . | |B+.o S . | |+o.o | |+.0. . | |o+= . E | |+=oo. . . | +----[SHA256]-----+
The keys are ready. I saved them to the current directory, so I will see them by running ls
ls
andrei-key101 andrei-key101.pub
It is important to remember that if you generate a key for another user you need to take care of the correct access rights to that key.
Which key goes where?
.pub
key is sent to the remote machine
keep the private key on your client
Copying the key to a remote host
After the keys are created you need to copy the
.pub
key to the remote host.
There are several ways to do this, let us start with the utility
ssh-copy-id
ssh-copy-id
I prefer to use it with the flag -i and to specify the path to the required key
sudo ssh-copy-id -i ~/.ssh/andrei-key.pub andrei@192.168.0.2
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/andrei/.ssh/andrei-key.pub" The authenticity of host '192.168.0.2 (192.168.0.2)' can't be established. ECDSA key fingerprint is SHA256:abcdefgh1234567890abcdefgh1234567890abc+def. Are you sure you want to continue connecting (yes/no/[fingerprint])?
Enter yes
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys andrei@192.168.0.2's password:
Enter the password
Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'andrei@192.168.0.2'" and check to make sure that only the key(s) you wanted were added.
Now on the host 192.168.0.2 in the file /home/andrei/.ssh/authorized_keys a new entry of the form has appeared
ssh-rsa AAAAB3NzaC1y … lseP/jXcq … Uydr/2CwQ &hellip ++TpY19pHqD/AnhL … Az62T/Ipyx … 8U2T andrei@host.andrei.com
The … sign replaces long sequences of random characters to save space.
You can check the key with the command
ssh -i ~/.ssh/mykey user@host
In our case
ssh -i ~/.ssh/andrei-key andrei@192.168.0.2
If you did not set a password for the key, you will get to the remote host without any extra steps
Last login: Sun Jan 10 16:48:27 2021 from 192.168.0.1
Finding the OpenSSH version in Linux
To find the OpenSSH version in your Linux distribution, run
ssh -V
OpenSSH_7.4p1, OpenSSL 1.0.2k-fips 26 Jan 2017
Running a command from a script on a remote computer
If the ssh connection is made from a bash script , and you also need to run a number of commands after connecting, it is enough to list these commands separated by a semicolon
#!/bin/bash
ssh andrei@192.168.0.2 "ls;cd /home/andrei/bash_scripts;ls;ip a;cal"
If you need to run a command that requires sudo, try the -t flag
#!/bin/bash
ssh -t andrei@192.168.0.2 "sudo apt upgrade"
known_hosts
The list of known hosts is in the file
known_hosts
Full path:
/home/$(whoami)/.ssh/known_hosts
Usually the file known_hosts has the following format (the entries are separated by spaces) ( more details )
{server-id} algorithm {public-key-string} {comment}
Examples of algorithms: ssh-rsa, ssh-dss, ssh-ed25519, ecdsa-sha2-nistp256 …
Example line:
|1|abcdef+abcdefghijklmnopqrst=|abcdefghijklmnopqrstuvwxyz1= ssh-rsa abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrst/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz12345/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzB1234567
Thus
abcdef+abcdefghijklmnopqrst=|abcdefghijklmnopqrstuvwxyz1=
This is a hash of the server name.
ssh-rsa
This is the encryption algorithm
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrst/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz12345/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzB1234567
This is the host's public key
Creating an SSH tunnel
Tunnels are usually created to redirect traffic. An SSH tunnel is the same thing as SSH port forwarding.
Suppose you want to direct traffic from your localhost (127.0.0.1) to the
remote
host 192.168.0.2.
On
remote
host you have a user named andrei and you know his password.
First you need to decide on the ports on the local host and on the remote one.
Suppose you chose 9119 for the local and
9200 for the
remote
hosts.
That is, you want everything going to localhost:9119 to be redirected to
192.168.0.2:9200
Run
ssh -L 9119:192.168.0.2:9200 andrei@192.168.0.2
The authenticity of host '192.168.0.2 (192.168.0.2)' can't be established.
ECDA …
…
andrei@192.168.0.2's password:
Last login: Sun Jan 31 13:23:00 2021
Check the ip by running
ip a
If you need a tunnel with support for the graphical interface X Window System use flag -X
ssh -X -L 9119:192.168.0.2:9200 andrei@192.168.0.2
Demonstration
The tunnel is created, do not close the terminal. Open two new terminals or two new tabs in the old one.
You have two empty terminals, both on the local host. Let us call them 1 and 2.
From terminal 2 let us connect to the remote host 192.168.0.2 over ssh and
listen on port 9200 with nmap
ssh andrei@192.168.0.2
nmap -l 9200
On terminal 1, with nmap, let us send a message to port 9119 of the local host. This is the port that we configured for forwarding.
nmap localhost 9119
Enter any text
heihei.ru
Open terminal 2, the same text should appear there
heihei.ru
List of all open SSH tunnels
To get the list of tunnels opened specifically by ssh, run
sudo lsof -i -n | egrep '\<ssh\>'
ssh 14695 andrei 3u IPv4 230080 0t0 TCP 192.168.0.1:46356->192.168.0.2:ssh (ESTABLISHED) ssh 14695 andrei 4u IPv6 230103 0t0 TCP [::1]:9119 (LISTEN) ssh 14695 andrei 5u IPv4 230104 0t0 TCP 127.0.0.1:9119 (LISTEN)
The output of this command is for some reason different under practically identical conditions.
Below is an example of the second variant. If you know why this happens, write in the comments.
ssh 15151 andrei 3u IPv4 239364 0t0 TCP 192.168.0.1:46464->192.168.0.2:ssh (ESTABLISHED) ssh 15151 andrei 4u IPv6 239380 0t0 TCP [::1]:mxit (LISTEN) ssh 15151 andrei 5u IPv4 239381 0t0 TCP 127.0.0.1:mxit (LISTEN) ssh 15151 andrei 9u IPv6 239428 0t0 TCP [::1]:mxit->[::1]:54306 (ESTABLISHED)
Closing all SSH tunnels
To close everything related to ssh you can run
sudo killall ssh sshd
This method is good only if you work alone, for example on some virtual machine.
Running SSH in the background
There are several ways to run an ssh connection in the background, that is, to free up the current terminal.
-L, screen, tmux, nohup
nohup helped me run ssh in the background from a script, so let us start with it
nohup ssh user@host "cd scripts;python3 my_script.py $ARG1 $ARG2; exit" &
Why this was needed: Python script first
opened one ssh connection from
subprocess
there a command was run to start
memory usage monitoring
and nothing more was needed from that connection, but new connections with a load had to be made from another script.
To leave the first connection without cutting off the memory usage monitoring, nohup had to be added before ssh, and & put at the very end
SSH_MSG_USERAUTH_BANNER
A client that has connected to the ssh server can be shown a banner
SSH_MSG_USERAUTH_BANNER
Specification
rfc4252
Run
sudo vi /etc/issue.net
And edit the file by adding your banner
\S
Kernel \r on an \m
#########################################################
# ANDREYOLEGOVICH.RU and URN.SU #
#########################################################
Open sshd_config and specify the path to the banner
sudo vi /etc/ssh/sshd_config
/banner
# no default banner path
#Banner none
This banner will be shown BEFORE authorization, that is, while the password is being entered
To create a banner that will be shown after a successful login, run
sudo vi /etc/motd
#########################################################
# YOU ARE HERE: urn.su/linux/ssh.php #
#########################################################
After editing the files restart sshd
sudo systemctl restart sshd.service
Converting certificates
Let us look at a simple example: you retrieved from the database a certificate MIIC4jCCAc … A7A6Rpt8V9Q== , but it is not formatted and does not pass validation
The certificate is, of course, longer; I put an ellipsis to save space and your time.
Run
echo 'MIIC4jC … 7A6Rpt8V9Q==' | base64 -d | openssl x509 -inform der
Or, if you need to work with files, save the source certificate to the file raw_cert
echo MIIC4jC … 7A6Rpt8V9Q== > raw_cert
cat raw_cert | base64 -d | openssl x509 -inform der > cert
cat cert
-----BEGIN CERTIFICATE-----
MIIC4jC … 7A6Rpt8V9Q==
-----END CERTIFICATE-----
The same result could be achieved by carefully adding -----BEGIN CERTIFICATE----- at the beginning and -----END CERTIFICATE----- at the end of the file, but things are not always that simple.
Existing OpenSSH versions
OpenSSH 8.2 FEATURE: Add FIDO/U2F Support OpenSSH 8.1, released in October 2019 ssh, sshd, ssh-agent: add protection for private keys at rest in RAM against speculation and memory side-channel attacks like Spectre, Meltdown and Rambleed. OpenSSH 8.0, released in April 2019 SECURITY: CVE-2019-6111 related to scp tool and protocol allowing to overwrite arbitrary files in the scp client target directory OpenSSH 7.9, released in October 2018 allow key revocation lists (KRLs) to revoke keys specified by SHA256 hash OpenSSH 7.8, released in August 2018 Incompatible changes: ssh-keygen write OpenSSH format private keys by default instead of using OpenSSL's PEM format. OpenSSH 7.7, released in February 2018 FEATURE: Add "expiry-time" option in sshd for authorized_keys files to allow for expiring keys. OpenSSH 7.6, released in October 2017 FEATURE: Add RemoteCommand option FEATURE: Add SyslogFacility option to ssh matching the equivalent option in sshd FEATURE: ssh client reverse dynamic forwarding -R OpenSSH 7.5, released in March 2017 BUGFIX: This is a mainly a bugfix release. OpenSSH 7.4, released Template:Release date and age sshd(8): Add a sshd_config DisableForwarding option OpenSSH 7.3, released August 01, 2016 FEATURE: Adds ProxyJump option (-J) FEATURE: Add an Include directive for ssh_config(5) files OpenSSH 7.1: August 20, 2015 This is a bugfix release. OpenSSH 7.0: August 11, 2015 The focus of this release is primarily to deprecate weak, legacy and unsafe cryptography. OpenSSH 6.9: July 1, 2015 BUGFIX: This is primarily a bugfix release. OpenSSH 6.8: March 18, 2015 Added new hostkeys@openssh.com extension to facilitate public key discovery and rotation for trusted hosts (for transition from DSA to Ed25519 public host keys) AuthenticationMethods=publickey,publickey to require that users authenticate using two different public keys OpenSSH 6.7: October 6, 2014 The default set of ciphers and MACs has been altered to remove unsafe algorithms. In particular, CBC ciphers and arcfour* are disabled by default. Compile-time option to not depend on OpenSSL Add support for Unix domain socket forwarding OpenSSH 6.6: March 16, 2014 This is primarily a bugfix release. OpenSSH 6.5: January 30, 2014 Added new ssh-ed25519 and ssh-ed25519-cert-v01@openssh.com public key types (available since 2005 but more popular since some suspicious that NSA had chosen values that gave them an advantage in factoring public-keys) Added new chacha20-poly1305@openssh.com transport cipher Added curve25519-sha256@libssh.org key exchange FEATURE: ssh, added Match keyword for ssh_config that allows conditional configuration to be applied FEATURE: client-side hostname canonicalisation: CanonicalDomains, CanonicalizeFallbackLocal, CanonicalizeHostname, CanonicalizeMaxDots and CanonicalizePermittedCNAMEs. Add a new private key format that uses a bcrypt KDF OpenSSH 6.4: November 8, 2013 This release fixes a security bug with AES-GCM OpenSSH 6.3: September 13, 2013 This release is predominantly a bugfix release OpenSSH 6.2: March 22, 2013 Add a GCM-mode for the AES cipher, similar to RFC 5647 Added support for encrypt-then-mac MAC modes Added support for multiple required authentication methods Added support for Key Revocation Lists (KRL) OpenSSH 6.1: August 29, 2012 This is primarily a bugfix release. Enables pre-auth sandboxing by default Finds ECDSA keys in ssh-keyscan and SSHFP DNS records by default now OpenSSH 6.0: April 22, 2012 This is primarily a bugfix release. OpenSSH 5.9: September 6, 2011 Introduce sandboxing of the pre-auth privilege separated child OpenSSH 5.8: February 4, 2011 OpenSSH 5.7: January 24, 2011 Added support for elliptic curve cryptography for key exchange as well as host/user keys, per RFC 5656 OpenSSH 5.6: August 23, 2010 Added a ControlPersistoption to ssh_config OpenSSH 5.5: April 16, 2010 OpenSSH 5.4: March 8, 2010 Disabled SSH protocol 1 default support. Clients and servers must now explicitly enable it. Added PKCS11 authentication support for ssh(1) (-I pkcs11) Added Certificate based authentication Added "Netcat mode" for ssh(1) (-W host:port). Similar to "-L tunnel", but forwards instead stdin and stdout. This allows, for example, using ssh(1) itself as a ssh(1) ProxyCommand to route connections via intermediate servers, without the need for nc(1) on the server machine. Added the ability to revoke public keys in sshd(8) and ssh(1). While it was already possible to remove the keys from authorised lists, revoked keys will now trigger a warning if used. OpenSSH 5.3: October 1, 2009 OpenSSH 5.2: February 23, 2009 OpenSSH 5.1: July 21, 2008 Added a MaxSessions option to sshd_config OpenSSH 5.0: April 3, 2008 OpenSSH 4.9: March 30, 2008 Added chroot support for sshd(8) Create an internal SFTP server for easier use of the chroot functionality OpenSSH 4.7: September 4, 2007 - Ubuntu 8.04 OpenSSH 4.6: March 9, 2007 OpenSSH 4.5: November 7, 2006 OpenSSH 4.4: September 27, 2006 OpenSSH 4.3: February 1, 2006 Added OSI layer 2/3 tun-based VPN (-w option on ssh(1)) OpenSSH 4.2: September 1, 2005 OpenSSH 4.1: May 26, 2005 OpenSSH 4.0: March 9, 2005 OpenSSH 3.9: August 18, 2004 Implement session multiplexing. ControlMaster option Added a MaxAuthTries option to sshd, allowing control over the maximum number of authentication attempts permitted per connection Added IdentitiesOnly option to ssh which specifies that it should use keys specified in ssh_config, rather than any keys in ssh-agent Re-introduce support for PAM password authentication OpenSSH 3.8: February 24, 2004 OpenSSH 3.7.1: September 16, 2003 OpenSSH 3.7: September 16, 2003 rhosts authentication has been removed in ssh(1) and sshd(8). OpenSSH 3.6.1: April 1, 2003 OpenSSH 3.6: March 31, 2003 OpenSSH 3.5: October 14, 2002 OpenSSH 3.4: June 26, 2002 OpenSSH 3.0: Improved Kerberos support in protocol v1 (KerbIV and KerbV) OpenSSH 2.9.9: OpenSSH 2.5.1p1: February 19, 2001 SkeyAuthentication absoleted, use ChallengeResponseAuthentication instead. OpenSSH 1.2.2p1: March 5, 2000
Article author: Andrei Olegovich