PDA

View Full Version : Unofficial FreeBSD Security Checklist / Links / Resources


vivek
May 19th, 2009, 14:47
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:

security/denyhosts Works with both jaild ssh and host sshd without firewall access. Blocks ssh access.
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

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:
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)

ClientAliveInterval 600
ClientAliveCountMax 0

Disable .rhosts Files
IgnoreRhosts yes

Disable Host-Based Authentication
HostbasedAuthentication no

Disable Empty Passwords
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:
AllowUsers foo bar

Configure public keybased login for ssh - http://www.freebsd.org/doc/en/books/handbook/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.

Keychain How to http://www.gentoo.org/proj/en/keychain/
security/keychain



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:

pf.conf
sshd
sshd_config
Openssh FAQ http://www.openssh.org/faq.html
Lots of suggestion @ slashdot thread - rundown on SSH Brute Force Attacks - http://it.slashdot.org/article.pl?sid=05/07/16/1615233


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-jail-add-multiple-ipv4-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.
security/aide - AIDE is Advanced Intrusion Detection Environment. This piece of software was written as a replacement and extension for Tripwire.
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.
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:

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.
Use shell tools such as tail, grep, awk and friends to monitor log files. A few quick examples:

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:

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.
Automatically log users out after a period of inactivity by setting
# csh / tcsh - 5 minutes time out
set -r autologout 5
# bash / sh 300 seconds time out
TMOUT=300
readonly TMOUT
export TMOUT
Add above to system global shell startup files.
Use sysutils/vlock a utility which locks a terminal so it can only be unlocked with the user's password (or the root password).
See Openssh and scripts for more info - http://www.cyberciti.biz/faq/linux-unix-login-bash-shell-force-time-outs/
See FreeBSD handbook for protecting root user - http://www.freebsd.org/doc/en/books/handbook/securing-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/handbook/security.html
Sample /etc/rc.conf settings:
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/handbook/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 (http://www.freebsd.org/doc/en/books/handbook/fs-acl.html) 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...

vivek
May 19th, 2009, 15:05
Continued from post # 1...

Apache Security
Run minimal built-in modules. To see all compiled modules:
httpd -l
Only following 4 compiled in modules should be listed to reduce the risk:

core.c
prefork.c
http_core.c
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
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:
/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 rule:

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 (http://www.cyberciti.biz/faq/freebsd-apache-php-mod_fastcgi-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, FreeBSD jails, www/mod_chroot, www/mod_security (mod_security tutorial (http://www.cyberciti.biz/faq/freebsd-install-configure-mod_security/) and project website (http://www.modsecurity.org/)) SecChrootDir directive. Some basic examples of mod_security:

# 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:
portsnap fetch update
pkg_version -vl '<'

Use portmaster 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.


Official Apache 2.2 Security (http://httpd.apache.org/docs/2.2/misc/security_tips.html) Tips

FreeBSD Apache HTTP Server tutorial (http://www.freebsd.org/doc/en/books/handbook/network-apache.html)

20 ways to Secure (http://www.petefreitag.com/item/505.cfm) your Apache Configuration

Recommended book - Apache Security (http://oreilly.com/catalog/9780596007249/)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
named_enable="YES"
named_chrootdir="/var/named"


Configure firewalls to protect the DNS server. Sample pf rules:
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 (http://www.oreillynet.com/pub/a/oreilly/networking/news/views_0501.html)information.


Authenticate Zone Transfers using TSIG. On primary ns:
cd /tmp
dnssec-keygen -a HMAC-MD5 -b 128 -n HOST ns1.freebsd.org
Note downl base64-key-string:
cat Kns1.freebsd.org.+NNN+MMMMM.key
Edit /var/named/etc/namedb/named.conf on the primary nameserver. Add the following:
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:
key zone-transfer-key {
algorithm hmac-md5;
secret "base64-key-string ";
};


Disable dynamic updates
zone "freebsd.org " IN {
allow-update { none; };
...
}

Configure the logging options for security and monitoring purpose:
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.



BIND/named manual pages: rndc, named, and named.conf
FreeBSD BIND Setup Tutorial (http://www.freebsd.org/doc/en/books/handbook/network-dns.html)
BIND TSIG tutorial (http://www.cyberciti.biz/faq/unix-linux-bind-named-configuring-tsig/) for more information.
ISC BIND Software and Documentations (https://www.isc.org/software/bind)
BIND and DNS (http://oreilly.com/catalog/9780596100575/) Book

FreeBSD Hardening System Via /etc/sysctl.conf

# 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 and sysctl for more info,

vivek
May 20th, 2009, 12:41
Continued from post # 2...
General security tips

Encrypt transmitted data whenever possible – Do not use rservices or insecure protocol such as telnet / ftp etc. Use scp, ssh and other secure alternative.

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
sockstat -4
sockstat -6
sockstat -4 | grep something

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.

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 fo (http://www.freebsd.org/doc/en/books/handbook/audit.html)r detecting problems. There are plenty of security tools for various purposes provides by FreeBSD security ports (located at/usr/ports/security)
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.

Updating and Upgrading FreeBSD (http://www.freebsd.org/doc/en/books/handbook/updating-upgrading.html)
FreeBSD Update Software and Apply Security Patches (http://www.cyberciti.biz/tips/howto-keep-freebsd-system-upto-date.html)
Install ports-mgmt/portaudit to monitor 3rd party apps (http://www.freebsd.org/doc/en/books/handbook/security-portaudit.html) and ports for security issues.
Subscribe to freebsd-security-notifications (http://lists.freebsd.org/mailman/listinfo/freebsd-security-notifications) mailing list or RSS feed (http://www.freebsd.org/security/rss.xml).

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.
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.
Delete all unwanted account - For e.g. laid-off employee may seek revenge
You need both host and firewall security.
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.
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, restore, tar etc. You can also use net/rsync, sysutils/rsnapshot and other 3rd party apps.
Always read /usr/ports/UPDATING before updating ports.
Always read /usr/src/UPDATING before starting buildworld procedure.

Tools for monitoring systems

nmap - scan your server for open ports.
top - display and update information about the top cpu processes.
vmstat - report virtual memory statistics.
fstat - identify active files
lsof - list open files, network connections and much more.
systat - display system statistics
iostat - report I/O statistics
pstat and swapinfo - display system data structures
netstat - show network status
sockstat - list open sockets
sysctl - get or set kernel state. Many security settings and system information can be displayed using this tool. Use /etc/sysctl.conf to store configuration.
ps - list process status.
w / who - display who is logged in and what they are doing
uptime - show how long system has been running
last - - indicate last logins of users and ttys
lastcomm - - show last commands executed
ac - connect time accounting
sa - print system accounting statistics


Resources
This is a just tiny list. Try the following resources / books:

Official FreeBSD handbook (http://www.freebsd.org/doc/en/books/handbook/)
The Six Dumbest Ideas in Computer Security (http://www.ranum.com/security/computer_security/editorials/dumb/)
Mastering FreeBSD and OpenBSD Security (http://oreilly.com/catalog/9780596006266/)
The Book of PF - A No-Nonsense Guide to the OpenBSD Firewall (http://oreilly.com/catalog/9781593271657/)
BSD Hacks 100 Industrial Tip & Tools (http://oreilly.com/catalog/9780596006792/)
Essential System Administration - (http://oreilly.com/catalog/9780596003432/) This book covers many fundamental tasks in system administration.
Learn shell scripting to automate the tasks. Checkout TLDP.org (http://tldp.org/LDP/abs/html/) shell scripting guide.


I've tried to keep this small but useful list. Please add other information and comments below. Good luck!

Beastie
October 26th, 2009, 01:18
OpenSSH server

[...]
Disable .rhosts Files
IgnoreRhosts yes

Disable Host-Based Authentication
HostbasedAuthentication no

Disable Empty Passwords
PermitEmptyPasswords no

I know it's not terribly important, but aren't these the default?

chrcol
January 21st, 2010, 02:02
nice guide but be aware on mod security it is very easy to break mainstream apps eg. the mysql injection filter that you printed breaks phpmyadmin. The rules on gotroot.com break various mainstream apps as well, the core ruleset I have never tested tho.

Savagedlight
January 22nd, 2010, 22:20
This is a really nice guide, but I feel I have to correct one minor error.

OpenSSH server
Set Idle Timeout Interval for User Logins (600 seconds)
ClientAliveInterval 600
ClientAliveCountMax 0


I think you were looking for "LoginGraceTime", as the aforementioned directives have nothing to do with "Idle Timeout Interval for User Logins".
Or was the intention to kick off anyone who successfully logged in but didn't do anything actively in the console for 10 mins? I might be a bit slow as I'm rather tired at the moment. :)

Quoting sshd_config:

ClientAliveCountMax
Sets the number of client alive messages (see below) which may be
sent without sshd(8) receiving any messages back from the client.
If this threshold is reached while client alive messages are
being sent, sshd will disconnect the client, terminating the ses-
sion. It is important to note that the use of client alive mes-
sages is very different from TCPKeepAlive (below). The client
alive messages are sent through the encrypted channel and there-
fore will not be spoofable. The TCP keepalive option enabled by
TCPKeepAlive is spoofable. The client alive mechanism is valu-
able when the client or server depend on knowing when a connec-
tion has become inactive.

The default value is 3. If ClientAliveInterval (see below) is
set to 15, and ClientAliveCountMax is left at the default, unre-
sponsive SSH clients will be disconnected after approximately 45
seconds. This option applies to protocol version 2 only.

ClientAliveInterval
Sets a timeout interval in seconds after which if no data has
been received from the client, sshd(8) will send a message
through the encrypted channel to request a response from the
client. The default is 0, indicating that these messages will
not be sent to the client. This option applies to protocol ver-
sion 2 only.

LoginGraceTime
The server disconnects after this time if the user has not suc-
cessfully logged in. If the value is 0, there is no time limit.
The default is 120 seconds.

graudeejs
February 27th, 2010, 23:26
I came across some pretty interesting blog
http://techrepublic.com

and I wanted to point out article related to FreeBSD file flags (chflags):
http://blogs.techrepublic.com.com/security/?p=2868

overmind
March 4th, 2010, 16:16
Any tips on PHP security? For example how to configure Apache+PHP so when a user upload a php file manager he will be "see" only his home folder (and not the entire structure of / and other users ).

kuyaedz
April 18th, 2010, 17:38
Jails are great and filesystem quotas are great, but as far as I can tell it is not possible to combine them? I've been working on a secure shell server for some users, which I've created inside a jail. I have not been able to figure out how to apply filesystem quotas for the jail users.

Is it possible to define filesystem quotas to users inside a jail? (I'm using ezjail-admin)

graudeejs
July 29th, 2010, 07:32
fix sysutils/logcheck to security/logcheck

rghq
August 3rd, 2010, 02:03
Any tips on PHP security? For example how to configure Apache+PHP so when a user upload a php file manager he will be "see" only his home folder (and not the entire structure of / and other users ).

Looks like you're looking for the FastCGI + Suexec combo in combo with PHP's open_basedir etc.

Related to IDS - you may add Yafic to the list - nice tool :)

To SSH - a simple SFTP only user may have nologin as login shell and in sshd:


Subsystem internal-sftp /usr/libexec/sftp-server

Match User example
ChrootDirectory /home/example
AllowTcpForwarding no
ForceCommand internal-sftp

graudeejs
August 3rd, 2010, 09:37
security/snort

lumiwa
August 4th, 2010, 01:52
http://www.cromwell-intl.com/security/security-stack-hardening.html
http://www.cromwell-intl.com/

graudeejs
August 21st, 2010, 20:13
port knocking:
http://www.linux.com/learn/tutorials/351079
security/knock
http://www.zeroflux.org/projects/knock

oliverh
August 22nd, 2010, 11:04
Don't forget TaoSecurity (http://taosecurity.blogspot.com/search?q=freebsd) the weblog of Richard Bejtlich.

graudeejs
May 8th, 2011, 21:03
http://home.nuug.no/~peter/pf/ << Peter N. M. Hansteen the author of "The Book of PF" has provided nice pf tutorial (html & pdf), also his AsiaBSDCon 2011 slides are available