LinuxQuestions.org
Help answer threads with 0 replies.
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - Security
User Name
Password
Linux - Security This forum is for all security related questions.
Questions, tips, system compromises, firewalls, etc. are all included here.

Notices


Reply
  Search this Thread
Old 06-18-2015, 09:28 PM   #1
jamtat
Member
 
Registered: Oct 2004
Distribution: Debian/Ubuntu, Arch, Gentoo, Void
Posts: 132

Rep: Reputation: 24
securing ssh using iptables?


I was recently reading an article on better securing ssh. It recommended taking a look at /var/log/auth.log to see if there had been any suspicious activity. I did that, and sure enough, someone with a Chinese IP had been trying to ssh into my home desktop using root, admin, and postgres logins. It looks like they spent about 1.5 hours without success, then gave up. So I started looking into ways to tighten up ssh on my machine.

I should mention that ssh runs on an alternate port before getting to this machine, so the simplest form of obscuring the machine's presence has been taken. But that, of course, doesn't provide much security. I took the additional step today of disallowing root logins. But I wanted to do more.

The original article I'd read talked about setting up fail2ban, which I'm sure is effective. But I was hoping I'd find some way, using utilities already on my machine, to do something similar. So I ran across some articles that described how to create some iptables rules that would help defeat rogue logins by causing packets to be dropped after a certain number of unsuccessful logins within a certain time frame. A pretty decent, though slightly dated, description of how to do that can be found at https://blog.bigdinosaur.org/securin...with-iptables/

So, what do all the security experts here think of using an approach like that to better secure ssh? Would that, in combination with disallowing root log ins and running ssh on an alternate port, give reasonably good security for the home desktop computer? I should mention that this machine does sit behind a firewall, but the firewall is configured to forward to the alternate port to port 22 on the desktop.
 
Old 06-18-2015, 09:41 PM   #2
mralk3
Senior Member
 
Registered: May 2015
Distribution: Slackware, OpenBSD
Posts: 1,559

Rep: Reputation: 882Reputation: 882Reputation: 882Reputation: 882Reputation: 882Reputation: 882Reputation: 882
You should set up public key authentication and disable password log in. I would also switch the port you are using (since someone already knows its there) to a different port. Set up sshd to only allow log ins from an unprivileged user, usually the one user you use. Or set up sshd to only allow log ins from users in a specific group. You can also use rate limits in your iptable rules.

Aside from that you can use denyhosts (http://denyhosts.sourceforge.net/) or fail2ban (which you are already aware of). Daemons like denyhosts and fail2ban are mostly meant for servers that have public facing ip addresses.

Most of these methods can be found on LQ, one such example is found here: http://www.linuxquestions.org/questi...miting-881833/
 
Old 06-18-2015, 10:02 PM   #3
jamtat
Member
 
Registered: Oct 2004
Distribution: Debian/Ubuntu, Arch, Gentoo, Void
Posts: 132

Original Poster
Rep: Reputation: 24
Thanks for your input, mralk3. I've actually gone ahead and implemented the iptables scheme described in that blog posting. I'm currently testing to see how/if it will help.

I do want to implement public key authentication. In fact, I tried to set it up some time ago (probably a year or more?) using what seemed to me at the time a decent set of instructions. But somehow I could not get it working. I had to give up after a period of time and go back to password authentication. I still do want to set up public key encryption though. I'm currently doing another round of research on how to implement it. But I'm going to have to ask some questions before I can proceed further--initially about whether I'll need to undo any of what I've already done, of which I don't recall many details. Maybe I'll end up asking for advice later in this thread or in a different thread on this forum.

Last edited by jamtat; 06-18-2015 at 10:25 PM.
 
Old 06-18-2015, 10:23 PM   #4
Sefyir
Member
 
Registered: Mar 2015
Distribution: Linux Mint
Posts: 633

Rep: Reputation: 316Reputation: 316Reputation: 316Reputation: 316
I use this:

Code:
iptables -A INPUT -m recent --set --name SSH # Set SSH recent
iptables -A INPUT -p tcp --dport 22 ! -s 192.168.1.1/24 -m recent --name SSH --update --seconds 10 --hitcount 3 --rttl -m conntrack --ctstate NEW -j DROP # Drop if over counter
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
First rule sets the recent SSH marker
Each time someone connects to port 22 (not in LAN - 192.168.1.*), the hitcount goes up. If it's at or over three, it is dropped.
So someone connects 3 times in 10 second time period, dropped. 4, 5, 200 times - dropped.
If you connect 2 times in 10 second time period - it is accepted.

This has greatly reduced ssh attempts since there are a lot of dumb scripts that just keep trying as fast as they can - causing them all to drop.
It also lets me have full access since I rarely need more then 2 new connections in a 10 second time period.

Last edited by Sefyir; 06-18-2015 at 10:25 PM.
 
Old 06-18-2015, 10:26 PM   #5
berndbausch
LQ Addict
 
Registered: Nov 2013
Location: Tokyo
Distribution: Mostly Ubuntu and Centos
Posts: 6,211

Rep: Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958
Quote:
Originally Posted by jamtat View Post
I do want to implement public key authentication.
It's not clear to me where the difficulty is. On the server side it should work out of the box.

On the client side, you first have to create a key pair. On Linux/UNIX, ssh-keygen. If the client is Windows, your terminal emulator should have a tool for generating the key (PuTTY has puttygen, for example).

To copy the public key to the server, a comfortable tool is ssh-copy-id, but that requires password logon. I don't know if Windows has something similar.

Manually copying the public key to the server requires setting the permissions of the key file correctly - in a nutshell, as tight as possible (400, though 600 works as well) and owned by the login account.

Not many moving parts, not that hard to do IMHO.
 
Old 06-18-2015, 10:29 PM   #6
jamtat
Member
 
Registered: Oct 2004
Distribution: Debian/Ubuntu, Arch, Gentoo, Void
Posts: 132

Original Poster
Rep: Reputation: 24
Interesting contribution, Seyfir. One thing that's not clear to me is how long the dropping goes on. Does this scheme somehow log the IP of the connector, denying further attempts from that IP for a period of time (and, if so, for how long?). Or does it just create a momentary interruption? I guess I need to learn how better to interpret iptables rules
 
Old 06-18-2015, 10:39 PM   #7
jamtat
Member
 
Registered: Oct 2004
Distribution: Debian/Ubuntu, Arch, Gentoo, Void
Posts: 132

Original Poster
Rep: Reputation: 24
Quote:
Originally Posted by berndbausch View Post
It's not clear to me where the difficulty is. On the server side it should work out of the box.
It's not clear to me, either. If it were, I would have fixed it a year or so ago when I tried to get all this configured.
Quote:
Originally Posted by berndbausch View Post
On the client side, you first have to create a key pair. On Linux/UNIX, ssh-keygen.
I did that. This is Linux, btw. I've been using Linux long enough I should be able to do this sort of stuff. But I started late, and my memory is not improving with age. So I got stuck and need to get moving anew.
Quote:
Originally Posted by berndbausch View Post
To copy the public key to the server, a comfortable tool is ssh-copy-id, but that requires password logon.
I believe that's what I used. I'll have to try and relocate the set of directions I found on the web and was using.
Quote:
Originally Posted by berndbausch View Post
Manually copying the public key to the server requires setting the permissions of the key file correctly - in a nutshell, as tight as possible (400, though 600 works as well) and owned by the login account.
Hmmm. They're set for 644, but are owned by root: maybe file ownership was part of my problem?
Quote:
Originally Posted by berndbausch View Post
Not many moving parts, not that hard to do IMHO.
Famous last words . Like I said, I'm not by any means a newbie. But I may have some mild dyslexia that causes me to get mixed up easily with client/server configuration scenarios. Anyway, I've really got to tackle it this time: I've got Chinese IP's trying to log in by ssh and I'm not even entirely certain they've not already compromised this machine. So, back to the drawing board.

Last edited by jamtat; 06-18-2015 at 10:40 PM.
 
Old 06-18-2015, 10:41 PM   #8
Sefyir
Member
 
Registered: Mar 2015
Distribution: Linux Mint
Posts: 633

Rep: Reputation: 316Reputation: 316Reputation: 316Reputation: 316
As long as the computer logging in has connected more then 2 times in 10 seconds, it is dropped. So if you wait 10 seconds you are free to attempt again. I like this because it cripples brute force attempts by forcing the script or attacker to intelligently determine that it can only do 2 new attempts every 10 seconds. However, it isn't a huge annoyance on a actual user with no long lasting (+ 5 minutes) consequences.

The tracking is by ip address yes. So another computer with a separate ip address may make its own attempts without being affected by other computers.
So while it is a momentary interruption, continuing to attempt to login will continue to trigger the rule.

As a analogy..

If you say hello and I say Hi.
You say hello again and I say Hi.
If you say hello again I say nothing.

If you wait 10 seconds and say hello I will say Hi.
But if you keep saying hello (hello,hello,hello...) I will never say anything again. At least, until you shut up for 10 seconds.

____

Quote:
Hmmm. They're set for 644, but are owned by root: maybe file ownership was part of my problem?
It must be 600. It cannot be world readable or it will fail. It must also be owned by the user - not root.
Also it's the private key that must be 600 - public keys do not need to be secured.
Also ~/.ssh should be 700 (not sure if ssh requires this or not but it's smart to do)

Last edited by Sefyir; 06-18-2015 at 10:47 PM.
 
Old 06-19-2015, 09:57 AM   #9
Habitual
LQ Veteran
 
Registered: Jan 2011
Location: Abingdon, VA
Distribution: Catalina
Posts: 9,374
Blog Entries: 37

Rep: Reputation: Disabled
2 alternatives to consider...
Code:
/etc/hosts.allow:sshd: 127.0.0.1 192.168.1.1/24 <your_homeip> <another_safe_ip>
/etc/hosts.deny:sshd: ALL
But this is no longer supported IF openssh-server is > v 6.6
to see your version, run
Code:
sudo dpkg -l openssh-server
and fail2ban works out of the box for ssh attempts.
 
Old 06-19-2015, 02:39 PM   #10
jamtat
Member
 
Registered: Oct 2004
Distribution: Debian/Ubuntu, Arch, Gentoo, Void
Posts: 132

Original Poster
Rep: Reputation: 24
Thanks for the additional input, folks. I'm liking Seyfir's iptables rules more and more: it seems a simpler and more manageable solution for my scenario. I may well end up just flushing my current rules, adding his, and editing /etc/iptables/rules.v4 so that it contains those rules. Of course I'd also want to get rid of iptables-persistent and start using a script at /etc/network/if-pre-up.d/firewall that contains
Code:
#!/bin/sh
/sbin/iptables-restore < /etc/iptables/rules.v4
to make the rules persist across reboots. So far so good.
 
Old 06-19-2015, 02:47 PM   #11
jamtat
Member
 
Registered: Oct 2004
Distribution: Debian/Ubuntu, Arch, Gentoo, Void
Posts: 132

Original Poster
Rep: Reputation: 24
On the public-key-authentication front, it seems what I said was in error. I rechecked files under the .ssh directory of the user I'm trying to log in as, and they're all 0600 (think I got confused about root ownership of files since I'd also looked at file properties under /etc/ssh).

Let me ask about the following. When I ssh into this machine--which has not yet had password log-ins disabled, here's what I get:
Quote:
me ~ $ ssh -p 12345 me.mymachine.com
Enter passphrase for key '/home/me/.ssh/id_rsa':
Enter passphrase for key '/home/me/.ssh/id_dsa':
Enter passphrase for key '/home/me/.ssh/id_ecdsa':
me@me.mymachine.com's password:
That started showing up, as I recall, when I initially tried setting up public key encryption (previously, I would just get a password prompt). This is a bit confusing to me: is this expected behavior?

Also, I was at one time loooking into passwordless log in, since I am most often logging into this machine from my LAN. Are passwordless and public key encryption pretty much the same thing when it comes to log-ins?

Last edited by jamtat; 06-19-2015 at 02:50 PM.
 
Old 06-19-2015, 05:51 PM   #12
jamtat
Member
 
Registered: Oct 2004
Distribution: Debian/Ubuntu, Arch, Gentoo, Void
Posts: 132

Original Poster
Rep: Reputation: 24
I seem to be making progress on getting public-key authentication operational. I think my main point of confusion was concerning the password/passwordless options. After some more research and experimentation, I now have the following understanding. A "passwordless" public key authentication is one that has used no password in the creation of the key. When the key is generated, text like the following is part of the process:
Quote:
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
As I'm understanding this, if, instead of entering a password you just hit "enter," then, when you want to use this key (having copied it over to your ssh server), you initiate an ssh session and you will not be prompted for any password: you will simply be logged right into that machine. Have I understood this correctly?

I, on the other hand, entered a password when I created my key. Thus, when I was trying to ssh into my system, I was being prompted for a password. Which confused me, since I thought the point of generating this key was to enable passwordless log-ins.

Anyone have further corrections to offer on the matters I've just described?

Last edited by jamtat; 06-19-2015 at 05:53 PM.
 
Old 06-19-2015, 07:14 PM   #13
Sefyir
Member
 
Registered: Mar 2015
Distribution: Linux Mint
Posts: 633

Rep: Reputation: 316Reputation: 316Reputation: 316Reputation: 316
You should have a password for your private keys. This is preferable since it will encrypt the private key. This makes it so if someone were to access the files on your computer, they could not access the private key and imitate you. Your private key is you for all intents and purposes.
If you don't want to type in the password each time, you can use a ssh-agent to unlock the private key into ram whenever you login to desktop session. Check with your distro for the best way to implement that.

There is a little confusion on "passwordless" logins because of why you're typing in the password.

When you try to access a server and it asks for your password, you are telling the server what you know (username and password). Anyone with this knowledge can login
When you try to access a server and it asks for your key, you are unlocking the key with the password and presenting the server with what you have (the private key*). Only someone with the key and ability to unlock it can access the server.
You can have the key automatically unlocked (as explained with ssh-agent above). In this scenario since the private key is unlocked on login, it permits a "passwordless" login. However it continues to be very secure with minimal interference. Having a what-you-know setup is less secure since if someone guesses the password.. they are let in.

I would suggest reading into iptables and how firewalls work. This is more effective then "dropping in" code and can let you modify it to your own needs.
This has been a very helpful link and guide for me.
https://www.frozentux.net/documents/iptables-tutorial/

As for loading at boot, I have init loading this script. I don't suggest using it, rather using it as a reference. Hope this helps!

Code:
#!/bin/bash
### BEGIN INIT INFO
# Provides:          iptables
# Required-Start:    $network $remote_fs $syslog
# Required-Stop:     $network $remote_fs $syslog
# Should-Start:      $portmap
# Should-Stop:       $portmap
# X-Start-Before:    nis
# X-Stop-After:      nis
# Default-Start:     2 
# Default-Stop:      1
# X-Interactive:     false
# Short-Description: Iptable setup
# Description:       Sets iptable rules
#                    
### END INIT INFO

ipt="/sbin/iptables"

loadrules() {

if [ -e /etc/iptables_ruleset ]; then iptables-restore < /etc/iptables_ruleset && exit 0; fi

$ipt -F
$ipt -X

$ipt -P INPUT DROP
$ipt -P FORWARD DROP
$ipt -P OUTPUT ACCEPT

# Input table
$ipt -A INPUT -i lo -j ACCEPT # Permit loopback
$ipt -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT # Permit established connections

$ipt -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j SSH # SSH

$ipt -A INPUT -s 192.168.1.1/24 -j REJECT 

# SSH chain
$ipt -A SSH -p tcp --dport 22 -m recent --set --name SSH
$ipt -A SSH -p tcp --dport 22 ! -s 192.168.1.1/24 -m recent --update --rttl --seconds 10 --hitcount 3 --name SSH -j DROP
$ipt -A SSH -p tcp --dport 22 -j ACCEPT

iptables-save > /etc/iptables_ruleset
}

removerules() {
$ipt -P INPUT ACCEPT
$ipt -P FORWARD ACCEPT
$ipt -P OUTPUT ACCEPT
$ipt -F
$ipt -X
}

restartrules() {
rm /etc/iptables_ruleset
loadrules
}

case "$1" in
	start)
		loadrules
		;;
	stop)
		removerules
		;;
	restart)
		restartrules
		;;
	*)
		echo "Usage: $0 start|stop" >&2
		exit 3
		;;
