miércoles, 8 de mayo de 2013
Historia de los BSD
En 1969 la empresa AT&T encargo a Ken Thompson y Dennis Ritchie reducir el sistema operativo MULTICS para portarlo a los equipos más pequeños que la NASA utilizaba en sus misiones espaciales. A finales de ese año presentaron un sistema al que llamaron UNICS (UNiplexed Information and Computing Service) un ‘emasculated Multics’. Nadie sabe en que momento UNICS paso a ser Unix, pero según cuenta la layenda urbana, una secretaria no supo como escribir lo que le dictaban y escribió Unix y el nombre así se quedo.
El profesor Bob Fabry de la universidad de California en Berkely fue uno de los primeros interesados en conocer Unix y pidió una copia a la Universidad de Purdue, donde Thompson y Ritchie trabajaban. Sin embargo el mainframe de Berkeley poseía unos controladores de disco duales que Thompson no había previsto y trabajando junto con el departamento de matemáticas de Berkeley agregaron el soporte que faltaba. Esto fue el inicio de un intenso periodo de colaboración entre Berkeley y Bell Labs (subsidiaria de AT&T) al grado que Thompson tomó un año sabático en California para seguir desarrollando a Unix. Bajo su guía varios profesores y estudiantes de Berkeley realizaron cientos de mejoras y extensiones al kernel de Unix.
La segunda versión de Unix apareció en 1972. Por esas mismas fechas Ritchie reescribió el lenguaje B, creando a C. La sexta edición de Unix se libera en 1975, junto al nuevo Bourne Shell. En 1977 el estudiante graduado Bill Joy colocó todas las mejoras hechas en Berkeley y lo llamó “Berkeley Software Distribution.” Al poco tiempo Joy había enviado más de treinta copias de BSD a varias universidades. Las copias incluían al nuevo editor que Joy había creado: vi. Sin embargo, las características de las terminales variaban mucho y Joy decido escribir un pequeño intérprete que dibujaba la pantalla según sus características y así nació termcap. En 1979 se lanzó la séptima edicion de Unix y la tercera de BSD: 3BSD.
Por esos tiempos, el ejército estadunidense estaba preocupado por la escasa interoperatibilidad entre las plataformas que conformaban sus sistemas a través del país. Se pensó diseñar un hardware específico pero luego de pensarlo otra vez decidieron unir sus equipos a nivel de software, Unix fue el elegido para ello debido a su portabiliad. Los encargados del proyecto se pusieron en contacto con Berkeley para fondear el proyecto. En 1981 se lanzó la versión 4BSD con más de 400 envíos a todo el mundo. En 1982 Joy anunciá que deja Berkeley para incorporarse al equipo de Sun Microsystems y comienza a desarrollar Solaris, un sabor de Unix basado en BSD.
En 1985 los investigadores de la universidad Carnegie-Mellon comienzan a desarrollar su propio Kernel, conocido como Mach Kernel, el cual tomó librerias, código e ideas de BSD, si bien desarrollo e introdujo conceptos propios en su implementación de Unix. Posteriormente el Mach kernel sería usado para los sistemas de la empresa NeXT, la cual, a su vez, fue comprada por Apple Computers en 1996. El Mach Kernel es la base del Mac OSX actual y existe una versión que puede descargarse gratuitamente (claro, sin el ambiente gráfico) llamado Darwin.
En 1984 apareción 4.2BSD, con la cual se estrenaba el protocolo TCP/IP desarollado por la gente de Berkeley. Está versión de BSD fue quizás su mayor éxito vendiéndose miles de licencias, al grado de que las empresas comenzaron a migrar de Unix SysV al nuevo BSD pues poseía muchas facilidades de red y el nuevo sistema de archivos Berkeley Fast filesystem. Varias empresas comenzaron a acercarse a Berkeley para distribuir BSD por su cuenta.
Esto provoco una demanda de AT&T que tardo varios años en resolverse. Según Berkeley, el acuerdo de cooperación contemplababa el acceso al código fuente pero AT&T argumentaba que eso violaba sus derechos de autor pues en el código había secciones que le pertenecían. Todos los involucrados en el desarrolo de BSD tuvieron que testificar en el juicio y eso retrasaba el trabajo. Un grupo de desarolladores hicieron mejoras al kernel y lanzaron el primer NetBSD en 1993, poco tiempo después otro grupo lanzó FreeBSD. Por fin, en enero de 1994 el juez que llevaba el caso entregó una pequeña lista de archivos que debian reemplazarse de BSD y con ello la cuestión legal fue zanjada.
Theo de Raat, un talentoso y problemático desarrollador de NetBSD, tuvo problemas con otros miembros del equipo y por ello decidió comenzar su propio proyecto: OpenBSD. Este sistema operativo, se concentra en la portabilidad, el cumplimiento de normas y regulaciones, corrección, seguridad proactiva y criptografía integrada.
viernes, 3 de mayo de 2013
BlackBSD
BlackBSD
Is a NetBSD based LiveCD, with security tools on it, and fluxbox as a window manager.
Packages on it.
Beta Version 1.2 coming on soon.
Nmap – port scanner http://nmap.org/Beta Version 1.2 coming on soon.
Nessus – Vulnerability detector http://www.tenable.com/products/nessus
Air-Crack – Wireless Cracker http://www.aircrack-ng.org/
Ettercap – port sniffer http://ettercap.github.com/ettercap/
Iptraf – Network Monitor http://iptraf.seul.org/
Medusa – Login brute-forcer http://www.foofus.net/~jmk/medusa/medusa.html
Snort – Intrucion Detection http://www.snort.org/
W3af – Web Application Attack http://w3af.org/
NetCat – networking utility http://netcat.sourceforge.net/
THC-Hydra – network logon cracker http://thc.org/thc-hydra/
Wapiti – Web application vulnerability scanner http://wapiti.sourceforge.net/
http://blackbsd.org
BSD license.
Copyright (c) 2013 BlackBSD
All rights reserved.
All rights reserved.
Redistribution and use in source and
binary forms, with or without modification, are permitted provided that
the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-
The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR
“AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
DNS and BIND on NetBSD
Three advices:
Edit an example supfile in /usr/share/examples/supfiles:
Before starting BIND on host1, verify that named.conf and zone files are syntatically correct and valid.
Once all three hosts are up and running, lets put them into use by editing /etc/resolv.conf and add:
Obscure BIND version:
Firstly, people have no business in knowing what version of BIND is running. Secondly, according to the Project Honeynet, the two most popular scans from script kiddies on the internet today are BIND version and portmap (rpcbind). So this is another good reason to not give them the easy information they need.
In /etc/namedb/named.conf, add a version statement and put whatever you want between double quote.
In host1, edit /etc/namedb/db.example:
Query is similar to mail open relay concept. Only trusted mail clients can relay mails through the mail server. With DNS, only trusted clients can query the server.
Restrict recursive query to only trusted DNS clients:
Cache only name server basically caches information that it receives and uses it until the data expires. A cache only server is not authoritative for any zone.
Here is an example configuration of a cache only server:
A stealth server is a server that answers authoritatively for a zone, but is not listed in that zone.s NS records. Stealth servers can be used as a way to centralize distribution of a zone, without having to edit the zone on a remote nameserver. Where the master file for a zone resides on a stealth server in this way, it is often referred to as a ``hidden primary'' configuration. Stealth servers can also be a way to keep a local copy of a zone for rapid access to the zone.s records, even if all ``official'' nameservers for the zone are inaccessible.
Remote name daemon controller: rndc
BIND comes with rndc and is a tool to manage a running BIND. To use rndc, an /etc/rndc.conf is required. rndc uses an authenticated link to communicate with the name server. This will reduce the chance of message spoofing the link.
Get rndc to work:
First, generate a shared secret key. The key will be used by rndc and named to authenticate each other.
TSIG stands for transaction signatures and is for server-to-server communication. Useful for dynamic update and zone transfer.
First create a shared secret key for use during zone transfer between master and slave:
Tell local name server to sign all requests with key if it's the one who initiates the transaction.
The idea is to ask the domain registry to ``delegate'' example.com domain requests to your own DNS server and find a backup for the domain just in case your DNS is unreachable.
Here are what the domain registry required to update their DNS for proper delegation. Note that the information below are ficticious:
The last 2 lines are called glue records. Glue record is an A
record where the name appears on the right hand side of an NS
record.
Setup example.com zone to answer requests from the
internet:
Setup other.com zone to backup for example.com:
other.com will be able to transfer db.example and db.10.0.0 from example.com primary dns server. For other.com db.other and db.172.16.0 should have similar entries as example.com's db.example and db.10.0.0 zone files.
1. Get DNS and BIND book. It's nice to understand how DNS works. 2. DNS needs time to distribute its information. 3. BIND won't load if there is a syntax error.If you have two or more computers, it is recommended to use DNS instead of /etc/hosts. Another obvious advantage is mail routing. With traditional /etc/hosts, there is no easy way to specify backup mail servers for mail delivery. This howto is based on the author's experience with BIND on his favourite NetBSD 1.5.1 and 1.5X boxes.
- Download BIND
- Setup zone and DNS records
- Secure BIND
- Different DNS servers
- Run DNS for your own domain
- Familiarize with DNS tools
Download BIND
NetBSD 1.5.1 comes with BIND 8.2.3 and 8.2.4-REL-NOESW on NetBSD 1.5X. BIND8 is considered to be stable and is used by most root name servers. BIND9 is a complete rewrite with several new features:DNSSEC (signed zones) TSIG (signed DNS requests) IPv6 support Bitstring Labels DNS Protocol Enhancements IXFR, DDNS, Notify, EDNS0 Views (former split-dns) Multiprocessor Support Improved Portability ArchitectureSo it is worthwhile to run and play with new features.For the rest of the howto, BIND means BIND version 9. Since BIND is in the NetBSD packages collection, first, get the packages collection then install BIND. You can skip this part and just download the BIND source from here and just build yourself.
Edit an example supfile in /usr/share/examples/supfiles:
# cp /usr/share/examples/supfiles/sup.netbsd.org /etc/ports-supfileRemove other lines except for the ``current release'' below.
# $NetBSD: sup.netbsd.org,v 1.4.10.1 2000/08/10 23:15:24 soda Exp $ # # Example supfile for sup.netbsd.org. # current release=pkgsrc host=sup.netbsd.org hostbase=/ftp/pub \ base=/usr prefix=/usr backup use-rel-suffix compress deleteRetrieve the packages collection:
# cd /usr # sup /etc/ports-supfile ( packages downloading, it will take a while. Maybe now is a good time for an expresso cup... ) ...Once it is done, build and install BIND9 as:
# cd /usr/pkgsrc/net/BIND9 # make install clean ( BIND9 building, installing and cleaning...Another expresso cup would be nice ) ...BIND binaries will be installed mostly in /usr/pkg/sbin. It also comes with lwresd and named9 scripts in /usr/pkg/etc/rc.d. Copy named9 to /etc/rc.d and turn on the executable bit with chmod +x.
# cp /usr/pkg/etc/rc.d/named9 /etc/rc.d # chmod +x /etc/rc.d/named9lwresd is the lightweight resident daemon. Not a requirement to get BIND running. Now, enable BIND on startup:
# vi /etc/rc.conf.d/named9 and add: named9=YES named_flags="-c /etc/namedb/named.conf"This will start BIND as root user in non-chroot compartment. Section 3 of this howto will change how it runs.
Setup zone and DNS records
For this howto, assume the following ficticious information: Domain example.com:host1: IP: 10.0.0.1 Purpose: primary DNS server primary mail server primary web server host2: IP: 10.0.0.2 Purpose: secondary DNS server secondary mail server host3: IP: 10.0.0.3 Purpose: secondary DNS server primary ftp server network: 10.0.0/24 loopback: 127.0.0.1BIND configuration files for host1 as primary DNS server:
Configuration directory: /etc/namedb Main configuration file: named.conf example.com name-to-address zone: db.example example.com address-to-name zone: db.10.0.0 loopback zone: db.127.0.0 root hint zone: db.cache /* * Main configuration file * /etc/namedb/named.conf */ /* Global options */ options { /* BIND directory */ directory "/etc/namedb"; auth-nxdomain no; }; /* Local network name-to-address zone file */ zone "example.com" in { /* This zone is of type primary and will load the zone file * from local disk. */ type master; file "db.example"; }; /* Local network reverse map zone file */ zone "0.0.10.IN-ADDR.ARPA" in { /* This zone is of type primary and will load the zone file * from local disk. */ type master; file "db.10.0.0"; }; /* Loopback reverse map zone file */ zone "0.0.127.IN-ADDR.ARPA" in { /* This zone is of type primary and will load the zone file * from local disk. */ type master; file "db.127.0.0"; }; /* Use root servers for non-authoritative domains */ zone "." in { /* Consult root servers for other domains. */ type hint; file "db.cache"; }; /* * example.com name-to-address zone * /etc/namedb/db.example */ $TTL 86400 @ IN SOA host1.example.com. hostmaster.example.com. ( 2001081101 ; serial 21600 ; refresh after 6 hours 3600 ; retry after 1 hour 604800 ; expire after 1 week 86400 ; minimum negative cache TTL of 1 day ) ; ; Name servers ; IN NS host1.example.com. IN NS host2.example.com. IN NS host3.example.com. ; ; Mail MX RRs ; example.com. IN MX 0 host1.example.com. IN MX 10 host2.example.com. ; ; Addresses for the canonical names ; localhost IN A 127.0.0.1 host1 IN A 10.0.0.1 host2 IN A 10.0.0.2 host3 IN A 10.0.0.3 ; ; Aliases ; www IN CNAME host1.example.com. mail IN CNAME host2.example.com. ftp IN CNAME host3.example.com. /* * example.com address-to-name zone * /etc/namedb/db.10.0.0 */ $TTL 86400 @ IN SOA host1.example.com. hostmaster.example.com. ( 2001081101 ; serial 21600 ; refresh after 6 hours 3600 ; retry after 1 hour 604800 ; expire after 1 week 86400 ; minimum negative cache TTL of 1 day ) ; ; Name servers ; IN NS host1.example.com. IN NS host2.example.com. IN NS host3.example.com. ; ; Addresses point to canonical name ; 1 IN PTR host1.example.com. 2 IN PTR host2.example.com. 3 IN PTR host3.example.com. /* * example.com loopback zone * /etc/namedb/db.127.0.0 */ $TTL 86400 @ IN SOA host1.example.com. hostmaster.example.com. ( 2001081101 ; serial 21600 ; refresh after 6 hours 3600 ; retry after 1 hour 604800 ; expire after 1 week 86400 ; minimum negative cache TTL of 1 day ) ; ; Name servers ; IN NS host1.example.com. IN NS host2.example.com. IN NS host3.example.com. 1.0.0.127.IN-ADDR.ARPA. IN PTR localhost.For root hint zone, either rename root.hint to db.cache or execute this command to download the latest copy.
# dig @a.root-servers.net. . ns > /etc/namedb/db.cacheBIND configuration files for host2 as secondary:
Configuration directory: /etc/namedb Main configuration file: named.conf example.com name-to-address zone: secondary for host1 example.com address-to-name zone: secondary for host1 loopback zone: db.127.0.0 root hint zone: db.cache /* * BIND configuration file for host2 * /etc/namedb/named.conf */ /* Global options */ options { /* BIND directory */ directory "/etc/namedb"; auth-nxdomain no; }; /* Local network name to address zone file */ zone "example.com" in { /* This zone is of type secondary and will download the zone file * from host1. */ type slave; file "db.example"; masters { 10.0.0.1; }; }; /* Local network reverse map zone file */ zone "0.0.10.IN-ADDR.ARPA" in { /* This zone is of type secondary and will download the zone file * from host1. */ type slave; file "db.10.0.0"; masters { 10.0.0.1; }; }; /* Loopback reverse map zone file */ zone "0.0.127.IN-ADDR.ARPA" in { /* This zone is of type primary and will load the zone file from * local disk. */ type master; file "db.127.0.0"; }; /* Use root servers for non-authoritative domains */ zone "." in { /* Consult root servers for other domains. */ type hint; file "db.cache"; }; /* * example.com loopback zone * /etc/namedb/db.127.0.0 */ $TTL 86400 @ IN SOA host1.example.com. hostmaster.example.com. ( 2001081101 ; serial 21600 ; refresh after 6 hours 3600 ; retry after 1 hour 604800 ; expire after 1 week 86400 ; minimum negative cache TTL of 1 day ) ; ; Name servers ; IN NS host1.example.com. IN NS host2.example.com. IN NS host3.example.com. 1.0.0.127.IN-ADDR.ARPA. IN PTR localhost.For root hint zone, either rename root.hint to db.cache or execute this command to download the latest copy.
# dig @a.root-servers.net. . ns > /etc/namedb/db.cacheBIND configuration files for host3 as slave:
Configuration directory: /etc/namedb Main configuration file: named.conf example.com name-to-address zone: secondary for host1 example.com address-to-name zone: secondary for host1 loopback zone: db.127.0.0 root hint zone: db.cacheFrom this point on, host3 configuration files are identical to host2. Just repeat the steps for host2. Starting BIND:
Before starting BIND on host1, verify that named.conf and zone files are syntatically correct and valid.
# /usr/pkg/sbin/named-checkconf /etc/namedb/named.conf # /usr/pkg/sbin/named-checkzone example.com /etc/namedb/db.exampleAt this point, BIND is ready to start:
# /etc/rc.d/named9 start Starting named. #Check /var/log/messages for the last line for the word "running". e.g.: Aug 6 16:01:00 roseapple /usr/pkg/sbin/named[8203]: running Looks like BIND is running on host1. Repeat this step for host2 and host3.
Once all three hosts are up and running, lets put them into use by editing /etc/resolv.conf and add:
search example.com nameserver 10.0.0.1 nameserver 10.0.0.2 nameserver 10.0.0.3Then ping host2, host3 and localhost from host1 to see if name-to-address is working. They should resolve to 10.0.0.2, 10.0.0.3 and 127.0.0.1. Try to ping www.yahoo.com to see if BIND is perusing root hint zone. Finally, to test reverse mapping, use ``host'' and give the IP address of host2, 3 and localhost and the output should look similar to this:
# host 10.0.0.2 2.0.0.10.IN-ADDR.ARPA domain name pointer host2.example.comRepeat this on host2 and host3. Both should behave the same as host1. If all goes well, time for a third expresso cup. It is definitely boring doing all these steps. There is a utility called h2n which will convert a working /etc/hosts into configuration files above. However, doing manually is tedious but sure makes your brain smarter.
Secure BIND
Now that everything is working, there are other considerations to make it more secure. Early versions of BIND did not have a good security record. However, BIND is still the best implementation around.Obscure BIND version:
Firstly, people have no business in knowing what version of BIND is running. Secondly, according to the Project Honeynet, the two most popular scans from script kiddies on the internet today are BIND version and portmap (rpcbind). So this is another good reason to not give them the easy information they need.
In /etc/namedb/named.conf, add a version statement and put whatever you want between double quote.
options { directory "/etc/namedb"; version "Expresso cup"; };Now, use dig to query the version from a remote host and "Expresso cup" should appear instead of real BIND version.
# dig @host1.example.com txt chaos version.bindRestrict zone transfer: Zone transfer is intended for secondary nameservers to retrieve any zones for backup purposes. For other nameservers, they should not be able to retrieve any zones and use whatever information to mount attacks. Lets restrict zone transfer to trusted secondary nameservers only.
In host1, edit /etc/namedb/db.example:
zone "example.com" in { type master; file "db.example"; /* Only host2 and host3 can transfer this zone */ allow-transfer { 10.0.0.2; 10.0.0.3; }; };In host1, edit /etc/namedb/db.10.0.0:
zone "0.0.10.IN-ADDR.ARPA" in { type master; file "db.example"; /* Only host2 and host3 can transfer this zone */ allow-transfer { 10.0.0.2; 10.0.0.3; }; };Restrict zone transfer on any secondary too as attackers will try to zone transfer all authoritative dns servers. Restrict query:
Query is similar to mail open relay concept. Only trusted mail clients can relay mails through the mail server. With DNS, only trusted clients can query the server.
/* Define my network */ acl "example.com-net" { 10.0.0.0/24; };In host1, edit /etc/namedb/db.example:
zone "example.com" in { type master; file "db.example"; allow-transfer { 10.0.0.2; 10.0.0.3; }; allow-query { example.com-net; }; };In host1, edit /etc/namedb/db.10.0.0:
zone "0.0.10.IN-ADDR.ARPA" in { type master; file "db.example"; allow-transfer { 10.0.0.2; 10.0.0.3; }; allow-query { example.com-net; }; };Restrict recursive query: Recursive query is a query send to the nameserver for the information which the local nameserver is not authoritative and must ask other nameservers for the answer. The answer is then feed back to the client and the nameserver will cache the information for future requests. Trusted DNS clients use this feature by listing nameservers in /etc/resolv.conf. Even if untrusted clients putting our nameservers in their /etc/resolv.conf and our nameservers to do the work for free, prevent this from happen with allow-recursion below.
Restrict recursive query to only trusted DNS clients:
/* Define my network */ acl "example.com-net" { 10.0.0.0/24; }; options { directory "/etc/namedb"; version "Expresso cup"; allow-recursion { "example.com-net"; }; };Run BIND as non-root user inside chroot jail under NetBSD 1.5.1: Add named account to passwd using vipw:
named:*:14:14::0:0:Named pseudo-user:/var/named:/sbin/nologinAdd named group to /etc/group:
named:*:14:Populate the chroot compartment:
# mkdir -p /var/chroot/named # cd /var/chroot/named # mkdir -p dev etc/namedb/cache usr/libexec var/run var/tmp # chmod 775 etc/namedb/cache # chown -R named:named etc/namedb/cache # chmod 775 var/run # chmod 01775 var/tmp # chgrp named var/run var/tmp # mknod dev/null c 2 2 # mknod dev/random c 46 0 # chmod 666 dev/null dev/random # chgrp named /etc/rndc.conf /etc/rndc.key # chmod 640 /etc/rndc.conf /etc/rndc.key # cp -p /etc/rndc.key /var/chroot/named/etcEdit BIND startup configuration file so that it will run in chroot compartment with a non-priviledged user: Modify /etc/rc.conf.d/named9 and add -u named -t /var/chroot/named to named_flags:
named9=YES named_flags="-c /etc/namedb/named.conf -u named -t /var/chroot/named"Edit BIND script to point from old location of pid-file to new one:
# vi /etc/rc.d/named9and change:
pidfile="/var/run/${name}.pid"to:
pidfile="/var/chroot/named/var/run/${name}.pid"Copy BIND configuration files to chroot compartment and set proper permission:
# cp -p /etc/namedb/* /var/chroot/named/etc/namedbRestart BIND to pick up new changes:
# /etc/rc.d/named9 restartRun BIND as non-root user inside chroot jail under NetBSD 1.5 current: On 1.5X current, the chroot jail compartment is already populated and ready to use. All is needed is to copy the configuration files in /etc/namedb to /var/chroot/named/etc/namedb.
# cp -p /etc/namedb/* /var/chroot/named/etc/namedbEdit BIND startup config file so that it will run in chroot compartment with a non-priviledged user: Modify /etc/rc.conf.d/named9 and add -t /var/chroot/named and -u named to named_flags:
named9=YES named_flags="-c /etc/namedb/named.conf -t /var/chroot/named -u named"Starting with BIND 9.2.0, it requires /dev/random in chroot, so populate it:
# mknod /var/chroot/named/dev/random c 46 0If the nameserver is a slave for any other domains, BIND needs to have write access to that directory. /var/chroot/named/etc/namedb/cache is where BIND will download other domain zones. Modify named.conf accordingly for the backup zones and make sure the ``file'' statement is referring to ``cache'' directory. e.g.:
/* example.com zone name-to-address */ zone "example.com" in { type slave; file "cache/db.example"; masters { 10.0.0.1; }; allow-transfer { none; }; };Running rndc to manage BIND in chroot environment requires proper permission. Allow group BIND to use rndc in chroot:
# chgrp named /etc/rndc.conf /etc/rndc.keyOnly root and group BIND should know the secret key:
# chmod 640 /etc/rndc.conf /etc/rndc.keyFinally, BIND needs to know the secret key when loading:
# cp -p /etc/rndc.key /var/chroot/named/etcStart BIND in chroot:
# /etc/rc.d/named9 start
Different DNS servers
There are different type of DNS servers each serving a purpose. We have discussed and configured primary/master, secondary/slave. Others are cache only server, forwarding server and stealth server. Lets look at each one of them. Cache only name server:Cache only name server basically caches information that it receives and uses it until the data expires. A cache only server is not authoritative for any zone.
Here is an example configuration of a cache only server:
/* * file: /etc/namedb/named.conf * purpose: cache only name server */ acl "example.com.internal" { 192.168.1.0/24; }; options { directory "/etc/namedb"; allow-query { "example.com.internal"; }; }; zone "0.0.127.IN-ADDR.ARPA" in { type master; file "db.127.0.0"; }; zone "." in { type hint; file "db.cache"; };Stealth server: From BIND9 ARM:
A stealth server is a server that answers authoritatively for a zone, but is not listed in that zone.s NS records. Stealth servers can be used as a way to centralize distribution of a zone, without having to edit the zone on a remote nameserver. Where the master file for a zone resides on a stealth server in this way, it is often referred to as a ``hidden primary'' configuration. Stealth servers can also be a way to keep a local copy of a zone for rapid access to the zone.s records, even if all ``official'' nameservers for the zone are inaccessible.
Remote name daemon controller: rndc
BIND comes with rndc and is a tool to manage a running BIND. To use rndc, an /etc/rndc.conf is required. rndc uses an authenticated link to communicate with the name server. This will reduce the chance of message spoofing the link.
Get rndc to work:
First, generate a shared secret key. The key will be used by rndc and named to authenticate each other.
# dnssec-keygen -a hmac-md5 -b 512 -n HOST int-examplewill generate:
Kint-example.+157+23209.key Kint-example.+157+23209.privatethe shared secret key is in either file.
# cat Kint-example.+157+23209.key int-example. IN KEY 512 3 157 xCWxMply6q0NFFTIpL4Qf9qpFtg/DSADFSsdsdfgC9jq11QabdM+QHPaaOJG 9yzlnYp U0SWtSY10LXds6twdraoRsOA==The last long string is the shared secret key, copy and and paste in the secret statement of /etc/rndc.conf. In /etc/rndc.conf, only options and key statements are required.
/* * /etc/rndc.conf for example.com */ // Key int-example. key "int-example." { algorithm "hmac-md5"; secret"vCWxMply6q0NFFTIpL4Qf9qpFtg/Du67g3IgC9jq11QabdM+QHPddOJG 9yzlnYpU 0SWtSY9LXds6twdraoRsOA=="; }; // Default server is localhost and key name is int-example. options { default-server localhost; default-key "int-example."; }; server localhost { key "int-example." };In /etc/namedb/named.conf, declare the key and controls statement as below to enable the communicating channel.
// Use shared secret key for TSIG and rndc key "int-example." { algorithm hmac-md5; secret"vCWxMply6q0NFFTIpL4Qf9qpFtg/Du67g3IgC9jq11QabdM+QHPddOJG 9yzlnYpU 0SWtSY9LXds6twdraoRsOA=="; }; // Allow rndc to connect to 127.0.0.1 on port 953 controls { inet 127.0.0.1 allow { localhost; } keys { "int-example." ;}; };To test rndc, try reload /etc/namedb/named.conf file with:
# rndc reload rndc: reload command successful #View /var/log/messages to see if BIND is reloaded successfully. To view statistics:
# rndc stats rndc: stats command successful #A file /etc/namedb/named.stats is generated for viewing. TSIG:
TSIG stands for transaction signatures and is for server-to-server communication. Useful for dynamic update and zone transfer.
First create a shared secret key for use during zone transfer between master and slave:
# dnssec-keygen -a hmac-md5 -b 512 -n HOST example-exslave.Declare the key in /etc/namedb/named.conf:
// Use shared secret key for TSIG and rndc key "muine-secondary." { algorithm hmac-md5; secret"4BQV4cc6JbE5wlMlVr/+HdO2G7qzBZOSxsrpyR5QjSMXqPm37ZIHZc8x LcsIG6XE MLnzGK+H3NC7I4Xeoc70Jw=="; };For the the zone you want to permit slave to transfer add:
// All zone transfers to those signed with the example-other key allow-transfer { key example-other. ;};At this point, if the local name server receives a message signed with this key, it can verify the signature. If the signature succeeds, the response is signed by the same key. When using shared secret, /etc/namedb/named.conf should not set to world-readable. Transfering key from one server to another using ssh is better than telnet. TSIG requires that the clocks be no more than 5 minutes apart between master-slave because it will timestamp TSIG record to prevent replay attacks. Make sure your clock is synchronize properly.
Tell local name server to sign all requests with key if it's the one who initiates the transaction.
// Sign all requests with key example-other when communicating with 10.10.0.0 server 10.10.0.0 { keys { example-other. ;}; };
Run DNS for your own domain
If you're one of those people with a static IP address and a registered domain name, you might want to consider running your own DNS instead of relying on somebody else. First, update example.com DNS information at the domain registry where it was registered so that your new DNS will become the authoritative nameserver. Second, arrange with a friend to act as secondary DNS. Alternatively, use free 3rd party like Secondary.com or The Public DNS Service. Read DJB's Third-party DNS service page for some caveats.The idea is to ask the domain registry to ``delegate'' example.com domain requests to your own DNS server and find a backup for the domain just in case your DNS is unreachable.
Here are what the domain registry required to update their DNS for proper delegation. Note that the information below are ficticious:
domain to delegate: example.com primary dns server for example.com: ns.example.com ns.example.com IP address: 10.0.0.1 secondary dns server for example.com: ns.other.com ns.other.com IP address: 172.16.0.1Here is how it is going to look like in the parent/name registry DNS zone:
; ; Delegate example.com to ns.example.com DNS ;
Name | CLASS | TTL | TYPE | RR Data |
example.com | 86400 | IN | NS | ns.example.com |
86400 | IN | NS | ns.other.com | |
ns.example.com | 86400 | IN | A | 10.0.0.1 |
ns.other.com | 86400 | IN | A | 10.0.0.2 |
/* Global options */ options { directory "/etc/namedb"; auth-nxdomain no; recursion no; }; /* Control logging behaviour */ logging { category lame-servers { null; }; }; /* example.com zone name-to-address */ zone "example.com" in { type master; file "db.example"; allow-transfer { 172.16.0.1; }; }; /* example.com zone address-to-name */ zone "0.0.10.IN-ADDR.ARPA" in { type master; file "db.10.0.0"; allow-transfer { 172.16.0.1; }; }; /* loopback zone address-to-name */ zone "0.0.127.IN-ADDR.ARPA" in { type master; file "db.127.0.0"; }; /* root hint zone */ zone "." in { type hint; file "db.cache"; }; /* example.com zone name-to-address */ ; ; Default Time To Live for records with undefined TTLs ; $TTL 86400 @ IN SOA ns.example.com. hostmaster.example.com. ( 2001092401 ; serial 43200 ; refresh after 12 hours 3600 ; retry after 1 hour 1209600 ; expire after 2 weeks 86400 ; minimum negative cache TTL of 1 day ) ; ; Nameservers ; IN NS ns.example.com. IN NS ns.other.com. ; ; Mail servers ; example.com. IN MX 0 ns.example.com. IN MX 10 ns.other.com. ; ; example.com ; IN A 10.0.0.1 ; ; ns.example.com ; ns IN A 10.0.0.1 ; ; Aliases: ; www.example.com ; ftp.example.com ; www IN CNAME ns.example.com. ftp IN CNAME ns.example.com. /* example.com zone address-to-name */ ; ; Default Time To Live for the zone ; $TTL 86400 @ IN SOA ns.example.com. hostmaster.example.com. ( 2001092401 ; serial 43200 ; refresh after 12 hours 3600 ; retry after 1 hour 1209600 ; expire after 2 weeks 86400 ; minimum negative cache TTL of 1 day ) ; ; Nameservers ; IN NS ns.example.com. IN NS ns.other.com. ; ; Reverse mapping for ns ; 1 IN PTR ns.example.com.And the usual loopback zone address-to-name... And the usual root hint zone...
Setup other.com zone to backup for example.com:
other.com will be able to transfer db.example and db.10.0.0 from example.com primary dns server. For other.com db.other and db.172.16.0 should have similar entries as example.com's db.example and db.10.0.0 zone files.
/* Global options */ options { directory "/etc/namedb"; auth-nxdomain no; recursion no; }; /* Control logging behaviour */ logging { category lame-servers { null; }; }; /* example.com zone name-to-address */ zone "example.com" in { type slave; file "db.example"; masters { 10.0.0.1; }; allow-transfer { none; }; }; /* example.com zone address-to-name */ zone "0.0.10.IN-ADDR.ARPA" in { type master; file "db.10.0.0"; masters { 10.0.0.1; }; allow-transfer { none; }; }; /* other.com zone address-to-name */ zone "0.16.172.IN-ADDR.ARPA" in { type master; file "db.172.16.0"; allow-transfer { none; }; }; /* loopback zone address-to-name */ zone "0.0.127.IN-ADDR.ARPA" in { type master; file "db.127.0.0"; }; /* root hint zone */ zone "." in { type hint; file "db.cache"; };
Familiarize with DNS tools
DNS debugging tools: host,dig,nslookup,dnswalk,doc To find out mail exchange for example.com:# host -t mx example.comTo find out name server for example.com:
# host -t ns example.comTo manually transfer zone example.com:
# dig @ns.example.com AXFR example.comUse dnswalk to test example.com:
# dnswalk -d example.com.Use doc to verify that example.com is configured and functioning correctly:
# doc example.comdoc will produce log.example.com. file with all the information needed to verify the correctness of example.com To find out the authors of BIND:
% dig @ns.example.com authors.bind chaos txtLoad balance (round robin): BIND supports load balancing between 2 or more IP addresses. Ping postoffice will
; Name TTL CLASS TYPE RR Data postoffice 300 IN A 10.0.0.2 300 IN A 10.0.0.3 $ ping postoffice PING postoffice.example.com (10.0.0.2): 56 data bytes ... 1 packets transmitted, 1 packets received, 0.0% packet loss $ ping postoffice PING postoffice.example.com (10.0.0.3): 56 data bytes ... 1 packets transmitted, 1 packets received, 0.0% packet lossThe order will be: 10.0.0.2,10.0.0.3 and 10.0.0.3,10.0.0.2 and back to 10.0.0.2,10.0.0.3 and so on.
Reference
BIND home: http://www.isc.org/products/BIND/ DNS rfc: http://www.example.com/rfc/rfc1035.txt/ DNS and BIND bible: http://www.ora.com/catalog/dns4/ comp.protocols.tcp-ip.domains Frequently Asked Questions http://www.intac.com/~cdp/cptd-faq/ Name Server Operations Guide for BIND http://www.irbs.com/bog-4.9.5/ Read BIND Administrator Reference Manual: http://www.nominum.com/resources/documentation/Bv9ARM.pdf Mr. DNS questions archive: http://www.acmebw.com/askmrdns/ http://www.menandmice.com/9000/9300_DNS_Corner.html DNS Resources Directory: http://www.dns.net/dnsrd/ DNS implementation by qmail author: http://cr.yp.to/djbdns.html Operational guidelines for Root Name Servers. http://www.muine.org/rfc2870.txt Common DNS Operational and Configuration Errors http://www.muine.org/rfc/rfc1912.txt Selection and Operation of Secondary DNS Servers http://www.muine.org/rfc/rfc2182.txt Tools for DNS debugging http://www.muine.org/rfc/rfc1713.txt ftp://ftp.uu.net/.vol/1/ip/dns/ Securing an internet name server http://www.nsiregistry.com/dns/securing_an_internet_name_server.pdf Running BIND9 in a chroot cage using NetBSD's new startup system http://www.daemonnews.org/200110/named-chroot.html
viernes, 26 de abril de 2013
lunes, 22 de abril de 2013
jueves, 18 de abril de 2013
lunes, 8 de abril de 2013
NetBSD Most Secure OS ever
1. Introduction
Running on almost twenty different architectures, and easily portable to others, NetBSD gained its reputation as the most portable operating system on the planet. While that may indicate high quality code, the ever demanding networked world cares about more than just that. Over the past year, NetBSD evolved quite a bit in various areas. This paper, however, will focus on those aspects relating to security.This paper was written and structured to present a full overview of the recent security enhancements in NetBSD in an easily readable and balanced form that will satisfy new, intermediate, and experienced users. References were sprinkled across the text to provide more information to those who want more detail, while preserving the continuity.
Following this introduction, the paper is presented in five major sections, spread over eight pages. Section 2 presents the bigger picture of security in NetBSD: how NetBSD perceives security, the design decisions of NetBSD software in general and the security infrastructure and features more specifically. Section 3 presents a detailed overview of the recent enhancements in the security infrastructure and features of NetBSD including, where relevant, details about the design, implementation, and possible future development. Section 4 shows current security-related research and development in NetBSD, and then section 5 discusses how the described enhancements work together to provide a more secure platform. Section 6 concludes the paper, and summarizes the availability of the discussed features.
2. The Tao of NetBSD Security
We are all familiar with the mantra that security is a process, not a product. When we consider software development, specifically operating systems, it should be part of the design from the ground up. As the descendent of an operating system over 20 years old, NetBSD carries a security model designed and implemented with different threats in mind; the Internet was smaller, more naive, and less popular.The following sections will provide background to the approaches taken to enhance the security of the NetBSD operating system: the considerations, existing approaches, and case-studies.
2.1 Considerations
When investigating the enhancement of security in NetBSD, two of the most important leading principles were maintaining compatibility and interoperability [ref 1]. Presenting changes that would dramatically impact the user-base was out of question, and careful planning had to be done. In addition, any change to an underlying back-end had to be well thought-out so it maintains existing semantics without enforcing them during the design stage.2.2 Security Approaches
Operating system security is nothing new, and NetBSD is not the first to address the issue. In designing software, and security software in particular, it is mandatory to learn from the experience of previous work. Below are some common approaches to security and real-world case studies.2.2.1 Code Auditing
Code auditing addresses security issues by looking for programming glitches in the source code of the program, often with the assistance of automated tools [ref 2]. Normally the work of vulnerability researchers, when done proactively by the programmers themselves, code auditing has the potential of locating and fixing bugs that have security implications before anyone else finds and exploits them.While some would argue that striving to produce bug-free code is the one true way of achieving security, this view is a fallacy for two main reasons. The first is that security issues are not always the result of programming errors; while code auditing tries to ensure no software bugs will be maliciously exploited because said bugs would simply not exist, it alone ignores other important aspects, such as configuration errors and user behavior policies.
The second reason is that it is not possible to write bug-free code [ref 3]. Over the past decade, awareness on writing secure code rose significantly; automated tools evolved, allowing easy pinpointing of software bugs; open-source software is available for the review of thousands – if not millions – of people. Yet, we still see new security vulnerabilities on a daily basis. Some of those, ironically, are of the exact same type that affected us ten or twenty years ago [ref 4].
2.2.2 Exploit Mitigation
The unorthodox approach of exploit mitigation addresses bugs from the opposite direction of code auditing: instead of looking for them in and removing them from software to make it more secure, it adds bugs to the exploit code to prevent it from working. While that may be over-simplified, the purpose of exploit mitigation technologies is to interfere with the inner-workings of the exploit, eliminating the – often unusual – conditions that make it work.[ref 1] Two other leading principles – not impacting the system performance and an easy user interface, will not be discussed in this paper.
[ref 2] Coverity, for example, offered its services to various open-source projects, including NetBSD, for free. Seehttp://scan.coverity.com
[ref 3] http://www.cs.columbia.edu/~smb/papers/acm-predict.pdf
[ref 4] http://www.cert.org/homeusers/buffer_overflow.html
On one hand, some would claim that exploit mitigation discourages developers from writing secure code and vendors from quickly responding to security incidents: they know there’s a safety net guarding them, and so they pay less attention to security when writing code, or taking their time coming up with fixes for security issues.
On the other hand, however, this is also where exploit mitigation technologies excel: they introduce the concept of preventing the successful exploitation of security vulnerabilities, even before a fix is available. Moreover, they prevent entire classes of bugs, and don’t require constant updating.
2.2.3 Architectural Integration
So far, the previous two approaches assume the cause of a security breach is a bug in the code that is being exploited. The first approach tries to eliminate such bugs, and the second one tries to make it next to impossible to successfully exploit them. However, some environments require more than just that – for example, the ability to define detailed usage policies and associate them with entities on the system became a mandatory part of many security policies. In our context, we can relate that to the Unix permissions model; simply put, due to the coarse separation between a normal user and a superuser, it cannot be used to express many security policies as detailed as may be required.That led to the research of various modern security models, of which most recognized ones are fine-grained [ref 5] discretionary access controls (DACs) and mandatory access controls (MACs). To put things simple, DACs focus on the data owner’s ability to specify who can use it and for what; MACs focus on a mandatory policy that affects everyone.
These systems allow an administrator – and where applicable, the users – to specify fine-grained policies; effectively, this means that a user or a program can be made to work with the minimal amount of privileges required for their operation (which, as implied above, cannot be done with the traditional Unix security model), resulting in damage containment in case of compromise or otherwise minimized impact from security vulnerabilities.
2.2.4 Layered security
To itself, layered security [ref 6] is not a single approach. Where any of the previous three took a different route, the layered security approach suggests that maximized security can only be achieved by combining efforts on all fronts: code auditing is important, but does not come in place of useful exploit mitigation technologies; and architectural integration, of course, has little to do with any of them.Although the above may sound obvious, it is not too often when you see an operating system that puts an emphasis on all three aspects; it will usually be the case that only one of the approaches is fully practiced. Following are some short case-studies that illustrate the importance of each approach by using real-world examples.
2.2.5 Case Studies
Shortly after splitting from NetBSD in 1995, OpenBSD became widely known for its unique – at the time – approach to security: proactive code auditing. Instead of retroactively responding to security issues, OpenBSD developers performed thorough code auditing sessions, sweeping for bugs. This act proved itself more than once, after vulnerabilities found in other operating systems were already fixed [ref 7] in OpenBSD.This, however, did not last too long. In 2002, winds of change blew through the OpenBSD mindset: the long standing fort of code auditing fell, adopting exploit mitigation technologies to its lap [ref 8]. While the reasons behind the move were not published, some speculate that it was the release of an exploit allowing full system compromise of OpenBSD’s default configuration [ref 9] that finally proved that even a group of dedicated programmers cannot find all bugs; at least not first.
Said exploit mitigation technologies made their public debut around 1996, with the appearance of the Openwall [ref 10] project, and later evolved dramatically by the PaX [ref 11] project in 2000. Research done in both projects formed the basis of today’s exploit mitigation technologies. Another commonality of the two was that they offered an implementation based on Linux – which only makes one wonder why it was OpenBSD that was the first to officially adopt these technologies.
Linux, however, took a different direction. First with the addition of POSIX.1e [ref 12] capabilities in 1999, fine-grained discretionary access controls, later with SELinux [ref 13], an implementation of mandatory access controls, and finally with the introduction of the Linux Security Modules framework [ref 14], abstracting the implementation of both, Linux focused mainly on offering means for an administrator to define a detailed security policy, hoping to minimize the effect of a vulnerability.
Not lagging behind too much, though, exploit mitigation technologies also appeared in the official Linux kernel during 2004-2005; in fact, they also made an entrance to the official Windows world with Windows XP SP2 [ref 15], and Windows Vista is expected to include even more such technologies [ref 16].
Simply put, all three major approaches have been practiced by widely used operating systems at one point or another. It is clear to see that although initially a single approach was chosen, eventually it was understood that layered security is the key to stronger defense of computer systems.
2.3 The NetBSD Perception of Security
Learning from others’ experience, the approach taken by NetBSD employs three main principles:- Simplicity. There is no point in providing a feature, whether it’s a kernel subsystem or a userland tool, if it’s not intuitive and easy to use. Furthermore, overly complex code is harder to audit, which may lead to additional bugs.
- Layered security. It is well understood that there is no single solution to security. NetBSD addresses security from a variety of angles, including code auditing, adequate and extensible security infrastructure, and exploit mitigation technologies.
- Sane defaults. Accepting that security may not be the highest priority for all users, NetBSD provides sane defaults to fit the common case. Detailed supplementary documentation helps enable and configure the various security features.
[ref 5] I emphasize fine-grained because DACs already exist on Unix; however, as noted, they are too coarse.
[ref 6] Also known as Defense in Depth.
[ref 7] http://www.openbsd.org/security.html#process
[ref 8] http://www.monkey.org/openbsd/archive/misc/0207/msg01977.html
[ref 9] http://www.securityfocus.com/news/493
[ref 10] http://www.openwall.com
[ref 11] http://pax.grsecurity.net
[ref 12] http://wt.xpilot.org/publications/posix.1e/
[ref 13] http://www.nsa.gov/selinux/papers/module/t1.html
[ref 14] http://www.kroah.com/linux/talks/usenix_security_2002_lsm_paper/lsm.pdf
[ref 15] http://www.microsoft.com/technet/prodtechnol/winxppro/maintain/sp2mempr.mspx
[ref 16] http://blogs.msdn.com/michael_howard/archive/2006/05/26/608315.aspx
3. Overview of Recent NetBSD Security Enhancements
3.1 Kernel Authorization
The introduction of kernel authorization, often referred to as kauth(9), in the NetBSD kernel has been one of the larger-scale changes ever done in NetBSD. The interface is modeled after an interface of the same name developed by Apple for Mac OS X [ref 17], though unfortunately due to licensing issues it was impossible to make use of existing code, and so the NetBSD implementation was written completely from scratch.Kernel authorization redefines the way credentials are handled by the kernel, and offers a simple and easy to use – yet powerful and extensible – kernel programming interface to enforce security policies. It is important to emphasize that kernel authorization does not provide any additional security by itself, but rather provides an interface on top of which security policies can be easily implemented. The strength of the security directly depends on the strength of the policy used.
The kernel authorization infrastructure is required for supporting fine-grained capabilities, ACLs, and pluggable security models among other things. It will allow NetBSD administrators and users to maintain the existing traditional Unix security model, offer capabilities to replace set-user-id and set-group-id programs, and allow third-party developers and appliance manufacturers to implement a custom security model to either replace or sit on-top of the existing one.
3.1.1 Related Work
Similar infrastructures are Linux’s LSM (discussed earlier) and TrustedBSD’s (now in FreeBSD) MAC framework [ref 18]. Both have been in use for a couple of years, but like kernel authorization, are still very young to backup with real-world experiences.3.1.2 Design
Apple did most of the design work for the kernel authorization infrastructure. A large part of the design is available online, and it’s merely the implementation that was unavailable. Therefore, most of the design-related work in doing the native NetBSD port focused on completing the missing parts from the online documentation and taking care of compatibility issues.Kernel authorization maps the privilege landscape of the kernel to actions grouped as scopes. For example, theprocess scope groups actions such as “can trace”, “can see”, and “can signal” – which are all operations on processes.
When a request for an operation is made, the action is passed to the authorization wrapper of the relevant scope, together with related context. The context is variable: it is different for each request. The authorization wrapper dispatches the request and the context to the listeners associated with the scope. Each listener can return a decision – either allow, deny, or defer (indicating the decision should be left to the other listeners) – and the authorization wrapper evaluates the responses from all listeners to decide whether to allow or deny the request.
In order for a request to be allowed, no listener may return a deny decision. If all listeners return a defer decision, the request is denied.
3.1.3 Implementation
The implementation of kernel authorization in NetBSD was done in several stages. First, the backend was written. This included the majority of the code that worked behind the scenes to implement the credential memory management and reference counting, locking, and scope and listener management. It was then tested to ensure all parts work as a black-boxes, allowing initial integration in the NetBSD code. Part of that work included merging the contents of the ucred and pcred structs into a single, opaque (as possible) type called kauth_cred_t.The next step was a series of mechanical kernel programming interface changes. Credentials could no longer be allocated on the stack, and so a lot of code had to be modified to use the kauth(9) memory management routines. Additionally, code that directly referenced members of the ucred and pcred structures had to be modified to use the accessor and mutator routines provided by the kauth(9) interface. Existing interfaces such as suser(9) and groupmember(9) were deprecated in favor of calls to kernel authorization wrappers, and others such as sys_setgroups(2) and sys_getgroups(2) were modified to use the new interfaces.
The following step consisted of thorough testing – to ensure transparent integration and equivalent semantics – which uncovered some bugs with the kernel authorization code, most of them in the NFS portion of the kernel.
[ref 17] http://developer.apple.com/technotes/tn2005/tn2127.html
[ref 18] http://www.trustedbsd.org/trustedbsd-discex3.pdf
3.1.4 Future Development
While implementing the kernel authorization back-end and making the kernel dispatch its authorization requests to it was an important ground preparation, there is more work to be done before declaring this interface useful.The first step in the integration of kernel authorization was mostly mechanical and transparent to users, intended to preserve existing semantics. The next logical step is to examine the kernel to ensure the interface abstracts the security model used in NetBSD.
Given its heritage, the NetBSD kernel is too tightly coupled with the Unix security model, and the concept of a single super-user with a user-id of zero is often hard- coded. For example, a lot of privileged operations check for an effective user-id of zero directly in the process’ credentials structure, not making use of the suser(9) interface.
The next logical step will be to identify these locations, and properly replace these vague effective user-id checks with calls to the kernel authorization interface, describing the privilege required to complete the operation. The same applies to any authorization wrapper calls acting as placeholders, checking for super-user rights.
The above work will result in the complete abstraction of the security model used in the NetBSD kernel, allowing switching easy as a one-line change in the kernel configuration between the Unix security model, a finer-grained capabilities model, or a third-party security model possibly implemented using an LKM.
3.2 Veriexec
Veriexec is NetBSD’s file-integrity subsystem, allowing the verification of a file’s digital fingerprint before accessing it. Introduced in NetBSD by Brett Lymn in 2002 [ref 19] and later integrating work from Vexec of the Stephanie project [ref 20] in 2005, Veriexec provides means to ensure real-time file integrity and monitoring combined with intrusion detection and prevention capabilities.Initially self-contained, Veriexec’s core – the interface for associating meta-data with files regardless of file-system support using in-kernel memory – was recently abstracted [ref 21] to form the Fileassoc interface to satisfy similar needs from other features.
3.2.1 Related Work
Integrity checker implementations have been around for decades. Used for various purposes such as virus protection in DOS and file changes notifications in Unix, the concept itself is not new to the security industry. Dr. Fred Cohen’s research was among the first to offer insight about using integrity checkers to protect from malicious software [ref 22]. Tripwire [ref 23], presented by Eugene Spafford and Gene Kim, allowed system administrators to be notified about corrupted or altered files in a timely fashion.Yet, while there are numerous products for every computing environment, they all share a common set of flaws that prevents them from realizing their potential.
First, none of them integrates with the operating system deep enough to provide real- time protection: most are retroactive tools used to notify after changes were detected.
This approach does not address potential damage that be caused in the time-window between a file was altered and improperly used since and when the administrator receives notification of the matter and handles it. It also does not guarantee the integrity of the integrity checker itself: a successful compromise has the potential of remaining under the radar.
Furthermore, some implementations use weak algorithms [ref 24] to calculate a file’s checksum, or rely on a small data-set for checksum calculation. Other implementations rely on a file’s attributes rather than data to evaluate integrity. The impact of the above is that a file can be modified in such ways that even if the integrity checker tries to evaluate it after the change, it will not be able to detect it. Whether it’s by altering the file in a way to defeat the checksum algorithm, or modify areas of the file that the integrity checker is known to ignore, or even tamper with the file’s attributes – these implementation flaws can all be bypassed by an attacker quite easily.
And last, they all leave out an important aspect in today’s reality: the network. Our environments become more and more inter-connected; we access files from untrusted locations on a daily basis; some architectures rely on a networked environment for everyday operation: centralized storage, backup, and so on. Existing products may provide a certain level of local protection on a host, but leave an important – and interesting – question unanswered: how do you cope with the compromise of a remote resource?
While we cannot deal with all aspects of compromise of a remote resource we use, and it is certainly not our goal either, it is important to try and address the ones that can be solved by using an integrity checker integrated in the operating system.
3.2.2 Design
Veriexec was designed to be a file-system independent integrity subsystem protected from users, including root, by operating solely from the kernel. Recent attacks against various hashing algorithms once thought secure proven the need for interface flexibility – such that can be used both for easy addition of support for new hashing algorithms, as well as future work on digitally signed files.Careful analysis of the bottlenecks for file access and other file-system semantics (such as rename and remove) resulted in generic hooks, to be called with the required context for decision-making and policy enforcement. At the time of writing, it is impossible to implement the Veriexec policy on top of kauth(9) due to lack of required scopes.
The design process also took into account various environments for Veriexec – from workstations, through servers and critical systems, to embedded task-oriented appliances. Strict levels with varying implications were introduced to support multiple uses, and were named semi-descriptively to hint for said uses: learning mode (level 0), intrusion detection system (IDS) mode (level 1), intrusion prevention system (IPS) mode (level 2), and lockdown mode (level 3).
[ref 19] http://mail-index.netbsd.org/tech-security/2002/10/30/0000.html
[ref 20] http://ethernet.org/~brian/Stephanie/
[ref 21] http://mail-index.netbsd.org/tech-kern/2006/06/08/0007.html
[ref 22] http://vx.netlux.org/lib/afc03.html. Dr. Fred Cohen also introduced the concept of integrity shells, with which Veriexec is sharing some commonalities; no implementation was made available, however, and therefore it is impossible to tell whether the faults mentioned also apply to them.
[ref 23] http://portal.acm.org/citation.cfm?id=191183
[ref 24] For example, CRC: https://www.kb.cert.org/vuls/id/25309
3.2.3 Implementation
The most recent version of Veriexec is implemented using the Fileassoc subsystem for management of meta-data and file association, greatly simplifying the Veriexec code, and a device for kernel-userland interaction.Veriexec is implemented by hooking policy enforcement routines in various parts of the kernel, monitoring execution of normal executables as well as scripts, opening of regular files, and rename and remove operations.
When a file is opened or executed, the evaluation routine, is called with the context of the request (LWP, vnode, filename if any, and access flag indicating how the file was accessed) to make a decision whether the file can be accessed or not. The result is cached to speed-up further evaluations of the same file.
3.2.4 Future Development
During research work on Veriexec, Thor Lancelot Simon pointed out a potential attack [ref 25]. Although Veriexec ensures integrity of files on local file-systems, where all access is done via the kernel, it cannot ensure integrity of files located on remote hosts, imported via NFS, for example.While Veriexec could be told not to cache the evaluation of such files, the attack vector is when a process, or part of it, is paged-out and later paged in. Because the disk read is done by the VM system, and only of pieces (pages) of the program, Veriexec wasn’t aware of it. If the remote host would be compromised, an attacker could write malicious data to the on-disk program, force a memory flush, which would later force a page-in, effectively injecting the malicious data into the address space of the running process on the Veriexec-protected host.
The remedy to this problem is in the form of per-page fingerprints. During fingerprint database generation, the administrator can add the untrusted flag to entries located on remote hosts. Veriexec will generate per-page fingerprints for them, and hook the VM system so that when a page-in occurs, the fingerprints of the relevant pages will be evaluated and compared to those calculated previously.
Another natural development for Veriexec would be to introduce support for digital signatures; that is discussed in subsection 4.2.
3.3 Exploit Mitigation
Exploit mitigation techniques are part of the layered security approach of NetBSD, complementing code auditing and more traditional security features, not intending on replacing them.The purpose of exploit mitigation technologies is to interfere with the exploit code itself, preventing entire classes of exploits from working by short-circuiting common exploitation techniques. One popular example is making sure areas of the memory that are writable, such as the stack and the heap, are non-executable, and vice versa: areas that are executable, such as the where the program’s code is, are not writable.
This prevents exploits that rely on injecting malicious code to a program’s memory from working, because said code cannot be executed.
3.3.1 PaX MPROTECT
For a while NetBSD had support for non-executable mappings [ref 26] on hardware platforms that allow it. However, experienced hackers have found a variety of ways to bypass them. Two of these are return-to-lib exploits [ref 27] and trashing arguments to mprotect(2) to change the protection of memory [ref 28].The PaX MPROTECT [ref 29] feature was developed to address the latter. It enforces a policy where memory that was once writable will not be able to later gain executable permission, and vice versa. Naturally, this policy may break existing applications that make valid use of writable and executable memory, such as programs that load dynamic modules. For this reason, a tool is provided allowing marking executables as excluded from the PaX MPROTECT policy. It is also possible to revert the policy, applying it only to executables marked with an explicit enable flag. While it is possible to modify programs that currently violate the PaX MPROTECT policy to continue working correctly without doing so, this would be an unfeasible effort with third-party applications.
3.3.2 SSP (Stack Smashing Protection) Compiler Extensions
Hiroaki Etoh developed SSP (also known as ProPolice) in IBM Research [ref 30]. Its purpose is making exploitation of certain buffer overflows harder by placing random canary values right before the function return address on the stack, as well as reordering variables on the stack making it harder – if not impossible – to overflow stack buffers in order to overwrite integers or function pointers, preventing exploitation even without altering the return address.First introduced in the OpenBSD 3.4 release, a similar functionality is now available in the stock gcc 4.1 compiler, recently integrated in NetBSD by Matthew Green.
3.3.3 Future Development
One of the planned features in this area for NetBSD is implementing PaX Address Space Layout Randomization [ref 31]. Also developed by the PaX author, ASLR addresses exploitation via return-to-lib attacks [ref 32] by randomizing the location in memory of shared libraries used by the application, thus making it a lot harder to correctly guess the location of library functions within the application address space.As expected, hackers found ways to bypass ASLR. The two most commonly used attacks either combine an information leak bug leading to the disclosure of the location of libraries [ref 33], or brute-force exploitation on respawning daemons in an attempt to guess the correct address in one of many attempts [ref 34].
An ASLR implementation would not be complete without a solution to the latter technique. Such a solution, developed by Rafal Wojtczuk, is Segvguard [ref 35], employing the basic concept of monitoring the rate of SIGSEGV signals sent to an application in a given time-frame, in an attempt to detect when a brute-force exploitation attack is taking place and prevent it by denying execution of the offending application.
A similar monitor will be introduced in NetBSD once ASLR is implemented.
[ref 25] http://mail-index.netbsd.org/tech-security/2002/11/01/0010.html
[ref 26] http://netbsd.org/Documentation/kernel/non-exec.html
[ref 27] http://seclists.org/lists/bugtraq/1999/Mar/0004.html
[ref 28] See thread http://seclists.org/dailydave/2004/q2/0045.html.
[ref 29] http://pax.grsecurity.net/docs/mprotect.txt
[ref 30] http://www.trl.ibm.com/projects/security/ssp/
[ref 31] http://pax.grsecurity.net/docs/aslr.txt
[ref 32] PaX ASLR addresses more than that; it also randomizes stack/heap base addresses for both userland and kernel threads.
[ref 33] http://artofhacking.com/files/phrack/phrack59/P59-0X09.TXT (mirror)
[ref 34] http://artofhacking.com/files/phrack/phrack58/P58-0X04.TXT (mirror)
[ref 35] Ibid.
3.4 Miscellaneous Security Features
3.4.1 Information Filtering
One of the most common requirements from multi-user systems (such as public shell providers) is that users will not be able to tell what other users are doing – such as running programs, active network connections, login/logout times, etc.NetBSD implements the above using the kernel authorization interface, and presents the administrator with a single knob that can be either enabled or disabled. When enabled, the authorization wrappers will match credentials of the two objects (the looker and the lookee) and return the decision.
This abstraction makes it easier to change the behavior of this feature in the future.
3.4.2 Strong Digital Checksum Support
Support for SHA2 checksums has been available in the NetBSD kernel for a while, mainly for the use of the IPSec network stack. Userland, however, was largely neglected. Tools such as cksum(1) and mtree(8) were able to make use only of hashes that were proven weak [ref 36]. Given mtree(8) can be used to evaluate file-system integrity, this was rather dangerous.The recent improvements to Veriexec, allowing it to support SHA2 hashes, amplified the need for userland support for SHA2 hashes, and were the trigger to adding SHA2 hash routines to libc, as well as support in cksum(1) and mtree(8).
3.4.3 Fileassoc
Fileassoc is one of the latest additions to the NetBSD kernel. It allows associating custom meta-data with files, independent of file-system support (such as extended attributes) using in-kernel memory. The interface is the result of research of other security features that stressed the need for an abstraction of code previously used exclusively by Veriexec.3.4.3.1 Design
The Fileassoc interface extends an already-existing design used by Veriexec. The requirements for the design were performance – so that using it in performance- critical code would not cause a notable impact on system performance – and ease of use. The interface was extended, allowing more than one hook to add its own file meta-data.Designed with simplicity in mind, the interface allows multiple subsystems to hook private data on a per-file and/or per-device basis.
3.4.3.2 Implementation
To achieve the desired goal of near-zero performance impact of entry lookup, the Fileassoc subsystem makes use of hash tables and linked-lists to resolve collisions. The interface operates on struct mount * and struct vnode * to identify file-system mounts and files, respectively. While the internal implementation identifies a file as a pair ofstruct mount * and a file-id – the contents of va_fileid after a successful VOP_GETATTR() call – this is planned to change in the near future (see subsection 3.4.3.3).In the current implementation, Fileassoc allows four hooks (which can be modified with a kernel option) to add private data to each file. This is transparent to the users of the interface, allowing changing in the future, if such is required.
3.4.3.3 Future Development
As previously mentioned, Fileassoc still relies on the va_fileid field as the unique identifier for files. This is an internal implementation detail, and expected to replaced in the future with file-handles by using calls to the file-system specific vptofh() routines.3.4.4 Password Policy
Administrators often need to enforce a password policy on the system – either a system-global policy, per-application policy, or even a network-global policy. To address that issue, the password policy, or pw_policy(3), interface was developed.With flexibility and simplicity in mind, the pw_policy(3) interface was designed to allow an administrator to specify password policies via a collection of keywords, and applying them to named entities.
The interface is part of libutil and is small enough to be used from within any existing application. It was designed in a modular way, allowing future support for more keywords and evaluation routines.
[ref 36] http://www.schneier.com/essay-074.html
4. Current NetBSD Security Research and Development
Discussed so far are solutions already implemented and available in NetBSD. Below you will find the current goals of the security research done in NetBSD, some of which are planned to be introduced as soon as the NetBSD 5.0 release.4.1 Deprecating The Kernel Virtual Memory Interface kmem(4)
The kmem(4) device allows raw reading of kernel memory. It was introduced to allow programs that needed information from the kernel a way to extract it by reading the symbol list from the live kernel’s on-disk image and seeking to it.Several issues were raised regarding this device [ref 37], and with 4.4BSD a new interface meant to replace kmem(4) was introduced, named sysctl. Sysctl allowed structured and controlled access to kernel information via syscalls carrying a management information base (MIB). The kernel held a tree-like hierarchy of information it can provide, and the MIB described what information is looked up.
From a security point of view, the kmem(4) device allows malicious processes running with kmem or root privileges to directly read or write kernel memory [ref 38]. The attack vector here is widely abused[ref 39],[ref 40] mainly to introduce stealth rootkits into compromised systems.
Currently, NetBSD is doing loose usage of the kmem(4) interface, using it for more than a few userland utilities. There is an on-going effort to gradually convert programs using kmem(4) to sysctl with proper kernel support, allowing us to deprecate daily use of kmem(4) and maintain the interface for debugging needs only, if required.
4.2 Digitally Signed Files
At the moment, the Veriexec subsystem provides integrity based entirely on data. While it is strong enough to maintain file-system integrity on servers and critical systems, it lacks two important features: ability to securely modify the baseline during runtime, and ability to associate an identity with a file-system object.Securely modifying the baseline during runtime is forbidden, even for the super-user, for security reasons: a possible scenario is that the host can be fully compromised and trojanned by an attacker; preventing the super-user from modifying critical programs can prevent that.
Associating a digital signature with a file-system object, regardless of implementation, could solve the above two by allowing an administrator to specify trusted entities. These could run any programs – as long as they are signed by them. That would mean that introducing a new program on the system required digital signing by a trusted entity, rather than a super-user adding its digital checksum to a database and rebooting.
It is planned to extend the Veriexec subsystem with this capability, in either one of two possible directions for the implementation; either delegating the digital signature processing to a user-space daemon, or making use of the BSD-licensed BPG inside the kernel.
4.3 Access Control Lists
Perhaps one of the longest remaining Unix relics in NetBSD is the file-system security model. Proven weak over time, modern operating systems implemented file- system access control lists, or ACLs.An ACL allows finer-grained file access, extending the owner-group-other scheme currently used.
There are two main issues when approaching file-system ACLs. The first is where to store them, and how to associate a potentially variable sized data-structure with a file. The second is what ACL model to use, which may dictate interoperability with other operating systems.
For the former, NetBSD provides both the UFS2 file-system [ref 41], where extended attributes were introduced especially to address this issue, as well as the Fileassoc kernel interface, allowing file-system independent association of meta-data, after such data has been loaded via a driver.
Given recent standardization in ACL structure between Windows NT, Mac OS X, and NFSv4, it was decided to go with the same model for the latter, allowing NetBSD to properly operate in a heterogeneous environment.
4.4 Capabilities
Part of Unix’s long-standing weaknesses is the use of set-id programs to elevate privileges of a normal user, either temporarily or permanently, required to complete an operation restricted to the super-user – for example, open a raw socket, bind to a reserved port, and so on.The above lead to the absurdity that bugs in often trivial and non-critical programs could result in privilege abuse or even full system compromise.
Introducing capabilities, implemented as a set of kernel authorization listeners, will replace the role of the set-id bit in today’s systems. Providing a fine-grained privilege model, each program will run with the minimal set of capabilities required for its operation. Furthermore, associating capabilities with users will allow us to define user roles, dividing the work-load of the super-user – possibly eliminating it entirely!
While a design for NetBSD capabilities hasn’t been laid out yet, it is expected that support for capabilities will be provided on the file-system layer, allowing the association of capabilities with a program using extended attributes, as well as an API a la OpenSolaris ppriv(3) for dropping unneeded capabilities during runtime, and a mechanism for associating capabilities with users on the system.
[ref 37] “The Design and Implementation of the 4.4BSD OS”, pages 509-510.
[ref 38] The use of raw access to bypass a security guard isn’t limited to kernel memory: on-disk inodes could be modified using raw disk access, for example.
[ref 39] http://artofhacking.com/files/phrack/phrack58/P58-0X07.TXT (mirror)
[ref 40] “Rootkits: Subverting the Windows Kernel”, chapter 7.
[ref 41] http://www.usenix.org/events/bsdcon03/tech/mckusick.html
5. Component Interaction
So far the focus was on introducing the new infrastructure and features in NetBSD, as well as some on-going development. However, no emphasis was put on the interaction between the various components, and how they all cooperate and contribute to NetBSD’s layered security model.Throughout this section we’ll examine the role of each feature in the layered security model.
5.1 Attack Vectors
Attacks can be conducted on various parts of the system, most commonly exploiting bugs in services (remote and local), misconfigurations, general program misuse, and user actions monitoring. Furthermore, post-compromise attacks include implanting trojan horses, backdoors, and rootkits.Being a multipurpose operating system, NetBSD’s security was designed to also be flexible and without a single point of failure: acknowledging different needs in different environments, the various security features are fully customizable, and the system is configured with sane defaults to ease administration.
5.2 Layer One: Exploit Mitigation and Privacy
In attempt to render an exploitation attempt itself as useless, the exploit mitigation features in NetBSD provide the first layer of security. The curtain hooks help protect the privacy of users in a multi-user environment, minimizing the potential of pre- attack information gathering and reconnaissance.5.3 Layer Two: Capabilities
As discussed in subsection 4.4, capabilities are planned to replace the set-id bit. This effectively reduces the amount of privilege each program is running with. Successful exploitation of programs that today could result in pivoting [ref 42] or super-user account compromise will result in a less critical privilege elevation in the worst case, limiting the impact of vulnerabilities on the overall security of the host.5.4 Layer Three: Signed Files
Mentioned in subsection 4.2, signed files are the natural evolution of Veriexec, basically associating a signing entity with a file in addition to its digital fingerprint. The immediate benefit is obviously in introducing trust in networked environments, where files can be safely exchanged without fear of attacks such as man-in-the- middle [ref 43].Accessing files – in particular, running programs – that are signed by “trusted” entities in the default configuration could help reduce the possibility of running manipulated binaries even in face of attacks on the digital checksum algorithm. Doing so in the event of a compromise, combined with Veriexec’s lockdown mode, will allow real- time investigation and remedy.
5.5 Layer Four: File-System Integrity
Interesting uses for Veriexec (presented in subsection 3.2) are its IDS and IPS modes. With functionality somewhat resembling a fly-trap, Veriexec in IDS mode can be used to silently monitor operations on critical system files (services, configuration files) in real-time, preventing any access to them once changed. This can make post- mortem analysis an easier task. IPS mode can be used to prevent access to these files altogether and generate proper log-files to help identify the source of the attack.These two modes of operation can ensure file-system integrity even in the face of a super-user compromise, making it easier for an administrator to handle an attack without fear of trojanned, backdoored, or otherwise modified (via configuration files) services.
5.6 Layer Five: Protected Kernel Memory
Aimed at preserving kernel memory integrity, the work-in-progress for deprecating kmem(4) usage should result in the ability to remove the interface altogether [ref 44], preventing the possibility of kernel memory manipulation by a malicious superuser on a compromised host. The benefit is obvious: no sophisticated rootkits or kernel-level backdoors can be implemented [ref 45].6. Conclusion
Throughout this paper I’ve outlined the recent enhancements in NetBSD security in terms of infrastructure and features, and how they conform to NetBSD’s perception of security. Finally, I’ve exposed some on-going research and development, and showed how it all works together to create a more secure platformWhile it is true that a lot of work is still ahead of us, this paper exposed the lot of work that is behind us. Over the past year NetBSD improved a lot on the security front, and it is expected that these efforts will pay off – if not already – within the next major release.
6.1 Availability
NetBSD 4.0 will include kernel authorization [ref 46], PaX MPROTECT [ref 47], GCC 4.1 with ProPolice, the information filtering hooks [ref 48], fileassoc(9) [ref 49], and pw_policy(3) [ref 50].Complete abstraction of the security model using kernel authorization is being considered for NetBSD 5.0, as well as PaX ASLR and a SegvGuard, Veriexec support for per-page fingerprints and digital signatures, file-system ACLs, and capabilities.
7. Credits
Thanks to the folks who reviewed this paper, either in part or in whole, helping improve its accuracy, readability, and quality. Jason V. Miller, Brian Mitchell and the guys at ISS, the PaX author, and Sean Trifero, Johnny Zackrisson, and Christos Zoulas.Thanks to Brett Lymn, the PaX author, Bill Studenmund, YAMAMOTO Takashi, Matt Thomas, Jason R. Thorpe, and Christos Zoulas for helping with implementing the features discussed in this paper.
8. About the author
Elad Efrat is part of the NetBSD team. He will be presenting some of the content in this paper at EuroBSDcon in Italy, in November 2006.[ref 42] Transition from one user to another.
[ref 43] Assuming, of course, that the kernel itself cannot be manipulated.
[ref 44] From most systems. X would still require it without the use of an aperture driver.
[ref 45] Unless, of course, a kernel vulnerability is successfully exploited.
[ref 46] http://netbsd.gw.com/cgi-bin/man-cgi?kauth++NetBSD-current
[ref 47] http://netbsd.gw.com/cgi-bin/man-cgi?paxctl++NetBSD-current
[ref 48] See the security.curtain knob.
[ref 49] http://netbsd.gw.com/cgi-bin/man-cgi?fileassoc++NetBSD-current
[ref 50] http://netbsd.gw.com/cgi-bin/man-cgi?pw_policy++NetBSD-current. No programs were made aware of the interface yet, though.
This article originally appeared on SecurityFocus.com
Suscribirse a:
Entradas (Atom)