212.3 Secure shell (SSH)
Weight: 4
Description: Candidates should be able to configure and secure an SSH daemon. This objective includes managing keys and configuring SSH for users. Candidates should also be able to forward an application protocol over SSH and manage the SSH login.
Key Knowledge Areas:
    OpenSSH configuration files, tools and utilities
    Login restrictions for the superuser and the normal users
    Managing and using server and client keys to login with and without password
    Usage of multiple connections from multiple hosts to guard against loss of connection to remote host following configuration changes
Terms and Utilities:
    ssh
    sshd
    /etc/ssh/sshd_config
    /etc/ssh/
    Private and public key files
    PermitRootLogin, PubKeyAuthentication, AllowUsers, PasswordAuthentication, Protocol
As an administrator we need deep knowledge about remote login protocols such as rlogin, rsh , telnet and ssh.

Whats is SSH?

The SSH protocol (also referred to as Secure Shell) is a method for secure remote login from one computer to another. It provides several alternative options for strong authentication, and it protects the communications security and integrity with strong encryption. It is a secure alternative to the non-protected login protocols (such as telnet, rlogin) and insecure file transfer methods (such as FTP).
Typical uses of the SSH protocol are:
    providing secure access for users and automated processes
    interactive and automated file transfers
    issuing remote commands
    managing network infrastructure and other mission-critical system components.

How does the ssh protocol work?

The way SSH works is by making use of a client-server model to allow for authentication of two remote systems and encryption of the data that passes between them.
SSH operates on TCP port 22 by default (though this can be changed if needed). The host (server) listens on port 22 (or any other SSH assigned port) for incoming connections.
SSH provides multiple mechanisms for authenticating the server and the client. Two of the commonly used authentication mechanism are password based, and key based authentication. Although password based authentication is also secure, its advisable to use key based authentication instead.
the connection is established by the SSH client connecting to the SSH server. The SSH client drives the connection setup process and uses public key cryptography to verify the identity of the SSH server. After the setup phase the SSH protocol uses strong symmetric encryption and hashing algorithms to ensure the privacy and integrity of the data that is exchanged between the client and server.

What is OpenSSH?

OpenSSH is a free open source set of computer tools used to provide secure and encrypted communication over a computer network by using the ssh protocol. it is developed by the Open BSD group and it is released under Simplified BSD License. Open OpenSSH is so popular among system administrators because of its multi-platform capability and very useful nice features.
All communications and user credentials using OpenSSH are encrypted, they are also protected from man in the middle attacks. If a third party tries to intercept our connection, OpenSSH detects it and informs us about that.
Lets get started, We use CentOS7-1 as our server :
1
[[email protected] ~]# yum search openssh | grep -i server
2
openssh-server-sysvinit.x86_64 : The SysV initscript to manage the OpenSSH
3
: server.
4
gsi-openssh-server.x86_64 : SSH server daemon with GSI authentication
5
openssh-ldap.x86_64 : A LDAP support for open source SSH server daemon
6
openssh-server.x86_64 : An open source SSH server daemon
Copied!

/etc/ssh

OpenSSH has two different sets of configuration files: one for client programs (ssh, scp, and sftp) and one for the server daemon (sshd).
1
[[email protected] ~]# cd /etc/ss
2
ssh/ ssl/ sssd/
3
[[email protected] ~]# cd /etc/ssh
4
[[email protected] ssh]# ls -l
5
total 608
6
-rw-r--r--. 1 root root 581843 Apr 11 00:21 moduli
7
-rw-r--r--. 1 root root 2276 Apr 11 00:21 ssh_config
8
-rw-------. 1 root root 3905 Jun 10 04:54 sshd_config
9
-rw-------. 1 root root 3907 Apr 11 00:21 sshd_config.rpmnew
10
-rw-r-----. 1 root ssh_keys 227 Oct 28 2017 ssh_host_ecdsa_key
11
-rw-r--r--. 1 root root 162 Oct 28 2017 ssh_host_ecdsa_key.pub
12
-rw-r-----. 1 root ssh_keys 387 Oct 28 2017 ssh_host_ed25519_key
13
-rw-r--r--. 1 root root 82 Oct 28 2017 ssh_host_ed25519_key.pub
14
-rw-r-----. 1 root ssh_keys 1679 Oct 28 2017 ssh_host_rsa_key
15
-rw-r--r--. 1 root root 382 Oct 28 2017 ssh_host_rsa_key.pub
Copied!
Thesshd_configis the ssh daemon(or ssh server process) configuration file, Whereas, the ssh_config file is the ssh client configuration file. The client configuration file only has bearing on when you use the ssh command to connect to another ssh host . As you can see there are public keys and private keys here with different algorithems and they can be used by SSH to encrypt the session.

