Skip to content

Instantly share code, notes, and snippets.

@leommoore
Last active March 31, 2021 17:03
Show Gist options
  • Save leommoore/5618606 to your computer and use it in GitHub Desktop.
Save leommoore/5618606 to your computer and use it in GitHub Desktop.
Linux - SSH (Secure SHell) Basics

#Linux - SSH (Secure SHell) Basics ssh is a secure mechanism to interact with a computer remotely.

##Logging on ssh allows a user to log in remotely to a server with a ssh server running (ie openSSHServer). For example:

ssh pi@192.168.1.2

or, using a domain name like:

ssh pi@server1.mycompany.com

will log in the user pi to the specified computer.

##SSH Session Timeout If you are experiencing problems with your session timing out. This can be resolved by editing the ssh config file using:

sudo nano /etc/ssh/ssh_config

## Keep sessions from timing out
Host *
  ServerAliveInterval 55
  ServerAliveCountMax 2

##Compression If you want to add compression add this to the config:

Compression yes

##Transferring files scp (Secure CoPy) allows a user to copy a file onto a computer running a scp server.

scp file pi@192.168.1.2:/home/pi

This will copy the file into the /home/pi directory on the remote computer. You can also copy a file from the remote machine to the user's machine using:

scp pi@192.168.1.2:/home/pi/file

This will copy the file in the directory in /home/pi/ to the current directory.

If you need to use a different port then use:

scp pi@192.168.1.2:/home/pi/file -P 1234

You can also copy all the subdirectories to the destination using the -r switch:

scp -r file pi@192.168.1.2:/home/pi

However if you are only making updates, not re-creating the whole thing, you will probably find things move along faster if you use rsync over ssh instead of scp. Probably something like

rsync -av -e ssh source user@target:dest

##Running Commands Remotely You can also run commands in the remote computer using ssh user@server command. For example:

ssh pi@192.168.1.2 pwd

will return the current directory. You can also run multiple command by enclosing them in quotes and separating them with a semi-colon such as:

ssh pi@192.168.1.2 "pwd; ls -la"

This will give your the current directory, followed by the file in the directory. You can also feed the results into a local command.

ssh pi@192.168.1.2 ps | grep node

In this case the process list (ps) is being returned from the remote computer and fed into grep on the local computer which is checking to see if node is running.

##Running Applications Remotely You can also run GUI applications remotely on your local Linux instance if you have X11Forwarding yes in your /etc/ssh/sshd_config file. To run gedit remotely for example:

ssh -X pi@192.168.1.2 gedit

##SSH Aliases It is also possible to shorten the ssh commands by adding the host details to the ~/.ssh/config file.

Host work
  User pi
  Hostname 192.168.1.2
  Port 1234

You can then access the machine using:

ssh work

You can also use and identity file to remove the need to use a user and password to authenticate. This can be particularly useful when you want to have a process to copy files from one server to another (ie backup process).

Host pi@192.168.1.2
  Port 1234
  IdentityFile ~/.ssh/id_rsa.pub

##Creating a key pair Running ssh-keygen will generate a pair of key files in the ~/.ssh directory. By default the names are id_rsa and id_rsa.pub. The id_rsa file is readable only by your account and its contents are further protected by encrypting them with supplied during generation.

Copy the .pub file to the server and add its contents to ~/.ssh/authorized_keys. You don't need a password. You can copy and add the key with this command.

ssh-copy-id -i ~/.ssh/id_rsa.pub pi@server1.mycompany.com

Security Note: Key based authentication can be a security risk, especially if you cannot ensure the security of your local client.

##Adding the key pair to your agent You may encounter an error:

Agent admitted failure to sign using the key

If this happens, you may need to add the key pair to your ssh agent so that it is presented when you connect. This can be done by:

ssh-add

This will add the default id_rsa to your ssh agent.

##Changing the SSH Port It is a good idea to change the default port from Port 22 to some other port to reduce the number of malicious login attempts. There are many people scanning the default ports and attempting to log in using default or weak user logins. Note: ports below 1024 are normally reserved for system processes so it is better to choose one above 1024.

# What ports, IPs and protocols we listen for
Port 1234 

##Removing Password Authentication If you are using Key Based Authentication you can disable authentication via passwords to increase security by editing the remote server's config file which is usually in /etc/ssh/sshd_config and changing the PasswordAuthentication parameter from 'yes' to 'no'.

# Change to no to disable tunnelled clear text passwords
PasswordAuthentication no

##Restricting Users It is also a good idea to not permit root login's. You can still login and switch to the root user later.

# Authentication:
LoginGraceTime 120
PermitRootLogin no
StrictModes yes

You can also go further and specify which users can login remotely over ssh by adding AllowUsers to the end of the config file and specifying the users that can login.

AllowUsers leo john

##Restricting Remote IP Addresses It is always a good idea to restrict the access to users and hosts that you trust. To do this you need to:

Edit the /etc/hosts.deny and create a rule

sshd: ALL

This will deny access to all hosts. Next, edit the /etc/hosts.allow file and add:

sshd: 192.168.1 201.130.177.31

This will give access to the 192.168.1.0/24 network and the 201.130.177.31 host.

More information on the syntax for hosts.allow and hosts.deny can be found on man hosts_access. Information on additional options can be found on man hosts_options.

##Agent Forwarding It is also possible to copy from one server to another server from a remote location (ie your laptop). In this case you may want to do the following:

scp admin@server2.remote.com:/var/log/server.log logkeeper@server3.remote.com:/backup/server.log.$(date+%Y%m%d)

In this case you may get an error:

Permission denied, please try again
Permission denied, please try again
Permission denied (publickey,password)
lost connection

This is because when you run scp on your local machine, it first contacts server2.remote.com. But since we are copying the file to a third host, scp also invokes a second scp command to server3.remote.com. It is this second command that has the error. This is because while you have an active session to server2 and you can instruct it to copy to server3 but since you are not connected to server3 then you cannot authenticate using a password or key. You can edit your users config file in ~/.ssh/config, or the system-wide configuration file (usually in /etc/ssh/ssh_config) and add the following:

Host * 
ForwardAgent yes

This will cause the request for authentication to be forwarded to all remote hosts. When agent forwarding is turned on, the SSH authentication requests aren't passed directly to the local SSH agent.

##sshd_config

# Package generated configuration file
# See the sshd_config(5) manpage for details

# What ports, IPs and protocols we listen for
Port 22

# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes

# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600

# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes

# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 768

# Logging
SyslogFacility AUTH
LogLevel INFO

# Authentication:
LoginGraceTime 120
PermitRootLogin yes
StrictModes yes

RSAAuthentication yes
PubkeyAuthentication yes
#AuthorizedKeysFile     %h/.ssh/authorized_keys

# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2

RSAAuthentication yes
PubkeyAuthentication yes
#AuthorizedKeysFile     %h/.ssh/authorized_keys

# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes

# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no
                                                             
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes

# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication yes

# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no

#MaxStartups 10:30:60
#Banner /etc/issue.net

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

Subsystem sftp /usr/lib/openssh/sftp-server

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment