Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Advertise on LowEndTalk.com

[GUIDE] Basic steps to secure your Ubuntu / Debian server
New on LowEndTalk? Please read our 'Community Rules' by clicking on it in the right menu!

[GUIDE] Basic steps to secure your Ubuntu / Debian server

drserverdrserver Member, Host Rep
edited January 2014 in Tutorials

This is tutorial for newbies and it will help you that you harden a little bit your ubuntu/debian server.

1) Update and upgrade apt and your packages

apt-get update && apt-get upgrade

By doing this regularly you will always have up to date packages and current fixes.


2) Change SSH port as most of automated brute force attacks and sniffers are aimed to port 22. You will do half of the job by simply changing port that port to some high port. Lets say 222 is our target port for this tutorial. SSHd config file is located here: /etc/ssh/sshd_config

What we need to do is to launch nano and change port variable from 22 to 222

nano /etc/ssh/sshd_config

Look for following:

Port 22

We have to change it to port 222 then save changes

Port 222

Restart sshd to apply the change

service ssh restart


3) Install DenyHosts

Basic idea of deny hosts is to prevent multiple continuous unauthorized login attempts on your ssh server

apt-get install denyhosts

There is no config file tuning needed if you wish to have basic protection. If you wish to play with it little bit more config file is located at /etc/denyhosts.conf


This will help you a little bit. Keep your system always up to date, change your root password regularly and you will be safe.

Unmetered servers starting from $12.00 USD p/m. Xeon® E-2134 for $50.00 p/m ||| Xeon® Silver 4110 for $80.00 p/m
Live server stock ||| Feel free to contact me for custom deal.

«1