RELATIONSHIP OF CONFIGURATION FILES

The SSH server actually reads several configuration files. The sshd_config file specifies the locations of one or more host key files (mandatory) and the location of authorized_keys files for users. It may also refer to a number of other files.

/etc/sshd_config

The OpenSSH server reads a configuration file when it is started. Usually this file is /etc/ssh/sshd_config:
1
[[email protected] ssh]# cat sshd_config
2
# $OpenBSD: sshd_config,v 1.100 2016/08/15 12:32:04 naddy Exp $
3
4
# This is the sshd server system-wide configuration file. See
5
# sshd_config(5) for more information.
6
7
# This sshd was compiled with PATH=/usr/local/bin:/usr/bin
8
9
# The strategy used for options in the default sshd_config shipped with
10
# OpenSSH is to specify options with their default value where
11
# possible, but leave them commented. Uncommented options override the
12
# default value.
13
14
# If you want to change the port on a SELinux system, you have to tell
15
# SELinux about this change.
16
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
17
#
18
#Port 22
19
#AddressFamily any
20
#ListenAddress 0.0.0.0
21
#ListenAddress ::
22
23
HostKey /etc/ssh/ssh_host_rsa_key
24
#HostKey /etc/ssh/ssh_host_dsa_key
25
HostKey /etc/ssh/ssh_host_ecdsa_key
26
HostKey /etc/ssh/ssh_host_ed25519_key
27
28
# Ciphers and keying
29
#RekeyLimit default none
30
31
# Logging
32
#SyslogFacility AUTH
33
SyslogFacility AUTHPRIV
34
#LogLevel INFO
35
36
# Authentication:
37
38
#LoginGraceTime 2m
39
PermitRootLogin yes
40
#StrictModes yes
41
#MaxAuthTries 6
42
#MaxSessions 10
43
44
#PubkeyAuthentication yes
45
46
# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
47
# but this is overridden so installations will only check .ssh/authorized_keys
48
AuthorizedKeysFile .ssh/authorized_keys
49
50
#AuthorizedPrincipalsFile none
51
52
#AuthorizedKeysCommand none
53
#AuthorizedKeysCommandUser nobody
54
55
# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
56
#HostbasedAuthentication no
57
# Change to yes if you don't trust ~/.ssh/known_hosts for
58
# HostbasedAuthentication
59
#IgnoreUserKnownHosts no
60
# Don't read the user's ~/.rhosts and ~/.shosts files
61
#IgnoreRhosts yes
62
63
# To disable tunneled clear text passwords, change to no here!
64
#PasswordAuthentication yes
65
#PermitEmptyPasswords no
66
PasswordAuthentication yes
67
68
# Change to no to disable s/key passwords
69
#ChallengeResponseAuthentication yes
70
ChallengeResponseAuthentication no
71
72
# Kerberos options
73
#KerberosAuthentication no
74
#KerberosOrLocalPasswd yes
75
#KerberosTicketCleanup yes
76
#KerberosGetAFSToken no
77
#KerberosUseKuserok yes
78
79
# GSSAPI options
80
GSSAPIAuthentication yes
81
GSSAPICleanupCredentials no
82
#GSSAPIStrictAcceptorCheck yes
83
#GSSAPIKeyExchange no
84
#GSSAPIEnablek5users no
85
86
# Set this to 'yes' to enable PAM authentication, account processing,
87
# and session processing. If this is enabled, PAM authentication will
88
# be allowed through the ChallengeResponseAuthentication and
89
# PasswordAuthentication. Depending on your PAM configuration,
90
# PAM authentication via ChallengeResponseAuthentication may bypass
91
# the setting of "PermitRootLogin without-password".
92
# If you just want the PAM account and session checks to run without
93
# PAM authentication, then enable this but set PasswordAuthentication
94
# and ChallengeResponseAuthentication to 'no'.
95
# WARNING: 'UsePAM no' is not supported in Red Hat Enterprise Linux and may cause several
96
# problems.
97
UsePAM yes
98
99
#AllowAgentForwarding yes
100
#AllowTcpForwarding yes
101
#GatewayPorts no
102
X11Forwarding yes
103
#X11DisplayOffset 10
104
#X11UseLocalhost yes
105
#PermitTTY yes
106
#PrintMotd yes
107
#PrintLastLog yes
108
#TCPKeepAlive yes
109
#UseLogin no
110
#UsePrivilegeSeparation sandbox
111
#PermitUserEnvironment no
112
#Compression delayed
113
#ClientAliveInterval 0
114
#ClientAliveCountMax 3
115
#ShowPatchLevel no
116
#UseDNS no
117
#PidFile /var/run/sshd.pid
118
#MaxStartups 10:30:100
119
#PermitTunnel no
120
#ChrootDirectory none
121
#VersionAddendum none
122
123
# no default banner path
124
#Banner none
125
126
# Accept locale-related environment variables
127
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
128
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
129
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
130
AcceptEnv XMODIFIERS
131
132
# override default of no subsystems
133
Subsystem sftp /usr/libexec/openssh/sftp-server
134
135
# Example of overriding settings on a per-user basis
136
#Match User anoncvs
137
# X11Forwarding no
138
# AllowTcpForwarding no
139
# PermitTTY no
140
# ForceCommand cvs server
Copied!
lets talk about some of them:
Port: The port that the remote SSH daemon is running on. This option is only necessary if the remote SSH instance is not running on the default port 22.(If you have a plan to change it do not forget about discretionary access controls. Like selinux or appa rmor )
SyslogFacility : By default, the OpenSSH server logs to the AUTH facility of syslog.
    auth - is meant to log authentication and authorization related commands
    authpriv - is for non system authorization messages (for security information of a sensitive nature)