esac
* Technically I believe the ssh-agent indicates to the server you have the private key and thus should be permitted access.
According to man ssh-agent

Code:
     The idea is that the agent is run in the user's local PC, laptop, or terminal.  Authentication data need not be stored on any other machine, and authentication passphrases never go over the network.  However, the connection to
     the agent is forwarded over SSH remote logins, and the user can thus use the privileges given by the identities anywhere in the network in a secure way.
..
     The agent will never send a private key over its request channel.  Instead, operations that require a private key will be performed by the agent, and the result will be returned to the requester.  This way, private keys are not
     exposed to clients using the agent.

Last edited by Sefyir; 06-19-2015 at 07:18 PM.
 
Old 06-20-2015, 04:09 AM   #14
berndbausch
LQ Addict
 
Registered: Nov 2013
Location: Tokyo
Distribution: Mostly Ubuntu and Centos
Posts: 6,211

Rep: Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958
Quote:
Originally Posted by jamtat View Post
Are passwordless and public key encryption pretty much the same thing when it comes to log-ins?
I'd say yes.

By the way, if you are interested in learning about ssh, I can recommend the book SSH mastery by Michael Lucas. It's refreshingly thin and an easy read. The Kindle version is 10$ (I don't know the author and have no stake or affiliation whatsoever).
 