Comments

  • Thank you for the denyhosts suggestion, i have to check this out.

  • akzakz Member

    thanks for denyhosts was looking for a easy alternative to fail2ban

  • Mark_RMark_R Member
    edited January 2014

    I read through that entire non-straight-forward wall of text and in the end he didn't name 1 valid reason why putting ssh on another port than 22 is a bad idea.

  • drserverdrserver Member, Host Rep

    @Spencer I am aware that 22223 is not privileged port. Also i am aware that 99% of low end vps servers are simple single (root) user environments. This is basic hardening so in my personal opinion i think that it is more beneficial to change ssh port then to leave it.

    Unmetered servers starting from $12.00 USD p/m. Xeon® E-2134 for $50.00 p/m ||| Xeon® Silver 4110 for $80.00 p/m
    Live server stock ||| Feel free to contact me for custom deal.

  • drserverdrserver Member, Host Rep

    @Mark_R

    It is possible than other (non root) make port listener and spoof his malicious app to collect root user and pass. However i think that ssh will always be run before user scripts

    Unmetered servers starting from $12.00 USD p/m. Xeon® E-2134 for $50.00 p/m ||| Xeon® Silver 4110 for $80.00 p/m
    Live server stock ||| Feel free to contact me for custom deal.

  • Do you think denyhosts is better than fail2ban?

    LowEndHelpDesk | Find help to simple questions :-)

  • @drserver said:
    Mark_R

    It is possible than other (non root) make port listener and spoof his malicious app to collect root user and pass. However i think that ssh will always be run before user scripts

    Ah well then, what they write in that article isn't valid for me then, i'm the only user on my servers.

  • drserverdrserver Member, Host Rep

    @catalystium said:
    Do you think denyhosts is better than fail2ban?

    Booth are great

    Unmetered servers starting from $12.00 USD p/m. Xeon® E-2134 for $50.00 p/m ||| Xeon® Silver 4110 for $80.00 p/m
    Live server stock ||| Feel free to contact me for custom deal.

  • Shoaib_AShoaib_A Member
    edited January 2014

    @drserver Thanks for posting the basic hardening tutorial for Debian/Ubuntu, hope to see you doing one for CentOS/RHEL as well :) I am not a newbie but still I appreciate that you are trying to help people who are new to Linux

  • A very well written article that will probably save me several hours in my life of explaining this concept to people and why it doesn't work.

    Ontopic: that said I don't support moving the SSH port, I do appreciate the denyhosts suggestion. You should replace port swapping with teaching people to use proper key authentication instead...

  • @catalystium said:
    Do you think denyhosts is better than fail2ban?

    Fail2ban is far more powerful and can be used for other listening services other then just ssh.

    Both suck in the sense they use python and therefore use more resources.

    Check out sshguard.

  • darkshire said: Both suck in the sense they use python and therefore use more resources.

    You cannot make a comparison with only one side. What do you consider resource-light and what implementation would that be in?

  • howardsl2howardsl2 Member
    edited January 2014

    I wrote up a detailed IPTables security guide at my tech blog at this link. Anyone interested can take a look. Although it is for Asterisk server, you can just disregard that one section related to Asterisk.

  • Any comparison between the denyhost to fail2ban, I like fail2ban, as it also defend other services.

    My site, powered by Netlify and Let's Encrypt.

  • Seems fail2ban can do more than just SSH and denyhosts is just for SSH. How much better on resources is sshguard than fail2ban @darkshire ?

    LowEndHelpDesk | Find help to simple questions :-)

  • drserverdrserver Member, Host Rep

    @Spencer i will adjust change to privlieged 222 port, then guide will be complete

    Unmetered servers starting from $12.00 USD p/m. Xeon® E-2134 for $50.00 p/m ||| Xeon® Silver 4110 for $80.00 p/m
    Live server stock ||| Feel free to contact me for custom deal.

  • painfreepcpainfreepc Member
    edited January 2014

    additional steps i do:

    Get two Ultra High Security Passwords from: https://www.grc.com/passwords.htm

    use 1 for root and the other for new-user

    Change Your root Password (if needed)

    passwd

    Add New User with root rights

    adduser user-name

    Give New User Root Privileges

    "export VISUAL=nano; visudo"

    Under root, add the following line, granting all the permissions to your new user:

    # User privilege specification
    root    ALL=(ALL:ALL) ALL
    user-name    ALL=(ALL:ALL) ALL
    

    Type ‘cntrl x’ to exit the file.
    Press Y to save; press enter, and the file will saved

    Add new user to SSH

    nano /etc/ssh/sshd_config

    Edit the following lines and save:

    Port <your port number>
    UseDNS no
    # YES you add root and other users on same line
    AllowUsers root user-name
    

    Type ‘cntrl x’ to exit the file.
    Press Y to save; press enter, and the file will saved

    Restart sshd to apply the change

    service ssh restart

    Test new settings (don’t logout of root yet),

    open new terminal window and login as your new user.

    Don’t forget to include the new port number

    now check to see if you can get root access

    type the word
    "sudo su"
    or
    "sudo -i"
    press enter

    enter password

    Your prompt should now say:
    [email protected]:~#


    may be a good ideal to logout of new-user and open new terminal

    to see if you can still login as root

    if all is ok, you now have root access as new user,


    Now reboot and login as new-user

    type the word
    "sudo su"
    or
    "sudo -i"
    press enter

    Note: "sudo -i" unlike "sudo su" only needs to be typed once

    Now lets remove root password

    sudo passwd -dl root

    ---------NOTE---------

    i don't use key, if someone can hack a 63 random alpha-numeric characters PW - God bless them

    "9miohq4AozopkVUfTFzzMWSShqoOgD7ZZck9Wo1JxpKZ58l4yfUFxk10sG24Uw9"

    i do not remove root from ssh login

    i just disable the root account password

    "sudo passwd -dl root"

    when i need the root account

    i enable the root account passward

    sudo passwd root

    when i am done using the root account i disable root password

    "sudo passwd -dl root"

    ---------NOTE---------

  • drserverdrserver Member, Host Rep

    @painfreepc Great addon

    Unmetered servers starting from $12.00 USD p/m. Xeon® E-2134 for $50.00 p/m ||| Xeon® Silver 4110 for $80.00 p/m
    Live server stock ||| Feel free to contact me for custom deal.

  • @catalystium said:
    Seems fail2ban can do more than just SSH and denyhosts is just for SSH. How much better on resources is sshguard than fail2ban darkshire ?

    the sshguard guys say it best; see here:

    http://www.sshguard.net/docs/faqs/#what-different-from-others

    Thanked by 1catalystium
  • painfreepc said: Under root, add the following line, granting all the permissions to your new user:

    User privilege specification

    root ALL=(ALL:ALL) ALL
    user-name ALL=(ALL:ALL) ALL

    You probably shouldn't do this. Install sudo and run

    sudo usermod -aG sudo user-name
  • What black said.

    No love for CSF?

    Moving the port SSH uses is only security thru obscurity and only cuts down on the noise in the logs.

    Security is a process not a product, and if a person is serious about having a server accessible to the public internet, they will need to learn to read logs and take note of how their system behaves normally so they can know if something is wrong with it (misconfiguration/owned/etc).

  • also @drserver clearly in the guide put 222 which is still a privileged port :)

  • edited January 2014

    @Mark_R

    Agreed, I read all as well could not find a valid reason not to change default 22 port

    ( I never use port 22 maybe as a honey pot).

    rsync -e"ssh -p[yournewporthere]" ...

    scp -P[yourenewporthere] ... (note capital P)

    ssh -p[yournewporthere] ...

    and you are set.

    ServerWholesale.com : Dedicated Intel Xeon QuadCore Servers starting at 49.95

  • Writing one up for CentOS now, since it was requested...

    Acting Director of Albino Geek Services Ltd. My Keybase ID ( gh )
    GoodHosting.co | Enterprise KVM Virtual Private Servers | Twitter / Status : @ GoodHostingCo

  • @wojons said:
    also drserver clearly in the guide put 222 which is still a privileged port :)

    It wasn't previously that's why it is mentioned :)

    Recommended Hosts: Bandwagonhost - Cool in-house panel | RamNode - Great Performance + Fast Support!

  • fail2ban works great.

    vpsdash.com - Tips and tricks in life, information and technology news to get things done

  • Yep, using fail2ban here and CSF.

    I'm Good!

  • NeoonNeoon Member
    edited January 2014

    Better would a port like: xxxx or xxxxx

    I also would recommend to use fail2ban instead of deny hosts.

    OK bad idea? lol

  • sleddogsleddog Member
    edited January 2014

    said: by simply changing port that port to some high port. Lets say 222

    Technically port 222 isn't a high port. All ports below 1024 are classed as well known ports, and associated with a service.

    If someone port-scans you, they may well scan the well known port range.

    So if you're going to move it, move it to a high port -- above 1024.

    Most of the arguments against moving it are centred around confusion, i.e., in a multi-user scenario some users will try to connect to the standard port and fail -- creating a support issue. For a personal server it doesn't matter.

    I always firewall the ssh port. Even if you have a dynamic IP, your ISP works within a limited range, so you can allow that range (or ranges, like me). You can setup a basic, static iptables firewall with a few config files without a full-fledged solution like CSF.

    fail2ban is (IMO) the solution of last resort. For a lowendbox it's a memory hog.

  • MonsteRMonsteR Member
    edited January 2014

    My Script basically does this, And alot more to secure servers, But only centos based at the moment, Considering making it for Ubuntu/Debian.
    http://lowendtalk.com/discussion/20033/script-autosecure-for-cpanel-auto-harden-cpanel

    RaptorNode.com - DDoS Protected|VPS|Cloud|Dedicated Servers|Collocation - Los Angeles, CA
    SamuraiBit Security
  • @sleddog said:
    I always firewall the ssh port. Even if you have a dynamic IP, your ISP works within a limited range, so you can allow that range (or ranges, like me). You can setup a basic, static iptables firewall with a few config files without a full-fledged solution like CSF.

    I do the same on my home server (white list a few IP addresses or a range), but my VPS runs CSF with SSH open to everyone.

    One thing I would recommend is using the AllowUsers directive when configuring sshd. Stops logging in as root dead in it's tracks even if you have PermitRootLogin set to yes and root isn't set in AllowUsers.

  • Why no CSF ? CSF is one of the best firewalls I have ever used...

  • painfreepcpainfreepc Member
    edited January 2014

    @ATHK said:
    Why no CSF ? CSF is one of the best firewalls I have ever used...

    I use it, love the country blocking, directory watch and the connection tracking
    .

  • drserverdrserver Member, Host Rep

    I have selected deny hosts as this app can share random attack data. You will block automatically all known bonnets, etc.

    I have no preference in deny hosts or fail2ban

    Booth are doing job great.

    As for higher port it is enough move ssh to anything different than port 22.
    It will harden things up.

    Remember that this is only basic tutorial, and i am inviting everyone to extend it.

    Unmetered servers starting from $12.00 USD p/m. Xeon® E-2134 for $50.00 p/m ||| Xeon® Silver 4110 for $80.00 p/m
    Live server stock ||| Feel free to contact me for custom deal.

  • nfnnfn Member
    edited January 2014

    I use some additional measures:

    1st: Allow access only to your country (can be changed to geoip city)
    http://ts1-en.blogspot.com/2009/06/ssh-access-control-with-geoip.html

    2nd: Email when someone login through ssh : http://askubuntu.com/questions/179889/how-do-i-set-up-an-email-alert-when-a-ssh-login-is-successful

    3rd:
    Email when the VPS start/reboot
    http://thepoch.com/tumblr/be-emailed-when-your-linux-server-starts-up-or-shuts.html

    Note: for debian you must change the headers to:

    #!/bin/bash
    
    ### BEGIN INIT INFO
    # Provides:          emailstartstop
    # Required-Start:    $syslog
    # Required-Stop:     $syslog
    # Default-Start:     2 3 4 5
    # Default-Stop:      0 1 6
    # Short-Description: emailstartstop init
    # Description:       Send an email on server startup and shutdown.
    #
    ### END INIT INFO
    
    Thanked by 2Mark_R howardsl2
  • TIL there's a $SSH_CONNECTION variable in bash.

  • https://library.linode.com/securing-your-server

    I just disable password login & enforce fail2ban most of the time

    serf

  • CharlesACharlesA Member
    edited January 2014

    @nfn said:
    I use some additional measures:

    1st: Allow access only to your country (can be changed to geoip city)
    http://ts1-en.blogspot.com/2009/06/ssh-access-control-with-geoip.html

    2nd: Email when someone login through ssh : http://askubuntu.com/questions/179889/how-do-i-set-up-an-email-alert-when-a-ssh-login-is-successful

    CSF can do #1 and #2. You'd need to do #3 manually, or set up uptime monitoring if you want real metrics on the server.

  • nfnnfn Member
    edited January 2014

    @CharlesA said:
    CSF can do #1 and #2. You'd need to do #3 manually, or set up uptime monitoring if you want real metrics on the server.

    Not everyone uses CSF ...

    1, I think CSF block all ports. With host.deny/allow you can block by service.

    2, I think LFD is the one who send email. I don't use LFD.

  • nocomnocom Member
    edited January 2014

    100% ssh security

    /etc/init.d/dropbear stop

    howto start ssh

    reboot server

    also

    chmod 000 /usr/bin/cc
    chmod 000 /usr/bin/gcc

    Drop incoming connections if IP make more than 10 connection attempts to port 80 within 100 seconds (add rules to your iptables shell script)

    IPT=/sbin/iptables

    Max connection in seconds

    SECONDS=100

    Max connections per IP

    BLOCKCOUNT=10

    ....

    ..

    default action can be DROP or REJECT

    DACTION="DROP"

    $IPT -I INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --set

    $IPT -I INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --update --seconds

    ${SECONDS} --hitcount ${BLOCKCOUNT} -j ${DACTION}

    ----------Lignttpd: Limit All Connections

    server.kbytes-per-second=1024

    ----------Set limit to 64 kbyte/s for each single connection per IP:

    connection.kbytes-per-second=64

  • @nocom said:
    100% ssh security

    chmod 000 /usr/bin/cc
    chmod 000 /usr/bin/gcc

    I can understand dropping traffic after a certain number of hits, but what purpose does it serve to remove all permissions from cc and gcc?

  • to disable compiler

  • @nocom said:
    to disable compiler

    For what? Why not to generate keys & allow only your country?

  • 0xdragon0xdragon Member
    edited January 2014

    @nocom said:
    to disable compiler

    AFAIK - If someone has access to a user, they can generally bring along their own packaged compiler and use the existing libraries on the system :)

    It's kinda pointless.

    This signature wasted 121 bytes of your data allocation.

    https://nixstats.com/report/56b53d6465689e44598b4567

  • nocomnocom Member
    edited January 2014

    Agree It's kinda pointless.

  • darkshire said:

    Fail2ban is far more powerful and can be used for other listening services other then just ssh.

    Both suck in the sense they use python and therefore use more resources.

    Check out sshguard.

    Fail2ban uses like 3MB on my VPS. It's worth it.

    I imagine sshguard uses <1MB of RAM since it is coded in C. But it does not allow you to specify custom "attack signatures" i.e. custom regex patterns. You can do that with fail2ban.

    said:

    1) Update and upgrade apt and your packages

    apt-get update && apt-get upgrade

    By doing this regularly you will always have up to date packages and current fixes.

    Install apticron and unattended-upgrades. The former tells you when new updates are available and the latter does the upgrades automatically:

    apt-get install apticron unattended-upgrades

  • drserverdrserver Member, Host Rep

    Well, I will put all those together and make tutorial, how to build bulletproof unbreakable fortress of your LEB.

    Unmetered servers starting from $12.00 USD p/m. Xeon® E-2134 for $50.00 p/m ||| Xeon® Silver 4110 for $80.00 p/m
    Live server stock ||| Feel free to contact me for custom deal.

  • howardsl2howardsl2 Member
    edited January 2014

    Just want to add my $.02. I posted this in an older thread.

    I wrote a script to check that IPTables is running with the correct rules every 5 minutes. It has the following components:

    1 Somewhere in your IPTables rules, add this:
    -A INPUT -m comment --comment "CHECKME"
    OR
    -A INPUT -m recent --set --name CHECKME

    2 Create a script /root/check_iptables.sh

    #!/bin/bash
    /sbin/iptables -n -L | grep "CHECKME" > /dev/null
    if [ $? -eq 0 ]; then
      touch /var/run/ipt_timestamp
    fi
    

    3 Create a cron job /etc/cron.d/check_iptables

    */5 * * * * root /root/check_iptables.sh &>/dev/null
    

    4 Create a script /root/iptablesload.sh

    #!/bin/sh
    /sbin/iptables-restore < /etc/iptables.rules
    exit 0
    

    5 Install Monit (e.g. apt-get install monit, yum install monit), and modify its config file.
    Here's part of my /etc/monit/monitrc for your reference. This is for Ubuntu. More Monit examples are here:
    http://mmonit.com/wiki/Monit/ConfigurationExamples

      set daemon 120             # check services at 2-minute intervals
        with start delay 360     # optional: delay the first check by 6-minutes
    
      set logfile /var/log/monit.log
    
      set idfile /var/lib/monit/id
    
      set statefile /var/lib/monit/state
    
      # Be sure to configure your VPS to be able to send emails (127.0.0.1:25)
      # Or you can specify another mailserver. Please refer to: 
      # http://mmonit.com/monit/documentation/monit.html#setting_a_mail_server_for_alert_messages
    
      set mailserver localhost  
    
      set eventqueue
          basedir /var/lib/monit/events # set the base directory where events will be stored
          slots 1000                    # optionally limit the queue size
    
      set alert YOUR_EMAIL_ADDRESS_HERE but not on { action, instance, uid, pid, ppid }
    
      set httpd port 2812 and
          use address localhost     # only accept connection from localhost
          allow localhost           # allow localhost to connect to the server and
          allow admin:password      # require user 'admin' with password 'password'
    
      ... More rules here ...
    
      # This is the relevant rule!
      check file iptables-ts with path /var/run/ipt_timestamp
        if timestamp > 6 minutes then exec "/root/iptablesload.sh"
        if timestamp > 6 minutes for 2 cycles then alert
    

    And you are done.

    For more IPTables security tips, check out my tech blog article. You can ignore the Asterisk section.
    https://blog.ls20.com/securing-your-asterisk-voip-server-with-iptables/

Sign In or Register to comment.