all logs are logged to /var/log/auth.log for debian based systems or /var/log/secure for RedHat CentOS based systems
LogLevel: By default OpenSSH logs at the INFO level. If we want to record more information ( such as failed login attempts) we should increase the logging level to VERBOSE.
PermitRootLogin : Specifies whether root can log in over ssh or not . The argument could be:
    yes - root is allowed to log in.
    without-password - password authentication is disabled for root and root can only login using key pairs.
    forced-commands-only - root login with public key authentication will be allowed, but only if the commandoption has been specified (which may be useful for taking remote backups even if root login is normally not allowed). All other authentication methods are disabled for root.
    no - root is not allowed to log in.
PubkeyAuthntication : Lets people to loging just using ssh key files without entering password.
PermitEmptyPassword : Allow users with empty password get connected to our ssh server.
PasswordAuthentication : Of course we want ssh server authenticate users before lets them get connected, But if we like to force users to autheticate using their key pairs we can set it to No.
Banner : specify a text file based on what we like to be displayed when some one trys to ssh.
PrintMotd : Print a message after some one logs in.
MaxAuthTries : Specifies the maximum number of authentication attempts permitted per connection. Once the number of failures reaches half this value, additional failures are logged. It can be over write by PAM if any PAM modules is associated.
By default all users with user accounts can log in trough ssh, but there are two options which can be added to sshd_config file in order to change the default behaviour:
AllowUsers : Specify user we like to let them log in trough ssh.(No other user can login)
DenyUsers : Avoid certain users to get login.
ForwardX11 : What is that ?