Old 06-20-2015, 12:00 PM   #15
jamtat
Member
 
Registered: Oct 2004
Distribution: Debian/Ubuntu, Arch, Gentoo, Void
Posts: 132

Original Poster
Rep: Reputation: 24
Thanks again for the input in this thread. I ended up going with a hybrid solution for the iptables part of this. I mainly followed directions I found at https://www.linode.com/docs/security...ng-your-server, though I had to adapt those a bit. I created the file /etc/iptables.firewall.rules and put there Seyfir's iptables rules, though some modifications were necessary (I ended up with a hybrid of the sample given at the linode link and Seyfir's rules). Then I created /etc/network/if-pre-up.d/firewall with appropriate content and chmod'd it, as stipulated in those linode directions. So I believe these modifications, in conjunction with finally getting public key authentication operational, I should be far more secure. For reference, here's what /etc/iptables.firewall.rules looks like:
Code:
*filter
# most rules below pilfered from https://www.linode.com/docs/security/securing-your-server
#  Allow all loopback (lo0) traffic and drop all traffic to 127/8 that doesn't use lo0
-A INPUT -i lo -j ACCEPT
-A INPUT -d 127.0.0.0/8 -j REJECT

#  Accept all established inbound connections
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

#  Allow all outbound traffic - you can modify this to only allow certain traffic
-A OUTPUT -j ACCEPT

