The FreeBSD Forums  

Go Back   The FreeBSD Forums > Miscellaneous > Howtos & FAQs

Howtos & FAQs Would you like to share some of your solutions for certain problems? Tips or tricks? Post here.

Reply
 
Thread Tools Display Modes
  #1  
Old May 19th, 2009, 14:47
vivek's Avatar
vivek vivek is offline
Member
 
Join Date: Nov 2008
Location: Hyper Space
Posts: 612
Thanks: 3
Thanked 94 Times in 76 Posts
Default Unofficial FreeBSD Security Checklist / Links / Resources

This is list of recommended security settings to protect FreeBSD server from both internal (done by your own users) and external attacks (done by crackers). Please discuss your recommendation below and I will update main post as and when required. The goal is to create a nice itemized and linked (to man files, handbook articles, etc.) article in the HOWTO section.
OpenSSH server
Unless the system needs to provide the remote login and file transfer capabilities of SSH, disable the OpenSSH server. However, it is required in 95% case.

Block ssh login attempts
Use any one of the following port:
  1. security/denyhosts Works with both jaild ssh and host sshd without firewall access. Blocks ssh access.
  2. security/sshguard-pf Protect hosts from brute force attacks against ssh and other services using pf
  3. security/sshguard-ipfw Protect hosts from brute force attacks against ssh and other services using ipfw
  4. security/sshguard-ipfilter Protect hosts from brute force attacks against ssh and other services using ipfilter
  5. security/sshblock Block abusive SSH login attempts
  6. security/sshit Checks for SSH/FTP bruteforce and blocks given IPs
Configure firewall such as pf to limit incomming port 22 traffic. Allow, ssh login from 192.168.1.0/24 220.1.2.3 only. A typical pf rule:
Code:
pass in on $ext_if inet proto tcp from {192.168.1.0/24, 220.1.2.3 } to 201.41.71.xxx port ssh flags S/SA synproxy state
/etc/ssh/sshd_config Settings
Set Idle Timeout Interval for User Logins (600 seconds)

Code:
ClientAliveInterval 600
ClientAliveCountMax 0
Disable .rhosts Files
Code:
IgnoreRhosts yes
Disable Host-Based Authentication
Code:
HostbasedAuthentication no
Disable Empty Passwords
Code:
PermitEmptyPasswords no
Limit Users' SSH Access, allow only foo (add foo to wheel so that he can su - root) and bar to login via ssh:
Code:
AllowUsers foo bar
Configure public keybased login for ssh - http://www.freebsd.org/doc/en/books/...k/openssh.html

Use Keychain from Gntoo project, which is a shell script which acts as a user-friendly front-end to ssh-agent(1), allowing you to have one long-running ssh-agent process per system rather than per login session. This is must for all servers, if you are configuring password less login for backup or any other purposes.

Other suggestions - Disable root login, change ssh port, Bind ssh to specific IP address,Only use SSH protocol 2,Deny root user login,Setup login banner ,Disable SSHD password authentication See: http://nixcraft.com/2516-post1.html


Recommend readings:
FreeBSD Jails
FreeBSD jail establish a clean cut separation between various services and users, mainly for security and ease of administration reasons. Run major services such as HTTPD, SMTPD, SQL Server and other public services in a jail. It offers the following features:
  • Virtualization: Each jail is a virtual environment running on the host machine with its own files, processes, user and superuser accounts. From within a jailed process, the environment is (almost) indistinguishable from a real system.
  • Security: Each jail is sealed from the others thus providing an additional level of security.
  • Ease of delegation: Thanks to the limited scope of a jail, it allows administrators to painlessly delegate several tasks which require superuser access without handing out complete control over the system.
  • Jail Setup Tutorial - http://www.freebsd.org/doc/en/books/handbook/jails.html
  • Multiple IPs in jail - http://www.cyberciti.biz/faq/freebsd...-ipv6-address/
  • Man pages - jail jls jexec
Host-based intrusion detection system
Use integrity checking software which can detect the intrusions. It monitors filesystem for unauthorized change such as find out if system binaries modified and new cracked versions installed or not.
  1. security/aide - AIDE is Advanced Intrusion Detection Environment. This piece of software was written as a replacement and extension for Tripwire.
  2. security/integrit - Integrit is an alternative to file integrity verification programs like tripwire and aide. It helps you determine whether an intruder has modified a computer system.
  3. security/tripwire is a tool that aids system administrators and users in monitoring a designated set of files for any changes.
Monitor log files
FreeBSD installs couple of scripts and email output to root account. Read those security emails. It contains lots of useful information and warnings. You can also use the following tools:
  1. sysutils/logcheck helps spot problems, anomalies and security violations in your logfiles automatically and will send the summaries to you via e-mail. Logcheck is run as a cron job.
    Logwatch is a customizable, pluggable log-monitoring system. 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.
  2. Use shell tools such as tail, grep, awk and friends to monitor log files. A few quick examples:
Code:
tail -f /var/log/messages
tail -f /var/log/maillog
egrep -i 'wanr|error' /var/log/messages
awk '{ print $1}'  /var/log/httpd-access.log| sort  | uniq -c  | sort -n
Root account security
You need to protect root account. A few tips:
  1. Never give out root password to anyone. Delegate root level access using sudo (port security/sudo. Never give shell or vi or any command that can escape to shell access using sudo. Keep an eye on sudo log file and /var/log/auth.log.
  2. Automatically log users out after a period of inactivity by setting
    Code:
    # csh  / tcsh - 5 minutes time out
    set -r autologout 5 
    # bash / sh 300 seconds time out
    TMOUT=300
    readonly TMOUT
    export TMOUT
  3. Add above to system global shell startup files.
  4. Use sysutils/vlock a utility which locks a terminal so it can only be unlocked with the user's password (or the root password).
  5. See Openssh and scripts for more info - http://www.cyberciti.biz/faq/linux-u...rce-time-outs/
  6. See FreeBSD handbook for protecting root user - http://www.freebsd.org/doc/en/books/...g-freebsd.html
kern.securelevel
  • Set kern.securelevel level 3 once *everything is configured* properly. Any super-user process can raise the level, but no process can lower it. See security man page and FreeBSD handbook security chapter - http://www.freebsd.org/doc/en/books/.../security.html
  • Sample /etc/rc.conf settings:
    Code:
    kern_securelevel_enable="YES"
    kern_securelevel="3"
Various limitations on users
  • Use limitations to avoid DoS attack from both internal and external threats.
  • Disk limitations via file system disk quota - See tutorial - http://www.freebsd.org/doc/en/books/...ok/quotas.html
  • Configure user resource limits, accounting limits via login class. You can control cputime, memory, vm usage, umask, path, open FDs, file limits, max process and so on. See login.conf man page for details.
  • ACL - Access Control Lists extend the standard UNIX® permission model in a highly compatible (POSIX®.1e) way. This feature permits an administrator to make use of and take advantage of a more sophisticated security model.

NOTE: I'm still working on a list...
__________________
"First they ignore you, then they laugh at you, then they fight you, then you win" -- Mahatma Gandhi.

Last edited by vivek; May 20th, 2009 at 11:47.
Reply With Quote
The Following 3 Users Say Thank You to vivek For This Useful Post:
hydra (May 21st, 2009), killasmurf86 (May 19th, 2009), techie (May 21st, 2009)
  #2  
Old May 19th, 2009, 15:05
vivek's Avatar
vivek vivek is offline
Member
 
Join Date: Nov 2008
Location: Hyper Space
Posts: 612
Thanks: 3
Thanked 94 Times in 76 Posts
Default

Continued from post # 1...

Apache Security
Run minimal built-in modules. To see all compiled modules:
Code:
httpd -l
Only following 4 compiled in modules should be listed to reduce the risk:
  1. core.c
  2. prefork.c
  3. http_core.c
  4. mod_so.c
Rebuild Apache if compiled-in modules is significantly larger than the above list.

Hide Apache version (/usr/local/etc/apache22/extra/httpd-default.conf
Code:
ServerTokens Prod
ServerSignature Off
Remove and minimize loadable modules. Open httpd.conf and start removing unwanted modules. After each module run the following to make sure module is not breaking something:
Code:
/usr/local/etc/rc.d/apache22 configtest
Turn off directory browsing (default index).

Turn off server side includes and server side scripting such as php, python and so on. Only grant access to certian diretories to run perl, python, php. Use mod_fastcgi or mod_fcgi

Disable symbolic links.

Secure /tmp and /var/tmp directories and mount it with noexec, nosuid, nosymfollow.

Disable .htaccess if not required.

Make sure you use mod_ssl to encrypt content.

Make sure you install and use mod security, which provides an application level firewall for Apache. A sample pf.conf(5) rule:

Code:
http_servers = "{ 202.54.1.1, 202.54.1.3, 202.54.1.5}"
https_servers = "{ 202.54.1.2, 202.54.1.3}"
# ....
pass in on $ext_if inet proto tcp from any to $http_servers port http flags S/SA synproxy state
pass in on $ext_if inet proto tcp from any to $https_servers port https flags S/SA synproxy state
Make sure you use DoS service protection modules such as mod_throttle mod_bwshare www/mod_limitipconn mod_dosevasive.

Configure php securely use suexec or other wrappers. If possible use www/mod_fastcgi (see FreeBSD apache FastCGI PHP tutorial) to start php externally with other UID.

Restrict file and directory access, use chmod and chgrp command to set permission on documentroot.

Configure firewall to allow access to the web server.

Run Apache in a chroot jail if possible. Use chroot(8), FreeBSD jails, www/mod_chroot, www/mod_security (mod_security tutorial and project website) SecChrootDir directive. Some basic examples of mod_security:

Code:
# Prevent directory traversal
SecFilter "\.\./"

# Filter on specific system specific paths
SecFilter /etc/passwd
SecFilter /bin/

# Prevent cross-site scripting
SecFilter "<[[:space:]]* script"

# Prevent SQL injection
SecFilter "delete[[:space:]]+from"
SecFilter "insert[[:space:]]+into"
SecFilter "select.+from"
Run updated apache version:
Code:
portsnap fetch update
pkg_version -vl '<'
Use portmaster(8) or other tool to update Apache version.

Run lightweight web server. If you just run a wordpress blog or static html site, switch to www/lighttpd or www/nginx web server.
  1. Official Apache 2.2 Security Tips
  2. FreeBSD Apache HTTP Server tutorial
  3. 20 ways to Secure your Apache Configuration
  4. Recommended book - Apache Security book.

BIND DNS Server
BIND9 is in base system.

Isolate DNS from Other Services. FreeBSD support chrooting bind server out of box. Add following to /etc/rc.conf
Code:
named_enable="YES"
named_chrootdir="/var/named"
Configure firewalls to protect the DNS server. Sample pf rules:
Code:
dns_servers = "{ 202.1.2.3 }"
# ...
pass in on $ext_if inet proto udp from any to $dns_servers  port domain
pass in on $ext_if inet proto tcp from any to $dns_servers  port domain flags S/SA synproxy state
Run separate DNS servers for External and Internal Queries (use jails).

Use Views to partition External and Internal information.


Authenticate Zone Transfers using TSIG. On primary ns:
Code:
cd /tmp
dnssec-keygen -a HMAC-MD5 -b 128 -n HOST ns1.freebsd.org
Note downl base64-key-string:
Code:
cat Kns1.freebsd.org.+NNN+MMMMM.key
Edit /var/named/etc/namedb/named.conf on the primary nameserver. Add the following:
Code:
key zone-transfer-key {
       algorithm hmac-md5;
       secret "base64-key-string";
     };
     zone "example.com " IN {
       type master;
       allow-transfer { key zone-transfer-key; };
       ...
     }
Edit /var/named/etc/namedb/named.conf on the secondary nameserver. Add the directives:
Code:
     key zone-transfer-key {
       algorithm hmac-md5;
       secret "base64-key-string ";
     };

Disable dynamic updates
Code:
zone "freebsd.org " IN {
  allow-update { none; };
  ...
}
Configure the logging options for security and monitoring purpose:
Code:
logging {
    channel security_channel {
        # Send log messages to the specified file
        file            "/var/log/security.log" versions 3 size 50m;
        # Log all messages
        severity        debug;
        # Log the date and time of the message
        print-time      yes;
        # Log the category of the message
        print-category  yes;
        # Log the severity level of the message
        print-severity  yes;
    };

    channel default {
        # Send logs to the syslog 'local0' facility
        syslog          local0;
        # Log messages of severity 'info' or higher
        severity        info;
        print-category  yes;
        print-severity  yes;
    };

    # Logs about approval and denial of requests
    category security {
        security_channel;
        default;
    };

    # Ignore logs about misconfigured remote servers
    category lame-servers { null; };

    # Default logging options
    category default { default; };

   channel "querylog" { file "/var/log/query.log" versions 3 size 50m; print-time yes; };
   category queries { querylog; };
};
Note /var/log/query.log will be created in /var/named/ jail i.e. actual location will be /var/named/var/log/query.log.

FreeBSD Hardening System Via /etc/sysctl.conf
Code:
# Security networking
# Limit ICMP
net.inet.icmp.icmplim=50
net.inet.icmp.maskrepl=0
net.inet.icmp.drop_redirect=1
net.inet.icmp.bmcastecho=0
net.inet.tcp.icmp_may_rst=0
# Drop synfin packets
net.inet.tcp.drop_synfin=1
# a single pass through the firewall
# net.inet.ip.fw.one_pass=1
# adds more queue buckets for ipfw dummynet
# net.inet.ip.dummynet.hash_size=2048
# increase the size of network mbufs to allocate
# kern.ipc.nmbclusters=65536
# If above used add the following to /boot/loader.conf - reboot needed
# kern.ipc.nmbclusers="65536"
# This is for dos protection 
# net.inet.tcp.msl=7500
# Turn off stealth IP networking 
net.inet.ip.stealth=0
# Try to protect against scans
net.inet.tcp.blackhole=2
net.inet.udp.blackhole=1
# Try to stop some syn flood attacks, and route cache degregation
net.inet.ip.rtexpire=2
net.inet.ip.rtminexpire=2
net.inet.ip.rtmaxcache=256
# Drop evil sourcerouted packets
net.inet.ip.accept_sourceroute=0
net.inet.ip.sourceroute=0
# Turn it on when you have two interfaces on same switch
# net.link.ether.inet.log_arp_wrong_iface=0
# IPCS - memory optimization 
kern.ipc.shmmax=134217728
kern.ipc.shmall=32768
kern.ipc.semmap=256

# Hide UID and GID from other users
security.bsd.see_other_gids=0
security.bsd.see_other_uids=0
security.bsd.unprivileged_read_msgbuf=0
# Max open file?
kern.maxfiles=65536
See sysctl.conf(5) and sysctl(8) for more info,
__________________
"First they ignore you, then they laugh at you, then they fight you, then you win" -- Mahatma Gandhi.

Last edited by vivek; May 27th, 2009 at 14:26.
Reply With Quote
The Following 5 Users Say Thank You to vivek For This Useful Post:
eayesta (May 26th, 2009), killasmurf86 (August 13th, 2009), Nokobon (June 22nd, 2009), overmind (August 25th, 2009), techie (May 21st, 2009)
  #3  
Old May 20th, 2009, 12:41
vivek's Avatar
vivek vivek is offline
Member
 
Join Date: Nov 2008
Location: Hyper Space
Posts: 612
Thanks: 3
Thanked 94 Times in 76 Posts
Default

Continued from post # 2...
General security tips
  1. Encrypt transmitted data whenever possible – Do not use rservices or insecure protocol such as telnet / ftp etc. Use scp, ssh and other secure alternative.
  2. Minimize software to minimize vulnerability - Only install required ports and applications. The simplest way to avoid vulnerabilities in software is to avoid installing that software. Run the following command to see open ports
    Code:
    sockstat -4
    sockstat -6
    sockstat -4 | grep something
  3. Run different network services on separate systems - If possible, a server should be dedicated to serving exactly one network service. This limits the number of other services that can be compromised in the event that an attacker is able to successfully exploit a software flaw in one network service. Use FreeBSD jails to save hardware costs.
  4. Use and configure security tools to improve system robustness - Use firewall for host based firewalling and kernel protection, MAC etc for protection against vulnerable services. Configure log auditing for detecting problems. There are plenty of security tools for various purposes provides by FreeBSD security ports (located at/usr/ports/security)
  5. Updating Software - You need to update both base system + kernel (via buildworld or binary tool called freebsd-update) and applications (ports) via various tools. It is recommended that you use the following tools to keep systems up to date with the latest security patches.
    1. Updating and Upgrading FreeBSD
    2. FreeBSD Update Software and Apply Security Patches
    3. Install ports-mgmt/portaudit to monitor 3rd party apps and ports for security issues.
    4. Subscribe to freebsd-security-notifications mailing list or RSS feed.
  6. Avoid weak and default passwords - Do not leave network ports open. Always follow close all, open required port policy using firewall. Do not expose internal hosts such as sql servers, backup servers to the Internet. Use nating / proxy to hide internal server IPs.
  7. Do not run insecure and badly configured programs - For e.g. do not run apache, dns or mail server as a root user. Do not grant full system access to php or perl script. Restrict them to directories.
  8. Delete all unwanted account - For e.g. laid-off employee may seek revenge
  9. You need both host and firewall security.
  10. Never ever assumed that you are not target - you can be targeted by both humans and automated worms and virus. All you can do is set tight permissions and make sure you are always prepared for attacks.
  11. Always make a backup. Keep offsite backups on tape or dvd. RAID is not backup solution. Second hard disk on the same system is not a backup solution. Mirroring (to other server or disk) is not a backup. Backups are physically removed from the machine and stored where they can't be altered until they're needed for a restore. Always, check backup media and run dummy restore procedure. Use tools such as dump(8), restore(8), tar(1) etc. You can also use net/rsync, sysutils/rsnapshot and other 3rd party apps.
  12. Always read /usr/ports/UPDATING before updating ports.
  13. Always read /usr/src/UPDATING before starting buildworld procedure.
Tools for monitoring systems
  1. nmap - scan your server for open ports.
  2. top(1) - display and update information about the top cpu processes.
  3. vmstat(8) - report virtual memory statistics.
  4. fstat(1) - identify active files
  5. lsof - list open files, network connections and much more.
  6. systat(1) - display system statistics
  7. iostat(8) - report I/O statistics
  8. pstat(8) and swapinfo(8) - display system data structures
  9. netstat(1) - show network status
  10. sockstat(1) - list open sockets
  11. sysctl(8) - get or set kernel state. Many security settings and system information can be displayed using this tool. Use /etc/sysctl.conf to store configuration.
  12. ps(1) - list process status.
  13. w(1) / who(1) - display who is logged in and what they are doing
  14. uptime(1) - show how long system has been running
  15. last(1) - - indicate last logins of users and ttys
  16. lastcomm(1) - - show last commands executed
  17. ac(8) - connect time accounting
  18. sa(8) - print system accounting statistics

Resources
This is a just tiny list. Try the following resources / books:
I've tried to keep this small but useful list. Please add other information and comments below. Good luck!
__________________
"First they ignore you, then they laugh at you, then they fight you, then you win" -- Mahatma Gandhi.

Last edited by vivek; June 16th, 2009 at 20:50.
Reply With Quote
The Following 10 Users Say Thank You to vivek For This Useful Post:
eayesta (May 26th, 2009), hitest (June 7th, 2009), killasmurf86 (August 13th, 2009), Mormegil (August 9th, 2009), overmind (August 25th, 2009), paleksic (May 26th, 2009), saxon3049 (August 20th, 2009), unicyclist (May 20th, 2009), WibbleWobble (October 11th, 2009), z0ran (May 30th, 2009)
  #4  
Old October 26th, 2009, 01:18
Beastie Beastie is offline
Member
 
Join Date: Mar 2009
Location: /dev/earth0
Posts: 326
Thanks: 0
Thanked 36 Times in 34 Posts
Default

Quote:
Originally Posted by vivek View Post
OpenSSH server

[...]
Disable .rhosts Files
Code:
IgnoreRhosts yes
Disable Host-Based Authentication
Code:
HostbasedAuthentication no
Disable Empty Passwords
Code:
PermitEmptyPasswords no
I know it's not terribly important, but aren't these the default?
__________________
May the source be with you!
Reply With Quote
Reply

Tags
freebsd, howto, security, tips

Thread Tools
Display Modes

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 On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Useful Links / Articles Ico Howtos & FAQs 4 October 26th, 2009 23:14
Limit CPU and other resources while port build surlyjake Ports Installation and Maintenance 7 June 4th, 2009 01:38
error sending response: not enough free resources meeinter Networking 1 April 2nd, 2009 00:26
using the links to send to another site cliedo Off-Topic 3 January 11th, 2009 05:06
Links to the forum on the main FreeBSD website trasz@ Feedback 18 December 4th, 2008 06:22


All times are GMT +1. The time now is 05:04.


Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
The mark FreeBSD is a registered trademark of The FreeBSD Foundation and is used by The FreeBSD Project with the permission of The FreeBSD Foundation.