What is SSH Tunneling / port forwarding ?

SSH tunneling is a method of transporting arbitrary networking data over an encrypted SSH connection. It can be used to add encryption to legacy applications. It can also be used to implement VPNs (Virtual Private Networks) and access intranet services across firewalls.
SSH is a standard for secure remote logins and file transfers over untrusted networks. It also provides a way to secure the data traffic of any given application using port forwarding, basically tunneling any TCP/IP port over SSH. This means that the application data traffic is directed to flow inside an encrypted SSH connection so that it cannot be eavesdropped or intercepted while it is in transit. SSH tunneling enables adding network security to legacy applications that do not natively support encryption.
so SSH port forwarding is a mechanism in SSH for tunneling application ports from the client machine to the server machine, or vice versa. some system administrators and IT professionals use it for opening backdoors into the internal network from their home machines. It can also be abused by hackers and malware to open access from the Internet to the internal network.
There are three types of SSH port forwarding:
    Local port forwarding - connections from an SSH client are forwarded, via the SSH server, to a destination server.
    Remote port forwarding - connections from an SSH server are forwarded, via the SSH client, to a destination server
    Dynamic port forwarding - connections from various programs are forwarded, via the SSH client to an SSH server, and finally to several destination servers.
Okey after this log explanation, lets go back to sshd_config file options .
X11Forwarding : It lets us to run graphical programs remotely from the linux server. X11 forwarding needs to be enabled on both the client side and the server side. on the server side, On the server side,X11Forwarding yesmust specified in /etc/ssh/sshd_config . On the client side, the-X(capital X) option tosshenables X11 forwarding, and you can make this the default (for all connections or for a specific conection) withForwardX11 yesin ~/.ssh/config.

/etc/ssh_config

ssh_config file has similar setting but its for ssh utilities, like scp, sftp. scp for secure copies and aftp for secure ftp.
1
[[email protected] ssh]# cat ssh_config
2
# $OpenBSD: ssh_config,v 1.30 2016/02/20 23:06:23 sobrado Exp $
3
4
# This is the ssh client system-wide configuration file. See
5
# ssh_config(5) for more information. This file provides defaults for
6
# users, and the values can be changed in per-user configuration files
7
# or on the command line.
8
9
# Configuration data is parsed as follows:
10
# 1. command line options
11
# 2. user-specific file
12
# 3. system-wide file
13
# Any configuration value is only changed the first time it is set.
14
# Thus, host-specific definitions should be at the beginning of the
15
# configuration file, and defaults at the end.
16
17
# Site-wide defaults for some commonly used options. For a comprehensive
18
# list of available options, their meanings and defaults, please see the
19
# ssh_config(5) man page.
20
21
# Host *
22
# ForwardAgent no
23
# ForwardX11 no
24
# RhostsRSAAuthentication no
25
# RSAAuthentication yes
26
# PasswordAuthentication yes
27
# HostbasedAuthentication no
28
# GSSAPIAuthentication no
29
# GSSAPIDelegateCredentials no
30
# GSSAPIKeyExchange no
31
# GSSAPITrustDNS no
32
# BatchMode no
33
# CheckHostIP yes
34
# AddressFamily any
35
# ConnectTimeout 0
36
# StrictHostKeyChecking ask
37
# IdentityFile ~/.ssh/identity
38
# IdentityFile ~/.ssh/id_rsa
39
# IdentityFile ~/.ssh/id_dsa
40
# IdentityFile ~/.ssh/id_ecdsa
41
# IdentityFile ~/.ssh/id_ed25519
42
# Port 22
43
# Protocol 2
44
# Cipher 3des
45
# Ciphers aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc
46
# MACs hmac-md5,hmac-sha1,[email protected],hmac-ripemd160
47
# EscapeChar ~
48
# Tunnel no
49
# TunnelDevice any:any
50
# PermitLocalCommand no
51
# VisualHostKey no
52
# ProxyCommand ssh -q -W %h:%p gateway.example.com
53
# RekeyLimit 1G 1h
54
#
55
# Uncomment this if you want to use .local domain
56
# Host *.local
57
# CheckHostIP no
58
59
Host *
60
GSSAPIAuthentication yes
61
# If this option is set to yes then remote X11 clients will have full access
62
# to the original X11 display. As virtually no X11 client supports the untrusted
63
# mode correctly we set this to yes.
64
ForwardX11Trusted yes
65
# Send locale-related environment variables
66
SendEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
67
SendEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
68
SendEnv LC_IDENTIFICATION LC_ALL LANGUAGE
69
SendEnv XMODIFIERS
Copied!