#  Allow SSH connections so long as not more than 3 in 10 seconds are attempted, in which latter case drop packets (courtesy Seyfir at Linuxquestions)
-A INPUT -m recent --set --name SSH
-A INPUT -p tcp --dport 22 ! -s 192.168.1.1/24 -m recent --name SSH --update --seconds 10 --hitcount 3 --rttl -m conntrack --ctstate NEW -j DROP
-A INPUT -p tcp --dport 22 -j ACCEPT

#  Allow ping
-A INPUT -p icmp --icmp-type echo-request -j ACCEPT

#  Log iptables denied calls
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7

#  Drop all other inbound - default deny unless explicitly allowed policy
-A INPUT -j DROP
-A FORWARD -j DROP

COMMIT

Last edited by jamtat; 06-20-2015 at 02:00 PM.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Securing SSH jonnybinthemix Linux - Newbie 3 06-04-2014 06:00 AM
Securing SSH ZilverZtream Linux - Security 5 12-10-2004 03:33 PM
securing using firestarter or iptables PennyroyalFrog Linux - Security 3 10-13-2004 01:36 PM
Securing iptables kola Linux - Security 20 09-13-2004 03:28 AM
securing ssh robberttheman Linux - Security 8 08-27-2004 07:36 AM

LinuxQuestions.org > Forums > Linux Forums > Linux - Security

All times are GMT -5. The time now is 11:48 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration