Harden the Secure Shell (SSH) & Create a Firewall
Let’s solidify the virtual private server by tweaking the OpenSSH security configuration and adding an iptables firewall.
If you’re following this series, you probably just want to get on and set up the web server, add the sites and host away. Sure, understandable.
But just like you don’t build a house on sand, you can’t set up a quality Linux host without first laying a secure foundation, ensuring a strong unmanaged VPS solution.
Setup Unmanaged VPS: The Ubuntu-Nginx Guide
Take your virtual private server from zero to hero
.. from blank box to cute-as server ..
with this easy-to-follow copy/paste guide.
22+ parts with video, here’s the index.
In the last part of this series Encrypt Data with OpenSSH & Auto-Login with PuTTY we secured dataflow between our local to remote machines, as well as simplifying the login process. If you’re using Linux locally you followed Setup openSSH for Linux-to-Linux instead and, lucky for you (or more likely thanks to Linux) it was easier.
So here, with a proper connection to support us, we turn our attention to grounding the server. We can do the lot in one go. (And praise be to that, huh
.)
Video: Solidify Server & Remote Shell
Watch the, er, guvideo for a better idea of how to do this.
Harden the Secure Shell (SSH)
Logged in at the CLI, type this to open the SSH configuration file:-
.. If you get a message like:-
.. no worries, that’s because we need to install Nano (which is a nice user-friendly text editor). Do this:-
.. and type y for yes when prompted, hitting return. The screen will spiel off and there may be some nagging about your locale not being set properly .. tssk, Linux is soooo impatient .. just pretend it’s the wife and ignore it. (Sorry, female VPS’ers .. you do know I’m only joshin’ huh
. Well, ish.)
Er, that sudo thing, hmmn …
What the Bejeebers is Sudo?
sudo, prefixing an Ubuntu command, gives our non-root user Super User permissions.
Then, for example, we can make core configuration changes that otherwise we could only perform by logging out, then back in as root (…then back out from root and back in to our regular username.) Wharrapalava!
When you use sudo, you’ll be prompted to give the root user password. That’s a good thing: it means you will be more aware that you are, potentially, playing with fire and, if the answer isn’t here, ‘cue Google’.
Right, so that’s all pretty crystal. Forgot where I was now. Oh yes, we did this:-
In this config file, find and change the following values. Here’s a little detail, too, if you really want to know:-
- Port 22
- - change from default 22 (and puzzle hackers), ie to “Port 54321″. (Don’t use 54321, that’s remotely obvious too.)
- PermitRootLogin yes
- - change “yes” to “no”. Makes root login impossible. *
- PasswordAuthentication yes
- - uncomment the line (lose the #) and change “yes” to “no”. Prevents login using a password, now unnecessary with OpenSSH keys. **
- X11Forwarding yes
- - change “yes” to “no”. X11 is a protocol enabling a GUI option.
- UsePAM yes
- - change “yes” to “no”. PAM is a password authentication agent.
And add 2 lines at the end of the file:-
- UseDNS no
- - new line. This prevents possible reverse host lookup problems.
- AllowUsers guv
- - substitute “guv” for your user name. More users? Add names here, separated by single spaces.
* With some unmanaged VPS providers like Linode or Slicehost, you can use the Ajax Console to login as root, in case of emergency.
** If you want to connect to your Linux distro from computers other than your main Windows box, using your user password rather than the PuTTY authentication keys, leave this set to “no”.
We’ll reload SSH to realise these changes. But first…
Set Up A Firewall Using iptables
iptables is a firewall & routing service, pretty much, set out via a bunch of rules. We’ll configure it on a pretty basic but essential level. You’ll need root, Super User permissions to toy with this, so type:-
After confirming the root password, save the pre-existing ruleset:-
…if that command throws an error, maybe your iptables aren’t installed yet. Try this:-
Complete the installation, then have another go:-
Create this blank file:-
…and paste this lot, below, into that blank file, to create our firewall:-
Before saving the file, you have to make one change. Look for the line…
…and change the Port 30000 to the port number you added above. Can’t remember? Hey, it’s in the sshd_config file. It had said Port 22. In my example, I changed it to 54321, so I would replace 30000 with, er, 54321! Damn, this is easy.
Of course, you may have more specific firewall requirements. Hmmn, that’s another tutorial, but iptables and Google go well together. Probably it’s not a bad idea to revisit your iptables later on, anyway.
Save that open file by hitting CTRL-X, then Enter.
Let’s execute our new ruleset:-
We’ll tweak a file to ensure the new rules are remembered after reboots. Open:-
Look for this line:-
…and add this line after it:-
Save and close.
Testing SSH
NOTE: Don’t logout from the CLI. JUST DON’T! Yet.
Reload SSH, enabling those new settings from above:-
What you do now depends on whether, locally, you’re a Linus Torvalds fan or whether you’re stuck with that Gates bloke.
I’m a Sensible Linux Person and Really Smug About It
.. where:-
- -p says we’re about to specify a non-default port
- 54321 is your new port as designated in the sshd config file
I Love Viruses Oh God It’s Blue Screened Again
Obviously, this takes longer ..
Open PuTTY. If you’ve followed Encrypt Data with OpenSSH & Auto-Login with PuTTY of this series – you did do that, didn’t you?! – then right-click the Pageant icon (the monitor wearing the hat, looks like a spaghetti western character, minus his cheroot) and click New session. If you didn’t follow the Part 5, I guess you know what you’re doing
Right, we need to make one simple change in our PuTTY configuration, to the Saved session profile we created in Encrypt Data with OpenSSH & Auto-Login with PuTTY. Do this:-
Click on your new Saved session profile (mine was called guv Session in the video, if that helps), then click Load.
In the Port field that currently says 22, you got it, add the new port number. My new number is 54321.
Now click Save.
Cross your fingers.
Double click the Saved session profile. All being well, you’ll get another one of those security alerts, that we saw in Set Up the Command Line Interface (CLI) using PuTTY. Click Yes. You’re in. Great, you can log in and out, at will.
If that didn’t work for you, retrace your steps, using that CLI we kept open. (You may need more caffeine.) In a worst case scenario, as I said above, many VPS providers have an emergency shell access. Linode, for example, has their Ajax console.
Fast Fwd
That’s it for the firewall and securing your Linux box with an advanced SSH configuration. In Edit bashrc for User-Friendly Linux, plus System Updates we’ll carry out some general housekeeping, making the CLI more user-friendly and updating the system and locale. Then in PHP5, MySQL and Xcache we’re really cooking on gas before, in Add a Domain Zone to Your VPS, we well on the way to adding our first test site and getting generally far too excited.
Hey, here’s the index…
Setup Unmanaged VPS: The Ubuntu-Nginx Guide
Take your virtual private server from zero to hero
with this easy-to-follow copy/paste guide.
“My local PC runs Windows” Show me for Linux
“My local PC runs Linux” Show me for Windows
22+ parts with video, here’s the index ..
-
Setup Unmanaged VPS: The Ubuntu-Nginx Guide
Introducing vpsBible’s how-to guide for setting up a super-charged unmanaged VPS featuring Ubuntu and Nginx.
-
VPS (Virtual Private Server) vs Shared vs Dedicated
Before getting stuck in, let’s compare the web host types in detail and weigh up the differences between managed & unmanaged VPS.
-
Set Up a VPS Linux Distribution
Opening a VPS hosting account, we’ll choose, configure & launch a Linux server ‘distribution’.
-
Set Up Command Line Interface (CLI) using PuTTY
Now we’ve got a server to play with, we’ll connect to it, using the ’ssh’ protocol for a super-secure link.
-
Create a Linux User & Set Permissions
Initially you’ve logged into your remote Linux machine as ‘root’. We’ll add you as a user now, with root or SuperUser permissions.
-
Encrypt Data with OpenSSH & Auto-Login with PuTTY
Now we can use ‘authentication keys’ to shore up our connection while simplifying login to an automated, password-free yet secure process.
-
Harden the Secure Shell (SSH) & Create a Firewall
The final security step: galvanizing the OpenSSH protocol and setting up an ‘iptables’ firewall. Now the server is rock ruddy solid.
-
Edit bashrc for User-Friendly Linux, plus System Updates
We use the terminal a whole lot so let’s cut ourselves a break and create some command shortcuts, then update the server.
-
Add a Domain Zone to Your VPS
To make your server aware of yourDomain.com you’ll need a few ‘DNS’ records. Damn this is simple I’m practically asleep!
-
Prepare Linux Server for Email with Postfix
In order to send and receive email from our web applications we’ll install some software and tweak the ‘RDNS’ record.
-
Install PHP5 & MySQL – The One-Stop FastCGI Index Page
Add PHP5 & MySQL, but which FastCGI method is best? Here’s the benchmarking, 4 ways to install/compile, add caching modules & more.
-
Nginx (better than Apache) Web Server
Let’s install this supersonic web server, tweaking its file structure & adding default configuration files.
-
Setup FileZilla for Secure FTP (SFTP)
There’s FTP, and then there’s ‘Secure FTP’. We’ll set up FileZilla using SFTP – and those authentication keys – for secure file transfers.
-
Serve Multiple Sites & Blogs with Virtual Hosts
We want a website folder structure, some permissions, some site-specific configuration files and, hey, we’ll hook up ‘FastCGI’.
-
Adding Sub-Domains with Nginx
Need a sub-domain? If you do, here’s how to add subDomain.yourSite.com with an ‘A record’ and a configuration file.
-
Integrate A CMS Like WordPress, WP MU, Drupal etc
For those of you wanting to use a specific content framework, such as a CMS, blogging or forum software, pop in here and we’ll sort that out.
-
Google Apps for Domain-Specific Email
GA’s free Standard Edition for catchall webmail – POP-ping or IMAP-ped to your desktop client – saves precious server resources for your webs.
-
Moving Day! How to Move Your Blog or Site
Nearly there. Here’s the web site or blog migration guide, relocating to your VPS with minimal or no downtime.
Manage Unmanaged VPS: Ubuntu-Nginx Administration
Already set it up? We’d best maintain it then.
Toggle to the .. Ubuntu-Nginx Admin Index
Manage Unmanaged VPS: Ubuntu-Nginx Administration
Maintain your virtual private server with ..
.. cheatsheets, tutorials, tips & guides.
Head back to the .. Ubuntu-Nginx Installation Index
-
Nginx Control Panel: Here’s the Deal
You’re migrating shared-to-VPS and want a GUI like cPanel? No you don’t, not after you read this! What’s more, you don’t need one either.
-
Nginx Control Panel Workarounds
For every control panel module there’s an equivalent (and faster) terminal command. Let’s compare these.
-
Upgrade to Nginx Latest Version with ZERO Downtime
Keep Nginx up-to-date – and optimized for security. This guide shows precisely how *with no missed server requests*.
-
Compile an Advanced Nginx Module Configuration
Need special web server functions? Here’s how to install or upgrade Nginx with bespoke required modules & parameters.
-
Add Web Sites Nginx Cheatsheet
Once you’ve set up your first site, adding more gets easier. Especially when you refer to this. (Let’s face it, I’m just too good to you.)
-
Adding Sub-Domains with Nginx
Rather than add somesite.tld, maybe you want some.subsite.tld? Here’s how to set your A record using a DNS manager and the vhost file for Nginx.
-
Add/Delete MySQL Database from Command Line
Need a database? Want to bin an old db? This tutorial shows you how using the terminal command line console whatnot.
-
Configure phpMyAdmin for Nginx to Maintain MySQL
Rather than have to crunch databases via the command line, we can make life easier by adding this splendid tool to manage them.
-
Backup/Export MySQL DB with CLI & mysqldump
Here’s how to backup a database from the command line using the handy mysqldump utility.
-
Import MySQL Database using Command Line
Import data to a new database with this simple mysqldump guide .. great for reinstating an old backed-up db, for instance.
-
Batch Replace/Delete Data in MySQL Database
Change repetitive db data with a single command. Rather than manually find & alter each instance, isolate the lot & update multiple content.
-
LOST a MySQL Password? How to RESET it
Lost your MySQL password? That’s a bit of a bummer .. or it would be if you didn’t have this new password setup guide, huh.
-
Backup or Upload with Secure Copy SCP (Linux to Linux)
Never mind FTP m8! Save time and download/upload your files using encrypted SCP (secure copy), the #1 Linux-Linux file transfer solution.
-
Backup or Upload with PuTTY PSFTP (Windows/Linux)
Equivalent to the above, how to transfer your files if you’re unlucky enough to be running Windows for your local PC. Not that I’m biased.
-
*USEFULLY* Park A Spare Domain with Nginx
Got a spare domain name sat around doing nothing? Put it to some use, have it point its traffic at your primary domain. Here’s the deal ..
-
Password Protect Nginx Web Files/Directories
Maybe you want a hidden website directory, say, for projects, or are developing a site and want it off-limits ’till launch day. Top tip ..
-
Redirect Web Pages with Nginx Rewrite Rule
Here’s the syntax to point a site or blog to another domain. That way, for instance, traffic from a passive site benefits an active one.
-
Nginx Error & Access Logs
Need to troubleshoot some error, or want to find out who’s trying to hack your site? Here’s a start .. those tell-tale logs.
-
Subversion for Easy CMS Updates ie WordPress/Drupal/etc
A brief introduction to install and know about the power of Subversion, the version control system to keep scripts and platforms up-to-date.
-
You Tell Me …
Something missing? Probably. Let me know what you’d like included. And if it’s listed below, shout out anyhow and I’ll try to bump it.
Nginx Admin: In the Works ..
This lot’s marked for addition already:-
- Setup or Edit DNS using Bind
- Network Tools Troubleshooting Guide
- The Comprehensive Permissions Guide
- Configuring Nginx Rewrites
- Custom Website Error Page
- Setting up Cron Jobs
- Rsync for Incremental Remote-to-Local Backup
- Cron & Rsync for Automatic Backup
- Cron & mysqldump for Auto DB Backup
- Safeguard Bandwidth with Hotlink Protection
- Block Access with Nginx’ IP Deny
Got a Question? Want to Comment?
This site has no comments system. We've got a better system!
Please use the link at the top of the post and goto this topic's forum thread:-
- to help build community
- for a superior knowledge base
- to keep info in one place, not diluted between forum & comments.
For those posts ported from Guvnr.com (pre-Feb/2010), archive comments remain.
Handy info from these comments is in the process of being ported to the forum and attributed to the original author.
If you think this idea sucks, let me know.
Thank you.





















Install/Upgrade WORDPRESS with SUBVERSION - VPS Bible #15 - GUVNR June 8th, 2009 at 9:38 am
[...] Part 6: * Harden the Secure Shell (SSH) & Create a Firewall [...]
Chris Foster June 9th, 2009 at 2:06 pm
Following on from my earlier comment reagarding losing putty access, it dawned on me that I changed the SSH port and didn’t change it in the putty client…doh!
Back to part 11…yahoo!
Cheers,
Chris
the_guv June 9th, 2009 at 2:12 pm
LOL – I nearly asked about that but figured, hey, Chris already got to Part 13, he must’ve done that!! Crack on m8…enjoy.
Jason July 13th, 2009 at 5:59 pm
when configuring the ip tables just ‘su’ didn’t work for me, I needed to do ‘sudo su’.
the_guv July 14th, 2009 at 12:43 am
@Jason .. well, hmmn. sounds like a permissions error. i’d retrace those steps with a fine toothcomb. any more detail, like what deviations you’ve made from the series, and maybe i or others can help more.
Ben September 18th, 2009 at 3:43 pm
Worked perfectly, thanks – liked the bit about creating a new session incase you make a mistake! Was suprised I didnt, and it logged me in again fine – bonza.
Robert October 15th, 2009 at 9:09 pm
I don’t know where that previous message went.
Anyway the problem with the hanging reload of the iptables with the test file was traced back to the status NEW matching with the new SSH port.
Remove that status matching and the rules set will load flawlessly.
Jeff and Rob at Rackwire found this out.
I want to add to this that the adding the line to load the chains with the new rules set to /etc/network/interfaces didn’t survive a reboot/restart of the container. I’m not on Xen.
The comment lines at the top of that file read :
QUOTE
# This configuration file is auto-generated.
# WARNING: Do not edit this file, otherwise your changes will be lost.
# Please edit template /etc/network/interfaces.template instead.
UNQUOTE
But this is a great learning experience.
I’m enjoying the ride.
the_guv October 15th, 2009 at 9:27 pm
@Robert .. thank you, pleased you’re enjoying. Much more to come too .. writing a bunch of admin guides right now.
Clearly a bit of house-keeping for me there then. In the midst of a move to the Middle East, but will test and apply these fine tips, soon as. Appreciate that feedback.
Dunno what happened to your msg .. probably caught in Akismet’s spam filter. Hmmn, must go and have a wade in there too .. hate doing that, trawling the spam page is a bit like wandering through a red light district
Robert October 17th, 2009 at 7:49 pm
@theguv:
Looking forward to the admin guides.
Yeah Akismet, sometimes too much of the wrong censorship. You noticed where I’m from then ?
No, not housekeeping for you. More likely for me.
Are you going to Rake in the money?
Don’t forget about us.
Hope that your move to Dubai is a smooth one.
Robert October 20th, 2009 at 8:09 pm
Apologies coming your way.
There is absolutely nothing wrong with your rules set.
It bugged me to no end that the rules set didn’t work out of the box. So I traced and debugged the problem (in my own way).
I traced the problem back to the connection tracking part of iptables not being enabled.
ip_tables iptable_filter ip_conntrack ip_conntrack_ftp ipt_state ipt_LOG
Like I said, I’m not on Xen. And that was the other part of the problem.
On sh.tty Virtuozzo you do not run your own kernel.
So these modules have to be loaded from the default vz. They “forgot” to add them to the file /etc/vz/conf/199.conf with IPTABLES=
Making this rule useless (not being honored/executed) :
-A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT
And me having to remove the status NEW checking from this rule :
-A INPUT -p tcp -m state –state NEW –dport 30000 -j ACCEPT
Otherwise this last rule would hang up the whole VPS and all open SSH sessions when iptables_restore.
Making a reboot necessary. (Luckily the rules set was not booted yet at start up.)
Also apt-get update (to archive.ubuntu.com:80) would timeout because of this.
There were some more screw ups with my manually setup private nameservers. This is supposed to be fully managed. I canceled and left screaming/angry.
Four days lost for ever.
the_guv October 23rd, 2009 at 8:55 am
tx Robert .. am here in the UAE now. Kind of weird .. got here to find my site is censored! Something to do with the fact I have some tutorials showing people how to proxy!!
Ironically, I have another such guide scheduled to publish today. I will not stop it as it was published from Spain, so I have broken no law.
This is rather strange though. In the west, we are so used to freedom of speech, relatively at least. Suddenly, I am having to reevaluate my position, legally. For sure I do not want to end up like something out of Midnight Express.
Will be posting about this ..
the_guv October 23rd, 2009 at 8:58 am
@Robert .. damn and blast
Pleased you got sorted.
And thank you for posting this feedback .. may well be handy to some.
Robert October 29th, 2009 at 4:33 am
Hi guv!
Had a bad cold to shake off.
That’s a bummer with your site being censored.
You are right, just keep at what you are doing.
Same thing with the Chinese Governement and censorship. Blogger, WordPress.com, Tumblr, all blocked. But their people are using VPN tunnels to circumvent the blocked internet.
Don’t take this as a hint for a next article.
Or you might end up in something like Midnight Express.
Are you settling in nicely ?
Robert October 29th, 2009 at 5:04 am
How did you manage to post those comments ?
Is only a certain portion of your site censored, not the whole site ?
the_guv October 29th, 2009 at 11:49 am
Hi Robert, thank you .. your comments are encouraging.
“people are using VPN tunnels to circumvent the blocked internet” .. but I do take that as a superb hint for a future post! It’s good to hear people as passionate as me about freedom of information.
Pidgeons aside, there are three ways I could be updating my site, as it is all, completely 100% blocked:-
- logging into my VPS and working directly, remotely, in the database (cos hey, the website is merely a frontend for a server .. and these oppressive types don’t seem to block an entire IP for some reason, just domain names)
- working remotely using a database client, which would simply give me a shiny GUI version of the above
- using a proxy after all and, well, fibbing a bit .. but clearly I simply couldn’t do that. Just a bit too blatent, no?
.. Take your pick! For sure, each method would work.
Thanh November 18th, 2009 at 10:29 pm
I’m trying to use SMTP to email my users via gmail. How do I unblock SMTP port 465?
HOW-TO SSH - Secure Server & Encrypt Data - VPS ADMIN #3 - GUVNR November 25th, 2009 at 10:42 am
[...] *** for this, edit your sshd_config file. Read the appropriate section in my tutorial Harden the Secure Shell (SSH) & Create a Firewall. [...]
SSH & PuTTY Authentication Keys: Hide Data & Easy Login: VPS BIBLE - vpsBible February 10th, 2010 at 5:01 pm
[...] Because you no longer need it, we can disable your VPS’ password access. (A little tweak in Harden the Secure Shell (SSH) & Create a Firewall.) [...]
SECURE SSH KEY SETUP 4 LINUX: local-PC-to-remote-server: VPS BIBLE - vpsBible February 27th, 2010 at 12:10 am
[...] *** for this, we must also edit the sshd_config file. We’ll get to that in Harden the Secure Shell (SSH) & Create a Firewall. [...]
Install/Upgrade WORDPRESS with SUBVERSION: VPS BIBLE - vpsBible July 7th, 2010 at 6:31 pm
[...] …While I’m nagging, if you’ve not already, you should also carry out Harden the Secure Shell (SSH) & Create a Firewall. [...]