ssh configuration files precedence

Do not forget that ssh client configuration file has precedence. The ssh program on a host receives its configuration from either the command line or from configuration files ~/.ssh/config and /etc/ssh/ssh_config.
Command-line options take precedence over configuration files. The user-specific configuration file ~/.ssh/config is used next. Finally, the global /etc/ssh/ssh_config file is used. The first obtained value for each configuration parameter will be used.

Configuring SSH Key Based authentication

Till now we have understood how ssh works. As we mentioned when ssh connection is started, the public key of ssh server is tranfered to the client(stored in ./ssh/known_hosts) and the client will use it to continue negotiation with the server and user will be required to get authenticated by sending username and password.
Its possible to omit entring user name and password and get connected to the ssh server using client public and private key.
Lets start by connecting to Centos7-1 from CentOS7-2 and see the keys:
1
[[email protected] ~]$ ssh centos7-1
2
The authenticity of host 'centos7-1 (192.168.10.133)' can't be established.
3
ECDSA key fingerprint is SHA256:QtfM2iXh5pxZeFdAUXEBEnRXNSP40MWIhnSYvpOBMoY.
4
ECDSA key fingerprint is MD5:27:db:c1:d0:da:35:80:92:81:fa:8f:1c:e5:d7:f3:2e.
5
Are you sure you want to continue connecting (yes/no)? yes
6
Warning: Permanently added 'centos7-1,192.168.10.133' (ECDSA) to the list of known hosts.
7
[email protected]'s password:
8
Last login: Sat Jul 28 03:34:33 2018
9
Managed by ansible
10
11
logout
12
Connection to centos7-1 closed.
Copied!
1
[[email protected] ~]$ cd .ssh/
2
3
known_hosts
4
[[email protected] .ssh]$ cat known_hosts
5
centos7-1,192.168.10.133 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBKuy5+nza9QN5cqDE2E7jJLEdqDrIkOprS8n/HP7Cj3V31kx4rOShL61zjuevHROlt4niShqS1wy584SGBMmHgg=
Copied!
Now lets generate public and private keys for client and copy client public key to the server, ssh-keygen - creates a key pair for public key authentication:
1
[[email protected] .ssh]$ ssh-keygen
2
Generating public/private rsa key pair.
3
Enter file in which to save the key (/home/user1/.ssh/id_rsa):
4
Enter passphrase (empty for no passphrase):
5
Enter same passphrase again:
6
Your identification has been saved in /home/user1/.ssh/id_rsa.
7
Your public key has been saved in /home/user1/.ssh/id_rsa.pub.
8
The key fingerprint is:
9
SHA256:2thZLmb/O+EAg5sWPNT2kiywZ+EbWpC2suZiiUcgKu4 [email protected]
10
The key's randomart image is:
11
+---[RSA 2048]----+
12
| . . |
13
| = o o |
14
| . O = o |
15
|o . o % * . |
16
|o. o = OS+. |
17
|o + . == +. . |
18
|++. .o B .o . |
19
|o+o o o o |
20
|oE ..oo |
21
+----[SHA256]-----+
22
23
id_rsa id_rsa.pub known_hosts
24
[[email protected] .ssh]$ cat id_rsa.pub
25
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDJhDyHAb49NlI64qN6hLrRcE4AYm5CxXbmLiB214Ea46rBB5UlkrLvDyBO8pPMbpyIMmTco2B39N2BfvB3zyb7Ddu5v4KU9PzfrpUskYgFHjHGnnnCn5xY6/UCb+/bpIh/GlLCX3WZLtj6+9cA+J1h7UTRkSUNH4mVHqA2Esvx3YJJT/MrANurWUe4uFOwwvRy1IJT9XM9Z9RvRoYkm4Ughi1IJlq4qlgeXD6qOMCj6vbFLZvyaxG0cdtDItGGDGs8jj14306nt6a1qvJoLGVb7bV4GCISUgLa/Nf+N+ZtSGSdaqS5OkJ+RtYfZWJ8r+iaE+WXzYANh40n2/83+RFN [email protected]
Copied!
We haven't set passphrase in our demonstration but if we set we would be asked to enter it when we copy it to the server. any how. we use ssh-copy-id - configures a public key as authorized on a server :
1
[[email protected] .ssh]$ ssh-copy-id -i id_rsa.pub [email protected]
2
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub"
3
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
4
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
5
[email protected]'s password:
6
7
Number of key(s) added: 1
8
9
Now try logging into the machine, with: "ssh '[email protected]'"
10
and check to make sure that only the key(s) you wanted were added.
Copied!
ssh-copy-id might not be available in your distro, no problem you can copy the public in a way that you like:
1
example : cat id_rsa.pub | ssh [email protected] 'cat >> .ssh/authorized_keys'
Copied!
Now lets take a look the server side:
1
[[email protected] ~]$ cd .ssh/
2
3
authorized_keys
4
[[email protected] .ssh]$ cat authorized_keys
5
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDJhDyHAb49NlI64qN6hLrRcE4AYm5CxXbmLiB214Ea46rBB5UlkrLvDyBO8pPMbpyIMmTco2B39N2BfvB3zyb7Ddu5v4KU9PzfrpUskYgFHjHGnnnCn5xY6/UCb+/bpIh/GlLCX3WZLtj6+9cA+J1h7UTRkSUNH4mVHqA2Esvx3YJJT/MrANurWUe4uFOwwvRy1IJT9XM9Z9RvRoYkm4Ughi1IJlq4qlgeXD6qOMCj6vbFLZvyaxG0cdtDItGGDGs8jj14306nt6a1qvJoLGVb7bV4GCISUgLa/Nf+N+ZtSGSdaqS5OkJ+RtYfZWJ8r+iaE+WXzYANh40n2/83+RFN [email protected]
Copied!
now lets check the result from the client:
2
[[email protected] .ssh]$ ssh centos7-1
3
Last login: Sat Jul 28 03:37:53 2018 from 192.168.10.138
4
Managed by ansible
Copied!
and it seems okey.We can copy and paste the keys for other users if you like, but do not forget that these keys give power to users to login with out the password.

