OpenSSH is the implementation of the SSH protocol. OpenSSH is recommended for remote login, making backups, remote file transfer via scp or sftp, and much more. SSH is perfect to keep confidentiality and integrity for data exchanged between two networks and systems. However, the main advantage is server authentication, through the use of public key cryptography. From time to time there are rumors about OpenSSH zero day exploit mentioend below. Here are a few things you need to tweak in order to improve OpenSSH server security.
OpenSSH Rumors
Over the past 24 hours we've had a number of readers tell us that there is an OpenSSH exploit in active use. We cannot confirm its existence, other than a DOS exploit for OpenSSH that is on Milw0rm. If you have any concrete evidence of this (not rumors or URLs to blogs where people are discussing that there might be a problem) please let us know via our contact form. Again, no rumors and no links to discussions of rumors please. We need reports of active exploitation or other evidence that this a real issue.UPDATE 1: One reader sent us a URL to a site showing the active exploitation of a vulnerable system that looks like it was recorded last Friday. So far this is the only "evidence" of an attack. It is against an older version of OpenSSH so if this is the source of the rumor, then it is NOT a problem with the most updated version. Without giving away everything (Google is your friend if you want to find the original), here is a snip from the log:
anti-sec:~/pwn# cd xpl/
anti-sec:~/pwn/xpl# ./0pen0wn -h xx.yy.143.133 -p 22
[+] 0wn0wn – anti-sec group
[+] Target: xx.yy.143.133
[+] SSH Port: 22
[~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~>]
sh-3.2# export HISTFILE=/dev/null
sh-3.2# id
uid=0(root) gid=0(root)
groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)
sh-3.2# uname -a
Linux xx.yy.net 2.6.24.5-grsec-hostnoc-4.0.0-x86_64-libata
#1 SMP Mon Aug 25 15:56:12 EDT 2008 x86_64 x86_64 x86_64 GNU/Linux
sh-3.2# head -n1 /etc/shadow
root:$1$t4e0hufX$UH4Q5jTj93EEAODNrSaWO/:14412:0:99999:7:::
sh-3.2# w
03:43:43 up 7 days, 54 min, 1 user, load average: 9.01, 9.78,
10.73
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root pts/0 125.238.144.224 20:17 7:26m 13:18 13:18 htop
sh-3.2# pwd
/root
UPDATE 2: Just to make things interesting, here is an anonymous email we received today. The author gave us permission to share the comments but not his/her name.
Expect the SSH exploit to be made public before BH/DC. I have proof that I can't share (sorry), that this exploit does exist, does not work against current versions of SSH, and is actively being used by members of the anti-sec movement.
However, you have no reason to believe anything I am telling you here, as its nothing that could not have been made public by the single blog posting that (amazingly) became public yesterday. As well, I am not giving you my contact information, etc. So, its no more then a rumor I am giving you, sorry for that.
It would be really great however if you suggested everyone to upgrade OpenSSH to the newest version, on the off chance the rumor is true thought, right? No harm if you are getting bad information in that case.
Once it becomes public (sorry, I am being fed information by someone that wants me to keep it private, and in trust I can't share), I will have some logs I can forward on to you.
Of course, that "proof" may be the log file that we snipped above. Regardless, keep your OpenSSH updated, control the access, and by all means turn it off if you don't need it (don't uninstall the updated binaries, just turn off the service - that way if it's needed you won't accidentally have an out of date version running.)
UPDATE 3: We've received a few emails that lend credibility to the rumor, and we've received a few more that paint an interesting picture - that the reports are all part of a cover-up to hide another breach that was caused by a sysadmin's mistake. What we are lacking is the actual exploit code. So if this is "for real" would somebody slip us a copy and leave it under the door mat? (Actually, our contact form is the best place.) We won't tell anybody where it came from but it sure would put a lid on this story.
Tip: Disable Root SSH Login
It’s a very bad idea to allow root user to login via SSH. It’s no secret that every Linux system has a user named root. Your server is vulnerable to brute-force attack if root is able to login via SSH. Instead, we can create another user that have the ability to SSH login and disable root SSH login. Thus, the attacker has to figure out both the user name and password.Use
useradd
to create another user. Replace newuser with your preferred user name.useradd newuserset a password for the user:
passwd newuserVerify that this new user can login via SSH and is able to use
su -
command to switch to root user. Then edit the SSH daemon configuration file.nano /etc/ssh/sshd_configFind the following line:
#PermitRootLogin yesChange it to the following which disables root SSH login
PermitRootLogin noAlso add the following line at the end of this file. This line ensures the new user can login via SSH.
AllowUsers newuserSave and close this file. Then restart SSH service
systemctl restart sshdFrom here on out, only the new user can login via SSH and after that this user can switch to root using
su -
command.If an attacker tries to login as a user with SSH disabled (such as root), you will see the following line in your SSH log.
Failed password for invalid user rootHere
invalid
means the user doesn’t exist on the system or has no SSH login permission. If a user who has SSH login permission typed a wrong password, then you will see a line like:Failed password for the-username
Tip: Change SSH Listening Port
By default, SSH server listens on port 22. Although some say that crackers can use port scanner such asnmap
to figure out what port SSH daemon listens on, but after changing the listening port of SSH, it almost eliminated all attacks against SSH on my server.To change the SSH listening port, edit the SSH daemon configuration file.
nano /etc/ssh/sshd_configFind this line:
Port 22You can change the port to whatever port your like, just make sure that other programs on the server is not using the port. Typically you want to change it to a port between 1 and 1024.
Save and close the file. Then restart SSH.
systemctl restart sshdWhen using SSH client, you need to specify the new port like below.
ssh user@remote-server -p new-port-numberYou also need to specify the new port when using
ssh-copy-id
and scp
.Tip : Scare Them Away
When the user tries to login via SSH, we can show a warning message to the user that if they are not authorized, they should go away. Or they will be prosecuted.To show a warning message, edit the SSH daemon configuration file.
nano /etc/ssh/sshd_configFind the following line:
#Banner noneRemove the pound sign (#). Then change none to a text file on your server like below.
Banner /etc/bannerIn the
/etc/banner
file, we can add a warning message like the following. You can be creative and show your preferred message to bad guys.**************************************************************************** This computer system is for authorized users only. All activities are logged and regularly checked. Unauthorized use of the system will be prosecuted to the extent of law. ****************************************************************************Save the configuration file, then restart SSH service.
Tip : Restrict IP Addresses Using Firewall
The IP address of your home computer is most likely a dynamic IP address. Servers on the other hand have fixed IP address. On a public-facing SSH server, we can configure iptables firewall to allow certain IP addresses to connect to SSH server and deny all other IP addresses. Having more than one server makes it easy for you to restrict IP addresses because servers have fixed IP address.Try to find some low-end Linux VPS.
As a matter of fact, I have a single-core, 128MB Linux VPS for $6 per year, a single-core 512MB Linux VPS for $10 per year. They are not meant for hosting my Web site but for other purposes like backup server or email server. They also help me to implement IP address restriction in OpenSSH server. I don’t ssh into my main Linux server directly from my desktop computer. What I do is ssh into one of my low-end Linux VPSs and then from there ssh into my main Linux server.
I recommend finding at least two low-end Linux VPSs from different hosting providers, then add these fixed IP addresses to the allow list of OpenSSH server in case one of your hosting providers shut down their business.
Using iptables Firewall to restrict IP
To prevent the current SSH connections drops out, we need to allow established sessions with the following iptables command.sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPTThen allow your own IP address to connect to the SSH port with the below command. Replace your-ip-address with your real IP address such as 74.125.128.103.
sudo iptables -A INPUT -p tcp --dport 22 -s your-ip-address -j ACCEPTLet me explain this command.
-A INPUT
is used to append the above rule to the INPUT chain which deals with incoming traffic.-p tcp
specifies the protocol is TCP since SSH daemon listens on TCP port.--dport 22
specifies the destination port is 22 which is the default SSH port. If you changed your SSH port, then you also need to adjust the port here.-s your-ip-address
specifies the source IP address.-j ACCEPT
means jump to the ACCEPT target which will allow this SSH connection.
After that’s done, reject all other IP addresses to connect to your SSH server. In the below command, we didn’t specify the source IP address which means all other IP addresses will be disallowed.
sudo iptables -A INPUT -p tcp --dport 22 -j REJECTCheck iptables firewall rules with the below command.
sudo iptables -LIf later you want to add a new IP address to the allowed list, then you need to insert a new rule.
sudo iptables -I INPUT -p tcp --dport 22 -s your-ip-address -j ACCEPTThe
-I
option is used to insert the above firewall rule to the INPUT chain. By default, it will insert the above rule as the first rule in the INPUT chain. Note that if we append this new rule to the bottom of INPUT chain, then this rule has no effect because it comes after the “reject all other IP” rule.Remember that iptables firewall rules by default are not persistent across reboots. If you accidentally locked yourself out by iptables firewall, you just need to reboot your server in the control panel of your hosting provider to reset iptables firewall rules.
Tip : Enable PrintLastLog
PrintLastLog is used to tell you when did the last login happened and from what IP address. You can see it after you ssh into your server. It looks something like this:Last login: Thu Jun 2 04:10:08 2016 from 12.34.56.78If you don’t recognize the IP address then you know something is not right. To enable PrintLastLog, edit SSH daemon configuration file.
nano /etc/ssh/sshd_configFind this line:
#PrintLastLog yesRemove the pound sign. Save the file and restart SSH service.
Your SSH Server is Being Attacked
Run the following command on your Linux server and you will see how often malicious people are trying to get SSH access to your server. To be honest, some of my SSH servers are being attacked every minute.sudo journalctl -xe | grep sshdIt’s very common for bad guy to brute-force attack the root user password. Here’s a snippet output of the above command on my Linux server.
sshd[27389]: Failed password for invalid user root from 116.31.116.30 port 42803 ssh2 sshd[27389]: Failed password for invalid user root from 116.31.116.30 port 42803 ssh2 sshd[27389]: Failed password for invalid user root from 116.31.116.30 port 42803 ssh2 sshd[27389]: Received disconnect from 116.31.116.30: 11: [preauth] sshd[27389]: PAM 2 more authentication failures; logname= uid=0 euid=0 tty=ssh ruser= rhost=116.31.116.30 user=rootBelow are tips to harden your SSH server against attacks.
Default Config Files and SSH Port
- /etc/ssh/sshd_config – OpenSSH server configuration file.
- /etc/ssh/ssh_config – OpenSSH client configuration file.
- ~/.ssh/ – Users ssh configuration directory.
- ~/.ssh/authorized_keys or ~/.ssh/authorized_keys – Lists the public keys (RSA or DSA) that can be used to log into the user’s account
- /etc/nologin – If this file exists, sshd refuses to let anyone except root log in.
- /etc/hosts.allow and /etc/hosts.deny : Access controls lists that should be enforced by tcp-wrappers are defined here.
- SSH default port : TCP 22
#1: Disable OpenSSH Server
Workstations and laptop can work without OpenSSH server. If you need not to provide the remote login and file transfer capabilities of SSH, disable and remove the SSHD server. CentOS / RHEL / Fedora Linux user can disable and remove openssh-server with yum command:# chkconfig sshd off
# yum erase openssh-server
Debian / Ubuntu Linux user can disable and remove the same with apt-get command:
# apt-get remove openssh-server
You may need to update your iptables script to remove ssh exception rule. Under CentOS / RHEL / Fedora edit the files /etc/sysconfig/iptables and /etc/sysconfig/ip6tables. Once done restart iptables service:
# service iptables restart
# service ip6tables restart
Redhat / CentOS / Fedora Linux Open Port
Q. You Have Redhat Enterprise Linux 5 server with Iptabeles firewall enabled. By default it is only allowing port 22. How do I open port 80 / 143 / 110 on Linux? I’ve started all services but don’t know how to open port using iptables.
A. By default iptables firewall stores its configuration at /etc/sysconfig/iptables file. You need to edit this file and add rules to open port number. This file only avilable under
Red Hat Enterprise Linux 3 / 4 / 5 and above
=> Old Red hat Linux version
=> CentOS 4 and above
=> Fedora Linux
Open port 80
Open flle /etc/sysconfig/iptables:# vi /etc/sysconfig/iptables
Append rule as follows:
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
Save and close the file. Restart iptables:
# /etc/init.d/iptables restart
Open port 110
Append rule as follows:-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 110 -j ACCEPT
Open port 143
Append rule as follows:-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 143 -j ACCEPT
Restart iptables service
Type the following command:# service iptables restart
Verify that port is open
Run following command:netstat -tulpn | less
Make sure iptables is allowing port 80 / 110 / 143 connections:
iptables -L -n
Refer to iptables man page for more information about iptables usage and syntax:
man iptables
#2: Only Use SSH Protocol 2
SSH protocol version 1 (SSH-1) has man-in-the-middle attacks problems and security vulnerabilities. SSH-1 is obsolete and should be avoided at all cost. Open sshd_config file and make sure the following line exists:Protocol 2
#3: Limit Users’ SSH Access
By default all systems user can login via SSH using their password or public key. Sometime you create UNIX / Linux user account for ftp or email purpose. However, those user can login to system using ssh. They will have full access to system tools including compilers and scripting languages such as Perl, Python which can open network ports and do many other fancy things. One of my client has really outdated php script and an attacker was able to create a new account on the system via a php script. However, attacker failed to get into box via ssh because it wasn’t in AllowUsers.Only allow root, vivek and jerry user to use the system via SSH, add the following to sshd_config:
AllowUsers root vivek jerryAlternatively, you can allow all users to login via SSH but deny only a few users, with the following line:
DenyUsers saroj anjali fooYou can also configure Linux PAM allows or deny login via the sshd server. You can allow list of group name to access or deny access to the ssh.
Linux PAM configuration that allows or deny login via the sshd server
The idea is very simple you want to limit who can use sshd based on a list of users. The text file contains a list of users that may not log in (or allowed to log in) using the SSH server. This is used for improving security.
PAM (Pluggable authentication modules) allows you to define flexible mechanism for authenticating users. See below how to deny or allow users using sshd configuration option. However, if you want to block or deny a large number of users, use PAM configuration.
A note for new sys admins
- Backup all data and PAM configuration files before any modification
- Please be careful to perform the configuration option. Wrong configuration can lock down all login access including root access.
- Read this Linux-PAM configuration file syntax guide
- Now continue reading below for pam_listfile.so configration…
Use of pam_listfile.so module
This PAM module authenticates users based on the contents of a specified file. For example, if username exists in a file /etc/sshd/ssh.allow, sshd will grant login access.How do I configure pam_listfile.so module to deny access?
You want to block a user, if user-name exists in a file /etc/sshd/sshd.deny file.Open /etc/pam.d/ssh (or /etc/pam.d/sshd for RedHat and friends)
# vi /etc/pam.d/ssh
Append following line:
auth required pam_listfile.so item=user sense=deny file=/etc/sshd/sshd.deny onerr=succeed
Save and close the file
Now add all usernames to /etc/sshd/sshd.deny file. Now a user is denied to login via sshd if they are listed in this file:
# vi /etc/sshd/sshd.deny
Append username per line:
user1
user2
...
Restart sshd service:
# /etc/init.d/sshd restart
Understanding the config directives:
- auth required pam_listfile.so : Name of module required while authenticating users.
- item=user : Check the username
- sense=deny : Deny user if existing in specified file
- file=/etc/sshd/sshd.deny : Name of file which contains the list of user (one user per line)
- onerr=succeed : If an error is encountered PAM will return status PAM_SUCCESS.
How do I configure pam_listfile.so module to allow access?
You want to ALLOW a user to use ssh, if user-name exists in a file /etc/sshd/sshd.allow file.Open /etc/pam.d/ssh (or /etc/pam.d/sshd for RedHat and friends)
# vi /etc/pam.d/ssh
Append following line:
auth required pam_listfile.so item=user sense=allow file=/etc/sshd/sshd.allow onerr=fail
Save and close the file.
Now add all usernames to /etc/sshd/sshd.allow file. Now a user is allowed to login via sshd if they are listed in this file.
# vi /etc/sshd/sshd.allow
Append username per line:
tony
om
rocky
Restart sshd service (optional):
# /etc/init.d/sshd restart
Now if paul try to login using ssh he will get an error:
Permission denied (publickey,keyboard-interactive).
Following log entry recorded into my log file (/var/log/secure or /var/log/auth.log file)
tail -f /var/log/auth.log
Output:
Jul 30 23:07:40 p5www2 sshd[12611]: PAM-listfile: Refused user paul for service ssh Jul 30 23:07:42 p5www2 sshd[12606]: error: PAM: Authentication failure for paul from 125.12.xx.xxUnderstanding the config directives:
- auth required pam_listfile.so : Name of module required while authenticating users.
- item=user : Check or specify the username
- sense=allow : Allow user if existing in specified file
- file=/etc/sshd/sshd.allow : Name of file which contains the list of user (one user per line)
- onerr=fail : If filename does not exists or username formatting is not coreect it will not allow to login.
OpenSSH Deny or Restrict Access To Users and Groups
SSH restricting which users can log in server
OpenSSH has two directives for allowing and denying ssh user access. You can use the following config for restricting which users can log in to your Linux or Unix or BSD bases server.
Restricting which users can log in
The syntax is:DenyUsers user1 user2 user3
Use DenyUsers to block user login. You can use wild cards as well as user1@cyberciti.com (user1 is not allowed to login from cyberciti.com host) pattern.
DenyGroups group1 group2
A list of group names, if user is part of primary of supplementary group login access is denied. You can use wildcards. Please note that you cannot use a numeric group or username ID. If these directives are not used, default is to allow everyone.
Allowing selected users or group explicitly to log in
The syntax is:AllowUsers user1 user2
This directive is opposite of DenyUsers directive i.e. user1 and user2 are only allowed to log in into the server.
AllowGroups group1 group2
This directive is opposite of DenyGroups directive i.e. members of group1 and group2 users are only allowed to log in into the server.
Examples
To help secure your OpenSSH based server you can be explicitly allowing users sai and vivek to log in via SSH. Edit the file /etc/ssh/sshd_config as the super user:sudo vi /etc/ssh/sshd_configAdd/edit/append the following line:
AllowUsers sai vivekSave and close the file. Next, restart your SSH daemon service:
## Ubuntu/debian user ## sudo service ssh restart # only for systemd based Ubuntu/Debian 8.x+ users # sudo systemctl restart ssh #### RHEL/CentOS/Fedora Linux user type #### sudo service sshd restart # only for systemd based RHEL/CentOS v7+ users # sudo systemctl restart sshd
Restricting root user
For security reason you should always block access to root user and group on a Linux or Unix-like systems. First, make sure at least one user is allowed to use ‘su -‘ or ‘sudo’ command on the server. Open the /etc/ssh/sshd_config file, enter:# vi /etc/ssh/sshd_config
$ sudo vi /etc/ssh/sshd_config
Append following names (directives):
DenyUsers root DenyGroups rootAlso make sure following set in sshd_config:
PermitRootLogin noSave the file and restart the sshd. This is a secure setup and you are restricting the users allowed to access the system via SSH with four above directives.
#4: Configure Idle Log Out Timeout Interval
User can login to server via ssh and you can set an idel timeout interval to avoid unattended ssh session. Open sshd_config and make sure following values are configured:ClientAliveInterval 300 ClientAliveCountMax 0You are setting an idle timeout interval in seconds (300 secs = 5 minutes). After this interval has passed, the idle user will be automatically kicked out (read as logged out). See how to automatically log BASH / TCSH / SSH users out after a period of inactivity for more details.
Linux / UNIX Automatically Logout BASH / TCSH / SSH Users After a Period of Inactivity
My development and testing webserver is used by over 100s of users. These users login from Windows XP, Linux, Mac OS X system via ssh/putty client. How do I set or automatically log users out after a period of inactivity under RHEL/Fedora/CentOS Linux server to improve server security and save some resources?
You can configure Linux or Unix-like system to automatically log users out after a period of inactivity. Simply login as the root user and create a file called /etc/profile.d/autologout.sh, enter:
# vi /etc/profile.d/autologout.sh
Append the following code:
TMOUT=300 readonly TMOUT export TMOUTSave and close the file. Set permissions:
# chmod +x /etc/profile.d/autologout.sh
Above script will implement a 5 minute idle time-out for the default /bin/bash shell.
A note about tcsh/csh user
You can also create tcsh version as follows:# vi /etc/profile.d/autologout.csh
Append the following code:
set -r autologout 5Save and close the file. Set permissions, enter:
# chmod +x /etc/profile.d/autologout.csh
Dealing with ssh clients
SSH allows administrators to set an idle timeout interval. After this interval has passed, the idle user will be automatically logged out. Open /etc/ssh/sshd config file, enter:# vi /etc/ssh/sshd_config
Find ClientAliveInterval and set to 300 (5 minutes) as follows:
ClientAliveInterval 300 ClientAliveCountMax 0Save and close the file. Restart sshd service:
# service sshd restart
OR use the following command on RHEL/CenOS 7.x or Fedora Linux server:
# systemctl restart sshd
#5: Disable .rhosts Files
Don’t read the user’s ~/.rhosts and ~/.shosts files. Update sshd_config with the following settings:IgnoreRhosts yesSSH can emulate the behavior of the obsolete rsh command, just disable insecure access via RSH.
#6: Disable Host-Based Authentication
To disable host-based authentication, update sshd_config with the following option:HostbasedAuthentication no
#7: Disable root Login via SSH
There is no need to login as root via ssh over a network. Normal users can use su or sudo (recommended) to gain root level access. This also make sure you get full auditing information about who ran privileged commands on the system via sudo. To disable root login via SSH, update sshd_config with the following line:PermitRootLogin noHowever, someone made point:
Saying “don’t login as root” is h******t. It stems from the days when people sniffed the first packets of sessions so logging in as yourself and su-ing decreased the chance an attacker would see the root pw, and decreast the chance you got spoofed as to your telnet host target, You’d get your password spoofed but not root’s pw. Gimme a break. this is 2005 – We have ssh, used properly it’s secure. used improperly none of this 1989 will make a damn bit of difference. -Bob
#8: Enable a Warning Banner
Set a warning banner by updating sshd_config with the following line:Banner /etc/issueSample /etc/issue file:
---------------------------------------------------------------------------------------------- You are accessing a XYZ Government (XYZG) Information System (IS) that is provided for authorized use only. By using this IS (which includes any device attached to this IS), you consent to the following conditions: + The XYZG routinely intercepts and monitors communications on this IS for purposes including, but not limited to, penetration testing, COMSEC monitoring, network operations and defense, personnel misconduct (PM), law enforcement (LE), and counterintelligence (CI) investigations. + At any time, the XYZG may inspect and seize data stored on this IS. + Communications using, or data stored on, this IS are not private, are subject to routine monitoring, interception, and search, and may be disclosed or used for any XYZG authorized purpose. + This IS includes security measures (e.g., authentication and access controls) to protect XYZG interests--not for your personal benefit or privacy. + Notwithstanding the above, using this IS does not constitute consent to PM, LE or CI investigative searching or monitoring of the content of privileged communications, or work product, related to personal representation or services by attorneys, psychotherapists, or clergy, and their assistants. Such communications and work product are private and confidential. See User Agreement for details. ----------------------------------------------------------------------------------------------Above is standard sample, consult your legal team for exact user agreement and legal notice details.
#8: Firewall SSH Port # 22
You need to firewall ssh port # 22 by updating iptables or pf firewall configurations. Usually, OpenSSH server must only accept connections from your LAN or other remote WAN sites only.Netfilter (Iptables) Configuration
Update /etc/sysconfig/iptables (Redhat and friends specific file) to accept connection only from 192.168.1.0/24 and 202.54.1.5/29, enter:-A RH-Firewall-1-INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 22 -j ACCEPT -A RH-Firewall-1-INPUT -s 202.54.1.5/29 -m state --state NEW -p tcp --dport 22 -j ACCEPTIf you’ve dual stacked sshd with IPv6, edit /etc/sysconfig/ip6tables (Redhat and friends specific file), enter:
-A RH-Firewall-1-INPUT -s ipv6network::/ipv6mask -m tcp -p tcp --dport 22 -j ACCEPTReplace ipv6network::/ipv6mask with actual IPv6 ranges.
*BSD PF Firewall Configuration
If you are using PF firewall update /etc/pf.conf as follows:pass in on $ext_if inet proto tcp from {192.168.1.0/24, 202.54.1.5/29} to $ssh_server_ip port ssh flags S/SA synproxy state
#9: Change SSH Port and Limit IP Binding
By default SSH listen to all available interfaces and IP address on the system. Limit ssh port binding and change ssh port (by default brute forcing scripts only try to connects to port # 22). To bind to 192.168.1.5 and 202.54.1.5 IPs and to port 300, add or correct the following line:Port 300 ListenAddress 192.168.1.5 ListenAddress 202.54.1.5A better approach to use proactive approaches scripts such as fail2ban or denyhosts (see below).
#10: Use Strong SSH Passwords and Passphrase
It cannot be stressed enough how important it is to use strong user passwords and passphrase for your keys. Brute force attack works because you use dictionary based passwords. You can force users to avoid passwords against a dictionary attack and use john the ripper tool to find out existing weak passwords. Here is a sample random password generator (put in your ~/.bashrc):genpasswd() { local l=$1 [ "$l" == "" ] && l=20 tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs }Run it:
genpasswd 16
Output:
uw8CnDVMwC6vOKgW
#11: Use Public Key Based Authentication
Use public/private key pair with password protection for the private key. See how to use RSA and DSA key based authentication. Never ever use passphrase free key (passphrase key less) login.SSH Public Key Based Authentication – Howto
The SSH protocol is recommended for remote login and remote file transfer which provides confidentiality and security for data exchanged between two computer systems, through the use of public key cryptography. The OpenSSH server provides this kind of setup under Linux. It is installed by default. This how-to covers generating and using ssh keys for automated usage such as:
- Automated Login using the shell scripts.
- Making backups.
- Run commands from the shell prompt etc.
Task: Generating SSH Keys
First, log on to your workstation ( for example log on to workstation called admin.fbsd.nixcraft.org as vivek user). Please refer the following sample setup – You will be log in, on your local system, AS THE USER you wish to make passwordless ssh connections.ssh key based authentication
Create the cryptographic Key on FreeBSD / Linux / UNIX workstation, enter:
ssh-keygen -t rsa
Assign the pass phrase (press [enter] key twice if you don’t want a passphrase). It will create 2 files in ~/.ssh directory as follows:
- ~/.ssh/id_rsa : identification (private) key
- ~/.ssh/id_rsa.pub : public key
scp .ssh/id_rsa.pub vivek@rh9linux.nixcraft.org:.ssh/authorized_keys2
From FreeBSD workstation login to server:
ssh rh9linux.nixcraft.org
Changing the pass-phrase on workstation (if needed):
ssh-keygen -p
Use of ssh-agent to avoid continues pass-phrase typing
At freebsd workstation type:
ssh-agent $BASH
ssh-add
Type your pass-phrase
Now ssh server will not use prompt for the password. Above two commands can be added to your ~/.bash_profile file so that as soon as you login into workstation you can set the agent.
Deleting the keys hold by ssh-agent
To list keys, enter:ssh-add -l
To delete all keys, enter:
ssh-add -D
To delete specific key, enter:
ssh-add -d key
Howto Linux / UNIX setup SSH with DSA public key authentication (password less login)
Q. How do you set-up SSH with DSA public key authentication? I have Linux laptop called tom and remote Linux server called jerry. How do I setup DSA based authentication so I don̢۪t have to type password?A. DSA public key authentication can only be established on a per system / user basis only i.e. it is not system wide. You will be setting up ssh with DSA public key authentication for SSH version 2 on two machines:
#1 machine : your laptop called tom
#2 machine : your remote server called jerry
Command to type on your laptop/desktop (local computer)
First login to local computer called tom and type the following command.Step #1: Generate DSA Key Pair
Use ssh-keygen command as follows:$ ssh-keygen -t dsa
Output:
Enter file in which to save the key (/home/vivek/.ssh/id_dsa): Press [Enter] key Enter passphrase (empty for no passphrase): myPassword Enter same passphrase again: myPassword Your identification has been saved in /home/vivek/.ssh/id_dsa. Your public key has been saved in /home/vivek/.ssh/id_dsa.pub. The key fingerprint is: 04:be:15:ca:1d:0a:1e:e2:a7:e5:de:98:4f:b1:a6:01 vivek@vivek-desktopCaution: a) Please enter a passphrase different from your account password and confirm the same.
b) The public key is written to /home/you/.ssh/id_dsa.pub.
c) The private key is written to /home/you/.ssh/id_dsa.
d) It is important you never-ever give out your private key.
Step #2: Set directory permission
Next make sure you have correct permission on .ssh directory:$ cd
$ chmod 755 .ssh
Step #3: Copy public key
Now copy file ~/.ssh/id_dsa.pub on Machine #1 (tom) to remote server jerry as ~/.ssh/authorized_keys:$ scp ~/.ssh/id_dsa.pub user@jerry:.ssh/authorized_keys
Command to type on your remote server called jerry
Login to your remote server and make sure permissions are set correct:$ chmod 600 ~/.ssh/authorized_keys
Task: How do I login from client to server with DSA key?
Use scp or ssh as follows from your local computer:$ ssh user@jerry
$ ssh user@remote-server.com
$ scp file user@jerry:/tmp
You will still be asked for the passphrase for the DSA key file each time you connect to remote server called jerry, unless you either did not enter a passphrase when generating the DSA key pair.
Task: How do I login from client to server with DSA key but without typing a passhrase i.e. password-less login?
Type the following command at shell prompt:$ exec /usr/bin/ssh-agent $SHELL
$ ssh-add
Output:
Enter passphrase for /home/vivek/.ssh/id_dsa: myPassword Identity added: /home/vivek/.ssh/id_dsa (/home/vivek/.ssh/id_dsa)Type your passhrase once. Now, you should not be prompted for a password whenever you use ssh, scp, or sftp command.
If you are using GUI such as Gnome use the command:
$ ssh-askpass
OR
$ /usr/lib/openssh/gnome-ssh-askpass
To save your passphrase during your GNOME session under Debian / Ubuntu, do as follows:
a) Click on System
b) Select Preferences
c) Select Session
d) Click on New
e) Enter “OpenSSH Password Management” in the Name text area
f) Enter /usr/lib/openssh/gnome-ssh-askpass in the command text area.
g) Click on close to save the changes
h) Log out and then log back into GNOME. After GNOME is started, a dialog box will appear prompting you for your passphrase. Enter the passphrase requested. From this point on, you should not be prompted for a password by ssh, scp, or sftp.
#12: Use Keychain Based Authentication
keychain is a special bash script designed to make key-based authentication incredibly convenient and flexible. It offers various security benefits over passphrase-free keys. See how to setup and use keychain software.#13: Chroot SSHD (Lock Down Users To Their Home Directories)
By default users are allowed to browse the server directories such as /etc/, /bin and so on. You can protect ssh, using os based chroot or use special tools such as rssh. With the release of OpenSSH 4.8p1 or 4.9p1, you no longer have to rely on third-party hacks such as rssh or complicated chroot(1) setups to lock users to their home directories.#14: Use TCP Wrappers
TCP Wrapper is a host-based Networking ACL system, used to filter network access to Internet. OpenSSH does supports TCP wrappers. Just update your /etc/hosts.allow file as follows to allow SSH only from 192.168.1.2 172.16.23.12 :sshd : 192.168.1.2 172.16.23.12
#15: Disable Empty Passwords
You need to explicitly disallow remote login from accounts with empty passwords, update sshd_config with the following line:PermitEmptyPasswords no
#16: Thwart SSH Crackers (Brute Force Attack)
Brute force is a method of defeating a cryptographic scheme by trying a large number of possibilities using a single or distributed computer network. To prevents brute force attacks against SSH, use the following softwares:- DenyHosts is a Python based security tool for SSH servers. It is intended to prevent brute force attacks on SSH servers by monitoring invalid login attempts in the authentication log and blocking the originating IP addresses.
- Explains how to setup DenyHosts under RHEL / Fedora and CentOS Linux.
- Fail2ban is a similar program that prevents brute force attacks against SSH.
- security/sshguard-pf protect hosts from brute force attacks against ssh and other services using pf.
- security/sshguard-ipfw protect hosts from brute force attacks against ssh and other services using ipfw.
- security/sshguard-ipfilter protect hosts from brute force attacks against ssh and other services using ipfilter.
- security/sshblock block abusive SSH login attempts.
- security/sshit checks for SSH/FTP bruteforce and blocks given IPs.
- BlockHosts Automatic blocking of abusive IP hosts.
- Blacklist Get rid of those bruteforce attempts.
- Brute Force Detection A modular shell script for parsing application logs and checking for authentication failures. It does this using a rules system where application specific options are stored including regular expressions for each unique auth format.
- IPQ BDB filter May be considered as a fail2ban lite.
#17: Rate-limit Incoming Port # 22 Connections
Both netfilter and pf provides rate-limit option to perform simple throttling on incoming connections on port # 22.Iptables Example
The following example will drop incoming connections which make more than 5 connection attempts upon port 22 within 60 seconds:#!/bin/bash inet_if=eth1 ssh_port=22 $IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent --set $IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent --update --seconds 60 --hitcount 5 -j DROPCall above script from your iptables scripts. Another config option:
$IPT -A INPUT -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state NEW -m limit --limit 3/min --limit-burst 3 -j ACCEPT $IPT -A INPUT -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT $IPT -A OUTPUT -o ${inet_if} -p tcp --sport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT # another one line example # $IPT -A INPUT -i ${inet_if} -m state --state NEW,ESTABLISHED,RELATED -p tcp --dport 22 -m limit --limit 5/minute --limit-burst 5-j ACCEPTSee iptables man page for more details.
*BSD PF Example
The following will limits the maximum number of connections per source to 20 and rate limit the number of connections to 15 in a 5 second span. If anyone breaks our rules add them to our abusive_ips table and block them for making any further connections. Finally, flush keyword kills all states created by the matching rule which originate from the host which exceeds these limits.sshd_server_ip="202.54.1.5" table <abusive_ips> persist block in quick from <abusive_ips> pass in on $ext_if proto tcp to $sshd_server_ip port ssh flags S/SA keep state (max-src-conn 20, max-src-conn-rate 15/5, overload <abusive_ips> flush)
#18: Use Port Knocking
Port knocking is a method of externally opening ports on a firewall by generating a connection attempt on a set of prespecified closed ports. Once a correct sequence of connection attempts is received, the firewall rules are dynamically modified to allow the host which sent the connection attempts to connect over specific port(s). A sample port Knocking example for ssh using iptables:$IPT -N stage1 $IPT -A stage1 -m recent --remove --name knock $IPT -A stage1 -p tcp --dport 3456 -m recent --set --name knock2 $IPT -N stage2 $IPT -A stage2 -m recent --remove --name knock2 $IPT -A stage2 -p tcp --dport 2345 -m recent --set --name heaven $IPT -N door $IPT -A door -m recent --rcheck --seconds 5 --name knock2 -j stage2 $IPT -A door -m recent --rcheck --seconds 5 --name knock -j stage1 $IPT -A door -p tcp --dport 1234 -m recent --set --name knock $IPT -A INPUT -m --state ESTABLISHED,RELATED -j ACCEPT $IPT -A INPUT -p tcp --dport 22 -m recent --rcheck --seconds 5 --name heaven -j ACCEPT $IPT -A INPUT -p tcp --syn -j door
- fwknop is an implementation that combines port knocking and passive OS fingerprinting.
- Multiple-port knocking Netfilter/IPtables only implementation.
#19: Use Log Analyzer
Read your logs using logwatch or logcheck. These tools make your log reading life easier. It will go through your logs for a given period of time and make a report in the areas that you wish with the detail that you wish. Make sure LogLevel is set to INFO or DEBUG in sshd_config:LogLevel INFO
#20: Patch OpenSSH and Operating Systems
It is recommended that you use tools such as yum, apt-get, freebsd-update and others to keep systems up to date with the latest security patches.Other Options
To hide openssh version, you need to update source code and compile openssh again. Make sure following options are enabled in sshd_config:# Turn on privilege separation UsePrivilegeSeparation yes # Prevent the use of insecure home directory and key file permissions StrictModes yes # Turn on reverse name checking VerifyReverseMapping yes # Do you need port forwarding? AllowTcpForwarding no X11Forwarding no # Specifies whether password authentication is allowed. The default is yes. PasswordAuthentication noVerify your sshd_config file before restarting / reloading changes:
# /usr/sbin/sshd -t
Tighter SSH security with two-factor or three-factor (or more) authentication.
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
DeleteYour Ssh Server Is Being Attackedssh Server Hardening ~ System Admin Share >>>>> Download Now
Delete>>>>> Download Full
Your Ssh Server Is Being Attackedssh Server Hardening ~ System Admin Share >>>>> Download LINK
>>>>> Download Now
Your Ssh Server Is Being Attackedssh Server Hardening ~ System Admin Share >>>>> Download Full
>>>>> Download LINK xR
John Smith Mar 23, 2018 at 8:36 PM
ReplyDeleteLEARN HOW TO BECOME MILLIONAIRE ONLINE
This is one of best online course about how to become millionaire online.
It is difficult to become a millionaire, so perhaps this course is only rated 4.4*.
source: How to become millionaire online in one year