Why use passphrase? Why it is for?

We have configured a password less ssh connection using key based authentication. But what would hapenned if our system compromised? An evil hacker would be able to get connected to other servers using key based authentication without knowning the passwords.
Passphrase can help us to avoid this kinds of security issues by requiring a passphrase ath the begining of every ssh keybased authentication. So let clear previous authorized_key, and start:
1
[[email protected] .ssh]$ vim authorized_keys
2
[[email protected] .ssh]$ cat authorized_keys
Copied!
Now generate a new key pairs with passphrase on the client (Let it over write current private and public key):
1
[[email protected] .ssh]$ ssh-keygen
2
Generating public/private rsa key pair.
3
Enter file in which to save the key (/home/user1/.ssh/id_rsa):
4
/home/user1/.ssh/id_rsa already exists.
5
Overwrite (y/n)? y
6
Enter passphrase (empty for no passphrase):
7
Enter same passphrase again:
8
Your identification has been saved in /home/user1/.ssh/id_rsa.
9
Your public key has been saved in /home/user1/.ssh/id_rsa.pub.
10
The key fingerprint is:
11
SHA256:UX/X1Kn95rTpPvEPJNTfSFpik0l0odnDaFZeBK6TmBQ [email protected]
12
The key's randomart image is:
13
+---[RSA 2048]----+
14
| E.o =+*|
15
| . + # +o|
16
| . . # & o|
17
| o B @ *.|
18
| S o * o +|
19
| + .+|
20
| .+=|
21
| =o|
22
| oo+|
23
+----[SHA256]-----+
24
[[email protected] .ssh]$ ls -l
25
total 12
26
-rw-------. 1 user1 user1 1766 Jul 29 02:15 id_rsa
27
-rw-r--r--. 1 user1 user1 397 Jul 29 02:15 id_rsa.pub
28
-rw-r--r--. 1 user1 user1 186 Jul 28 03:37 known_hosts
29
[[email protected] .ssh]$ cat id_rsa.pub
30
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC14333HmDgzDsdy7kRNklXPiNYF55ljyL/ma2A1ay/sS2KfX+M7BiWp99Utmx0H6eT/l0aqbQ/iSswC+ZGhpfScd6Hq5Gq1RX58Oy+dT1O6jlzEGbk402w/GyGRSNGOR2douZbta4joNwdDMSR+TtEdp65wpvosUcbEaa8zYVlrXD4n/jYmqQE95S7q0oPgD6eLFzsOsrjCvyH6mabIe0dzWhupw5OTdPGOpbw5uHZ/eRCUPzSw9Ex7dDB6yrjHefIYGpQ0wVooD/dVCMJQ7fHrLezvSzmIq9HAnLqVfnOlqIZosVTpiHbJ6gwV1ZxWtUD2bPmXQu0ZpntnBi6XT+/ [email protected]
Copied!
Now lets tranfer our new public key to the server:
1
[[email protected] .ssh]$ ssh-copy-id -i id_rsa.pub [email protected]
2
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub"
3
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
4
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
5
[email protected]'s password:
6
7
Number of key(s) added: 1
8
9
Now try logging into the machine, with: "ssh '[email protected]'"
10
and check to make sure that only the key(s) you wanted were added.
Copied!
Lets see the key we have copied on the server:
1
[[email protected] .ssh]$ cat authorized_keys
2
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC14333HmDgzDsdy7kRNklXPiNYF55ljyL/ma2A1ay/sS2KfX+M7BiWp99Utmx0H6eT/l0aqbQ/iSswC+ZGhpfScd6Hq5Gq1RX58Oy+dT1O6jlzEGbk402w/GyGRSNGOR2douZbta4joNwdDMSR+TtEdp65wpvosUcbEaa8zYVlrXD4n/jYmqQE95S7q0oPgD6eLFzsOsrjCvyH6mabIe0dzWhupw5OTdPGOpbw5uHZ/eRCUPzSw9Ex7dDB6yrjHefIYGpQ0wVooD/dVCMJQ7fHrLezvSzmIq9HAnLqVfnOlqIZosVTpiHbJ6gwV1ZxWtUD2bPmXQu0ZpntnBi6XT+/ [email protected]
Copied!
Now when we ssh to the remote server (CentOS7-1) from our client(CentOS7-2), we are asked to enter our local key passphrase intead of remote user account password:
1
[[email protected] .ssh]$ ssh centos7-1
2
Enter passphrase for key '/home/user1/.ssh/id_rsa':
3
Last login: Sat Jul 28 04:15:00 2018 from 192.168.10.145
4
Managed by ansible
Copied!
lets exit and ssh again and again:
2
logout
3
Connection to centos7-1 closed.
4
[[email protected] .ssh]$ ssh centos7-1
5
Enter passphrase for key '/home/user1/.ssh/id_rsa':
6
Last login: Sun Jul 29 02:22:34 2018 from 192.168.10.138
7
Managed by ansible
9
logout
10
Connection to centos7-1 closed.
11
[[email protected] .ssh]$ ssh centos7-1
12
Enter passphrase for key '/home/user1/.ssh/id_rsa':
13
Last login: Sun Jul 29 02:43:07 2018 from 192.168.10.138
14
Managed by ansible
15
16
logout
17
Connection to centos7-1 closed.
Copied!
as you can see each time we are asked to enter passphrase and that was what we were seeking for inorder to stop a hacker if our system get compromised. There is way to stick passphrase to the current user session and keept if for next ssh connections inorder to avoid entering passphrase again and again:
    ssh-agent - agent to hold private key for single sign-on
    ssh-add - tool to add a key to the agent
1
[[email protected] .ssh]$ ssh-agent /bin/bash
2
[[email protected] .ssh]$ ssh-add
3
Enter passphrase for /home/user1/.ssh/id_rsa:
4
Identity added: /home/user1/.ssh/id_rsa (/home/user1/.ssh/id_rsa)
5
[[email protected] .ssh]$ ssh centos7-1
6
Last login: Sun Jul 29 02:43:15 2018 from 192.168.10.138
7
Managed by ansible
Copied!
And it could happend again and agian :
2
logout
3
Connection to centos7-1 closed.
4
[[email protected] .ssh]$ ssh centos7-1
5
Last login: Sun Jul 29 02:54:43 2018 from 192.168.10.138
6
Managed by ansible
8
logout
9
Connection to centos7-1 closed.
10
[[email protected] .ssh]$ ssh centos7-1
11
Last login: Sun Jul 29 02:58:39 2018 from 192.168.10.138
12
Managed by ansible
13
14
logout
15
Connection to centos7-1 closed.
Copied!
Until we exit from the bash that uses associated key with that:
1
[[email protected] .ssh]$ exit
2
exit
3
[[email protected] .ssh]$ ssh centos7-1
4
Enter passphrase for key '/home/user1/.ssh/id_rsa':
Copied!
we would need to enter passphrase again.

SSH Client tools

Here we want to take a look at most usefull client tools(ssh, scp, sftp) commands:
SSH commands
Description
ssh -V
Shows ssh client version
Connect to the remote host, add "-v" for verbose mode
ssh -l user1 server1.example.com
Connect to the remote host, add "-v" for verbose mode.
ssh [email protected] <command>
Running <command> on the remote host over ssh
Enable Xforwarding on the clients side, X11Forwarding should be enabled on the server side in sshd_config file.

SCP Commands

We can use the scp command to copy the files securely between the local host and remote host using the ssh authentication.
    Copy file from the localhost to the remotehost:
1
scp localhostfile.txt [email protected]:/home/user1/localhostfile.txt
Copied!
    Copy file from the remotehost to the localhost:
1
scp [email protected]:/home/user1/remotehostfile.txt remotehostfile.txt
Copied!

sftp commands

SFTP (SSH File Transfer Protocol) is a secure file transfer protocol. It runs over the SSH protocol. It supports the full security and authentication functionality of SSH.
sftp commands
Desciption
get connected to the sftp server
sftp> ?
getting help
sftp> lpwd
Check Present Working Directory
sftp>ls
Listing files and directories in remote system
sftp>lls
Listing files and directories in local
sftp> put local.profile
upload file
sftp> mput *.txt
upload multiple files
sftp> get myfile.txt
get a single file
sftp> mget *.txt
get multiple files
sftp> cd testdir
switching directory on remote
sftp> lcd test
switching directory in local
sftp> mkdir mytestdir
creates directory on remote system
sftp> lmkdir mydownloads
creates directory on local machine
sftp > rm mytempfile.txt
remove file
sftp> rmdir myremotedir
remove directory
sftp> !
exit sftp shell
Last modified 2yr ago