Manual de Seguridad de Debian ============================= Javier Fernández-Sanguino Peña Copyright © 2012 The Debian Project GNU General Public License Notice: This work is free documentation: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This work is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. Resumen Este documento trata sobre la seguridad dentro del proyecto y del sistema operativo Debian. Comienza con el proceso de protección y fortalecimiento de la instalación de la distribución predeterminada de Debian GNU/Linux. También cubre algunas de las tareas comunes para configurar un entorno de red seguro utilizando Debian GNU/Linux, da información adicional sobre las herramientas de seguridad disponibles y habla sobre cómo el equipo de seguridad y auditoría hace valer la seguridad en Debian. ------------------------------------------------------------------------ Capítulo 1. Introducción ======================== Una de las cosas más dificiles sobre los documentos de seguridad es que cada caso es único. Dos cosas a las que se debe prestar atención son la amenaza del entorno y las necesidades de seguridad, tanto de cada parte individual como del servidor o de la red. Por ejemplo, las necesidades de seguridad de un usuario local son completamente diferentes a las de la red de un banco. Mientras que un usuario local necesita defenderse contra el cracker script-kiddie, un banco tiene que preocuparse de ataques dirigidos. Además, el banco tiene que proteger los datos de sus clientes con precisión milimétrica. En resumen, todo usuario debe considerar el equilibrio entre utilización y seguridad/paranoia. Observe que este manual solamente trata de asuntos relacionados con el software. Ni el mejor software del mundo podría protegerlo si alguien tuviera acceso físico a la máquina. Usted puede colocarla bajo su mesa o puede ponerla en un búnker con un ejército que la protega. Sin embargo, un ordenador de escritorio puede ser muchísimo más seguro (desde el punto de vista del software) que un sistema protegido físicamente si el primero de ellos se configura de la manera apropiada y el segundo está lleno de agujeros de seguridad. Lógicamente, usted debe considerar ambos casos. Este documento da una apreciación global de lo que usted puede hacer para incrementar la seguridad de su sistema Debian GNU/Linux. Si usted ha leido otros documentos con respecto a la seguridad en Linux, encontrará que describen problemas comunes, los cuales pueden solaparse con este documento. Sin embargo este documento no intenta ser la única fuente de información que usted debería usar, sólo intenta adaptar esa misma información para su aplicación sobre un sistema Debian GNU/Linux. La forma de trabajar de distintas distribuciones es diferente (el ejemplo habitual es la forma de arrancar y para los demonios del sistema); aquí usted encontrará material apropiado para los procedimientos y herramientas utilizadas por Debian. 1.1. Authors ------------ The current maintainer of this document is Javier Fernández-Sanguino Peña. Please forward him any comments, additions or suggestions, and they will be considered for inclusion in future releases of this manual. This manual was started as a HOWTO by Alexander Reelsen. After it was published on the Internet, Javier Fernández-Sanguino Peña incorporated it into the Debian Documentation Project. A number of people have contributed to this manual (all contributions are listed in the changelog) but the following deserve special mention since they have provided significant contributions (full sections, chapters or appendices): * Stefano Canepa * Era Eriksson * Carlo Perassi * Alexandre Ratti * Jaime Robles * Yotam Rubin * Frederic Schutz * Pedro Zorzenon Neto * Oohara Yuuma * Davor Ocelic 1.2. Lugares donde encontrar este manual (diversos formatos) ------------------------------------------------------------ You can download or view the latest version of the Securing Debian Manual from the Debian Documentation Project. If you are reading a copy from another site, please check the primary copy in case it provides new information. If you are reading a translation, please review the version the translation refers to to the latest version available. If you find that the version is behind please consider using the original copy or review the to see what has changed. If you want a full copy of the manual you can either download the text version or the PDF version from the Debian Documentation Project's site. These versions might be more useful if you intend to copy the document over to a portable device for offline reading or you want to print it out. Be forewarned, the manual is over two hundred pages long and some of the code fragments, due to the formatting tools used, are not wrapped in the PDF version and might be printed incomplete. The document is also provided in text, html and PDF formats in the harden-doc package. Notice, however, that the package maybe not be completely up to date with the document provided on the Debian site (but you can always use the source package to build an updated version yourself). This document is part of the documents distributed by the Debian Documentation Project. You can review the changes introduced in the document using a web browser and obtaining information from the version control logs online. You can also checkout the code using Git with the following call in the command line: $ git clone https://salsa.debian.org/ddp-team/securing-debian-manual.git 1.3. Notas/Retroalimentación/Organización ----------------------------------------- Ahora, la parte oficial. Tanto Alexander Reelsen como Javier Fernández-Sanguino escribieron la mayoría de párrafos de este manual, pero en opinión de ambos éste no debería ser el caso. Ambos han crecido y vivido con el software libre, es algo que usan a diario y supongo que usted también. Por eso animamos a todo el mundo a enviar todo tipo de retroalimentación, añadidos o cualquier otra sugerencia que usted pueda tener. Si desea mantener una cierta sección o mejor un párrafo, escriba a quien mantiene el documento y será bien recibido. Especialmente si encuentra una sección marcada como ARREGLAME, lo que significa que los autores no tienen el tiempo para hacerlo o el conocimiento total necesario sobre el tema, escríbales un correo inmediatamente. Por el tema de este manual está claro que es muy importante mantenerlo actualizado y usted puede hacer su parte. Por favor, contribuya. 1.4. Conocimiento previo ------------------------ La instalación de Debian GNU/Linux no es muy difícil y usted mismo debe haber sido capaz de instalarlo. Si tiene algún conocimiento sobre Linux u otro Unix y está familiarizado con la seguridad básica, le será más fácil entender este manual, dado que este documento no puede explicar cada pequeño detalle o característica (de lo contrario hubiera sido un libro en lugar de un manual). Si usted no está tan familiarizado, probablemente debería mirar references para saber como encontrar información más detallada. 1.5. Things that need to be written (FIXME/TODO) ------------------------------------------------ This section describes all the things that need to be fixed in this manual. Some paragraphs include FIXME or TODO tags describing what content is missing (or what kind of work needs to be done). The purpose of this section is to describe all the things that could be included in the future in the manual, or enhancements that need to be done (or would be interesting to add). If you feel you can provide help in contributing content fixing any element of this list (or the inline annotations), contact the main author (Sección 1.1, “Authors”). * This document has yet to be updated based on the latest Debian releases. The default configuration of some packages need to be adapted as they have been modified since this document was written. * Expand the incident response information, maybe add some ideas derived from Red Hat's Security Guide's chapter on incident response. * Write about remote monitoring tools (to check for system availability) such as monit, daemontools and mon. See Sysamin Guide. * Consider writing a section on how to build Debian-based network appliances (with information such as the base system, equivs and FAI). * Check if this site has relevant info not yet covered here. * Add information on how to set up a laptop with Debian, look here. * Add information on how to set up a firewall using Debian GNU/Linux. The section regarding firewalling is oriented currently towards a single system (not protecting others...) also talk on how to test the setup. * Add information on setting up a proxy firewall with Debian GNU/Linux stating specifically which packages provide proxy services (like xfwp, ftp-proxy, redir, smtpd, dnrd, jftpgw, oops, pdnsd, perdition, transproxy, tsocks). Should point to the manual for any other info. Note that zorp is now available as a Debian package and is a proxy firewall (they also provide Debian packages upstream). * Information on service configuration with file-rc. * Check all the reference URLs and remove/fix those no longer available. * Add information on available replacements (in Debian) for common servers which are useful for limited functionality. Examples: * local lpr with cups (package)? * remote lrp with lpr * bind with dnrd/maradns * apache with dhttpd/thttpd/wn (tux?) * exim/sendmail with ssmtpd/smtpd/postfix * squid with tinyproxy * ftpd with oftpd/vsftp * ... * More information regarding security-related kernel patches in Debian, including the ones shown above and specific information on how to enable these patches in a Debian system. * Linux Intrusion Detection (kernel-patch-2.4-lids) * Confianza en Linux (dentro del paquete trustees) * NSA Enhanced Linux * ipac-ng * ... * Details of turning off unnecessary network services (besides inetd), it is partly in the hardening procedure but could be broadened a bit. * Information regarding password rotation which is closely related to policy. * Policy, and educating users about policy. * More about tcpwrappers, and wrappers in general? * hosts.equiv and other major security holes. * Issues with file sharing servers such as Samba and NFS? * suidmanager/dpkg-statoverrides. * lpr and lprng. * Switching off the GNOME IP things. * Talk about pam_chroot (see http://lists.debian.org/debian-security/2002/05/msg00011.html) and its usefulness to limit users. Introduce information related to https://web.archive.org/web/20031204060940/http://www.securityfocus.com/infocus/1575. pdmenu, for example is available in Debian (whereas flash is not). * Talk about chrooting services, some more info on this Linux Focus article. * Talk about programs to make chroot jails. compartment and chrootuid are waiting in incoming. Some others (makejail, jailer) could also be introduced. * More information regarding log analysis software (i.e. logcheck and logcolorise). * 'advanced' routing (traffic policing is security related). * limiting ssh access to running certain commands. * using dpkg-statoverride. * secure ways to share a CD burner among users. * secure ways of providing networked sound in addition to network display capabilities (so that X clients' sounds are played on the X server's sound hardware). * securing web browsers. * setting up ftp over ssh. * using crypto loopback file systems. * encrypting the entire file system. * steganographic tools. * setting up a PKA for an organization. * using LDAP to manage users. There is a HOWTO of ldap+kerberos for Debian at http://www.bayour.com written by Turbo Fredrikson. * How to remove information of reduced utility in production systems such as /usr/share/doc, /usr/share/man (yes, security by obscurity). * More information on lcap based on the packages README file (well, not there yet, see http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=169465) and from the article from LWN: http://lwn.net/1999/1202/kernel.php3. * Add Colin's article on how to setup a chroot environment for a full sid system (https://web.archive.org/web/20030204012846/https://people.debian.org/~walters/chroot.html). * Add information on running multiple snort sensors in a given system (check bug reports sent to snort). * Add information on setting up a honeypot (honeyd). * Describe situation wrt to FreeSwan (orphaned) and OpenSwan. VPN section needs to be rewritten. * Add a specific section about databases, current installation defaults and how to secure access. * Add a section about the usefulness of virtual servers (Xen et al). * Explain how to use some integrity checkers (AIDE, integrit or samhain). The basics are simple and could even explain some configuration improvements. 1.6. Credits and thanks! ------------------------ * Alexander Reelsen escribió el documento original. * added more info to the original doc. * Robert van der Meulen aportó los párrafos de quota y muchas buenas ideas. * Ethan Benson corrigió los párrafos de PAM y sugirió buenas ideas. * Dariusz Puchalak hizo contribuciones a muchos capítulos. * Gaby Schilders contribuyó a una buena idea de Genio/Paranoia. * Era Eriksson resolvió problemas de idioma en muchos lugares y contribuyó al apéndice de la lista de comprobaciones. * Philipe Gaspar escribió la información de LKM. * Yotam Rubin contribuyó a los ajustes de muchos fallos ortográficos así como a la información con respecto a las versiones de bind y las contraseñas md5. * Francois Bayart provided the appendix describing how to set up a bridge firewall. * Joey Hess wrote the section describing how Secure Apt works on the Debian Wiki. * Martin F. Krafft wrote some information on his blog regarding fingerprint verification which was also reused for the Secure Apt section. * Francesco Poli did an extensive review of the manual and provided quite a lot of bug reports and typo fixes which improved and helped update the document. * All the people who made suggestions for improvements that (eventually) were included here (see Sección 1.2, “Lugares donde encontrar este manual (diversos formatos)”). * (de Alexander) A todas las personas que me animaron a escribir, este COMO (El cual posteriormente se convirtió en el manual) . * La totalidad del proyecto Debian. Capítulo 2. Antes de empezar ============================ 2.1. ¿Para qué quiere su sistema? --------------------------------- No hay muchas diferencias entre proteger Debian y proteger cualquier otro sistema; para hacerlo adecuadamente tiene primero que decidir qué es lo que piensa hacer con él. Tras esto, la siguiente consideración será preguntarse si quiere un sistema realmente seguro. Encontrará que este manual está escrito empezando desde abajo, esto es, leerá alguna información sobre tareas a realizar antes, durante y después de la instalación de su sistema Debian. Se puede pensar en tareas como: * Decidir qué servicios necesita y limitar el sistema a éstos. Esto incluye desactivar/desinstalar servicios innecesarios, y añadir filtros como cortafuegos, o «tcpwrappers». * Limitar los usuarios y permisos en su sistema. * Fortalecer los servicios ofrecidos de forma que, en el caso de que un servicio resulte comprometido, el impacto en el sistema sea mínimo. * Utilizar herramientas apropiadas para garantizar que se detecte el uso no autorizado, de forma que pueda usted tomar las medidas oportunas. 2.2. Sea consciente de los problemas de seguridad general --------------------------------------------------------- El siguiente manual no entrará en detalles (normalmente) sobre por qué algunos asuntos se consideran riesgos de seguridad. Sin embargo, usted podría querer tener una mejor formación relativa a la seguridad general de UNIX y específica de Linux. Tómese su tiempo en leer documentos relacionados con la seguridad, con objeto de tomar decisiones bien fundamentadas cuando se encuentre con diferentes alternativas. Debian GNU/Linux está basado en el núcleo de Linux, por ello también se puede aplicar mucha de la información relacionada con la seguridad de Linux, así como de otras distribuciones y de UNIX en general (incluso si las herramientas utilizadas, o los programas disponibles, difieren). Entre los documentos útiles se incluyen (N. del T., algunos de los documentos en inglés pueden encontrarse en internet traducidos al español): * The http://www.tldp.org/HOWTO/Security-HOWTO/ is one of the best references regarding general Linux security. * The http://www.tldp.org/HOWTO/Security-Quickstart-HOWTO/ is also a very good starting point for novice users (both to Linux and security). * The http://seifried.org/lasg/ is a complete guide that touches all the issues related to security in Linux, from kernel security to VPNs. Note that it has not been updated since 2001, but some information is still relevant. [1] * Kurt Seifried's http://seifried.org/security/os/linux/20020324-securing-linux-step-by-step.html. * En http://www.tldp.org/links/p_books.html#securing_linux puede encontrar un documento similar a este manual, pero relacionado con RedHat, algunos de los temas no son específicos de la distribución y son también aplicables a Debian. * Another Red Hat related document is https://web.archive.org/web/20050520170309/https://ltp.sourceforge.net/docs/RHEL-EAL3-Configuration-Guide.pdf. * IntersectAlliance has published some documents that can be used as reference cards on how to harden Linux servers (and their services), the documents are available at https://web.archive.org/web/20030210231943/http://www.intersectalliance.com/projects/index.html. * For network administrators, a good reference for building a secure network is the https://web.archive.org/web/20030418093551/http://www.linuxsecurity.com/docs/LDP/Securing-Domain-HOWTO/. * If you want to evaluate the programs you are going to use (or want to build up some new ones) you should read the http://www.tldp.org/HOWTO/Secure-Programs-HOWTO/ (master copy is available at http://www.dwheeler.com/secure-programs/, it includes slides and talks from the author, David Wheeler) * If you are considering installing firewall capabilities, you should read the http://www.tldp.org/HOWTO/Firewall-HOWTO.html and the http://www.tldp.org/HOWTO/IPCHAINS-HOWTO.html (for kernels previous to 2.4). * Finally, a good card to keep handy is the https://web.archive.org/web/20030308013020/http://www.linuxsecurity.com/docs/QuickRefCard.pdf. En cualquier caso, hay mas información concerniente a los servicios explicados aquí (NFS, NIS, SMB...) en muchos de los CÓMOs del http://es.tldp.org/. Alguno de estos documentos habla sobre seguridad vista ésta desde el lado de un servicio, por tanto, asegúrese de echar un vistazo también allí. Los documentos de CÓMO del Proyecto de documentación de Linux están disponibles en Debian GNU/Linux por medio de la instalación de doc-linux-text (versión de texto) o doc-linux-html (versión html). Tras la instalación, estos documentos estarán disponibles en los directorios /usr/share/doc/HOWTO/en-txt y /usr/share/doc/HOWTO/en-html, respectivamente. Otros libros recomendados de Linux: * Maximum Linux Security : A Hacker's Guide to Protecting Your Linux Server and Network. Anonymous. Paperback - 829 páginas. Sams Publishing. ISBN: 0672313413. Julio 1999. * Linux Security de John S. Flowers. New Riders; ISBN: 0735700354. Marzo 1999 * https://web.archive.org/web/20030202131658/https://www.linux.org/books/ISBN_0072127732.html By Brian Hatch. McGraw-Hill Higher Education. ISBN 0072127732. April, 2001 Otros libros (que podrían estar relacionados con asuntos generales relativos a UNIX y la seguridad, y no ser específicos de Linux): * https://web.archive.org/web/20030206231652/http://www.oreilly.com/catalog/puis/ Garfinkel, Simpson, and Spafford, Gene; O'Reilly Associates; ISBN 0-56592-148-8; 1004pp; 1996. * Firewalls and Internet Security Cheswick, William R. y Bellovin, Steven M.; Addison-Wesley; 1994; ISBN 0-201-63357-4; 320pp. Algunas páginas Web para conservar actualizadas relativas a seguridad: * http://csrc.nist.gov/. * https://cve.mitre.org/data/refs/refmap/source-BUGTRAQ.html CVE Reference Map for Source BUGTRAQ * http://www.linuxsecurity.com/. General information regarding Linux security (tools, news...). Most useful is the https://linuxsecurity.com/howtos page. 2.3. ¿Cómo maneja Debian la seguridad? -------------------------------------- Simplemente con objeto de tener una visión general sobre seguridad en Debian GNU/Linux, debería tomar nota de los diferentes asuntos que Debian trata de resolver para proporcionar un sistema global seguro: * Debian problems are always handled openly, even security related. Security issues are discussed openly on the debian-security mailing list. Debian Security Advisories (DSAs) are sent to public mailing lists (both internal and external) and are published on the public server. As the http://www.debian.org/social_contract states: We will not hide problems. We will keep our entire bug report database open for public view at all times. Reports that people file online will promptly become visible to others. * Debian sigue atentamente los asuntos de seguridad. El equipo de seguridad revisa muchas fuentes a la caza de paquetes relacionados con el tema de la seguridad, que pudieran incluirse en Debian, siendo la más importante http://www.securityfocus.com/cgi-bin/vulns.pl. * Las actualizaciones de seguridad son la primera prioridad. Cuando aparece un problema de seguridad en un paquete de Debian, la actualización de seguridad se prepara tan rápido como es posible y se distribuye para las versiones estable e inestable, incluyendo todas las arquitecturas. * La información relativa a la seguridad se centraliza en un único punto, http://security.debian.org/. * Debian está continuamente intentando mejorar la seguridad global de la distribución mediante nuevos proyectos, tales como los mecanismos automáticos de verificación de firma de los paquetes. * Debian proporciona un número de herramientas útiles, relacionadas con la seguridad, para la administración y supervisión del sistema. Los desarrolladores intentan integrar bien estas herramientas en la distribución, con objeto de que formen un paquete integrado que fortalezca las directrices de seguridad local. Las herramientas incluyen: comprobadores de integridad, herramientas de auditoría, herramientas de endurecimiento, herramientas de cortafuegos, herramientas de detección de intrusos, etc. * Package maintainers are aware of security issues. This leads to many "secure by default" service installations which could impose certain restrictions on their normal use. Debian does, however, try to balance security and ease of administration - the programs are not de-activated when you install them (as it is the case with say, the BSD family of operating systems). In any case, prominent security issues (such as setuid programs) are part of the http://www.debian.org/doc/debian-policy/. By publishing security information specific to Debian and complementing other information-security documents related to Debian (see Sección 1.4, “Conocimiento previo”), this document aims to produce better system installations security-wise. ------------------------------------------------------------------------ [1] At a given time it was superseded by the "Linux Security Knowledge Base". This documentation is also provided in Debian through the lskb package. Now it's back as the Lasg again. Capítulo 3. Antes y durante la instalación ========================================== 3.1. Elegir una contraseña para el BIOS --------------------------------------- Antes de instalar cualquier sistema operativo en su ordenador, establezca la contraseña del BIOS. Tras la instalación (una vez que haya habilitado el arranque desde el disco duro) debería volver al BIOS y cambiar la secuencia de arranque para deshabilitar el arranque desde la disquetera, la unidad de cdrom o cualquier otro dispositivo desde el que no se debería arrancar. De otra forma un «cracker» únicamente necesitará acceso físico y un disquete de arranque para acceder a todo su sistema. Incluso mejor es deshabilitar el arranque a menos que se proporcione una contraseña. Esto puede ser muy efectivo en un servidor, ya que no se rearranca muy a menudo. El inconveniente de esta táctica es que el rearranque requiere intervención humana, lo que puede causar problemas si no hay un acceso fácil a la máquina. Note: many BIOSes have well known default master passwords, and applications also exist to retrieve the passwords from the BIOS. Corollary: don't depend on this measure to secure console access to system. 3.2. Partitioning the system ---------------------------- 3.2.1. Elegir un esquema de particiones inteligente Un esquema de particiones inteligente depende del uso que vaya a tener la máquina. Una buena regla general es ser bastante liberal con las particiones y prestar atención a los siguientes factores: * Any directory tree which a user has write permissions to, such as e.g. /home, /tmp and /var/tmp/, should be on a separate partition. This reduces the risk of a user DoS by filling up your "/" mount point and rendering the system unusable (Note: this is not strictly true, since there is always some space reserved for root which a normal user cannot fill), and it also prevents hardlink attacks. [2] * Any partition which can fluctuate, e.g. /var (especially /var/log) should also be on a separate partition. On a Debian system, you should create /var a little bit bigger than on other systems, because downloaded packages (the apt cache) are stored in /var/cache/apt/archives. * Cualquier partición en la que quiera instalar software que no pertenezca a la distribución debería estar aparte. De acuerdo con la jerarquía estándar de archivos, debería hacerse con /opt o /usr/local. Si éstos están en particiones separadas, no se borrarán en caso de tener que reinstalar Debian. * Desde el punto de vista de la seguridad, cobra sentido intentar mover los datos estáticos a su propia partición, y luego montar esa partición como de sólo lectura. O mejor todavía, poner los datos en un medio de sólo lectura. Mire m~s adelante si quiere m~s detalles. In the case of a mail server it is important to have a separate partition for the mail spool. Remote users (either knowingly or unknowingly) can fill the mail spool (/var/mail and/or /var/spool/mail). If the spool is on a separate partition, this situation will not render the system unusable. Otherwise (if the spool directory is on the same partition as /var) the system might have important problems: log entries will not be created, packages cannot be installed, and some programs might even have problems starting up (if they use /var/run). Also, for partitions in which you cannot be sure of the needed space, installing Logical Volume Manager (lvm-common and the needed binaries for your kernel, this might be either lvm10, lvm6, or lvm5). Using lvm, you can create volume groups that expand multiple physical volumes. 3.2.2. Selecting the appropriate file systems During the system partitioning you also have to decide which file system you want to use. The default file system[3] selected in the Debian installation for Linux partitions is ext3, a journaling file system. It is recommended that you always use a journaling file system, such as ext3, reiserfs, jfs or xfs, to minimize the problems derived from a system crash in the following cases: * for laptops in all the file systems installed. That way if you run out of battery unexpectedly or the system freezes due to a hardware issue (such as X configuration which is somewhat common) you will be less likely to lose data during a hardware reboot. * for production systems which store large amounts of data (like mail servers, ftp servers, network file systems...) it is recommended on these partitions. That way, in the event of a system crash, the server will take less time to recover and check the file systems, and data loss will be less likely. Leaving aside the performance issues regarding journalling file systems (since this can sometimes turn into a religious war), it is usually better to use the ext3 file system. The reason for this is that it is backwards compatible with ext2, so if there are any issues with the journalling you can disable it and still have a working file system. Also, if you need to recover the system with a bootdisk (or CD-ROM) you do not need a custom kernel. If the kernel is 2.4 or 2.6 ext3 support is already available, if it is a 2.2 kernel you will be able to boot the file system even if you lose journalling capabilities. If you are using other journalling file systems you will find that you might not be able to recover unless you have a 2.4 or 2.6 kernel with the needed modules built-in. If you are stuck with a 2.2 kernel on the rescue disk, it might be even more difficult to have it access reiserfs or xfs. In any case, data integrity might be better under ext3 since it does file-data journalling while others do only meta-data journalling, see http://lwn.net/2001/0802/a/ext3-modes.php3. Notice, however, that there are some partitions that might not benefit from using a journaling filesystem. For example, if you are using a separate partition for /tmp/ you might be better off using a standard ext2 filesystem as it will be cleaned up when the system boots. 3.3. No se conecte a Internet hasta que no esté preparado --------------------------------------------------------- No debería conectarse a Internet de forma inmediata durante la instalación. Esto puede sonar como algo estúpido, pero la instalación por la red es un método común. Puesto que el sistema instalará y activará servicios de forma inmediata, si está conectado a Internet y los servicios no están configurados de forma apropiada, el sistema está abierto a un ataque. Observe también que algunos servicios podrían tener vulnerabilidades de seguridad no corregidas, en los paquetes que esté utilizando para la instalación. Esto es normalmente cierto si usted está realizando la instalación desde un medio antiguo (como CD-ROMs). En este caso, ¡el sistema podría estar comprometido incluso antes de terminar la instalación! Como la instalación y las actualizaciones de Debian pueden hacerse por Internet, podría usted pensar que es una buena idea utilizar esta característica en la instalación. Si el sistema se va a conectar directamente a Internet (sin la protección de un cortafuegos o NAT), es mejor instalar sin conexión a Internet, utilizando una réplica local de los paquetes tanto para las fuentes de Debian como para las actualizaciones de seguridad. Puede configurar las réplicas de paquetes, utilizando otro sistema conectado a Internet con herramientas específicas de Debian (si es un sistema Debian) como apt-move ó apt-proxy, u otras herramientas de replicación comunes, para proporcionar el archivo al sistema instalado. Si no puede hacer esto, puede configurar las reglas del cortafuegos para limitar el acceso al sistema mientras hace la actualización (vea Sección B.6, “Security update protected by a firewall”). 3.4. Establecer una contraseña para «root» ------------------------------------------ Setting a good root password is the most basic requirement for having a secure system. See passwd(1) for some hints on how to create good passwords. You can also use an automatic password generation program to do this for you (see Sección 4.11.20, “Generación de contraseñas de usuario”). Plenty of information on choosing good passwords can be found on the Internet; two that provide a decent summary and rationale are Eric Wolfram's http://wolfram.org/writing/howto/password.html and Walter Belgers' https://web.archive.org/web/20030218000949/http://www.belgers.com/write/pwseceng.txt 3.5. Ejecute el mínimo número de servicios requeridos ----------------------------------------------------- Los servicios son programas como los servidores de ftp y los servidores de web. Puesto que éstos tienen que estar escuchando las conexiones entrantes para detectar solicitudes de servicio, ordenadores externos pueden conectarse a los suyos. Los servicios son algunas veces vulnerables (p. ejem. pueden resultar comprometidos por un ataque determinado) y presentan por tanto un riesgo para la seguridad. No debería instalar servicios que su máquina no necesite. Cada servicio instalado podría introducir nuevos, quizás no obvios (o conocidos), agujeros de seguridad en su ordenador. As you may already know, when you install a given service the default behavior is to activate it. In a default Debian installation, with no services installed, the number of running services is quite low and the number of network-oriented services is even lower. In a default Debian 3.1 standard installation you will end up with OpenSSH, Exim (depending on how you configured it) and the RPC portmapper available as network services[4]. If you did not go through a standard installation but selected an expert installation you can end up with no active network services. The RPC portmapper is installed by default because it is needed for many services, for example NFS, to run on a given system. However, it can be easily removed, see Sección 5.13, “Securing RPC services” for more information on how to secure or disable RPC services. Cuando instala un nuevo servicio relacionado con la red (demonio) en su sistema Debian GNU/Linux, puede habilitarlo de dos formas: por medio del superdemonio inetd (esto es, añadiendo una línea a /etc/inetd.conf) o por medio de un programa autónomo que enlace con sus interfaces de red. Los programas autónomos se controlan a través de los archivos de /etc/init.d, a los que se llama durante el arranque por medio de los mecanismos de SysV (o un alternativo) utilizando enlaces simbólicos en /etc/rc?.d/* (para más información sobre cómo se hace esto, lea /usr/share/doc/sysvinit/README.runlevels.gz). If you want to keep some services but use them rarely, use the update-* commands, e.g. update-inetd and update-rc.d to remove them from the startup process. For more information on how to disable network services read Sección 3.5.1, “Deshabilitar servicios”. If you want to change the default behaviour of starting up services on installation of their associated packages[5] use policy-rc.d, please read /usr/share/doc/sysv-rc/README.policy-rc.d.gz for more information. invoke-rc.d support is mandatory in Debian, which means that for Debian 4.0 etch and later releases you can write a policy-rc.d file that forbids starting new daemons before you configure them. Although no such scripts are packaged yet, they are quite simple to write. See policyrcd-script-zg2. 3.5.1. Deshabilitar servicios Disabling a daemon service is quite simple. You either remove the package providing the program for that service or you remove or rename the startup links under /etc/rc${runlevel}.d/. If you rename them make sure they do not begin with 'S' so that they don't get started by /etc/init.d/rc. Do not remove all the available links or the package management system will regenerate them on package upgrades, make sure you leave at least one link (typically a 'K', i.e. kill, link). For more information read http://www.debian.org/doc/manuals/reference/ch-system.en.html#s-custombootscripts section of the Debian Reference (Chapter 2 - Debian fundamentals). You can remove these links manually or using update-rc.d (see update-rc.d(8)). For example, you can disable a service from executing in the multi-user runlevels by doing: # update-rc.d name stop XX 2 3 4 5 . Donde XX es un número que determinará cuándo se ejecutará la acción de parada de ese servicio. Por favor observe que, si no utiliza file-rc, update-rc.d -f service remove no funcionará correctamente, puesto que se eliminarán todos los enlaces, y éstos se regenerarán con la reinstalación o actualización del paquete (que probablemente no sea lo que desea). Si piensa que esto no es intuitivo, probablemente tenga razón (vea http://bugs.debian.org/67095). De la página del manual: Si alguno de los archivos /etc/rcrunlevel.d/[SK]??nombre ya existe, entonces update-rc.d no hará nada. Esto es así para que el administrador del sistema pueda reorganizar los enlaces, y siempre que deje al menos un enlace sin eliminar, su configuración no se sobreescribirá. Si utiliza file-rc toda la información relativa al arranque de servicios se manipula por un archivo de configuración común y se mantiene incluso si los paquetes se eliminan del sistema. You can use the TUI (Text User Interface) provided by sysv-rc-conf to do all these changes easily (sysv-rc-conf works both for file-rc and normal System V runlevels). You will also find similar GUIs for desktop systems. You can also use the command line interface of sysv-rc-conf: # sysv-rc-conf foobar off The advantage of using this utility is that the rc.d links are returned to the status they had before the 'off' call if you re-enable the service with: # sysv-rc-conf foobar on Other (less recommended) methods of disabling services are: * Removing the /etc/init.d/service_name script and removing the startup links using: # update-rc.d name remove * Move the script file (/etc/init.d/service_name) to another name (for example /etc/init.d/OFF.service_name). This will leave dangling symlinks under /etc/rc${runlevel}.d/ and will generate error messages when booting up the system. * Remove the execute permission from the /etc/init.d/service_name file. That will also generate error messages when booting. * Edit the /etc/init.d/service_name script to have it stop immediately once it is executed (by adding an exit 0 line at the beginning or commenting out the start-stop-daemon part in it). If you do this, you will not be able to use the script to startup the service manually later on. Nevertheless, the files under /etc/init.d are configuration files and should not get overwritten due to package upgrades if you have made local changes to them. A diferencia de otros sistemas operativos (UNIX), los servicios en Debian no pueden deshabilitarse mediante la modificación de los archivos en /etc/default/service_name. ARRÉGLEME: Añada más información sobre la manipulación de demonios utilizando file-rc 3.5.2. Disabling inetd or its services You should check if you really need the inetd daemon nowadays. Inetd was always a way to compensate for kernel deficiencies, but those have been taken care of in modern Linux kernels. Denial of Service possibilities exist against inetd (which can increase the machine's load tremendously), and many people always preferred using stand-alone daemons instead of calling services via inetd. If you still want to run some kind of inetd service, then at least switch to a more configurable Inet daemon like xinetd, rlinetd or openbsd-inetd. You should stop all unneeded Inetd services on your system, like echo, chargen, discard, daytime, time, talk, ntalk and r-services (rsh, rlogin and rcp) which are considered HIGHLY insecure (use ssh instead). Puede deshabilitar servicios editando directamente /etc/inetd.conf, pero Debian proporciona una mejor alternativa: update-inetd (que comenta los servicios en una forma que hace fácil volver a activarlos). Podría detener el demonio de telnet mediante la ejecución de estos comandos para cambiar el archivo de configuración y volver a arrancar el demonio (en este caso el servicio de telnet está deshabilitado): /usr/sbin/update-inetd --disable telnet Si quiere tener servicios escuchando, pero no quiere tenerlos escuchando en todas las direcciones IP de su ordenador principal, podría querer utilizar una característica no documentada de inetd (remplazar el nombre del servicio por la sintaxis servicio@ip) o utilizar un demonio alternativo como xinetd. 3.6. Install the minimum amount of software required ---------------------------------------------------- Debian comes with a lot of software, for example the Debian 3.0 woody release includes 6 or 7 (depending on architecture) CD-ROMs of software and thousands of packages, and the Debian 3.1 sarge release ships with around 13 CD-ROMs of software. With so much software, and even if the base system installation is quite reduced [6] you might get carried away and install more than is really needed for your system. Since you already know what the system is for (don't you?) you should only install software that is really needed for it to work. Any unnecessary tool that is installed might be used by a user that wants to compromise the system or by an external intruder that has gotten shell access (or remote code execution through an exploitable service). The presence, for example, of development utilities (a C compiler) or interpreted languages (such as perl - but see below -, python, tcl...) may help an attacker compromise the system even further: * allowing him to do privilege escalation. It's easier, for example, to run local exploits in the system if there is a debugger and compiler ready to compile and test them! * providing tools that could help the attacker to use the compromised system as a base of attack against other systems. [7] Of course, an intruder with local shell access can download his own set of tools and execute them, and even the shell itself can be used to make complex programs. Removing unnecessary software will not help prevent the problem but will make it slightly more difficult for an attacker to proceed (and some might give up in this situation looking for easier targets). So, if you leave tools in a production system that could be used to remotely attack systems (see Sección 8.1, “Herramientas de evaluación de vulnerabilidades remotas.”) you can expect an intruder to use them too if available. Please notice that a default installation of Debian sarge (i.e. an installation where no individual packages are selected) will install a number of development packages that are not usually needed. This is because some development packages are of Standard priority. If you are not going to do any development you can safely remove the following packages from your system, which will also help free up some space: Package Size ------------------------+-------- gdb 2,766,822 gcc-3.3 1,570,284 dpkg-dev 166,800 libc6-dev 2,531,564 cpp-3.3 1,391,346 manpages-dev 1,081,408 flex 257,678 g++ 1,384 (Note: virtual package) linux-kernel-headers 1,377,022 bin86 82,090 cpp 29,446 gcc 4,896 (Note: virtual package) g++-3.3 1,778,880 bison 702,830 make 366,138 libstdc++5-3.3-dev 774,982 This is something that is fixed in releases post-sarge, see http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=301273 and http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=301138. Due to a bug in the installation system this did not happen when installing with the installation system of the Debian 3.0 woody release. 3.6.1. Removing Perl You must take into account that removing perl might not be too easy (as a matter of fact it can be quite difficult) in a Debian system since it is used by many system utilities. Also, the perl-base is Priority: required (that about says it all). It's still doable, but you will not be able to run any perl application in the system; you will also have to fool the package management system to think that the perl-base is installed even if it's not. [8] Which utilities use perl? You can see for yourself: $ for i in /bin/* /sbin/* /usr/bin/* /usr/sbin/*; do [ -f $i ] && { type=`file $i | grep -il perl`; [ -n "$type" ] && echo $i; }; done These include the following utilities in packages with priority required or important: * /usr/bin/chkdupexe of package util-linux. * /usr/bin/replay of package bsdutils. * /usr/sbin/cleanup-info of package dpkg. * /usr/sbin/dpkg-divert of package dpkg. * /usr/sbin/dpkg-statoverride of package dpkg. * /usr/sbin/install-info of package dpkg. * /usr/sbin/update-alternatives of package dpkg. * /usr/sbin/update-rc.d of package sysvinit. * /usr/bin/grog of package groff-base. * /usr/sbin/adduser of package adduser. * /usr/sbin/debconf-show of package debconf. * /usr/sbin/deluser of package adduser. * /usr/sbin/dpkg-preconfigure of package debconf. * /usr/sbin/dpkg-reconfigure of package debconf. * /usr/sbin/exigrep of package exim. * /usr/sbin/eximconfig of package exim. * /usr/sbin/eximstats of package exim. * /usr/sbin/exim-upgrade-to-r3 of package exim. * /usr/sbin/exiqsumm of package exim. * /usr/sbin/keytab-lilo of package lilo. * /usr/sbin/liloconfig of package lilo. * /usr/sbin/lilo_find_mbr of package lilo. * /usr/sbin/syslogd-listfiles of package sysklogd. * /usr/sbin/syslog-facility of package sysklogd. * /usr/sbin/update-inetd of package netbase. So, without Perl and, unless you remake these utilities in shell script, you will probably not be able to manage any packages (so you will not be able to upgrade the system, which is not a Good Thing). If you are determined to remove Perl from the Debian base system, and you have spare time, submit bug reports to the previous packages including (as a patch) replacements for the utilities above written in shell script. If you wish to check out which Debian packages depend on Perl you can use $ grep-available -s Package,Priority -F Depends perl or $ apt-cache rdepends perl 3.7. Lea las listas de correo de seguridad de Debian ---------------------------------------------------- Nunca está de más echar un vistazo a la lista de correo debian-security-announce, donde el equipo de seguridad de Debian anuncia los avisos y reparaciones para los paquetes publicados, o a la lista mailto:debian-security@lists.debian.org, donde puede participar en discusiones sobre asuntos relacionados con la seguridad en Debian. Con objeto de recibir alertas sobre actualizaciones de seguridad importantes, envíe un correo a mailto:debian-security-announce-request@lists.debian.org con la palabra "subscribe" en el asunto. También puede suscribirse a esta lista de correo moderada a través de la página web http://www.debian.org/MailingLists/subscribe Esta lista de correo tiene un volumen de mensajes muy bajo, y al suscribirse comenzará inmediatamente a recibir alertas de actualizaciones de seguridad para la distribución Debian. Esto le permitirá descargarse rápidamente nuevos paquetes con los errores de seguridad reparados, lo que es muy importante para mantener un sistema seguro. (Vea Sección 4.2, “Ejecute una actualización de seguridad” para obtener detalles sobre cómo hacer esto.) ------------------------------------------------------------------------ [2] A very good example of this kind of attacks using /tmp is detailed in http://www.hackinglinuxexposed.com/articles/20031111.html and http://www.hackinglinuxexposed.com/articles/20031214.html (notice that the incident is Debian-related). It is basicly an attack in which a local user stashes away a vulnerable setuid application by making a hard link to it, effectively avoiding any updates (or removal) of the binary itself made by the system administrator. Dpkg was recently fixed to prevent this (see http://bugs.debian.org/225692) but other setuid binaries (not controlled by the package manager) are at risk if partitions are not setup correctly. [3] Since Debian GNU/Linux 4.0, codename etch [4] The footprint in Debian 3.0 and earlier releases wasn't as tight, since some inetd services were enabled by default. Also standard installations of Debian 2.2 installed the NFS server as well as the telnet server. [5] This is desirable if you are setting up a development chroot, for example. [6] For example, in Debian woody it is around 400-500 Mbs, try this: $ size=0 $ for i in `grep -A 1 -B 1 "^Section: base" /var/lib/dpkg/available | grep -A 2 "^Priority: required" |grep "^Installed-Size" |cut -d : -f 2 `; do size=$(($size+$i)); done $ echo $size 47762 [7] Many intrusions are made just to get access to resources to do illegitimate activity (denial of service attacks, spam, rogue ftp servers, dns pollution...) rather than to obtain confidential data from the compromised system. [8] You can make (on another system) a dummy package with equivs. Capítulo 4. Después de la instalación ===================================== Once the system is installed you can still do more to secure the system; some of the steps described in this chapter can be taken. Of course this really depends on your setup but for physical access prevention you should read Sección 4.3, “Change the BIOS (again)”,Sección 4.4, “Colocar una contraseña a lilo o grub”, Sección 4.6, “Eliminar el prompt de root del núcleo”, Sección 4.7, “Restricción del acceso a la consola”, and Sección 4.8, “Restricting system reboots through the console”. Before connecting to any network, especially if it's a public one you should, at the very least, execute a security update (see Sección 4.2, “Ejecute una actualización de seguridad”). Optionally, you could take a snapshot of your system (see Sección 4.19, “Taking a snapshot of the system”). 4.1. Subscribe to the Debian Security Announce mailing list ----------------------------------------------------------- In order to receive information on available security updates you should subscribe yourself to the debian-security-announce mailing list in order to receive the Debian Security Advisories (DSAs). See Sección 7.1, “Equipo de seguridad” for more information on how the Debian security team works. For information on how to subscribe to the Debian mailing lists read http://lists.debian.org. DSAs are signed with the Debian Security Team's signature which can be retrieved from http://security.debian.org. You should consider, also, subscribing to the http://lists.debian.org/debian-security for general discussion on security issues in the Debian operating system. You will be able to contact other fellow system administrators in the list as well as Debian developers and upstream developers of security tools who can answer your questions and offer advice. FIXME: Add the key here too? 4.2. Ejecute una actualización de seguridad ------------------------------------------- As soon as new security bugs are detected in packages, Debian maintainers and upstream authors generally patch them within days or even hours. After the bug is fixed, a new package is provided on http://security.debian.org. If you are installing a Debian release you must take into account that since the release was made there might have been security updates after it has been determined that a given package is vulnerable. Also, there might have been minor releases (there have been four for the Debian 3.0 sarge release) which include these package updates. During installation security updates are configured for your system and pending updates downloaded and applied, unless you specifically opt out of this or the system was not connected to the Internet. The updates are applied even before the first boot, so the new system starts its life as up to date as possible. To manually update the system, put the following line in your sources.list and you will get security updates automatically, whenever you update your system. Replace [CODENAME] with the release codename, e.g. squeeze. deb http://security.debian.org/ [CODENAME]/updates main contrib non-free Note: If you are using the testing branch use the security testing mirror sources as described in Sección 10.1.4, “Security support for the testing branch”. Once you've done this you can use multiple tools to upgrade your system. If you are running a desktop system you will have[9] an application called update-notifier that will make it easy to check if new updates are available, by selecting it you can make a system upgrade from the desktop (using update-manager). For more information see Sección 10.1.2.2, “Checking for updates at the Desktop”. In desktop environments you can also use synaptic (GNOME), kpackage or adept (KDE) for more advanced interfaces. If you are running a text-only terminal you can use aptitude, apt or dselect (deprecated) to upgrade: * If you want to use aptitude's text interface you just have to press u (update) followed by g (to upgrade). Or just do the following from the command line (as root): # aptitude update # aptitude upgrade * If you want to use apt do just like with aptitude but substitute the aptitude lines above with apt-get. * If you want to use dselect then first [U]pdate, then [I]nstall and finally, [C]onfigure the installed/upgraded packages. If you like, you can add the deb-src lines to /etc/apt/sources.list as well. See apt(8) for further details. 4.2.1. Security update of libraries Once you have executed a security update you might need to restart some of the system services. If you do not do this, some services might still be vulnerable after a security upgrade. The reason for this is that daemons that are running before an upgrade might still be using the old libraries before the upgrade [10]. From Debian Jessie and up, you can install the needrestart package, which will run automatically after each APT upgrade and prompt you to restart services that are affected by the just-installed updates. In earlier releases, you can run the checkrestart program (available in the debian-goodies package) manually after your APT upgrade. Some packages (like libc6) will do this check in the postinst phase for a limited set of services specially since an upgrade of essential libraries might break some applications (until restarted)[11]. Bringing the system to run level 1 (single user) and then back to run level 3 (multi user) should take care of the restart of most (if not all) system services. But this is not an option if you are executing the security upgrade from a remote connection (like ssh) since it will be severed. Excercise caution when dealing with security upgrades if you are doing them over a remote connection like ssh. A suggested procedure for a security upgrade that involves a service restart is to restart the SSH daemon and then, immediately, attempt a new ssh connection without breaking the previous one. If the connection fails, revert the upgrade and investigate the issue. 4.2.2. Security update of the kernel First, make sure your kernel is being managed through the packaging system. If you have installed using the installation system from Debian 3.0 or previous releases, your kernel is not integrated into the packaging system and might be out of date. You can easily confirm this by running: $ dpkg -S `readlink -f /vmlinuz` linux-image-2.6.18-4-686: /boot/vmlinuz-2.6.18-4-686 If your kernel is not being managed you will see a message saying that the package manager did not find the file associated to any package instead of the message above, which says that the file associated to the current running kernel is being provided by the linux-image-2.6.18-4-686. So first, you will need to manually install a kernel image package. The exact kernel image you need to install depends on your architecture and your prefered kernel version. Once this is done, you will be able to manage the security updates of the kernel just like those of any other package. In any case, notice that the kernel updates will only be done for kernel updates of the same kernel version you are using, that is, apt will not automatically upgrade your kernel from the 2.4 release to the 2.6 release (or from the 2.4.26 release to the 2.4.27 release[12]). The installation system of recent Debian releases will handle the selected kernel as part of the package system. You can review which kernels you have installed by running: $ COLUMNS=150 dpkg -l 'linux-image*' | awk '$1 ~ /ii/ { print $0 }' To see if your kernel needs to be updated run: $ kernfile=`readlink -f /vmlinuz` $ kernel=`dpkg -S $kernfile | awk -F : '{print $1}'` $ apt-cache policy $kernel linux-image-2.6.18-4-686: Installed: 2.6.18.dfsg.1-12 Candidate: 2.6.18.dfsg.1-12 Version table: *** 2.6.18.dfsg.1-12 0 100 /var/lib/dpkg/status If you are doing a security update which includes the kernel image you need to reboot the system in order for the security update to be useful. Otherwise, you will still be running the old (and vulnerable) kernel image. If you need to do a system reboot (because of a kernel upgrade) you should make sure that the kernel will boot up correctly and network connectivity will be restored, specially if the security upgrade is done over a remote connection like ssh. For the former you can configure your boot loader to reboot to the original kernel in the event of a failure (for more detailed information read Remotely rebooting Debian GNU/Linux machines). For the latter you have to introduce a network connectivity test script that will check if the kernel has started up the network subsystem properly and reboot the system if it did not[13]. This should prevent nasty surprises like updating the kernel and then realizing, after a reboot, that it did not detect or configure the network hardware properly and you need to travel a long distance to bring the system up again. Of course, having the system serial console [14] in the system connected to a console or terminal server should also help debug reboot issues remotely. 4.3. Change the BIOS (again) ---------------------------- Remember Sección 3.1, “Elegir una contraseña para el BIOS”? Well, then you should now, once you do not need to boot from removable media, to change the default BIOS setup so that it only boots from the hard drive. Make sure you will not lose the BIOS password, otherwise, in the event of a hard disk failure you will not be able to return to the BIOS and change the setup so you can recover it using, for example, a CD-ROM. Another less secure but more convenient way is to change the setup to have the system boot up from the hard disk and, if it fails, try removable media. By the way, this is often done because most people don't use the BIOS password that often; it's easily forgotten. 4.4. Colocar una contraseña a lilo o grub ----------------------------------------- Anybody can easily get a root-shell and change your passwords by entering init=/bin/sh Es muy fácil entrar a una shell con el usuario root y cambiar las contraseñas simplemente tecleando " init=/bin/sh". Luego de cambiar las contraseñas y reingresar al sistema, la persona ha tiene acceso ilimitado (como root) y puede hacer cualquier cosa que el/ella quiera en el sistema. Después de este procedimiento, usted no tendrá acceso a su sistema, porque usted no conoce la contraseña de root. Asegúrese que esto no pueda suceder, usted debería colocar una contraseña para el cargador de linux. Usted puede escoger entre una contraseña global y una contraseña para una imagen. Para LILO usted necesita editar el archivo /etc/lilo.conf y agregar una contraseña y restringirlo como en el siguiente ejemplo: image=/boot/2.2.14-vmlinuz label=Linux read-only password=hackme restricted Then, make sure that the configuration file is not world readable to prevent local users from reading the password. When done, rerun lilo. Omitting the restricted line causes lilo to always prompt for a password, regardless of whether LILO was passed parameters. The default permissions for /etc/lilo.conf grant read and write permissions to root, and enable read-only access for lilo.conf's group, root. Si usted usa GRUB en lugar de LILO, edite /boot/grub/menu.lst y agregue las siguientes dos líneas al inicio (sustituyendo, por supuesto 'hackme' con la contraseña deseada). Esto previene a los usuarios de editar los ítems de entrada. 'timeout3' especifica tres segundos antes del arranque del sistema por defecto. timeout 3 password hackme Para asegurar mas la integridad de la contraseña, usted podría guardarla una forma encriptada. La utilidad de grub-d5-crypt es que genera una contraseña la cual es compatible con el algorítmo (md5) de encripción de grub. Para especificar en GRUB que el formato de la contraseña md5 será usado, use la siguiente instrucción: timeout 3 password --md5 $1$bw0ez$tljnxxKLfMzmnDVaQWgjP0 El parámetro --md5 fue agregado para instruir a grub a realizar el proceso de autenticación. La contraseña proporcionada es la versión encriptada en md5 de "hackme". Usar el método de encripción md5 es preferible a su contraparte en solo texto. Mas información acera de la contraseña GRUB puede ser encontrada en el paquete de grub-doc. 4.5. Disable root prompt on the initramfs ----------------------------------------- Note: This applies to the default kernels provided for releases after Debian 3.1 Los núcleos de Linux 2.6 proporcionan una forma para tener acceso a la línea de comandos del administrador que será presentada justo después de cargar el sistema de archivos cramfs. Un mensaje aparecerá para permitir al administrador entrar en una línea de comandos con permisos de root, esta línea de comandos puede ser usada manualmente para cargar módulos cuando la autodetección falla. Este comportamiento es el predeterminado para initrd's linuxrc. El siguiente mensaje aparecerá: "ALERT! /dev/sda1 does not exist. Dropping to a shell! In order to remove this behavior you need to set the following boot argument:panic=0. Add this to the variable GRUB_CMDLINE_LINUX in /etc/default/grub and issue update-grub or to the append section of /etc/lilo.conf. 4.6. Eliminar el prompt de root del núcleo ------------------------------------------ Note: This does not apply to the kernels provided for Debian 3.1 as the timeout for the kernel delay has been changed to 0. Los núcleos de Linux 2.6 proporcionan una forma para tener acceso a la línea de comandos del administrador que será presentada justo después de cargar el sistema de archivos cramfs. Un mensaje aparecerá para permitir al administrador entrar en una línea de comandos con permisos de root, esta línea de comandos puede ser usada manualmente para cargar módulos cuando la autodetección falla. Este comportamiento es el predeterminado para initrd's linuxrc. El siguiente mensaje aparecerá: Press ENTER to obtain a shell (waits 5 seconds) Para eliminar este comportamiento usted necesita cambiar /etc/mkinitrd/mkinitrd.conf y colocar: # DELAY define lo segundos que el script linuxrc debe esperar para # que el ususario pueda interrunpir el inicio del sistema DELAY=0 Luego regenera su imagen del disco RAM. Usted puede hacer esto por ejemplo con: # cd /boot # mkinitrd -o initrd.img-2.4.18-k7 /lib/modules/2.4.18-k7 O hacer (preferir): # dpkg-reconfigure kernel-image-2.4.x-yz 4.7. Restricción del acceso a la consola ---------------------------------------- Algunas políticas de seguridad quieren forzar a los administradores para registrarse en el sistema a través de la consola con su usuario/contraseña y luego llegar a ser un superusuario (consu o sudo). Esta política es implementada en Debian al editar el archivo /etc/login.defs o /etc/securetty cuando se usa PAM. En: /etc/pam.d/login In older Debian releases you would need to edit login.defs, and use the CONSOLE variable which defines a file or list of terminals on which root logins are allowed. enables the pam_securetty.so module. This module, when properly configured will not ask for a password when the root user tries to login on an insecure console, rejecting access as this user. securetty The /etc/securetty is a configuration file that belongs to the login package. by adding/removing the terminals to which root access will be allowed. If you wish to allow only local console access then you need console, ttyX Or ttyvX in GNU/FreeBSD, and ttyE0 in GNU/KNetBSD. and vc/X (if using devfs devices), you might want to add also ttySX Or comX in GNU/Hurd, cuaaX in GNU/FreeBSD, and ttyXX in GNU/KNetBSD. if you are using a serial console for local access (where X is an integer, you might want to have multiple instances. The default configuration for Wheezy The default configuration in woody includes 12 local tty and vc consoles, as well as the console device but does not allow remote logins. In sarge the default configuration provides 64 consoles for tty and vc consoles. includes many tty devices, serial ports, vc consoles as well as the X server and the console device. You can safely adjust this if you are not using that many consoles. You can confirm the virtual consoles and the tty devices you have by reviewing /etc/inittab Look for the getty calls. . For more information on terminal devices read the Text-Terminal-HOWTO Cuando use PAM se hacen otros cambios para el proceso de registro, los cuales pueden incluir restricciones para usuarios y grupos a tiempos dados, puede ser configurado en /etc/pam.d/login. Una interesante característica que puede ser incapacitada es la posibilidad de registrar con contraseñas sin efecto (nulas). Esta característica puede ser limitada removiendo el nullok de la linea: auth required pam_unix.so nullok 4.8. Restricting system reboots through the console --------------------------------------------------- If your system has a keyboard attached to it anyone (yes anyone) with physical access to the system can reboot the system through it without login in just pressing the Ctrl+Alt+Delete keyboard combination, also known as the three finger salute. This might, or might not, adhere to your security policy. This is aggravated in environments in which the operating system is running virtualised. In these environments, the possibility extends to users that have access to the virtual console (which might be accessed over the network). Also note that, in these environments, this keyboard combination is used constantly (to open a login shell in some GUI operating systems) and an administrator might virtually send it and force a system reboot. There are two ways to restrict this: * configure it so that only allowed users can reboot the system, * disable this feature completely. If you want to restrict this, you must check the /etc/inittab so that the line that includes ctrlaltdel calls shutdown with the -a switch. The default in Debian includes this switch: ca:12345:ctrlaltdel:/sbin/shutdown -t1 -a -r now The -a switch, as the shutdown(8) manpage describes,makes it possible to allow some users to shutdown the system. For this the file /etc/shutdown.allow must be created and the administrator has to include there the name of users which can boot the system. When the three finger salute combination is pressed in a console the program will check if any of the users listed in the file are logged in. If none of them is, shutdown will not reboot the system. If you want to disable the Ctrl+Alt+Del combination you just need to comment the line with the ctrlaltdel definition in the /etc/inittab. Remember to run init q after making any changes to the /etc/inittab file for the changes to take effect. 4.9. Restricting the use of the Magic SysRq key ----------------------------------------------- The Magic SysRq key is a key combination that allows users connected to the system console of a Linux kernel to perform some low-level commands. These low-level commands are sent by pressing simultaneously Alt+SysRq and a command key. The SysRq key in many keyboards is labeled as the Print Screen key. Since the Etch release, the Magic SysRq key feature is enabled in the Linux kernel to allow console users certain privileges. You can confirm this by checking if the /proc/sys/kernel/sysrq exists and reviewing its value: $ cat /proc/sys/kernel/sysrq 438 The default value shown above allows all of the SysRq functions except for the possibility of sending signals to processes. For example, it allow users connected to the console to remount all systems read-only, reboot the system or cause a kernel panic. In all the features are enabled, or in older kernels (earlier than 2.6.12) the value will be just 1. You should disable this functionality ifaccess to the console is not restricted to authorised users: the console is connected to a modem line, there is easy physical access to the system or it is running in a virtualised environment and other users access the console. To do this edit the /etc/sysctl.conf and add the following lines: # Disables the magic SysRq key kernel.sysrq = 0 For more information, read security chapter in the Remote Serial Console HOWTO, Kernel SysRQ documentation. and the Magic_SysRq_key wikipedia entry. 4.10. Montando particiones de manera correcta --------------------------------------------- When mounting an Ext file system (ext2, ext3 or ext4), there are several additional options you can apply to the mount call or to /etc/fstab. For instance, this is my fstab entry for the /tmp partition: /dev/hda7 /tmp ext2 defaults,nosuid,noexec,nodev 0 2 usted ve la diferencia a las secciones de opciones . La opción nosuid ignora los bits setuid y setgid completamente , mientras que noexec prohibe la ejecución de programas en ese punto de montaje, y nodev, ignora los dispositivos.Esto suena grandioso , pero esto * only applies to ext2 or ext3 file systems * puede ser evitado fácilmente La opción noexec previene los binarios de ejecutarse directamente, pero se engaña fácilmente: alex@joker:/tmp# mount | grep tmp /dev/hda7 on /tmp type ext2 (rw,noexec,nosuid,nodev) alex@joker:/tmp# ./date bash: ./date: Permission denied alex@joker:/tmp# /lib/ld-linux.so.2 ./date Sun Dec 3 17:49:23 CET 2000 Newer versions of the kernel do however handle the noexec flag properly: angrist:/tmp# mount | grep /tmp /dev/hda3 on /tmp type ext3 (rw,noexec,nosuid,nodev) angrist:/tmp# ./date bash: ./tmp: Permission denied angrist:/tmp# /lib/ld-linux.so.2 ./date ./date: error while loading shared libraries: ./date: failed to map segment from shared object: Operation not permitted Sin embargo, muchos "script kiddies" cuentan con "xploits" que intentan crear y ejecutar los archivos en /tmp.Si ellos no tienen una pista, ellos entrarán en esta trampa. En otros términos, un usuario no puede engañarse en ejecutar un binario troyanizado en /tmp e.g. por ejemplo cuando él agrega a propósito /tmpdentro de su PATH. También se previene de algún programa que podría depender en que /tmp sea ejecutable. Más notablemente, Debconf tiene (¿tenía?) algunos problemas que consideran esto, para más información vea Bug http://bugs.debian.org/116448. The following is a more thorough example. A note, though: /var could be set noexec, but some software [15] keeps its programs under in /var. The same applies to the nosuid option. /dev/sda6 /usr ext2 defaults,ro,nodev 0 2 /dev/sda12 /usr/share ext2 defaults,ro,nodev,nosuid 0 2 /dev/sda7 /var ext2 defaults,nodev,usrquota,grpquota 0 2 /dev/sda8 /tmp ext2 defaults,nodev,nosuid,noexec,usrquota,grpquota 0 2 /dev/sda9 /var/tmp ext2 defaults,nodev,nosuid,noexec,usrquota,grpquota 0 2 /dev/sda10 /var/log ext2 defaults,nodev,nosuid,noexec 0 2 /dev/sda11 /var/account ext2 defaults,nodev,nosuid,noexec 0 2 /dev/sda13 /home ext2 rw,nosuid,nodev,exec,auto,nouser,async,usrquota,grpquota 0 2 /dev/fd0 /mnt/fd0 ext2 defaults,users,nodev,nosuid,noexec 0 0 /dev/fd0 /mnt/floppy vfat defaults,users,nodev.nosuid,noexec 0 0 /dev/hda /mnt/cdrom iso9660 ro,users,nodev.nosuid,noexec 0 0 4.10.1. Setting /tmp noexec Tenga cuidado si esta poniendo /tmpy usted quiere instalar el nuevo software, desde que alguno podría usarlo para la instalación. Apt es uno de esos programas (vea http://bugs.debian.org/116448) si no configuró propiamente APT::ExtractTemplates::TempDir (vea apt-extracttemplates(1)). Usted puede poner esta variable en /etc/apt/apt.conf a otro directorio con privilegios exec que no sea /tmp 4.10.2. Serie /usr leer-únicamente Si usted pusiera /usr leer - únicamente usted no podrá instalar los nuevos paquetes en su Debian GNU / sistema Linux. Usted tendrá, primero que remontar leer -escribir, instale los paquetes y entonces remóntelo leer-únicamente. La última versión apt (en Debian 3.0ŽwoodyŽ) puede configurarse para ejecutar las órdenes antes y después de instalar los paquetes, para que usted pueda propiamente querer configurarlo. Hacer esto modifica /etc/apt/apt.conf y agrega: DPkg { Pre-Invoke { "mount /usr -o remount,rw" }; Post-Invoke { "mount /usr -o remount,ro" }; }; Note that the Post-Invoke may fail with a "/usr busy" error message. This happens mainly when you are using files during the update that got updated. You can find these programs by running # lsof +L1 Stop or restart these programs and run the Post-Invoke manually. Beware! This means you'll likely need to restart your X session (if you're running one) every time you do a major upgrade of your system. You might want to reconsider whether a read-only /usr is suitable for your system. See also this discussion on debian-devel about read-only. 4.11. Acceso seguro para los usuarios ------------------------------------- 4.11.1. Uso de la autentificación: PAM PAM (Pluggable Authentication Modules) allows system administrators to choose how applications authenticate users. Note that PAM can do nothing unless an application is compiled with support for PAM. Most of the applications that are shipped with Debian have this support built in (Debian did not have PAM support before 2.2). The current default configuration for any PAM-enabled service is to emulate UNIX authentication (read /usr/share/doc/libpam0g/Debian-PAM-MiniPolicy.gz for more information on how PAM services should work in Debian). Each application with PAM support provides a configuration file in /etc/pam.d/ which can be used to modify its behavior: * what backend is used for authentication. * what backend is used for sessions. * how do password checks behave. The following description is far from complete, for more information you might want to read the Linux-PAM Guides as a reference. This documentation is available in the system if you install the libpam-doc at /usr/share/doc/libpam-doc/html/. PAM le ofrece a usted la posibilidad a ir por varios pasos de autenticación una vez, sin el uso de conocimientos .Usted puede autenticar de nuevo una base de datos Berkeley y de nuevo el archivo de password normal y el uso únicamente de registros en si correctamente autenticos en ambos. Usted puede limitar a muchos con PAM , así como usted puede abrir sus puertas del sistema muy extensamente. Así que tenga cuidado. Una línea de la típica configuración tiene un campo de mando como su segundo elemento. 4.11.2. Password security in PAM Review the /etc/pam.d/common-password, included by /etc/pam.d/passwd[16] This file is included by other files in /etc/pam.d/ to define the behaviour of password use in subsystems that grant access to services in the machine, like the console login (login), graphical login managers (such as gdm or lightdm), and remote login (such as sshd). This definition is You have to make sure that the pam_unix.so module uses the "sha512" option to use encrypted passwords. This is the default in Debian Squeeze. The line with the definition of the pam_unix module will look something like: password [success=1 default=ignore] pam_unix.so nullok obscure minlen=8 sha512 Esta definición * Enforces password encryption when storing passwords, using the SHA-512 hash function (option sha512), * Enables password complexity checks (option obscure) as defined in the pam_unix(8) manpage, * Imposes a minimum password length (option min) of 8. You have to ensure that encrypted passwords are used in PAM applications, since this helps protect against dictionary cracks. Using encryption also makes it possible to use passwords longer than 8 characters. Since this module is also used to define how passwords are changed (it is included by chpasswd) you can strengthen the password security in the system by installing libpam-cracklib and introducing this definition in the /etc/pam.d/common-password configuration file: # Asegúrese de tener instalado libpam-cracklib, sino no podrá entrar en el sistema password required pam_cracklib.so retry=3 minlen=12 difok=3 password [success=1 default=ignore] pam_unix.so obscure minlen=8 sha512 use_authok So, what does this incantation do? The first line loads the cracklib PAM module, which provides password strength-checking, prompts for a new password with a minimum size [17] of 12 characters, and difference of at least 3 characters from the old password, and allows 3 retries. Cracklib depends on a wordlist package (such as wenglish, wspanish, wbritish, ...), so make sure you install one that is appropriate for your language or cracklib might not be useful to you at all. The second line (using the pam_unix.so module) is the default configuration in Debian, as described above, save for the use_authok option. The use_authok option is required if pam_unix.so is stacked after pam_cracklib.so, and is used to hand over the password from the previous module. Otherwise, the user would be prompted for the password twice. For more information about setting up Cracklib, read the pam_cracklib(8) manpage and the article Linux Password Security with pam_cracklib by Hal Pomeranz. By enabling the cracklib PAM module you setup a policy that forces uses to use strong passwords. Alternatively, you can setup and configure PAM modules to use double factor authentication such as: libpam-barada, libpam-google-authenticator, libpam-oath, libpam-otpw, libpam-poldi, libpam-usb or libpam-yubico. The configuration of these modules would make it possible to access the system using external authentication mechanisms such as smartcards, external USB keys, or One-Time-Passwords generated by external applications running, for example, in the user's mobile phone. Please note that these restrictions apply to all users but not to the password changes done by the root user. The root user will be able to set up any password (any length or complexity) for personal use or others regardless of the restrictions defined here. 4.11.3. Control de acceso de usuarios con PAM Para asegurarse que el root (administrador de Linux) del usuario sólo puede anotarse en el sistema de los términos locales, la línea siguiente debe habilitarse en /etc/pam.d/login: auth requisite pam_securetty.so Then you should modify the list of terminals on which direct root login is allowed in /etc/securetty (as described in Sección 4.7, “Restricción del acceso a la consola”). Alternatively, you could enable the pam_access module and modify /etc/security/access.conf which allows for a more general and fine-tuned access control, but (unfortunately) lacks decent log messages (logging within PAM is not standardized and is particularly unrewarding problem to deal with). We'll return to access.conf a little later. 4.11.4. Limites para los usuarios mediante PAM The following line should be enabled in /etc/pam.d/login to set up user resource limits. session required pam_limits.so Esto restringe los recursos del sistema que se permiten a los usuarios (vea en la siguiente pagina user-limits. Por ejemplo, usted podría restringir el número de logins coexistente (de un grupo dado de usuarios, o sistema-ancho) usted puede tener, el número de procesos, el tamaño de memoria...... 4.11.5. Control de 'su' mediante PAM Si usted quiere proteger su (un comando), para que sólo algunas personas puedan usarlo para volverse a root en su sistema, usted necesita agregar uno nuevo para agregar un nuevo "wheel" de grupo a su sistema (ésa es la manera más limpia, desde que ningún archivo tiene tal un permiso de grupo todavía). Agregue el root y los otros usuarios que deberian ser capaces de ejecutar su a el usuario de root a este grupo. Entonces agregue la línea siguiente a /etc/pam.d/su: auth requisite pam_wheel.so group=wheel debug Esto asegura que sólo personas de el grupo wheel pueden usar su para volverse root. Otros usuarios no seran capaces de volverse root. De hecho ellos conseguirán un mensaje negado si ellos intentan volverse volverse root. Si usted quiere que sólo ciertos usuarios autentiquen a un servicio de PAM, esto es bastante fácil de lograr usando los archivos dónde los usuarios que son permitidos al login (o no) se guarden. Sólo imagine que usted quiere permitirle el login de ŽrefŽto al usuario vía ssh. Así que usted lo pone en /etc/sshusers-allowed y le escribe lo siguiente en /etc/pam.d/ssh: auth required pam_listfile.so item=user sense=allow file=/etc/sshusers-allowed onerr=fail 4.11.6. Carpetas temporales en PAM Since there have been a number of so called insecure tempfile vulnerabilities, thttpd is one example (see DSA-883-1), the libpam-tmpdir is a good package to install. All you have to do is add the following to /etc/pam.d/common-session: session optional pam_tmpdir.so There has also been a discussion about adding this by default in Debian configuration, but it s. See http://lists.debian.org/debian-devel/2005/11/msg00297.html for more information. 4.11.7. Configuración de aplicaciones genéricas de PAM Por último, pero no menos importante, cree /etc/pam.d/other y coloque las líneas siguientes: auth required pam_securetty.so auth required pam_unix_auth.so auth required pam_warn.so auth required pam_deny.so account required pam_unix_acct.so account required pam_warn.so account required pam_deny.so password required pam_unix_passwd.so password required pam_warn.so password required pam_deny.so session required pam_unix_session.so session required pam_warn.so session required pam_deny.so Estas líneas mantendrán una buena configuración predefinida en todas las aplicaciones que apoyan PAM (se niega el acceso por el valor predeterminado). 4.11.8. Limitación de recursos: archivo limits.conf You should really take a serious look into this file. Here you can define user resource limits. In old releases this configuration file was /etc/limits.conf, but in newer releases (with PAM) the /etc/security/limits.conf configuration file should be used instead. If you do not restrict resource usage, any user with a valid shell in your system (or even an intruder who compromised the system through a service or a daemon going awry) can use up as much CPU, memory, stack, etc. as the system can provide. This resource exhaustion problem can be fixed by the use of PAM. There is a way to add resource limits to some shells (for example, bash has ulimit, see bash(1)), but since not all of them provide the same limits and since the user can change shells (see chsh(1)) it is better to place the limits on the PAM modules as they will apply regardless of the shell used and will also apply to PAM modules that are not shell-oriented. Resource limits are imposed by the kernel, but they need to be configured through the limits.conf and the PAM configuration of the different services need to load the appropriate PAM. You can check which services are enforcing limits by running: $ find /etc/pam.d/ \! -name "*.dpkg*" | xargs -- grep limits |grep -v ":#" Commonly, login, ssh and the graphic session managers (gdm, kdm or xdm) should enforce user limits but you might want to do this in other PAM configuration files, such as cron, to prevent system daemons from taking over all system resources. The specific limits settings you might want to enforce depend on your system's resources, that's one of the main reasons why no limits are enforced in the default installation. For example, the configuration example below enforces a 100 process limit for all users (to prevent fork bombs) as well as a limit of 10MB of memory per process and a limit of 10 simultaneous logins. Users in the adm group have higher limits and can produce core files if they want to (there is only a soft limit). * soft core 0 * hard core 0 * hard rss 1000 * hard memlock 1000 * hard nproc 100 * - maxlogins 1 * hard data 102400 * hard fsize 2048 @adm hard core 100000 @adm hard rss 100000 @adm soft nproc 2000 @adm hard nproc 3000 @adm hard fsize 100000 @adm - maxlogins 10 These would be the limits a default user (including system daemons) would have: $ ulimit -a core file size (blocks, -c) 0 data seg size (kbytes, -d) 102400 file size (blocks, -f) 2048 max locked memory (kbytes, -l) 10000 max memory size (kbytes, -m) 10000 open files (-n) 1024 pipe size (512 bytes, -p) 8 stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) 100 virtual memory (kbytes, -v) unlimited estos son los limites para un usuarios administrador: $ ulimit -a core file size (blocks, -c) 0 data seg size (kbytes, -d) 102400 file size (blocks, -f) 100000 max locked memory (kbytes, -l) 100000 max memory size (kbytes, -m) 100000 open files (-n) 1024 pipe size (512 bytes, -p) 8 stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) 2000 virtual memory (kbytes, -v) unlimited For more information read: * PAM reference guide for available modules * PAM configuration article. * Seifried's Securing Linux Step by Step on the Limiting users overview section. * LASG in the Limiting and monitoring users section. 4.11.9. User login actions: edit /etc/login.defs The next step is to edit the basic configuration and action upon user login. Note that this file is not part of the PAM configuration, it's a configuration file honored by login and su programs, so it doesn't make sense tuning it for cases where neither of the two programs are at least indirectly called (the getty program which sits on the consoles and offers the initial login prompt does invoke login). FAILLOG_ENAB yes Si usted habilita esta variable, se anotarán los logins fallados. Es importante guardar huella de ellos para coger a alguien que pruebe un ataque de fuerza bruta. LOG_UNKFAIL_ENAB no If you set this variable to 'yes' it will record unknown usernames if the login failed. It is best if you use 'no' (the default) since, otherwise, user passwords might be inadvertenly logged here (if a user mistypes and they enter their password as the username). If you set it to 'yes', make sure the logs have the proper permissions (640 for example, with an appropriate group setting such as adm). SYSLOG_SU_ENAB yes Este uno habilita el logging de la pueba su a syslog. Bastante importante en serias maquinas pero note que esto puede crear el retiro de los resultados a medida que esten bien. SYSLOG_SG_ENAB yes The same as SYSLOG_SU_ENAB but applies to the sg program. ENCRYPT_METHOD SHA512 As stated above, encrypted passwords greatly reduce the problem of dictionary attacks, since you can use longer passwords. This definition has to be consistent with the value defined in /etc/pam.d/common-password. 4.11.10. User login actions: edit /etc/pam.d/login You can adjust the login configuration file to implement an stricter policy. For example, you can change the default configuration and increase the delay time between login prompts. The default configuration sets a 3 seconds delay: auth optional pam_faildelay.so delay=3000000 Increasing the delay value to a higher value to make it harder to use the terminal to log in using brute force. If a wrong password is typed in, the possible attacker (or normal user!) has to wait longer seconds to get a new login prompt, which is quite time consuming when you test passwords. For example, if you set delay=10000000, users will have to wait 10 seconds if they type a wrong password. In this file you can also set the system to present a message to users before a user logs in. The default is disabled, as shown below: # auth required pam_issue.so issue=/etc/issue If required by your security policy, this file can be used to show a standard message indicating that access to the system is restricted and user acess is logged. This kind of disclaimer might be required in some environments and jurisdictions. To enable it, just include the relevant information in the /etc/issue[18] file and uncomment the line enabling the pam_issue.so module in /etc/pam.d/login. In this file you can also enable additional features which might be relevant to apply local security policies such as: * setting rules for which users can access at which times, by enabling the pam_time.so module and configuring /etc/security/time.conf accordingly (disabled by default), * setup login sessions to use user limits as defined in /etc/security/limits.conf (enabled by default), * present the user with the information of previous login information (enabled by default), * print a message (/etc/motd and /run/motd.dynamic) to users after login in (enabled by default), 4.11.11. Restricting ftp: editing /etc/ftpusers Este archivo contiene una lista de usuarios no autorizados a entrar en el sistema mediante ftp. Sĺo debería emplear este archivo si desea prpoprcionar ftp (lo cual es -en general- poco aconsejable debido al uso de contraseñas sin cifrar). Si incorpora soporte para PAM, puede autorizar o denegar el uso de ciertos servicios a los usuarios. FIXME (BUG): Is it a bug that the default ftpusers in Debian does not include all the administrative users (in base-passwd). A convenient way to add all system accounts to the /etc/ftpusers is to run $ awk -F : '{if ($3<1000) print $1}' /etc/passwd > /etc/ftpusers 4.11.12. Uso de su Si usted realmente necesita que los usuarios se vuelvan el super usuario en su sistema,e.g. por instalar los paquetes o agregar usuarios, usted puede usar el comando su para cambiar su identidad. Usted debe intentar evitar cualquier login como root del usuario y en cambio usar su. Realmente, la mejor solución es quitar su y cambiar a sudo, como él tiene más rasgos que su. Sin embargo,su es más común como se usa en muchos otro Unixes. 4.11.13. Uso de sudo sudo le permite al usuario ejecutar los comandos definidos bajo la identidad de otro usuario, así como root. Si el usuario agrega a /etc/sudoers y se autentica correctamente, él es capaz de avanzar comandos en que se ha definido /etc/sudoers. Las Violaciones, como las contraseñas incorrectas o intentos de ejecutar un programa usted no tienen permiso para ser anotado y mandado por correo a root. 4.11.14. Prohibición administración remota You should also modify /etc/security/access.conf to disallow remote logins to administrative accounts. This way users need to invoke su (or sudo) to use any administrative powers and the appropriate audit trace will always be generated. You need to add the following line to /etc/security/access.conf, the default Debian configuration file has a sample line commented out: -:wheel:ALL EXCEPT LOCAL Remember to enable the pam_access module for every service (or default configuration) in /etc/pam.d/ if you want your changes to /etc/security/access.conf honored. 4.11.15. Restringiendo usuarios A veces usted podría pensar que necesita tener los usuarios creados en su sistema local para proporcionar un servicio (pop3 manda por correo el servicio o ftp). Antes de hacer eso, primero recuerde que la aplicación de PAM en Debian GNU/Linux le permite validar a los usuarios con una variedad ancha de el servicio de directorio externo (el radio, el ldap, etc.) con tal de que por el ,el libpam sea empacado. Si los usuarios necesitan ser creados y el sistema puede ser remotamente de acceso tome en cuenta que los usuarios sean capaces al login al sistema. Usted puede arreglar esto dando a los usuarios una nula (/dev/null) interfaz de comandos (él necesitaría ser listada en /etc/shells). Si usted quiere permítales a los usuarios acceder a el sistema pero limitar sus movimientos, usted puede usar el /bin/rbash, equivalente a agregar la opción -r en bash (RESTICTED SHELL ver bash(1)). Por favor note que incluso con la interfaz de comandos restringido, un usuario que entra en acceso a un programa interactivo (eso podría permitirle la ejecución de un subshell) podría poder desviar los límites de el shell. Debian currently provides in the unstable release (and might be included in the next stable releases) the pam_chroot module (in the libpam-chroot). An alternative to it is to chroot the service that provides remote logging (ssh, telnet). [19] Si usted desea restringirlo when los usuarios pueden acceder a el sistema que usted quiere tener personalizado /etc/security/access.conf para sus necesidades. Information on how to chroot users accessing the system through the ssh service is described in Sección B.7, “Chroot environment for SSH”. 4.11.16. Auditoría de usuarios If you are really paranoid you might want to add a system-wide configuration to audit what the users are doing in your system. This sections presents some tips using diverse utilities you can use. 4.11.16.1. Input and output audit with script You can use the script command to audit both what the users run and what are the results of those commands. You cannot setup script as a shell (even if you add it to /etc/shells). But you can have the shell initialization file run the following: umask 077 exec script -q -a "/var/log/sessions/$USER" Of course, if you do this system wide it means that the shell would not continue reading personal initialization files (since the shell gets overwritten by script). An alternative is to do this in the user's initialization files (but then the user could remove this, see the comments about this below) You also need to setup the files in the audit directory (in the example /var/log/sessions/) so that users can write to it but cannot remove the file. This could be done, for example, by creating the user session files in advance and setting them with the append-only flag using chattr. A useful alternative for sysadmins, which includes date information would be: umask 077 exec script -q -a "/var/log/sessions/$USER-`date +%Y%m%d`" 4.11.16.2. Using the shell history file If you want to review what does the user type in the shell (but not what the result of that is) you can setup a system-wide /etc/profile that configures the environment so that all commands are saved into a history file. The system-wide configuration needs to be setup in such a way that users cannot remove audit capabilities from their shell. This is somewhat shell specific so make sure that all users are using a shell that supports this. For example, for bash, the /etc/profile could be set as follows [20] : HISTFILE=~/.bash_history HISTSIZE=10000 HISTFILESIZE=999999 # Don't let the users enter commands that are ignored # in the history file HISTIGNORE="" HISTCONTROL="" readonly HISTFILE readonly HISTSIZE readonly HISTFILESIZE readonly HISTIGNORE readonly HISTCONTROL export HISTFILE HISTSIZE HISTFILESIZE HISTIGNORE HISTCONTROL For this to work, the user can only append information to .bash_history file. You need also to set the append-only option using chattr program for .bash_history for all users. [21]. Note that you could introduce the configuration above in the user's .profile. But then you would need to setup permissions properly in such a way that prevents the user from modifying this file. This includes: having the user's home directories not belong to the user (since the user would be able to remove the file otherwise) but at the same time allow the user to read the .profile configuration file and write on the .bash_history. It would be good to set the immutable flag (also using chattr) for .profile too if you do it this way. 4.11.16.3. Auditoría total de usuarios mediante contabilidad de utilidades El ejemplo anterior es una manera simple de configurar el usuario interviniendo el cual no podría ser útil para los sistemas complejos. Si éste es su caso, usted necesita mirar a acct, la contabilidad de utilidades. Éstos anotarán todos los comandos corridos por usuarios o procesos en el sistema, al gasto de espacio del disco. Al activar la contabilidad, toda la información sobre los procesos y el usuario se guarda bajo /var/account/, más específicamente en el pacct. El paquete de contabilidad incluye algunas herramientas (sa y ac) para analizar estos datos. 4.11.16.4. Otros métodos de auditoría If you are completely paranoid and want to audit every user's command, you could take bash source code, edit it and have it send all that the user typed into another file. Or have ttysnoop constantly monitor any new ttys [22] and dump the output into a file. Other useful program is snoopy (see also github: https://github.com/a2o/snoopy) which is a user-transparent program that hooks in as a library providing a wrapper around execve() calls, any command executed is logged to syslogd using the authpriv facility (usually stored at /var/log/auth.log). 4.11.17. Repasando los perfiles del usuario Si usted quiere normalmente see a los usuarios qué están haciendo, cuando esten ellos conectándos usted pueden usar la base de datos de wtmp que incluye toda la información del login. Este archivo puede procesarse con varias utilidades, entre ellos sac el cual puede hacer un profile en cada usuario que muestra en que estructura de tiempo ellos normalmente anotan adelante en el sistema. En caso de que usted tiene la contabilidad activada, usted también puede usar las herramientas con tal de que por esto en el comando determine cuando los usuarios acceden a el sistema y qué ellos ejecuten. 4.11.18. Setting users umasks Depending on your user policy you might want to change how information is shared between users, that is, what the default permissions of new files created by users are. Debian's default umask setting is 022 this means that files (and directories) can be read and accessed by the user's group and by any other users in the system. This definition is set in the standard configuration file /etc/profile which is used by all shells. If Debian's default value is too permissive for your system you will have to change the umask setting for all the shells. More restrictive umask settings include 027 (no access is allowed to new files for the other group, i.e. to other users in the system) or 077 (no access is allowed to new files to the members the user's group). Debian (by default[23]) creates one group per user so that only the user is included in its group. Consequently 027 and 077 are equivalent as the user's group contains only the user. This change is set by defining a proper umask setting for all users. You can change this by introducing an umask call in the shell configuration files: /etc/profile (source by all Bourne-compatible shells), /etc/csh.cshrc, /etc/csh.login, /etc/zshrc and probably some others (depending on the shells you have installed on your system). You can also change the UMASK setting in /etc/login.defs, Of all of these the last one that gets loaded by the shell takes precedence. The order is: the default system configuration for the user's shell (i.e. /etc/profile and other system-wide configuration files) and then the user's shell (his ~/.profile, ~/.bash_profile, etc...). Some shells, however, can be executed with a nologin value which might skip sourcing some of those files. See your shell's manpage for additional information. For connections that make use of login the UMASK definition in /etc/login.defs is used before any of the others. However, that value does not apply to user executed programs that do not use login such as those run through su, cron or ssh. Don't forget to review and maybe modify the dotfiles under /etc/skel/ since these will be new user's defaults when created with the adduser command. Debian default dotfiles do not include any umask call but if there is any in the dotfiles newly created users might a different value. Note, however that users can modify their own umask setting if they want to, making it more permissive or more restricted, by changing their own dotfiles. The libpam-umask package adjusts the users' default umask using PAM. Add the following, after installing the package, to /etc/pam.d/common-session: session optional pam_umask.so umask=077 Finally, you should consider changing root's default 022 umask (as defined in /root/.bashrc) to a more strict umask. That will prevent the system administrator from inadvertenly dropping sensitive files when working as root to world-readable directories (such as /tmp) and having them available for your average user. 4.11.19. Limitar el acceso a los usuarios FIXME: Content needed. Describe the consequences of changing packages permissions when upgrading (an admin this paranoid should chroot his users BTW) if not using dpkg-statoverride. If you need to grant users access to the system with a shell think about it very carefully. A user can, by default unless in a severely restricted environment (like a chroot jail), retrieve quite a lot of information from your system including: * some configuration files in /etc. However, Debian's default permissions for some sensitive files (which might, for example, contain passwords), will prevent access to critical information. To see which files are only accessible by the root user for example find /etc -type f -a -perm 600 -a -uid 0 as superuser. * your installed packages, either by looking at the package database, at the /usr/share/doc directory or by guessing by looking at the binaries and libraries installed in your system. * some log files at /var/log. Note also that some log files are only accessible to root and the adm group (try find /var/log -type f -a -perm 640 ) and some are even only available to the root user (try find /var/log -type f -a -perm 600 -a -uid 0 ). What can a user see in your system? Probably quite a lot of things, try this (take a deep breath): find / -type f -a -perm +006 2>/dev/null find / -type d -a -perm +007 2>/dev/null The output is the list of files that a user can see and the accessable directories. 4.11.19.1. Limitar el acceso a los datos de otros usuarios If you still grant shell access to users you might want to limit what information they can view from other users. Users with shell access have a tendency to create quite a number of files under their $HOMEs: mailboxes, personal documents, configuration of X/GNOME/KDE applications... In Debian each user is created with one associated group, and no two users belong to the same group. This is the default behavior: when an user account is created, a group of the same name is created too, and the user is assigned to it. This avoids the concept of a common users group which might make it more difficult for users to hide information from other users. However, users' $HOME directories are created with 0755 permissions (group-readable and world-readable). The group permissions is not an issue since only the user belongs to the group, however the world permissions might (or might not) be an issue depending on your local policy. You can change this behavior so that user creation provides different $HOME permissions. To change the behavior for new users when they get created, change DIR_MODE in the configuration file /etc/adduser.conf to 0750 (no world-readable access). Users can still share information, but not directly in their $HOME directories unless they change its permissions. Note that disabling world-readable home directories will prevent users from creating their personal web pages in the ~/public_html directory, since the web server will not be able to read one component in the path - namely their $HOME directory. If you want to permit users to publish HTML pages in their ~/public_html, then change DIR_MODE to 0751. This will allow the web server to access the final public_html directory (which itself should have a mode of 0755) and provide the content published by users. Of course, we are only talking about a default configuration here; users can generally tune modes of their own files completely to their liking, or you could keep content intended for the web in a separate location which is not a subdirectory of user's $HOME directory. 4.11.20. Generación de contraseñas de usuario There are many cases when an administrator needs to create many user accounts and provide passwords for all of them. Of course, the administrator could easily just set the password to be the same as the user's account name, but that would not be very sensitive security-wise. A better approach is to use a password generating program. Debian provides makepasswd, apg and pwgen packages which provide programs (the name is the same as the package) that can be used for this purpose. Makepasswd will generate true random passwords with an emphasis on security over pronounceability while pwgen will try to make meaningless but pronounceable passwords (of course this might depend on your mother language). Apg has algorithms to provide for both (there is a client/server version for this program but it is not included in the Debian package). Passwd does not allow non-interactive assignation of passwords (since it uses direct tty access). If you want to change passwords when creating a large number of users you can create them using adduser with the --disabled-login option and then use usermod or chpasswd[24] (both from the passwd package so you already have them installed). If you want to use a file with all the information to make users as a batch process you might be better off using newusers. 4.11.21. Comprobación de contraseñas de usuarios User passwords can sometimes become the weakest link in the security of a given system. This is due to some users choosing weak passwords for their accounts (and the more of them that have access to it the greater the chances of this happening). Even if you established checks with the cracklib PAM module and password limits as described in Sección 4.11.1, “Uso de la autentificación: PAM” users will still be able to use weak passwords. Since user access might include remote shell access (over ssh, hopefully) it's important to make password guessing as hard as possible for the remote attackers, especially if they were somehow able to collect important information such as usernames or even the passwd and shadow files themselves. A system administrator must, given a big number of users, check if the passwords they have are consistent with the local security policy. How to check? Try to crack them as an attacker would if having access to the hashed passwords (the /etc/shadow file). An administrator can use john or crack (both are brute force password crackers) together with an appropriate wordlist to check users' passwords and take appropriate action when a weak password is detected. You can search for Debian GNU packages that contain word lists using apt-cache search wordlist, or visit some Internet wordlist sites. 4.11.22. Sacando usuarios inactivos Idle users are usually a security problem, a user might be idle maybe because he's out to lunch or because a remote connection hung and was not re-established. For whatever the reason, idle users might lead to a compromise: * because the user's console might be unlocked and can be accessed by an intruder. * because an attacker might be able to re-attach to a closed network connection and send commands to the remote shell (this is fairly easy if the remote shell is not encrypted as in the case of telnet). Some remote systems have even been compromised through an idle (and detached) screen. Automatic disconnection of idle users is usually a part of the local security policy that must be enforced. There are several ways to do this: * If bash is the user shell, a system administrator can set a default TMOUT value (see bash(1)) which will make the shell automatically log off remote idle users. Note that it must be set with the -o option or users will be able to change (or unset) it. * Install timeoutd and configure /etc/timeouts according to your local security policy. The daemon will watch for idle users and time out their shells accordingly. * Install autolog and configure it to remove idle users. The timeoutd or autolog daemons are the preferred method since, after all, users can change their default shell or can, after running their default shell, switch to another (uncontrolled) shell. 4.12. Uso de tcpwrappers ------------------------ TCP wrappers were developed when there were no real packet filters available and access control was needed. Nevertheless, they're still very interesting and useful. The TCP wrappers allow you to allow or deny a service for a host or a domain and define a default allow or deny rule (all performed on the application level). If you want more information take a look at hosts_access(5) manual page. Muchos servicios instalados en Debian son cualquiera de estos dos: * lanzó a través del servicio del tcpwrapper (tcpd) * compiló con el soporte libwrapper incorporado. On the one hand, for services configured in /etc/inetd.conf (this includes telnet, ftp, netbios, swat and finger) you will see that the configuration file executes /usr/sbin/tcpd first. On the other hand, even if a service is not launched by the inetd superdaemon, support for the tcp wrappers rules can be compiled into it. Services compiled with tcp wrappers in Debian include ssh, portmap, in.talk, rpc.statd, rpc.mountd, gdm, oaf (the GNOME activator daemon), nessus and many others. To see which packages use tcpwrappers [25] try: $ apt-cache rdepends libwrap0 Tenga en cuenta esto cuando el tcpchk está avanzando. Usted puede agregar servicios en que se unen a la biblioteca de la envoltura de los archivos host.deny y hosts.allow pero los tcpchk advertirá que este no puede encontrar esos servicios desde que parece para ellos en /etc/inetd.conf (el manpage no es totalmente exacto aquí). Ahora, aquí viene un truco pequeño, y probablemente la intrusión más pequeña del sistema de descubrimiento disponible. En general, usted debe tener una política decente del cortafuego como una primera línea, y envolturas del tcp como la segunda línea de defensa. Un truco pequeño es poner un comando SPAWN [26]en /etc/hosts.deny que envía correos a root siempre que hay un servicio negado en las envolturas de los gatillos: ALL: ALL: SPAWN ( \ echo -e "\n\ TCP Wrappers\: Connection refused\n\ By\: $(uname -n)\n\ Process\: %d (pid %p)\n\ User\: %u\n\ Host\: %c\n\ Date\: $(date)\n\ " | /usr/bin/mail -s "Connection to %d blocked" root) & Beware (tenga cuidado): El ejemplo anterior impreso puede fácilmente ser DoSed por estar haciendo las muchas conexiones en un período corto de tiempo. Muchos correos electrónicos significan mucho del archivo I/O para enviar únicamente unos correos. 4.13. La importancia de logs y alarmas -------------------------------------- Cómo las bitácoras y alarmas son tratadas es un problema importante en un sistema seguro. Es fácil ver que, aun cuando el sistema está perfectamente configurado y, supuestamente, 99% asegurado. Si el 1% sucede, y no hay seguridad midiendo en tales situaciones, primero, descubra esto y, segundo, las alarmas del aumento, el sistema no está en absoluto seguro. Debian GNU/Linux provides some tools to perform log analysis, most notably swatch, [27] logcheck or log-analysis (all will need some customisation to remove unnecessary things from the report). It might also be useful, if the system is nearby, to have the system logs printed on a virtual console. This is useful since you can (from a distance) see if the system is behaving properly. Debian's /etc/syslog.conf comes with a commented default configuration; to enable it uncomment the lines and restart syslogd (/etc/init.d/syslogd restart): daemon,mail.*;\ news.=crit;news.=err;news.=notice;\ *.=debug;*.=info;\ *.=notice;*.=warn /dev/tty8 To colorize the logs, you could take a look at colorize, ccze or glark. There is a lot to log analysis that cannot be fully covered here, so a good information resource would be books should as http://books.google.com/books?id=UyktqN6GnWEC. In any case, even automated tools are no match for the best analysis tool: your brain. 4.13.1. Uso y personalización de logcheck The logcheck package in Debian is divided into the three packages logcheck (the main program), logcheck-database (a database of regular expressions for the program) and logtail (prints loglines that have not yet been read). The Debian default (in /etc/cron.d/logcheck) is that logcheck is run every hour and after reboots. Hay también un número de registros de auditorias de herramientas, en el site, como logcheck. Estas herramientas pueden ser absolutamente usables si se garantiza propiamente para alertar al administrador sobre eventos inusuales en el sistema de archivos locales. logcheck. pude ser enteramente garantizado, pude enviar mensajes desde eventos recuperados y desde los registros que son meritorios de atención. El abandono de instalación incluye perfiles para eventos ignorados y violaciones políticas para tres diferentes montajes (estación de trabajo, servidor y paranoia). Los paquetes de Debian incluyen un archivo de configuración /etc/logcheck/logcheck.conf, dirigido por el programa, que define al usuario y que también revisa sus envios. También suministra una forma de paquete que provee servicios para implementar nuevas políticas en los directorios: /etc/logcheck/hacking.d/_packagename_, /etc/logcheck/violations.d/_packagename_, /etc/logcheck/violations.ignore.d/_packagename_, /etc/logcheck/ignore.d.paranoid/_packagename_, /etc/logcheck/ignore.d.server/_packagename_, and /etc/logcheck/ignore.d.workstation/_packagename_. Sin embargo, no muchos paquetes lo hacen actualmente. Si usted tiene una política que puede ser útil para otros usuarios , por favor envielo como un pequeño reporte para los paquetes apropiados, mire mas información en /usr/share/doc/logcheck/README.Debian The best way to configure logcheck is to edit its main configuration file /etc/logcheck/logcheck.conf after installation. Change the default user (root) to whom reports should be mailed. You should set the reportlevel in there, too. logcheck-database has three report levels of increasing verbosity: workstation, server, paranoid. "server" being the default level, paranoid is only recommended for high-security machines running as few services as possible and workstation for relatively sheltered, non-critical machines. If you wish to add new log files just add them to /etc/logcheck/logcheck.logfiles. It is tuned for default syslog install. Once this is done you might want to check the mails that are sent, for the first few days/weeks/months. If you find you are sent messages you do not wish to receive, just add the regular expressions (see regex(7) and egrep(1)) that correspond to these messages to the /etc/logcheck/ignore.d.reportlevel/local. Try to match the whole logline. Details on howto write rules are explained in /usr/share/doc/logcheck-database/README.logcheck-database.gz. It's an ongoing tuning process; once the messages that are sent are always relevant you can consider the tuning finished. Note that if logcheck does not find anything relevant in your system it will not mail you even if it does run (so you might get a mail only once a week, if you are lucky). 4.13.2. Configurando el sitio donde las alertas son enviadas Debian viene con una configuración de syslog estándard dentro de (etc/syslog.conf)que anota mensajes para apropiar archivos dependiendo de la facilidad del sistema. Usted debería familiarizarse con ésto, debe mirar el archivo syslog.conf o sino la documentación. Si usted pretende mantener un sistema seguro usted podrá estar precavido de a dónde se mandan los mensajes de registro de manera que no pasen inadvertidos. Por ejemplo, enviar mensajes a la consola es una configuración interesante ya que es útil para muchos sistemas de nivel de producción. Pero para muchos sistemas también es importante añadir una nueva máquina que podría servir como servidor de registro (i.e. esto recibe los registros desde todos los otros sistemas). El correo de Root también deberia ser considerado, muchos controles de seguridad como snort) envían alarmas al buzón de Root. Este buzón normalmente apunta al primer usuario que se creó en el sistema (compruebe /etc/aliases). Tenga cuidado de enviar correo de root a cualquier lugar donde pueda ser leído (ya sea local ó remotamente) Hay otros informes y alianzas en su sistema. En un pequeño sistema, ésto probablemente lo más simple para asegurarse de que todas las alianzas apunten hacia la cuenta de root, y que el correo para root este dispuesto para el sistema de buzón personal del administrador. ARREGLAME: it would be interesting to tell how a Debian system can send/receive SNMP traps related to security problems (jfs). Check: snmptraglogd, snmp and snmpd. 4.13.3. Usar un servidor de registro A loghost is a host which collects syslog data remotely over the network. If one of your machines is cracked, the intruder is not able to cover the tracks, unless hacking the loghost as well. So, the loghost should be especially secure. Making a machine a loghost is simple. Just start the syslogd with syslogd -r and a new loghost is born. In order to do this permanently in Debian, edit /etc/default/syslogd and change the line SYSLOGD="" a SYSLOGD="-r" Luego, configure las otras máquinas al enviar los datos al servidor de registro. Agrege una entrada como la siguiente /etc/syslog.conf: facility.level @your_loghost Mire la documentación para saber que usar en lugar de facility y level (ellos no deben ser introducirse de forma literal como se hace aquí). Si usted quiere registrar todo remotamente, escriba: *.* @your_loghost into your syslog.conf. Logging remotely as well as locally is the best solution (the attacker might presume to have covered his tracks after deleting the local log files). See the syslog(3), syslogd(8) and syslog.conf(5) manpages for additional information. 4.13.4. Permisos para el archivo de registro It is not only important to decide how alerts are used, but also who has read/modify access to the log files (if not using a remote loghost). Security alerts which the attacker can change or disable are not worth much in the event of an intrusion. Also, you have to take into account that log files might reveal quite a lot of information about your system to an intruder who has access to them. Algunos permisos para el achivo de registro no son perfectos despúes de la instalación. Primero /var/log/lastlog y /var/log/faillogno necesitan tener un permiso de lectura para un usuario normal. En el archivo lastlog usted puede ver quien entró recientemente y en faillog usted mira un resumen de las entradas fallidas. El autor recomienda cambiar permisos a 660.Haga una breve revisión en sus archivos de registro y decida muy cuidadosamente cuales logfile deben tener permiso de lectura y escritura para un usuario con UID distinto a 0 y un grupo aparte de 'adm' o 'root'. # find /var/log -type f -exec ls -l {} \; | cut -c 17-35 |sort -u (see to what users do files in /var/log belong) # find /var/log -type f -exec ls -l {} \; | cut -c 26-34 |sort -u (see to what groups do files in /var/log belong) # find /var/log -perm +004 (files which are readable by any user) # find /var/log \! -group root \! -group adm -exec ls -ld {} \; (files which belong to groups not root or adm) To customize how log files are created you will probably have to customize the program that generates them. If the log file gets rotated, however, you can customize the behavior of creation and rotation. 4.14. Añadiendo parches al kernel --------------------------------- Debian GNU/Linux suministra algunos de los parches para el kernel de Linux que aumentan su aseguramiento. Estos incluyen: * Linux Intrusion Detection provided in the kernel-patch-2.4-lids package. This kernel patch makes the process of hardening your Linux system easier by allowing you to restrict, hide and protect processes, even from root. It implements mandatory access control capabilities. * Linux Trustees, provided in package trustees. This patch adds a decent advanced permissions management system to your Linux kernel. Special objects (called trustees) are bound to every file or directory, and are stored in kernel memory, which allows fast lookup of all permissions. * NSA Enhanced Linux (in package selinux). Backports of the SElinux-enabled packages are available at https://salsa.debian.org/selinux-team. More information available at SElinux in Debian Wiki page, at Manoj Srivastava's and Russell Cookers's SElinux websites. * The kernel patch http://people.redhat.com/mingo/exec-shield provided in the kernel-patch-exec-shield package. This patch provides protection against some buffer overflows (stack smashing attacks). * The Grsecurity patch, provided by the kernel-patch-2.4-grsecurity and kernel-patch-grsecurity2 packages [28] implements Mandatory Access Control through RBAC, provides buffer overflow protection through PaX, ACLs, network randomness (to make OS fingerprinting more difficult) and many more features. * The kernel-patch-adamantix provides the patches developed for Adamantix, a Debian-based distribution. This kernel patch for the 2.4.x kernel releases introduces some security features such as a non-executable stack through the use of http://pageexec.virtualave.net/ and mandatory access control based on http://www.rsbac.org/. Other features include: http://www.vanheusden.com/Linux/sp/, AES encrypted loop device, MPPE support and an IPSEC v2.6 backport. * cryptoloop-source. This patches allows you to use the functions of the kernel crypto API to create encrypted filesystems using the loopback device. * IPSEC kernel support (in package linux-patch-openswan). If you want to use the IPsec protocol with Linux, you need this patch. You can create VPNs with this quite easily, even to Windows machines, as IPsec is a common standard. IPsec capabilities have been added to the 2.5 development kernel, so this feature will be present by default in the future Linux Kernel 2.6. Homepage: http://www.openswan.org. FIXME: The latest 2.4 kernels provided in Debian include a backport of the IPSEC code from 2.5. Comment on this. The following security kernel patches are only available for old kernel versions in woody and are deprecated: * http://acl.bestbits.at/ (ACLs) for Linux provided in the package kernel-patch-acl. This kernel patch adds access control lists, an advanced method for restricting access to files. It allows you to control fine-grain access to files and directory. * The http://www.openwall.com/linux/ linux kernel patch by Solar Designer, provided in the kernel-patch-2.2.18-openwall package. This is a useful set of kernel restrictions, like restricted links, FIFOs in /tmp, a restricted /proc file system, special file descriptor handling, non-executable user stack area and other features. Note: This package applies to the 2.2 release, no packages are available for the 2.4 release patches provided by Solar. * kernel-patch-int. This patch also adds cryptographic capabilities to the Linux kernel, and was useful with Debian releases up to Potato. It doesn't work with Woody, and if you are using Sarge or a newer version, you should use a more recent kernel which includes these features already. However, some patches have not been provided in Debian yet. If you feel that some of these should be included please ask for it at the http://www.debian.org/devel/wnpp/. 4.15. Protección contra desbordamiento de búfer ----------------------------------------------- Buffer overflow is the name of a common attack to software [29] which makes use of insufficient boundary checking (a programming error, most commonly in the C language) in order to execute machine code through program inputs. These attacks, against server software which listen to connections remotely and against local software which grant higher privileges to users (setuid or setgid) can result in the compromise of any given system. There are mainly four methods to protect against buffer overflows: * patch the kernel to prevent stack execution. You can use either: Exec-shield, OpenWall or PaX (included in the Grsecurity and Adamantix patches). * fix the source code by using tools to find fragments of it that might introduce this vulnerability. * recompile the source code to introduce proper checks that prevent overflows, using the http://www.research.ibm.com/trl/projects/security/ssp/ patch for GCC (which is used by http://www.adamantix.org) Debian GNU/Linux, as of the 3.0 release, provides software to introduce all of these methods except for the protection on source code compilation (but this has been requested in http://bugs.debian.org/213994). Notice that even if Debian provided a compiler which featured stack/buffer overflow protection all packages would need to be recompiled in order to introduce this feature. This is, in fact, what the Adamantix distribution does (among other features). The effect of this new feature on the stability of software is yet to be determined (some programs or some processor architectures might break due to it). In any case, be aware that even these workarounds might not prevent buffer overflows since there are ways to circumvent these, as described in phrack's magazine http://packetstorm.linuxsecurity.com/mag/phrack/phrack58.tar.gz or in CORE's Advisory http://online.securityfocus.com/archive/1/269246. If you want to test out your buffer overflow protection once you have implemented it (regardless of the method) you might want to install the paxtest and run the tests it provides. 4.15.1. Parches contra el desbordamiento de búfer para el núcleo Kernel patches related to buffer overflows include the Openwall patch provides protection against buffer overflows in 2.2 linux kernels. For 2.4 or newer kernels, you need to use the Exec-shield implementation, or the PaX implementation (provided in the grsecurity patch, kernel-patch-2.4-grsecurity, and in the Adamantix patch, kernel-patch-adamantix). For more information on using these patches read the the section Sección 4.14, “Añadiendo parches al kernel”. 4.15.2. Testing programs for overflows The use of tools to detect buffer overflows requires, in any case, of programming experience in order to fix (and recompile) the code. Debian provides, for example: bfbtester (a buffer overflow tester that brute-forces binaries through command line and environment overflows). Other packages of interest would also be rats, pscan, flawfinder and splint. 4.16. Transferencia segura de archivos -------------------------------------- During normal system administration one usually needs to transfer files in and out from the installed system. Copying files in a secure manner from a host to another can be achieved by using the ssh server package. Another possibility is the use of ftpd-ssl, a ftp server which uses the Secure Socket Layer to encrypt the transmissions. Any of these methods need special clients. Debian does provide client software, such as scp from the ssh package, which works like rcp but is encrypted completely, so the bad guys cannot even find out WHAT you copy. There is also a ftp-ssl package for the equivalent server. You can find clients for these software even for other operating systems (non-UNIX), putty and winscp provide secure copy implementations for any version of Microsoft's operating system. Note that using scp provides access to the users to all the file system unless chroot'ed as described in Sección 5.1.1, “Chrooting ssh”. FTP access can be chroot'ed, probably easier depending on you chosen daemon, as described in Sección 5.3, “Asegurando FTP”. If you are worried about users browsing your local files and want to have encrypted communication you can either use an ftp daemon with SSL support or combine clear-text ftp and a VPN setup (see Sección 8.5, “Redes virtuales privadas”). 4.17. Límites y control de los sistemas de archivos --------------------------------------------------- 4.17.1. Uso de Quotas Tener una buena política de quotas es importante, esto abstiene a los usuarios de llenar el disco duro. Usted puede usar dos sistemas diferentes de quotas: quota de usuario y quota de grupo. Como usted provablemente dedujo, la quota del usuario límita la cantidad de espacio del que un usuario puede disponer, la quota del grupo hace lo equivalente para los grupos. Tenga en cuenta ésto cuando esté organizando el tamaño de quotas. Hay algunos puntos importantes para considerar acerca de la configuración del sistema de quotas: * Mantener las quotas suficientemente pequeñas, para que los usuarios no ocupen el espacio de su disco. * Mantener las quotas lo suficientemente grandes, para que los usuarios no se quejen o su quota de correo les impida aceptar un correo por un periodo de tiempo largo. * Use las quotas para todas las áreas en las que los usuarios puedan escribir, en /home como también en /tmp. Every partition or directory to which users have full write access should be quota enabled. Calculate and assign a workable quota size for those partitions and directories which combines usability and security. Ahora que usted quiere usar quotas. Primero que todo usted necesita revisar que habilito el uso de quotas en el kernel. Si no, usted necesitará recompilarla. Después de ésto dése cuenta que el paquete 'quota' esté instalado. Si no está usted necesitará este. Habilitar la quota para los respectivos sistemas de archivos es tan fácil como modificar la configuración inicial ajustándola a defaults,usrquota en su archivo /etc/fstab . Si usted necesita un quota para grupos, sustituya usrquota por grpquota. Puede usar ambos. Luego cree unos archivos quota.user y quota.group vacios en la raíz de los sistemas de archivos en los que usted quiera usar quotas (Ej. con touch /home/quota.user /home/quota.group para el sistema de archivos /home). touch /home/quota.user /home/quota.group for a /home file system). Restart quota by doing /etc/init.d/quota stop;/etc/init.d/quota start . Now quota should be running, and quota sizes can be set. Editing quotas for a specific user can be done by edquota -u . Group quotas can be modified with edquota -g . Then set the soft and hard quota and/or inode quotas as needed. Para más información acerca de las quotas, lea el manual de páginas sobre las quotas, y el mini-howto (/usr/share/doc/HOWTO/en-html/mini/Quota.html). 4.17.2. The ext2 filesystem specific attributes (chattr/lsattr) In addition to the usual Unix permissions, the ext2 and ext3 filesystems offer a set of specific attributes that give you more control over the files on your system. Unlike the basic permissions, these attributes are not displayed by the usual ls -l command or changed using chmod, and you need two other utilities, lsattr and chattr (in package e2fsprogs) to manage them. Note that this means that these attributes will usually not be saved when you backup your system, so if you change any of them, it may be worth saving the successive chattr commands in a script so that you can set them again later if you have to restore a backup. Among all available attributes, the two that are most important for increasing security are referenced by the letters 'i' and 'a', and they can only be set (or removed) by the superuser: * The 'i' attribute ('immutable'): a file with this attribute can neither be modified nor deleted or renamed and no link can be created to it, even by the superuser. * The 'a' attribute ('append'): this attribute has the same effect that the immutable attribute, except that you can still open the file in append mode. This means that you can still add more content to it but it is impossible to modify previous content. This attribute is especially useful for the log files stored in /var/log/, though you should consider that they get moved sometimes due to the log rotation scripts. These attributes can also be set for directories, in which case everyone is denied the right to modify the contents of a directory list (e.g. rename or remove a file, ...). When applied to a directory, the append attribute only allows file creation. It is easy to see how the 'a' attribute improves security, by giving to programs that are not running as the superuser the ability to add data to a file without modifying its previous content. On the other hand, the 'i' attribute seems less interesting: after all, the superuser can already use the basic Unix permissions to restrict access to a file, and an intruder that would get access to the superuser account could always use the chattr program to remove the attribute. Such an intruder may first be confused when noticing not being able to remove a file, but you should not assume blindness - after all, the intruder got into your system! Some manuals (including a previous version of this document) suggest to simply remove the chattr and lsattr programs from the system to increase security, but this kind of strategy, also known as "security by obscurity", is to be absolutely avoided, since it provides a false sense of security. A secure way to solve this problem is to use the capabilities of the Linux kernel, as described in Sección 10.4.2.1, “Defensa proactiva.”. The capability of interest here is called CAP_LINUX_IMMUTABLE: if you remove it from the capabilities bounding set (using for example the command lcap CAP_LINUX_IMMUTABLE) it won't be possible to change any 'a' or 'i' attribute on your system anymore, even by the superuser ! A complete strategy could be as follows: * Set the attributes 'a' and 'i' on any file you want; * Add the command lcap CAP_LINUX_IMMUTABLE (as well as lcap CAP_SYS_MODULE, as suggested in Sección 10.4.2.1, “Defensa proactiva.”) to one of the startup scripts; * Set the 'i' attribute on this script and other startup files, as well as on the lcap binary itself; * Execute the above command manually (or reboot your system to make sure everything works as planned). Now that the capability has been removed from the system, an intruder cannot change any attribute on the protected files, and thus cannot change or remove the files. If the machine is forced to reboot (which is the only way to restore the capabilities bounding set), it will easily be detected, and the capability will be removed again as soon as the system restarts anyway. The only way to change a protected file would be to boot the system in single-user mode or using another bootdisk, two operations that require physical access to the machine ! 4.17.3. Integridad de su sistema de archivos ¿Está usted seguro de que el /bin/login en su disco duro es todavía el binario que instaló allí hace unos meses? ¿Qué pasaría si es una versión hackeada, que guarda la contraseña introducida en un archivo oculto o la envía por un correo claro pro todoel internet? El único método para tener alguna protección es comprobar sus archivos cada día/hora/mes (yo prefiero cada día) comparando la vieja md5sum y la actual. Dos archivos no pueden tener la misma md5sum, de modo que anda sobre seguro aquí, excepto alquien que hackeó el algoroitmo para crear md5sums un la máquina. Esto es bueno, extremadamente difícil y muy improbable. Realmente usted debería considerar que auditar sus binarios es muy importante, ya que es un modo fácil para reconocer los cambios en sus binarios. Las herramientas que comúnmente se uaan para ésto son sXid, AIDE (Ambientación Avanzada de Detección de Intrusos), TripWire (no es libre; la nueva versió será GPL), integrit y samhain. Common tools used for this are sxid, aide (Advanced Intrusion Detection Environment), tripwire, integrit and samhain. Installing debsums will also help you to check the file system integrity, by comparing the md5sums of every file against the md5sums used in the Debian package archive. But beware: those files can easily be changed by an attacker and not all packages provide md5sums listings for the binaries they provided. For more information please read Sección 10.2, “Do periodic integrity checks” and Sección 4.19, “Taking a snapshot of the system”. You might want to use locate to index the whole filesystem, if so, consider the implications of that. The Debian findutils package contains locate which runs as user nobody, and so it only indexes files which are visible to everybody. However, if you change it's behaviour you will make all file locations visible to all users. If you want to index all the filesystem (not the bits that the user nobody can see) you can replace locate with the package slocate. slocate is labeled as a security enhanced version of GNU locate, but it actually provides additional file-locating functionality. When using slocate, the user only sees the actually accessible files and you can exclude any files or directories on the system. The slocate package runs its update process with higher privledges than locate, and indexes every file. Users are then able to quickly search for every file which they are able to see. slocate doesn't let them see new files; it filters the output based on your UID. You might want to use bsign or elfsign. elfsign provides an utility to add a digital signature to an ELF binary and a second utility to verify that signature. The current implementation uses PKI to sign the checksum of the binary. The benefits of doing this are that it enables one to determine if a binary has been modified and who created it. bsign uses GPG, elfsign uses PKI (X.509) certificates (OpenSSL). 4.17.4. Configuración de revisión de setuid The Debian checksecurity package provides a cron job that runs daily in /etc/cron.daily/checksecurity[30]. This cron job will run the /usr/sbin/checksecurity script that will store information of this changes. El comportamiento por defecto no manda la información al superusuario, pero en cambio guarda diariamente copias de los cambios dentro de /var/log/setuid.changes. Usted debe colocar el CHECKSECURITY_EMAIL (dentro de /etc/checksecurity.conf) a 'root'. Mire checksecurity(8) para mas información de configuración. 4.18. Conectividad de red segura -------------------------------- FIXME: More (Debian-specific) content needed. 4.18.1. Características de la red configurando kernel Many features of the kernel can be modified while running by echoing something into the /proc file system or by using sysctl. By entering /sbin/sysctl -A you can see what you can configure and what the options are, and it can be modified running /sbin/sysctl -w variable=value (see sysctl(8)). Only in rare cases do you need to edit something here, but you can increase security that way as well. For example: net/ipv4/icmp_echo_ignore_broadcasts = 1 This is a Windows emulator because it acts like Windows on broadcast ping if this option is set to 1. That is, ICMP echo requests sent to the broadcast address will be ignored. Otherwise, it does nothing. If you want to prevent you system from answering ICMP echo requests, just enable this configuration option: net/ipv4/icmp_echo_ignore_all = 0 Los paquetes con direcciones imposibles (debido a las rutas incorectas) sobre el registro que obtuvo su red. /proc/sys/net/ipv4/conf/all/log_martians = 1 For more information on what things can be done with /proc/sys/net/ipv4/* read /usr/src/linux/Documentation/filesystems/proc.txt. All the options are described thoroughly under /usr/src/linux/Documentation/networking/ip-sysctl.txt[31]. 4.18.2. Configuring syncookies This option is a double-edged sword. On the one hand it protects your system against syn packet flooding; on the other hand it violates defined standards (RFCs). net/ipv4/tcp_syncookies = 1 If you want to change this option each time the kernel is working you need to change it in /etc/network/options by setting syncookies=yes. This will take effect when ever /etc/init.d/networking is run (which is typically done at boot time) while the following will have a one-time effect until the reboot: echo 1 > /proc/sys/net/ipv4/tcp_syncookies This option will only be available if the kernel is compiled with the CONFIG_SYNCOOKIES. All Debian kernels are compiled with this option builtin but you can verify it running: $ sysctl -A |grep syncookies net/ipv4/tcp_syncookies = 1 For more information on TCP syncookies read http://cr.yp.to/syncookies.html. 4.18.3. Securing the network on boot-time When setting configuration options for the kernel networking you need configure it so that it's loaded every time the system is restarted. The following example enables many of the previous options as well as other useful options. There are actually two ways to configure your network at boot time. You can configure /etc/sysctl.conf (see: sysctl.conf(5)) or introduce a script that is called when the interface is enabled. The first option will be applied to all interfaces, whileas the second option allows you to configure this on a per-interface basis. An example of a /etc/sysctl.conf configuration that will secure some network options at the kernel level is shown below. Notice the comment in it, /etc/network/options might override some values if they contradict those in this file when the /etc/init.d/networking is run (which is later than procps on the startup sequence). # # /etc/sysctl.conf - Configuration file for setting system variables # See sysctl.conf (5) for information. Also see the files under # Documentation/sysctl/, Documentation/filesystems/proc.txt, and # Documentation/networking/ip-sysctl.txt in the kernel sources # (/usr/src/kernel-$version if you have a kernel-package installed) # for more information of the values that can be defined here. # # Be warned that /etc/init.d/procps is executed to set the following # variables. However, after that, /etc/init.d/networking sets some # network options with builtin values. These values may be overridden # using /etc/network/options. # #kernel.domainname = example.com # Additional settings - adapted from the script contributed # by Dariusz Puchala (see below) # Ignore ICMP broadcasts net/ipv4/icmp_echo_ignore_broadcasts = 1 # # Ignore bogus ICMP errors net/ipv4/icmp_ignore_bogus_error_responses = 1 # # Do not accept ICMP redirects (prevent MITM attacks) net/ipv4/conf/all/accept_redirects = 0 # _or_ # Accept ICMP redirects only for gateways listed in our default # gateway list (enabled by default) # net/ipv4/conf/all/secure_redirects = 1 # # Do not send ICMP redirects (we are not a router) net/ipv4/conf/all/send_redirects = 0 # # Do not forward IP packets (we are not a router) # Note: Make sure that /etc/network/options has 'ip_forward=no' net/ipv4/conf/all/forwarding = 0 # # Enable TCP Syn Cookies # Note: Make sure that /etc/network/options has 'syncookies=yes' net/ipv4/tcp_syncookies = 1 # # Log Martian Packets net/ipv4/conf/all/log_martians = 1 # # Turn on Source Address Verification in all interfaces to # prevent some spoofing attacks # Note: Make sure that /etc/network/options has 'spoofprotect=yes' net/ipv4/conf/all/rp_filter = 1 # # Do not accept IP source route packets (we are not a router) net/ipv4/conf/all/accept_source_route = 0 To use the script you need to first create the script, for example, in /etc/network/interface-secure (the name is given as an example) and call it from /etc/network/interfaces like this: auto eth0 iface eth0 inet static address xxx.xxx.xxx.xxx netmask 255.255.255.xxx broadcast xxx.xxx.xxx.xxx gateway xxx.xxx.xxx.xxx pre-up /etc/network/interface-secure In this example, before the interface eth0 is enabled the script will be called to secure all network interfaces as shown below. #!/bin/sh -e # Script-name: /etc/network/interface-secure # # Modifies some default behavior in order to secure against # some TCP/IP spoofing & attacks for all interfaces. # # Contributed by Dariusz Puchalak. # echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts # Broadcast echo protection enabled. echo 0 > /proc/sys/net/ipv4/conf/all/forwarding # IP forwarding disabled. echo 1 > /proc/sys/net/ipv4/tcp_syncookies # TCP syn cookies protection enabled. echo 1 >/proc/sys/net/ipv4/conf/all/log_martians # Log strange packets. # (this includes spoofed packets, source routed packets, redirect packets) # but be careful with this on heavy loaded web servers. echo 1 > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses # Bad error message protection enabled. # IP spoofing protection. echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter # Disable ICMP redirect acceptance. echo 0 > /proc/sys/net/ipv4/conf/all/accept_redirects echo 0 > /proc/sys/net/ipv4/conf/all/send_redirects # Disable source routed packets. echo 0 > /proc/sys/net/ipv4/conf/all/accept_source_route exit 0 Notice that you can actually have per-interface scripts that will enable different network options for different interfaces (if you have more than one), just change the pre-up line to: pre-up /etc/network/interface-secure $IFACE And use a script which will only apply changes to a specific interface, not to all of the interfaces available. Notice that some networking options can only be enabled globally, however. A sample script is this one: #!/bin/sh -e # Script-name: /etc/network/interface-secure # # Modifies some default behavior in order to secure against # some TCP/IP spoofing & attacks for a given interface. # # Contributed by Dariusz Puchalak. # IFACE=$1 if [ -z "$IFACE" ] ; then echo "$0: Must give an interface name as argument!" echo "Usage: $0 " exit 1 fi if [ ! -e /proc/sys/net/ipv4/conf/$IFACE/ ]; then echo "$0: Interface $IFACE does not exit (cannot find /proc/sys/net/ipv4/conf/)" exit 1 fi echo 0 > /proc/sys/net/ipv4/conf/$IFACE/forwarding # IP forwarding disabled. echo 1 >/proc/sys/net/ipv4/conf/$IFACE/log_martians # Log strange packets. # (this includes spoofed packets, source routed packets, redirect packets) # but be careful with this on heavy loaded web servers. # Protección contra falsificación de IP (IP spoofing). echo 1 > /proc/sys/net/ipv4/conf/$IFACE/rp_filter # Disable ICMP redirect acceptance. echo 0 > /proc/sys/net/ipv4/conf/$IFACE/accept_redirects echo 0 > /proc/sys/net/ipv4/conf/$IFACE/send_redirects # Desativa el ruteo en origen (source routing). echo 0 > /proc/sys/net/ipv4/conf/$IFACE/accept_source_route exit 0 An alternative solution is to create an init.d script and have it run on bootup (using update-rc.d to create the appropriate rc.d links). 4.18.4. Configuarción de las características de los cortafuegos Para tener la capacidad del cortafuego, para proteger el sistema local u otros detrás de este, el kernel necesita estar compidalo con las capacidades del cortefuego. El Debian normal 2.2 kernel (también 2.2) susmistra el paquete de filtro del cortafuego ipchains, el kernel normal de Debian 3.0 (kernel 2.4) suministra el poderoso paquete de filtros de cortafuegos iptables (filtro de la red). Las distribucines más viejas de Debian necesitan el parche apropiado del kernel (Debian 2.1 usa el kernel 2.0.34). En todo caso, es bastante fácil usar un kernel diferente al suministrado por Debian. Usted puede encontrar paquetes de kernel pre-compilados que puede instalar fácilmente en el sistemas de Debian. Usted tambiém puede obtener las fuentes del kernel usando kernel-source-X y armar paquetes de kernel personalizados con make-kpkg. Configurando los cortafuegos en Debian se discute más a fondo en Sección 5.14, “Añadir capacidades al cortafuegos”. 4.18.5. Disabling weak-end hosts issues Systems with more than one interface on different networks can have services configured so that they will bind only to a given IP address. This usually prevents access to services when requested through any other address. However, this does not mean (although it is a common misconception) that the service is bound to a given hardware address (interface card). [32] It seems, however, not to work with services bound to 127.0.0.1, you might need to write the tests using raw sockets. This is not an ARP issue and it's not an RFC violation (it's called weak end host in RFC1122, (in the section 3.3.4.2). Remember, IP addresses have nothing to do with physical interfaces. On 2.2 (and previous) kernels this can be fixed with: # echo 1 > /proc/sys/net/ipv4/conf/all/hidden # echo 1 > /proc/sys/net/ipv4/conf/eth0/hidden # echo 1 > /proc/sys/net/ipv4/conf/eth1/hidden ..... On later kernels this can be fixed either with: * Reglas Iptables * properly configured routing. [33] * kernel patching. [34] Along this text there will be many occasions in which it is shown how to configure some services (sshd server, apache, printer service...) in order to have them listening on any given address, the reader should take into account that, without the fixes given here, the fix would not prevent accesses from within the same (local) network. [35] FIXME: Comments on Bugtraq indicate there is a Linux specific method to bind to a given interface. FIXME: Submit a bug against netbase so that the routing fix is standard behavior in Debian? 4.18.6. Protección contra ataques ARP When you don't trust the other boxes on your LAN (which should always be the case, because it's the safest attitude) you should protect yourself from the various existing ARP attacks. As you know the ARP protocol is used to link IP addresses to MAC addresses (see ftp://ftp.isi.edu/in-notes/rfc826.txt for all the details). Every time you send a packet to an IP address an ARP resolution is done (first by looking into the local ARP cache then if the IP isn't present in the cache by broadcasting an ARP query) to find the target's hardware address. All the ARP attacks aim to fool your box into thinking that box B's IP address is associated to the intruder's box's MAC address; Then every packet that you want to send to the IP associated to box B will be send to the intruder's box... Those attacks (ARP cache poisoning, ARP spoofing...) allow the attacker to sniff the traffic even on switched networks, to easily hijack connections, to disconnect any host from the network... ARP attacks are powerful and simple to implement, and several tools exists, such as arpspoof from the dsniff package or http://arpoison.sourceforge.net/. However, there is always a solution: * Use a static ARP cache. You can set up "static" entries in your ARP cache with: arp -s host_name hdwr_addr By setting static entries for each important host in your network you ensure that nobody will create/modify a (fake) entry for these hosts (static entries don't expire and can't be modified) and spoofed ARP replies will be ignored. * Detect suspicious ARP traffic. You can use arpwatch, karpski or more general IDS that can also detect suspicious ARP traffic (snort, http://www.prelude-ids.org...). * Implement IP traffic filtering validating the MAC address. 4.19. Taking a snapshot of the system ------------------------------------- Before putting the system into production system you could take a snapshot of the whole system. This snapshot could be used in the event of a compromise (see Capítulo 11, After the compromise (incident response)). You should remake this upgrade whenever the system is upgraded, especially if you upgrade to a new Debian release. For this you can use a writable removable-media that can be set up read-only, this could be a floppy disk (read protected after use), a CD on a CD-ROM unit (you could use a rewritable CD-ROM so you could even keep backups of md5sums in different dates), or a USB disk or MMC card (if your system can access those and they can be write protected). The following script creates such a snapshot: #!/bin/bash /bin/mount /dev/fd0 /mnt/floppy trap "/bin/umount /dev/fd0" 0 1 2 3 9 13 15 if [ ! -f /usr/bin/md5sum ] ; then echo "Cannot find md5sum. Aborting." exit 1 fi /bin/cp /usr/bin/md5sum /mnt/floppy echo "Calculating md5 database" >/mnt/floppy/md5checksums.txt for dir in /bin/ /sbin/ /usr/bin/ /usr/sbin/ /lib/ /usr/lib/ do find $dir -type f | xargs /usr/bin/md5sum >>/mnt/floppy/md5checksums-lib.txt done echo "post installation md5 database calculated" if [ ! -f /usr/bin/sha1sum ] ; then echo "Cannot find sha1sum" echo "WARNING: Only md5 database will be stored" else /bin/cp /usr/bin/sha1sum /mnt/floppy echo "Calculating SHA-1 database" >/mnt/floppy/sha1checksums.txt for dir in /bin/ /sbin/ /usr/bin/ /usr/sbin/ /lib/ /usr/lib/ do find $dir -type f | xargs /usr/bin/sha1sum >>/mnt/floppy/sha1checksums-lib.txt done echo "post installation sha1 database calculated" fi exit 0 Note that the md5sum binary (and sha1sum, if available) is placed on the floppy drive so it can be used later on to check the binaries of the system (just in case it gets trojaned). However, if you want to make sure that you are running a legitimate binary, you might want to either compile a static copy of the md5sum binary and use that one (to prevent a trojaned libc library from interfering with the binary) or to use the snapshot of md5sums only from a clean environment such as a rescue CD-ROM or a Live-CD (to prevent a trojaned kernel from interfering). I cannot stress this enough: if you are on a compromised system you cannot trust its output, see Capítulo 11, After the compromise (incident response). The snapshot does not include the files under /var/lib/dpkg/info which includes the MD5 hashes of installed packages (in files ending with .md5sums). You could copy this information along too, however you should notice: * the md5sums files include the md5sum of all files provided by the Debian packages, not just system binaries. As a consequence, that database is bigger (5 Mb versus 600 Kb in a Debian GNU/Linux system with a graphical system and around 2.5 Gb of software installed) and will not fit in small removable media (like a single floppy disk, but would probably fit in a removable USB memory). * not all Debian packages provide md5sums for the files installed since it is not (currently) mandated policy. Notice, however, that you can generate the md5sums for all packages using debsums after you've finished the system installation: # debsums --generate=missing,keep Once the snapshot is done you should make sure to set the medium read-only. You can then store it for backup or place it in the drive and use it to drive a cron check nightly comparing the original md5sums against those on the snapshot. If you do not want to setup a manual check you can always use any of the integrity systems available that will do this and more, for more information please read Sección 10.2, “Do periodic integrity checks”. 4.20. Otras recomendaciones --------------------------- 4.20.1. No use software que dependa de svgalib SVGAlib es muy bueno para los amantes de la consola como yo, pero durante mucho tiempo se ha comprobado que esto ha sido muy inseguro. Han sido liberadas fallas en contra de zgv y era sencillo convertirse en root. Intente evitar el uso de programas que usen SVGAlib siempre que sea posible. ------------------------------------------------------------------------ [9] In Etch and later releases [10] Even though the libraries have been removed from the filesystem the inodes will not be cleared up until no program has an open file descriptor pointing to them. [11] This happened, for example, in the upgrade from libc6 2.2.x to 2.3.x due to NSS authentication issues, see http://lists.debian.org/debian-glibc/2003/03/msg00276.html. [12] Unless you have installed a kernel metapackage like linux-image-2.6-686 which will always pull in the latest kernel minor revision for a kernel release and a given architecture. [13] A sample script called testnet is available in the Remotely rebooting Debian GNU/Linux machines article. A more elaborate network connectivity testing script is available in this Testing network connectivity article. [14] Setting up a serial console is beyond the scope of this document, for more information read the Serial HOWTO and the Remote Serial Console HOWTO. [15] Some of this includes the package manager dpkg since the installation (post,pre) and removal (post,pre) scripts are at /var/lib/dpkg/ and Smartlist [16] In old Debian releases the configuration of the modules was defined directly in /etc/pam.d/passwd. [17] The minlen option is not entirely straightforward and is not exactly the number of characters in the password. A tradeoff can be defined between complexity and length by adjusting the "credit" parameters of different character classes. For more information read the pam_cracklib(8) manpage. [18] The default content of this file provides information about the operating system and version run by the system, which you might not want to provide to anonymous users. [19] libpam-chroot has not been yet thoroughly tested, it does work for login but it might not be easy to set up the environment for other programs [20] Setting HISTSIZE to a very large number can cause issues under some shells since the history is kept in memory for every user session. You might be safer if you set this to a high-enough value and backup user's history files (if you need all of the user's history for some reason) [21] Without the append-only flag users would be able to empty the contents of the history file running > .bash_history [22] Ttys are spawned for local logins and remote logins through ssh and telnet [23] As defined in /etc/adduser.conf (USERGROUPS=yes). You can change this behaviour if you set this value to no, although it is not recommended [24] Chpasswd cannot handle MD5 password generation so it needs to be given the password in encrypted form before using it, with the -e option. [25] On older Debian releases you might need to do this: $ apt-cache showpkg libwrap0 | egrep '^[[:space:]]' | sort -u | \ sed 's/,libwrap0$//;s/^[[:space:]]\+//' [26] beware of the case here since spawn will not work [27] there's a very good article on it written by http://www.spitzner.net/swatch.html [28] Notice that this patch conflicts with patches already included in Debian's 2.4 kernel source package. You will need to use the stock vanilla kernel. You can do this with the following steps: # apt-get install kernel-source-2.4.22 kernel-patch-debian-2.4.22 # tar xjf /usr/src/kernel-source-2.4.22.tar.bz2 # cd kernel-source-2.4.22 # /usr/src/kernel-patches/all/2.4.22/unpatch/debian For more information see http://bugs.debian.org/194225, http://bugs.debian.org/199519, http://bugs.debian.org/206458, http://bugs.debian.org/203759, http://bugs.debian.org/204424, http://bugs.debian.org/210762, http://bugs.debian.org/211213, and the http://lists.debian.org/debian-devel/2003/09/msg01133.html [29] So common, in fact, that they have been the basis of 20% of the reported security vulnerabilities every year, as determined by http://icat.nist.gov/icat.cfm?function=statistics [30] In previous releases, checksecurity was integrated into cron and the file was /etc/cron.daily/standard [31] In Debian the kernel-source-version packages copy the sources to /usr/src/kernel-source-version.tar.bz2, just substitute version to whatever kernel version sources you have installed [32] To reproduce this (example provided by Felix von Leitner on the Bugtraq mailing list): host a (eth0 connected to eth0 of host b): ifconfig eth0 10.0.0.1 ifconfig eth1 23.0.0.1 tcpserver -RHl localhost 23.0.0.1 8000 echo fnord host b: ifconfig eth0 10.0.0.2 route add 23.0.0.1 gw 10.0.0.1 telnet 23.0.0.1 8000 [33] The fact that this behavior can be changed through routing was described by Matthew G. Marsh in the Bugtraq thread: eth0 = 1.1.1.1/24 eth1 = 2.2.2.2/24 ip rule add from 1.1.1.1/32 dev lo table 1 prio 15000 ip rule add from 2.2.2.2/32 dev lo table 2 prio 16000 ip route add default dev eth0 table 1 ip route add default dev eth1 table 2 [34] There are some patches available for this behavior as described in Bugtraq's thread at http://www.linuxvirtualserver.org/~julian/#hidden and http://www.fefe.de/linux-eth-forwarding.diff. [35] An attacker might have many problems pulling the access through after configuring the IP-address binding while not being on the same broadcast domain (same network) as the attacked host. If the attack goes through a router it might be quite difficult for the answers to return somewhere. Capítulo 5. Asegurando los servicios que se ejecutan en su sistema ================================================================== Los servicios que corren en su sistema pueden ser asegurados de dos maneras: * Haciéndolos accequibles dentro de los puntos (interfaces) en los que tienen que estar. * Configurándolos de una manera apropiada para que puedan ser debidamente usados por los usuarios legítimos de una manera autorizada. Restringir los servicios de modo que solamente puedan ser accedidos desde un lugar dado puede ser hecho restringiendo el acceso al nivel del kernel (i.e. cortafuego), configúrelos sólo para escuchar en un interfaz dada (algunos servicios no pueden suministrar ésta característica) o usando otros métodos, por ejemplo el parche linux vserver (para 2.4.16) puede ser usado para forzar procesos de forma que usen solo una interfaz. Regarding the services running from inetd (telnet, ftp, finger, pop3...) it is worth noting that inetd can be configured so that services only listen on a given interface (using service@ip syntax) but that's an undocumented feature. One of its substitutes, the xinetd meta-daemon includes a bind option just for this matter. See ixnetd.conf(5) manual page. service nntp { socket_type = stream protocol = tcp wait = no user = news group = news server = /usr/bin/env server_args = POSTING_OK=1 PATH=/usr/sbin/:/usr/bin:/sbin/:/bin +/usr/sbin/snntpd logger -p news.info bind = 127.0.0.1 } Laa siguientes secciones detallan como cada servicio determinado puede ser configurado debidamente dependiendo de los usos que se quieran dar. 5.1. Asegurando ssh ------------------- Si aún está usando telnet en vez de ssh, debe detener la lectura de este manual y cambiar esto. Ssh debería ser usado para todas las entradas remotas en vez de telnet. En una época donde es fácil husmear el tráfico de internet y obtener contraseñas en texto plano, debe usar sólo protocólos que usen criptografía. De una vez, ejecute un apt-get install ssh en su sistema. Anime a todos los usuarios de su sistema para usar ssh en vez de telnet, o mejor aún, desinstale telnet/telnetd. Además, debe evitar las entradas al sistema usando ssh como root y use métodos alternativos en vez de root, como su o sudo. Finalmente, el archivo sshd_config, dentro de /etc/ssh, debe ser modificado para aumentar la seguridad así: * Haga que ssh escuche solo la interfaz dada, sólo en un caso de que haya más de uno (y no necesite un ssh disponible sobre éste) o que en un futuro agrege una nueva tarjeta de red (y no necesite una conexión desde ssh en ésta). * Intente no permitir al Root entrar tanto como sea posible. Si alguien quiere volverse root por vía ssh, dos logins serán necesarios y la contraseña root no puede ser obtenida a fuerza bruta por vía SSH. * Port 666 or ListenAddress 192.168.0.1:666 Change the listen port, so the intruder cannot be completely sure whether a sshd daemon runs (be forewarned, this is security by obscurity). * PermitEmptyPasswords no Empty passwords make a mockery of system security. * AllowUsers alex ref me@somewhere Allow only certain users to have access via ssh to this machine. user@host can also be used to restrict a given user from accessing only at a given host. * Permita que solamente los miembros de ciertos grupos tengan acceso vía a ssh a esta máquina. AllowGroups y AllowUsers tienen directivas equivalentes para denegar el acceso a una máquina. Predeciblemente se llaman "DenyUsers" y "DenyGroups". * Queda completamente a su elección lo que usted quiera hacer. Es más seguro permitir el acceso a la máquina solamente a usuarios con llaves ssh en el archivo ~/.ssh/authorized_keys. Si es lo que quiere déle el valor "no". * Disable any form of authentication you do not really need, if you do not use, for example RhostsRSAAuthentication, HostbasedAuthentication, KerberosAuthentication or RhostsAuthentication you should disable them, even if they are already by default (see the manpage sshd_config(5) manual page). * Protocol 2 Disable the protocol version 1, since it has some design flaws that make it easier to crack passwords. For more information read http://earthops.net/ssh-timing.pdf or the http://xforce.iss.net/static/6449.php. * Banner /etc/some_file Add a banner (it will be retrieved from the file) to users connecting to the ssh server. In some countries sending a warning before access to a given system about unauthorized access or user monitoring should be added to have legal protection. You can also restrict access to the ssh server using pam_listfile or pam_wheel in the PAM control file. For example, you could keep anyone not listed in /etc/loginusers away by adding this line to /etc/pam.d/ssh: auth required pam_listfile.so sense=allow onerr=fail item=user file=/etc/loginusers Como nota final, dese cuenta que estas directivas son de los archivos de la configuración de OpenSSH. Ahora mismo hay tres demonios SSH usadados habitualmente, ssh1, ssh2, y el OpenSSH de la gente de OpenBSD. Ssh1 fue el primer domonio ssh diaponible y aún es el más comunmente usado (hay rumores de que existe incluso un porte a windows). Ssh2 tiene muchas ventajas sobre ssh1, pero se distribuye con una licencia mixta de código abierto-cerrado. OpenSSH es un demonio completamente libre que soporta tanto ssh1 como ssh2. La versión instalada en Debian cuando se escoge el paquete 'ssh' es OpenSSH. You can read more information on how to set up SSH with PAM support in the http://lists.debian.org/debian-security/2001/11/msg00395.html. 5.1.1. Chrooting ssh Currently OpenSSH does not provide a way to chroot automatically users upon connection (the commercial version does provide this functionality). However there is a project to provide this functionality for OpenSSH too, see http://chrootssh.sourceforge.net, it is not currently packaged for Debian, though. You could use, however, the pam_chroot module as described in Sección 4.11.15, “Restringiendo usuarios”. In Sección B.7, “Chroot environment for SSH” you can find several options to make a chroot environment for SSH. 5.1.2. Ssh clients If you are using an SSH client against the SSH server you must make sure that it supports the same protocols that are enforced on the server. For example, if you use the mindterm package, it only supports protocol version 1. However, the sshd server is, by default, configured to only accept version 2 (for security reasons). 5.1.3. Disallowing file transfers If you do not want users to transfer files to and from the ssh server you need to restrict access to the sftp-serverand the scp access. You can restrict sftp-server by configuring the proper Subsystem in the /etc/ssh/sshd_config. You can also chroot users (using libpam-chroot so that, even if file transfer is allowed, they are limited to an environment which does not include any system files. 5.1.4. Restricing access to file transfer only You might want to restrict access to users so that they can only do file transfers and cannot have interactive shells. In order to do this you can either: * disallow users from login to the ssh server (as described above either through the configuration file or PAM configuration). * give users a restricted shell such as scponly or rssh. These shells restrict the commands available to the users so that they are not provided any remote execution priviledges. 5.2. Asegurando Squid --------------------- Squid is one of the most popular proxy/cache server, and there are some security issues that should be taken into account. Squid's default configuration file denies all users requests. However the Debian package allows access from 'localhost', you just need to configure your browser properly. You should configure Squid to allow access to trusted users, hosts or networks defining an Access Control List on /etc/squid/squid.conf, see the https://web.archive.org/web/20061206052115/http://www.deckle.co.za/squid-users-guide/Main_Page for more information about defining ACLs rules. Notice that Debian provides a minimum configuration for Squid that will prevent anything, except from localhost to connect to your proxy server (which will run in the default port 3128). You will need to customize your /etc/squid/squid.conf as needed. The recommended minimum configuration (provided with the package) is shown below: acl all src 0.0.0.0/0.0.0.0 acl manager proto cache_object acl localhost src 127.0.0.1/255.255.255.255 acl SSL_ports port 443 563 acl Safe_ports port 80 # http acl Safe_ports port 21 # ftp acl Safe_ports port 443 563 # https, snews acl Safe_ports port 70 # gopher acl Safe_ports port 210 # wais acl Safe_ports port 1025-65535 # unregistered ports acl Safe_ports port 280 # http-mgmt acl Safe_ports port 488 # gss-http acl Safe_ports port 591 # filemaker acl Safe_ports port 777 # multiling http acl Safe_ports port 901 # SWAT acl purge method PURGE acl CONNECT method CONNECT (...) # Only allow cachemgr access from localhost http_access allow manager localhost http_access deny manager # Only allow purge requests from localhost http_access allow purge localhost http_access deny purge # Deny requests to unknown ports http_access deny !Safe_ports # Deny CONNECT to other than SSL ports http_access deny CONNECT !SSL_ports # # INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS # http_access allow localhost # And finally deny all other access to this proxy http_access deny all #Default: # icp_access deny all # #Allow ICP queries from everyone icp_access allow all You should also configure Squid based on your system resources, including cache memory (option cache_mem), location of the cached files and the amount of space they will take up on disk (option cache_dir). Además, si no configuró debidamente, algúien puede enviar correo a través de Squid, puesto que el diseño de los protocolos HTTP y SMTP es semejante. El archivo de configuración Squid niega por defecto el acceso al puerto 25. Si desea permitir las conexiones del puerto 25 adiciónelo a la lista Safe_ports. Sin embargo, esto NO is recomendado. Ajustar y configurar debidamente el proxy/cache es solamente una parte para mantener su sitio seguro. Otra tarea necesaria es analizar los registros de Squid asegurándose que todas las cosas que están trabajando, deben hacerlo como se espera. Hay algunos paquetes en Debian GNU/Linux que pueden ayudar al administrador a hacer esto. Los siguientes paquetes estan disponibles en woody (Debian 3.0): * calamaris - Analizar de las bitácoras de los proxy Squid y Oops. * modlogan - Analizador modular de bitácoras. * sarg - Generador de Reportes de Análisis de Squid. * squidtaild - Squid log monitoring program. When using Squid in Accelerator Mode it acts as a web server too. Turning on this option increases code complexity, making it less reliable. By default Squid is not configured to act as a web server, so you don't need to worry about this. Note that if you want to use this feature be sure that it is really necessary. To find more information about Accelerator Mode on Squid see the https://web.archive.org/web/20070104164802/http://www.deckle.co.za/squid-users-guide/Accelerator_Mode 5.3. Asegurando FTP ------------------- Si realmente tiene que usar FTP (sin enmascararlo con sslwrap o dentro de un tunel ssl o ssh), debería hacer cambio del directorio raíz de FTP hacia el directorio de los usuarios ftp, de modo que que el usuario sea incapaz de mirar cualquier otra cosa que su propio derectorio. De otra manera ellos pueden atravesar su sistema de archivos tal como si tuvieran una línea de comandos. Usted puede añadir la siguiente línea en su proftpd.conf en la sección global para habilitar esta característica del cambio de directorio raíz: feature: DefaultRoot ~ Reinicie proftpd con /etc/init.d/proftpd restart y revise si puede escapar desde su directorio raíz ahora. Para impedir los ataques de Proftp DoS use ../../.., y adicione la siguiente línea en /etc/proftpd.conf: DenyFilter \*.*/ No olvide que FTP envía login y contraseñas de autenticación en el texto plano (esto no es un problema si usted está proporcionando un servicio público anónimo) y hay buenas alternativas en Debian para ésto. Por elemplo, sftp (sumistrado por ssh). También hay implementaciones libres de SSH para otros sistemas operativos, por ejemplo: http://www.chiark.greenend.org.uk/~sgtatham/putty/ y http://www.cygwin.com. Sin, embargo, si aún mantiene el servidor de FTP mientras los usuarios acceden a SSH podría encontrar un problema típico. Usuarios que acceden a los servidores Anónimos de FTP dentro de un sistema asegurado con SSH es el camino intentar entrar en el servidor FTP. Mientras el acceso se niegue, la contraseña nunca se enviará por la red en texto plano. Para evitar esto, el desarrollador de ProFTPd, TJ Saunders, creó un parche que impide a los usuarios anónimos del servidor FTP intentar contraseñas con cuentas SSH válidas. Más información y parches disponibles en: http://www.castaglia.org/proftpd/#Patches. 5.4. Asegurando el acceso al sistema X Window --------------------------------------------- Hoy en día, más y más empresas usan las terminales X cuando necesitan un servicio para muchas estaciones de trabajo, ésto puede ser peligroso porque necesita permitir que un servidor de archivos se conecte con los clientes (el servicio X, desde el punto de vista X. X intercambia la definición de cliente y servidor) Si sigue la (muy mala) sugerencia de muchos documentos, tecleé xhost + en su máquina. Esto permite conenctar con su sistema a cualquier cliente X. Para tener una seguridad ligeramente mejor, puede usar el comando xhost +hostname en vez de la anterior para permitir un acceso desde servidores específicos. A much more secure solution, though, is to use ssh to tunnel X and encrypt the whole session. This is done automatically when you ssh to another machine. For this to work, you have to configure both the ssh client and the ssh server. On the ssh client, ForwardX11 should be set to yes in /etc/ssh/ssh_config. On the ssh server, X11Forwarding should be set to yes in /etc/ssh/sshd_config and the package xbase-clients should be installed because the ssh server uses /usr/X11R6/bin/xauth (/usr/bin/xauth on Debian unstable) when setting up the pseudo X display. In times of SSH, you should drop the xhost based access control completely. Para mayor seguridad, si no necesita acceso a X desde otras máquinas, dehabilite el enlace con el puerto tcp 6000 tecleando simplemente: startx -- -nolisten tcp $ startx -- -nolisten tcp Este es el comportamiento original en XFree 4.0 (el servidor X suministrado en Debian 3.0). Si está usando XFree 3.3.6 (i.e. tiene un Debian 2.2 instalado) puede editar /etc/X11/xinit/xserverrcc para que tenga unas líneas como las siguientes: #!/bin/sh exec /usr/bin/X11/X -dpi 100 -nolisten tcp If you are using XDM set /etc/X11/xdm/Xservers to: :0 local /usr/bin/X11/X vt7 -dpi 100 -nolisten tcp. If you are using Gdm make sure that the DisallowTCP=true option is set in the /etc/gdm/gdm.conf (which is the default in Debian). This will basically append -nolisten tcp to every X command line [36]. You can also set the default's system timeout for xscreensaver locks. Even if the user can override it, you should edit the /etc/X11/app-defaults/XScreenSaver configuration file and change the lock line: *lock: False (which is the default in Debian) to: *lock: True FIXME: Add information on how to disable the screensavers which show the user desktop (which might have sensitive information). Lea mas sobre la seguridad X Window en http://www.linuxdoc.org/HOWTO/XWindow-User-HOWTO.html (/usr/share/doc/HOWTO/en-txt/XWindow-User-HOWTO.txt.gz). ARREGLAME: Add info on thread of debian-security on how to change config files of XFree 3.3.6 to do this. 5.4.1. Revisar su administrador visual Si usted solamente quiere tener un administrador visual instalado para el uso local (teniendo un bonito login grafico), asegurarse que el material seguro XDMCP (control de protocolo de administrador visual X) este inhabilitado. En XDM usted puede hacer esto con la siguiente linea. /etc/X11/xdm/xdm-config: DisplayManager.requestPort: 0 For GDM there should be in your gdm.conf: [xdmcp] Enable=false Normalmente, todos los administradores visuales estan configurados para no iniciar los servicios de XDMCP por defecto en Debian. 5.5. Seguridad en el acceso de impresión (El asunto de lpd y lprng) ------------------------------------------------------------------- Imagine, que usted llega al trabajo, y la impresora está botando interminables cantidades de papel porque alguien está negando el servicio de linea de su demonio de impresión. ¿No es terrible? En cualquier arquitectura de impresión Unix, tiene que haber la forma de enviar los datos de los clientes a los servidores de impresión. En el lpr ylp tradicional, el comando del cliente es copiado o se hace un enlace simbólico de los datos en el directorio de cola (por lo cual usualmente estos programas son SUID o SGID). Para evitar algunos asuntos usted debe mantener seguros, los servidores de impresión. Esto significa que usted necesita configurar su servicio de impresión para que solo se permita la conexión del conjunto de servidores confiables. Para hacer esto es necesario, añadir los servidores a los que se les va a permitir imprimir en /etc/hosts.lpd. Sin embargo, incluso si usted hace esto, el demonio lpr acepta las conexiones entrantes en el puerto 515 de cualquier interfaz. Deberia considerar hacer una regla de cortafuegos para las conexiones de red/servidor a las cuales no se permite la impresión (el demoniolpr no puede ser limitado a escuchar únicamente a una dirección IP dada). Lprng se prefiere en lugar de lpr porque este puede ser configurado para hacer el control de acceso a IP, ademas se puede especificar cual interfaz va a emplear (aunque sea un poco extraño). Si está usando el servicio de impresión de su sistema, pero solo localmente, no querrá compartir este servicio en la red. Puede considerar el uso de otros sistemas de impresión, como el servicio proporcionado en cups http://pdq.sourceforge.net/ el cual se basa en el permiso de un usuario del dispositivo/dev/lp0 En cups, los datos de impresión se transfieren al servidor vía el protocolo http. Esto significa que el programa del cliente no necesita ningún privilegio especial, solamente requiere que el servidor esté escuchando sobre un puerto cualquiera. Sin embargo, si usted quiere usar cups, pero solo localmente usted puede configurar esto para escuchar a la interfaz loopback cambiando /etc/cups/cupsd.conf: Listen 127.0.0.1:631 Hay muchas otras opciones de seguridad, como por ejemplo permitir o negar redes y servidores en este archivo de configuración. Sin embargo si no los necesita, debería limitar posibilidad de escuchar el puerto. Cups también ofrece documentación a través del puerto HTTP, si no quiere revelar información potencialmente útil para agresores externos (estando abierto el puerto), también agregue: Order Deny,Allow Deny From All Allow From 127.0.0.1 Este archivo de configuración puede ser modificado para añadir muchas caracteristicas incluyendo certficados SSL/TLS y criptografía. Los manuales estan disponibles en http://localhost:631/ or at cups.org. ARREGLAME: Add more content (the article on http://www.rootprompt.org provides some very interesting views). ARREGLAME: Check if PDG is available in Debian, and if so,suggest this as the preferred printing system. ARREGLAME: Check if Farmer/Wietse has a replacement for printer daemon and if it's available in Debian. 5.6. Reforzando el servidor de correo ------------------------------------- Si su servidor no es un sistema de correo, usted realmente no necesita tener un demonio de correo escuchando conexiones entrantes, pero usted podría querer envío de correo local, por ejemplo para recibir el correo del usuario Root desde cualquier sistema de alerta que usted tenga en algún lugar. If you have exim you do not need the daemon to be working in order to do this since the standard cron job flushes the mail queue. See Sección 3.5.1, “Deshabilitar servicios” on how to do this. 5.6.1. Configuring a Nullmailer You might want to have a local mailer daemon so that it can relay the mails sent locally to another system. This is common when you have to administer a number of systems and do not want to connect to each of them to read the mail sent locally. Just as all logging of each individual system can be centralized by using a central syslog server, mail can be sent to a central mailserver. Such a relay-only system should be configured properly for this. The daemon could, as well, be configured to only listen on the loopback address. The following configuration steps only need to be taken to configure the exim package in the Debian 3.0 release. If you are using a later release (such as 3.1 which uses exim4) the installation system has been improved so that if the mail transport agent is configured to only deliver local mail it will automatically only allow connections from the local host and will not permit remote connections. In a Debian 3.0 system using exim, you will have to remove the SMTP daemon from inetd: $ update-inetd --disable smtp y configurar el demonio de correo solo para escuchar en la interfaz loopback. En exim (el MTA por defecto) usted puede hacer esto añadiendo la siguiente línea editando: /etc/exim.conf y añadiendo la siguiente linea: local_interfaces = "127.0.0.1" Reinicie ambos demonios (inetd y exim) y estarán escuchando en el socket 127.0.0.1:25 solamente. Sea cuidadoso, y primero desconecte inetd, de lo contrario, exim no iniciara ya que el demonio inetd está manejando las conexiones entrantes. Para usar postfix edite /etc/postfix/main.conf: inet_interfaces = localhost Si usted solo quiere un correo local, este metodo es mejor que usar la cubierta tcp-wrapping al demonio de correo o añadir las reglas del cortafuego para limitar el acceso de cualquier persona a este. Sin embargo, si necesita que escuche en otras interfaces, debería considerar lanzarlo desde inetd y añadir un tcp-wraping de forma que las conexiones sean revisadas contra /etc/hosts.allow y /etc/hosts.deny también será advertido cuando un acceso no autorizado está atentando en contra de su demonio de correo, usted debe instaurar un registrador apropiado para cualquiera de los metodos mencionados anteriormente. In any case, to reject mail relay attempts at the SMTP level, you can change /etc/exim/exim.conf to include: receiver_verify = true Even if your mail server will not relay the message, this kind of configuration is needed for the relay tester at http://www.abuse.net/relay.html to determine that your server is not relay capable. If you want a relay-only setup, however, you can consider changing the mailer daemon to programs that can only be configured to forward the mail to a remote mail server. Debian provides currently both ssmtp and nullmailer for this purpose. In any case, you can evaluate for yourself any of the mail transport agents [37] provided by Debian and see which one suits best to the system's purposes. 5.6.2. Providing secure access to mailboxes If you want to give remote access to mailboxes there are a number of POP3 and IMAP daemons available.[38] However, if you provide IMAP access note that it is a general file access protocol, it can become the equivalent of a shell access because users might be able to retrieve any file that they can through it. Try, for example, to configure as your inbox path {server.com}/etc/passwd if it succeeds your IMAP daemon is not properly configured to prevent this kind of access. Of the IMAP servers in Debian the cyrus server (in the cyrus-imapd package) gets around this by having all access to a database in a restricted part of the file system. Also, uw-imapd (either install the uw-imapd or better, if your IMAP clients support it, uw-imapd-ssl) can be configured to chroot the users mail directory but this is not enabled by default. The documentation provided gives more information on how to configure it. Also, you might want to run an IMAP server that does not need valid users to be created on the local system (which would grant shell access too), courier-imap (for IMAP) and courier-pop, teapop (for POP3) and cyrus-imapd (for both POP3 and IMAP) provide servers with authentication methods beside the local user accounts. cyrus can use any authentication method that can be configured through PAM while teapop might use databases (such as postgresql and mysql) for user authentication. FIXME: Check: uw-imapd might be configured with user authentication through PAM too. 5.6.3. Recibiendo Correo de forma segura Leer/recibir correo es el protocolo más común de texto plano. Si usted usa POP3 o IMAP para obtener su correo, la contraseña es enviada en texto plano a través de la red, de modo que casi cualquiera podría leer su correo a partir de ahora. En lugar de esto, use SSL (Capa segura de Sockets) para recibir su correo. La otra alternativa es ssh, si tiene una cuenta shell en la máquina que actua como el servidor POP o IMAP. Este es un ejemplo básico fetchmailrc para demostrar esto: poll my-imap-mailserver.org via "localhost" with proto IMAP port 1236 user "ref" there with password "hackme" is alex here warnings 3600 folders .Mail/debian preconnect 'ssh -f -P -C -L 1236:my-imap-mailserver.org:143 -l ref my-imap-mailserver.org sleep 15 /dev/null' La preconexión es la línea más importante. Este lanza una sesión ssh y crea el tunel necesario, el cual automaticamente envía las conexiones para tener acceso a localhost puerto 1236 al servidor de correo IMAP, pero codificado. Otra posibilidad seria, usar el fetchmail con la caracteristica ssl. Si usted quiere suministrar un servicio de correo codificado como POP e IMAP,apt-get install stunnel e inicie sus demonios de esta es la forma: stunnel -p /etc/ssl/certs/stunnel.pem -d pop3s -l /usr/sbin/popd Este comando encapsula al demonio proveido (-l) en el puerto (-d) y usa el certificado ssl especificado (-p). 5.7. Asegurando BIND -------------------- Hay diferentes consideraciones que puede implementar para asegurar el demonio de servidor de nombres, las cuales son similares a las mismas que cuando se asegura cualquier servicio dado: * Configurar el demonio por si solo apropiadamente para que este no pueda ser afectado desde afuera. Esto abarca limitar las posibles dudas de los clientes: zona transferida y consultas recursivas. * Limitar el acceso del demonio al servidor mismo, de modo que si este es usado para entrar, el daño en el sistema esté limitado. Esto incluye correr el demonio como un usuario no privilegiado y cambiarle el directorio raiz. 5.7.1. Bind configuration to avoid misuse Deberia restringir alguna de la información que es dada por el servidor DNS para clientes externos para que no pueda ser usado para acceder a información valiosa de su organización que usted no quiere dar. Esto incluye añadir las siguientes opciones: allow-transfer, allow-query, allow-recursive y version.Puede limitar en una sección global (para que se aplica a todas las zonas presentes) o sobre una base por zona. Esta información esta documentada en el paquete bind-doc, lea más sobre esto en /usr/share/doc/bind/html/index.html una vez el paquete este instalado. Imagine que su servidor está conectado a Internet y a su red interna (su IP interno es 192.168.1.2)(un servicio de multi domicilio basico). Usted no quiere dar ningun servicio para Internet y solo quiere permitir el lookups DNS desde su servidor interno. Usted podria restringir esto para incluirlo en: /etc/bind/named.conf: options { \t allow-query { 192.168.1/24; } ; \t allow-transfer { none; } ; allow-recursion { 192.168.1/24; } ; \t listen-on { 192.168.1.2; } ; \t forward { only; } ; \t forwarders { A.B.C.D; } ; }; La opciónlisten-onhace el bind DNS solo para la interfaz que tiene la dirección interna, pero si esta interfaz es la misma como la interfaz que se conecta a Internet (por ejemplo, si usted está usando NAT), las dudas seran solamente aceptadas si llegan desde su servidor interno. Si el sistema tiene multiples interfaces y el listen-on no está presente, solamente los usuarios internos podrian pregutar, ya que el puerto seria accesible para los atacantes exteriores, ellos podrian tratar de arrojarlo al servidor DNS (o explotar el amortiguador desbordandose agresivamente). Usted aun podría leer esto en 127.0.0.1 si usted no está dando el servicio DNS por ningun otro sistema que el de usted mismo. El registro version.bind en la clase caos contiene la versión del proceso bind que se está ejecutando. Esta información es frecuentemente usada por dispositivos automaticos e individuos maliciosos que desean determinar si el bind de uno es vulnerable a un ataque específico. Para proporcionar falsa o negativa información en el registro de la version.bind, uno limita la probabilidad que un servidor pueda ser atacado basandonos en la versión publicitaria.Para suministrar su proia versión, utilice la version dirigida de la siguiente manera: options { ... various options here ... version "Not available."; }; Cambiar el registro de la version.bind que no proporciona una protección actual en contra de los ataques, pero este debería ser considerado un salva guardia útil. A sample named.conf configuration file might be the following: acl internal { 127.0.0.1/32; // localhost 10.0.0.0/8; // internal aa.bb.cc.dd; // eth0 IP }; acl friendly { ee.ff.gg.hh; // slave DNS aa.bb.cc.dd; // eth0 IP 127.0.0.1/32; // localhost 10.0.0.0/8; // internal }; options { directory "/var/cache/bind"; allow-query { internal; }; allow-recursion { internal; }; allow-transfer { none; }; }; // From here to the mysite.bogus zone // is basically unmodified from the debian default logging { category lame-servers { null; }; category cname { null; }; }; zone "." { type hint; file "/etc/bind/db.root"; }; zone "localhost" { type master; file "/etc/bind/db.local"; }; zone "127.in-addr.arpa" { type master; file "/etc/bind/db.127"; }; zone "0.in-addr.arpa" { type master; file "/etc/bind/db.0"; }; zone "255.in-addr.arpa" { type master; file "/etc/bind/db.255"; }; // zones I added myself zone "mysite.bogus" { type master; file "/etc/bind/named.mysite"; allow-query { any; }; allow-transfer { friendly; }; }; Please (again) check the Bug Tracking System regarding Bind, specifically http://bugs.debian.org/94760. Feel free to contribute to the bug report if you think you can add useful information. 5.7.2. Changing BIND's user Con respecto a limitar los privilegios de BIND, usted debe darse cuenta que si un usuario del non-root recorre Bind, Bind no podra detectar las nuevas interfaces automaticamente. Como por ejemplo si usted pone en un portatil una tarjeta PCMCIA. Cambie el archivo README Debian en el directorio nombrado (/usr/share/doc/bind/README.Debian)para mas información acerca de este uso. Recientemente han habido muchos problemas de seguridad en lo que concierne a BIND, y por esto es necesario cambiar el usuario util cuando sea posible. Notice, in any case, that this only applies to BIND version 8. In the Debian packages for BIND version 9 (since the 9.2.1-5 version, available since sarge) the bind user is created and used by setting the OPTIONS variable in /etc/default/bind9. If you are using BIND version 9 and your name server daemon is not running as the bind user verify the settings on that file. Para correr BIND bajo un usuario diferente, primero cree un usuario separado y un grupo para esto (no es buena idea usar,not nobody o nogroup para todo sevicio que no corra como raiz). En este ejemplo, el usuario y el grupo namedserán usados. Usted puede hacer esto entrando a: addgroup named adduser --system --home /home/named --no-create-home --ingroup named \ --disabled-password --disabled-login named Notice that the user named will be quite restricted. If you want, for whatever reason, to have a less restrictive setup use: adduser --system --ingroup named named Ahora edite /etc/init.d/bind con su editor favorito y cambie la linea comenzando con: start-stop-daemon --start to[39] start-stop-daemon --start --quiet --exec /usr/sbin/named -- -g named -u named Or you can change (create it if it does not exit) the default configuration file (/etc/default/bind for BIND version 8) and introduce the following: OPTIONS="-u named -g named" Change the permissions of files that are used by Bind, including /etc/bind/rndc.key: -rw-r----- 1 root named 77 Jan 4 01:02 rndc.key and where bind creates its pidfile, using, for example, /var/run/named instead of /var/run: $ mkdir /var/run/named $ chown named.named /var/run/named $ vi /etc/named.conf [ ... update the configuration file to use this new location ...] options { ... pid-file "/var/run/named/named.pid"; }; [ ... ] Also, in order to avoid running anything as root, change the reload line in the init.d script by substituting: reload) /usr/sbin/ndc reload para: reload) $0 stop sleep 1 $0 start Note: Depending on your Debian version you might have to change the restart line too. This was fixed in Debian's bind version 1:8.3.1-2. Todo lo que usted necesita hacer ahora es reiniciar Bind'/etc/init.d/bind, y luego cambiar su syslog por dos entradas como estas: Sep 4 15:11:08 nexus named[13439]: group = named Sep 4 15:11:08 nexus named[13439]: user = named Voilà! Your named now does not run as root. If you want to read more information on why BIND does not run as non-root user on Debian systems, please check the Bug Tracking System regarding Bind, specifically http://bugs.debian.org/50013 and http://bugs.debian.org/132582, http://bugs.debian.org/53550, http://bugs.debian.org/52745, and http://bugs.debian.org/128129. Feel free to contribute to the bug reports if you think you can add useful information. 5.7.3. Chrooting the name server To achieve maximum BIND security, now build a chroot jail (see Sección 5.10, “Cambio general de directorio raíz y paranoia suid”) around your daemon. There is an easy way to do this: the -t option (see the named(8) manual page or page 100 of http://www.nominum.com/content/documents/bind9arm.pdf). This will make Bind chroot itself into the given directory without you needing to set up a chroot jail and worry about dynamic libraries. The only files that need to be in the chroot jail are: dev/null etc/bind/ - should hold named.conf and all the server zones sbin/named-xfer - if you do name transfers var/run/named/ - should hold the pid and the name server cache (if any) this directory needs to be writable by named user var/log/named - if you set up logging to a file, needs to be writable for the named user dev/log - syslogd should be listening here if named is configured to log through it Para que su denmonio BIND trabeje apropiedamente, este necesita permiso en los archivos nombrados. Ésta es una tarea fácil ya que los archivos de configuarción estan siempre en /etc/named/. Tenga en cuenta que esto solamente necesita acceso de lectura para los archivos de la zona, a menos que este sea un secundario o un servidor llamado cache. Si este es su caso usted tendra que dar permiso de lecto-escritura a las zonas necesarias (asi como la zona transferida desde los tarbajos del servidor primario). Also, you can find more information regarding Bind chrooting in the http://www.tldp.org/HOWTO/Chroot-BIND-HOWTO.html (regarding Bind 9) and http://www.tldp.org/HOWTO/Chroot-BIND8-HOWTO.html (regarding Bind 8). This same documents should be available through the installation of the doc-linux-text (text version) or doc-linux-html (HTML version). Another useful document is http://web.archive.org/web/20011024064030/http://www.psionic.com/papers/dns/dns-linux. If you are setting up a full chroot jail (i.e. not just -t) for Bind in Debian, make sure you have the following files in it[40]: dev/log - syslogd should be listening here dev/null etc/bind/named.conf etc/localtime etc/group - with only a single line: "named:x:GID:" etc/ld.so.cache - generated with ldconfig lib/ld-2.1.3.so lib/libc-2.1.3.so lib/ld-linux.so.2 - symlinked to ld-2.1.3.so lib/libc.so.6 - symlinked to libc-2.1.3.so sbin/ldconfig - may be deleted after setting up the chroot sbin/named-xfer - if you do name transfers var/run/ And modify also syslogd listen on $CHROOT/dev/log so the named server can write syslog entries into the local system log. If you want to avoid problems with dynamic libraries, you can compile bind statically. You can use apt-get for this, with the source option. It can even download the packages you need to properly compile it. You would need to do something similar to: $ apt-get source bind # apt-get build-dep bind $ cd bind-8.2.5-2 (edit src/port/linux/Makefile so CFLAGS includes the '-static' option) $ dpkg-buildpackage -rfakeroot -uc -us $ cd .. # dpkg -i bind-8.2.5-2*deb After installation, you will need to move around the files to the chroot jail[41] you can keep the init.d scripts in /etc/init.d so that the system will automatically start the name server, but edit them to add --chroot /location_of_chroot in the calls to start-stop-daemon in those scripts or use the -t option for BIND by setting it in the OPTIONS argument at the /etc/default/bind (for version 8) or /etc/default/bind9 (for version 9) configuration file. For more information on how to set up chroots see Sección 5.10, “Cambio general de directorio raíz y paranoia suid”. FIXME: Merge info from http://people.debian.org/~pzn/howto/chroot-bind.sh.txt, http://www.cryptio.net/~ferlatte/config/ (Debian-specific), http://web.archive.org/web/20021216104548/http://www.psionic.com/papers/whitep01.html and http://csrc.nist.gov/fasp/FASPDocs/NISTSecuringDNS.htm. 5.8. Asegurando Apache ---------------------- FIXME: Add content: modules provided with the normal Apache installation (under /usr/lib/apache/X.X/mod_*) and modules that can be installed separately in libapache-mod-XXX packages. Usted puede limitar el acceso a el servidor Apache si si usted quiere usar esto solo internamente (para objetivos de prueba, para tener acceso al archivodoc-central etc..) y si no quiere que extraños tengan esto. Para hacer esto use el Listen o BindAddress dirigidos en /etc/apache/http.conf. Usando Listen: Listen 127.0.0.1:80 Usando BindAddress: BindAddress 127.0.0.1 Luego reinicie Apache con /etc/init.d/apache restart y vera que esto es de solo Audición en la interfaz loopback. De todos modos, que usted no este usando todo lo funcionamiento suministrado por Apache, usted podria querer dar un vistazo a otro servicio de la web proporcionados en Debian como dhttpd. La http://httpd.apache.org/docs/misc/security_tips.html proporciona información relacxionada con las medidas de seguridad que deben ser tomadas en el servidor web del Apache (esta misma información está suministrada en Debian por el paqueteapache-doc). More information on further restricting Apache by setting up a chroot jail is provided in Sección B.7.3, “Chroot environment for Apache”. 5.8.1. Disabling users from publishing web contents The default Apache installation in Debian permits users to publish content under the $HOME/public_html. This content can be retrieved remotely using an URL such as: http://your_apache_server/~user. If you do not want to permit this you must change the /etc/apache/http.conf configuration file commenting out (in Apache 1.3) the following module: LoadModule userdir_module /usr/lib/apache/1.3/mod_userdir.so If you are using Apache 2.0 you must remove the file /etc/apache2/mods-enabled/userdir.load or restrict the default configuration by modifying /etc/apache2/mods-enabled/userdir.conf. However, if the module was linked statically (you can list the modules that are compiled in running apache -l) you must add the following to the Apache configuration file: Userdir disabled An attacker might still do user enumeration, since the answer of the web server will be a 403 Permission Denied and not a 404 Not available. You can avoid this if you use the Rewrite module. 5.8.2. Permisos para el archivo de registro Apache logfiles, since 1.3.22-1, are owned by user 'root' and group 'adm' with permissions 640. These permissions are changed after rotation. An intruder that accessed the system through the web server would not be able (without privilege escalation) to remove old log file entries. 5.8.3. Published web files Apache files are located under /var/www. Just after installation the default file provides some information on the system (mainly that it's a Debian system running Apache). The default webpages are owned by user root and group root by default, while the Apache process runs as user www-data and group www-data. This should make attackers that compromise the system through the web server harder to deface the site. You should, of course, substitute the default web pages (which might provide information you do not want to show to outsiders) with your own. 5.9. Asegurando finger ---------------------- Si usted quiere recorrer el servicio de finger, primero preguntese si usted necesita realizar esto. Si lo hace, usted mismo descubrira que Debian proporciona muchos demonios finger (Puest fuera de apt-cache search fingerd): * cfingerd - Demonio finger configurable * efingerd - Es otro demonio finger para unix capaz de una fina-sintonización de su rendimiento. * ffingerd - Un demonio seguro. * fingerd - Remoto servidor de la información del usuario * BSD- Demonio finger con soporte qmail. ffingerd es el demonio finger recomendado para si usted va ausar esto para un servicio publico. De todos modos usted se fortalece, cuando establece este a traves de inetd, xinetd o tcpserver para: limitar el numero de procesos que estaran corriendo al mismo tiempo, limitar el acceso para el demonio finger a partir de un numero dado por los servidores (usando el wrappers tcp) y teniendo esto solamente por audición para la interfaz en la que usted necesita estar. 5.10. Cambio general de directorio raíz y paranoia suid ------------------------------------------------------- chroot es una de las posibilidades más poderosas para restringir un demonio, un ususario u otro servicio. Sólo imagine una cárcel alrededor de su objetivo, del cual no puede escapar (normalmente, hay sin embargo muchas condiciones que permiten un escape fuera de su cárcel). Si usted no confía en un usuario, puede crear un cambio en el ambiente. Ésto puede usar un pequeño espacio adicional de disco, puesto que se necesita copiar todos los ejecutables necesarios, así como las biblioteca dentro de la cárcel. Aún si el usuario hace algo malicioso, el alcance de un daño es limitado al aseguramiento. Many services running as daemons could benefit from this sort of arrangement. The daemons that you install with your Debian distribution will not come, however, chrooted[42] per default. This includes: name servers (such as bind), web servers (such as apache), mail servers (such as sendmail) and ftp servers (such as wu-ftpd). It is probably fair to say that the complexity of BIND is the reason why it has been exposed to a lot of attacks in recent years (see Sección 5.7, “Asegurando BIND”). However, Debian does provide some software that can help set up chroot environments. See Sección 5.10.1, “Making chrooted environments automatically”. Anyway, if you run any service on your system, you should consider running them as secure as possible. This includes: revoking root privileges, running in a restricted environment (such as a chroot jail) or replacing them with a more secure equivalent. Sin embargo, esté prevenido que el seguro chroot puede estar dañado si el usuario entra en éste es el superusuario. Así que usted necesita que el servicio corra como un usuario no privilegiado. Límitando su ambien usted está límitando la palabra leíbles que el servicio de archivos ejecutables puede acceder, así, usted límita las posibilidades de una subida del privilegio por el uso de vulnerabilidades de seguridad de los sistemas locales. Incluso en ésta situación usted no puede estar copmpletamente seguro de que no hay ninguna manera para que un atacante hábil se escape de algún modo del aseguramiento. Usando solamente un servidor de programa, el cual tiene una reputación de medida de aseguramiento que es buena. Incluso la cavidad minusiosa de archivos manuales puede ser abierta por un atacante hábil interrumpiendo el sistema por dentro. Despues de todo, chroot no fue diseñado como una herramienta de comprobación. 5.10.1. Making chrooted environments automatically There are several programs to chroot automatically servers and services. Debian currently (accepted in May 2002) provides Wietse Venema's chrootuid in the chrootuid package, as well as compartment and makejail. These programs can be used to set up a restricted environment for executing any program (chrootuid enables you to even run it as a restricted user). Some of these tools can be used to set up the chroot environment easily. The makejail program for example, can create and update a chroot jail with short configuration files (it provides sample configuration files for bind, apache, postgresql and mysql). It attempts to guess and install into the jail all files required by the daemon using strace, stat and Debian's package dependencies. More information at http://www.floc.net/makejail/. Jailer is a similar tool which can be retrieved from http://www.balabit.hu/downloads/jailer/ and is also available as a Debian package. 5.11. Texto claro general con el password paranoia -------------------------------------------------- Usted deberia tratar de evitar cualquier servicio de red el cual envia y recibe contraseñas en un texto claro sobre una red como FTP/Telnet/NIS/RPC. El autor recomienda para todos el uso de ssh en cambio de telnet y ftp. Mantenga en mente que migrar de telenet a ssh pero usando otros protocolos de texto claro no aumentan su seguridad de NINGUNA forma! lo mejor seria eliminar ftp, telnet, pop, imap, http y suplantarlos con sus respectivos servicios codificados. Usted debe considerar moverse desde otros servicios hasta sus versiones SSL, ftp-ssl, telnet-ssl, pop-ssl, https... Muchos de estas indicaciones numeradas en la parte superior se aplican a documentos en todo el sistema Unix (Usted los encontrara si lee cualquier otro hardening-related relacionado con lo que tiene que ver con Linux y otros Unix). 5.12. Incapacitar NIS --------------------- Es posible que usted no tenga que usar NIS, en el servicio de información de la red, porque este permite que la contraseña actue. Este puede ser demasiado inseguro si su organización está rota. Si usted necesita que la contraseña actue entre maquinas, usted deberia considerar usar otras alternativas. Por ejemplo usted puede colocar un servidor LDAP y configurar PAM en su sistema para contactar el servidor LDAP para la autenticación del usuario. Usted puede encontrar una detallada organización en el http://www.linuxdoc.org/HOWTO/LDAP-HOWTO.html (/usr/share/doc/HOWTO/en-txt/LDAP-HOWTO.txt.gz). Lea mas sobre la seguridad en http://www.linuxdoc.org/HOWTO/NIS-HOWTO.html (/usr/share/doc/HOWTO/en-txt/NIS-HOWTO.txt.gz). ARREGLAME (jfs): Add info on how to setup this in Debian 5.13. Securing RPC services --------------------------- You should disable RPC if you do not need it. Remote Procedure Call (RPC) is a protocol that programs can use to request services from other programs located on different computers. The portmap service controls RPC services by mapping RPC program numbers into DARPA protocol port numbers; it must be running in order to make RPC calls. RPC-based services have had a bad record of security holes, although the portmapper itself hasn't (but still provides information to a remote attacker). Notice that some of the DDoS (distributed denial of service) attacks use RPC exploits to get into the system and act as a so called agent/handler. You only need RPC if you are using an RPC-based service. The most common RPC-based services are NFS (Network File System) and NIS (Network Information System). See the previous section for more information about NIS. The File Alteration Monitor (FAM) provided by the package fam is also an RPC service, and thus depends on portmap. NFS services are quite important in some networks. If that is the case for you, then you will need to find a balance of security and usability for your network (you can read more about NFS security in the http://www.tldp.org/HOWTO/NFS-HOWTO.html (/usr/share/doc/HOWTO/en-txt/NFS-HOWTO.txt.gz)). 5.13.1. Desactivar los servicios RPC Inhabilitar el paquete portmap es super sencillo. Hay diferentes mátodos. Uno de los más sencillos en un sistema Debian 3.0 es hacer un desinstalamiento del paquete portmap. Si usted está usando otra versión, tendrá que desactivar el servicio como se ve en disableserv, esto es debido a el programa que forma parte del paquete net-base (el cual no puede ser desinstalado sin que el sistema se haya destruido). Notice that some desktop environments (notably, GNOME) use RPC services and need the portmapper for some of the file management features. If this is your case, you can limit the access to RPC services as described below. 5.13.2. Limites al acceso de servicios RPC Unfortunately, in some cases removing RPC services from the system is not an option. Some local desktop services (notably SGI's fam) are RPC based and thus need a local portmapper. This means that under some situations, users installing a desktop environment (like GNOME) will install the portmapper too. There are several ways to limit access to the portmapper and to RPC services: * Block access to the ports used by these services with a local firewall (see Sección 5.14, “Añadir capacidades al cortafuegos”). * Block access to these services using tcp wrappers, since the portmapper (and some RPC services) are compiled with libwrap (see Sección 4.12, “Uso de tcpwrappers”). This means that you can block access to them through the hosts.allow and hosts.deny tcp wrappers configuration. * Since version 5-5, the portmap package can be configured to listen only on the loopback interface. To do this, modify /etc/default/portmap, uncomment the following line: #OPTIONS="-i 127.0.0.1" and restart the portmapper. This is sufficient to allow local RPC services to work while at the same time prevents remote systems from accessing them (see, however, Sección 4.18.5, “Disabling weak-end hosts issues”). 5.14. Añadir capacidades al cortafuegos --------------------------------------- The Debian GNU/Linux operating system has the built-in capabilities provided by the Linux kernel. If you install a recent Debian release (default kernel installed is 2.6) you will have iptables (netfilter) firewalling available[43]. 5.14.1. El sistema local corta fuegos Usted puede usar las reglas de corta fuegos cono una forma para asegurar el acceso en un sistema local, invluso para limitaer la salida de comunicación hecha por este. Las reglas corta fuegos pueden ser usadas también para protejer procesos que no pueden ser configurados apropiadamente ni proveer servicios para algunas redes, direcciones, IP, etc... Sin embargo, este paso se presentara despues en el manual, basicamente porque es mucho mejor para no depender únicamente de la capacidad del corta fuegos para protejer un sistema dado. La seguridad en un sistema no puede ser hecho de cubiertas, el corta fuegos deberia ser el ultimo en incluirse, una vez todos los servicios hayan sido fortalecidos. Usted puede fácilmente imaginar un plan en el cual el sistema está protegido solamente por un corta fuegos incorporadoy un administrador blissfully que remueve las reglas del corta fuegos por cualquiera que sea la razón (problemas con la instalación, molestias, errores humanos...), este sistema abierto ampliamnete para un ataque. On the other hand, having firewall rules on the local system also prevents some bad things from happening. Even if the services provided are configured securely, a firewall can protect from misconfigurations or from fresh installed services that have not yet been properly configured. Also, a tight configuration will prevent trojans calling home from working unless the firewalling code is removed. Note that an intruder does not need superuser access to install a trojan locally that could be remotely controlled (since binding on ports is allowed if they are not priviledged ports and capabilities have not been removed). Thus, a proper firewall setup would be one with a default deny policy, that is: * incoming connections are allowed only to local services by allowed machines. * outgoing connections are only allowed to services used by your system (DNS, web browsing, POP, email...).[44] * the forward rule denies everything (unless you are protecting other systems, see below). * el resto de conexiones entrantes o salientes son denegadas. 5.14.2. Usar otros corta fuegos para proteger otros sistemas A Debian firewall can also be installed in order to protect, with filtering rules, access to systems behind it, limiting their exposure to the Internet. A firewall can be configured to prevent access from systems outside of the local network to internal services (ports) that are not public. For example, on a mail server, only port 25 (where the mail service is being given) needs to be accessible from the outside. A firewall can be configured to, even if there are other network services besides the public ones running in the mail server, throw away packets (this is known as filtering) directed towards them. You can even set up a Debian GNU/Linux box as a bridge firewall, i.e. a filtering firewall completely transparent to the network that lacks an IP address and thus cannot be attacked directly. Depending on the kernel you have installed, you might need to install the bridge firewall patch and then go to 802.1d Ethernet Bridging when configuring the kernel and a new option netfilter ( firewalling ) support. See the Sección B.4, “Setting up a bridge firewall ” for more information on how to set this up in a Debian GNU/Linux system. 5.14.3. Configurando un cortafuegos The default Debian installation, unlike other Linux distributions, does not yet provide a way for the administrator to setup a firewall configuration throughout the default installation but you can install a number of firewall configuration packages (see Sección 5.14.3.1, “Paquetes del Corta Fuegos”). Of course, the configuration of the firewall is always system and network dependant. An administrator must know beforehand what is the network layout and the systems to protect, the services that need to be accessed, and whether or not other network considerations (like NAT or routing) need to be taken into account. Be careful when configuring your firewall, as Laurence J. Lane says in the iptables package: The tools can easily be misused, causing enormous amounts of grief by completely crippling network access to a system. It is not terribly uncommon for a remote system administrator to accidentally get locked out of a system hundreds or thousands of miles away. You can even manage to get locked out of a computer who's keyboard is under your own fingers. Please, use due caution. Remember this: just installing the iptables (or the older firewalling code) does not give you any protection, just provides the software. In order to have a firewall you need to configure it! Si usted no tiene un indicio sobre como colocar sus reglas al corta fuegos consulte el Paquete Filtrador HOWTO proporcionado por iptables al leer fuera de la linea en /usr/share/doc/iptables/html/ If you do not know much about firewalling you should start by reading the http://www.tldp.org/HOWTO/Firewall-HOWTO.html, install the doc-linux-text package if you want to read it offline. If you want to ask questions or need help setting up a firewall you can use the debian-firewall mailing list, see http://lists.debian.org/debian-firewall. Also see Sección 1.4, “Conocimiento previo” for more (general) pointers on firewalls. Another good iptables tutorial is http://iptables-tutorial.frozentux.net/iptables-tutorial.html. 5.14.3.1. Paquetes del Corta Fuegos Setting up manually a firewall can be complicated for novice (and sometimes even expert) administrators. However, the free software community has created a number of tools that can be used to easily configure a local firewall. Be forewarned that some of these tools are oriented more towards local-only protection (also known as personal firewall) and some are more versatile and can be used to configure complex rules to protect whole networks. Hay un software completo que pueden ser usados para colocar reglas de corta fuegos en un sistema Debian * Para entornos gráficos * firestarter, a GNOME application oriented towards end-users that includes a wizard useful to quickly setup firewall rules. The application includes a GUI to be able to monitor when a firewall rule blocks traffic. * guarddog, a KDE based firewall configuration package oriented both to novice and advanced users. * knetfilter, a KDE GUI to manage firewall and NAT rules for iptables (alternative/competitor to the guarddog tool although slightly oriented towards advanced users). * fireflier, an interactive tool to create iptables rules based on traffic seen on the system and applications. It has a server-client model so you have to install both the server (fireflier-server) and one of the available clients, with one client available for different desktop environments: fireflier-client-gtk (Gtk+ client), fireflier-client-kde (KDE client) and fireflier-client-qt (QT client). * For servers (headless) systems: * fwbuilder, an object oriented GUI which includes policy compilers for various firewall platforms including Linux' netfilter, BSD's pf (used in OpenBSD, NetBSD, FreeBSD and MacOS X) as well as router's access-lists. It is similar to enterprise firewall management software. Complete fwbuilder's functionality is also available from the command line. * shorewall, a firewall configuration tool which provides support for IPsec as well as limited support for traffic shaping as well as the definition of the firewall rules. Configuration is done through a simple set of files that are used to generate the iptables rules. * bastille, this hardening application is described in Capítulo 6, Fortalecimiento automático de sistemas Debian. One of the hardening steps that the administrator can configure is a definition of the allowed and disallowed network traffic that is used to generate a set of firewall rules that the system will execute on startup. Lots of other iptables frontends come with Debian; an extensive list comparing the different packages in Debian is maintained at the http://wiki.debian.org/Firewalls. Notice that some of the packages outlined previously will introduce firewalling scripts to be run when the system boots. Test them extensively before rebooting or you might find yourself locked from the box. If you mix different firewalling packages you can have undesired effects, usually, the firewalling script that runs last will be the one that configures the system (which might not be what you intend). Consult the package documentation and use either one of these setups. As mentioned before, some programs, like firestarter, guarddog and knetfilter, are administration GUIs using either GNOME or KDE (last two). These applications are much more user-oriented (i.e. for home users) than some of the other packages in the list which might be more administrator-oriented. Some of the programs mentioned before (like bastille) are focused at setting up firewall rules to protect the host they run in but are not necessarily designed to setup firewall rules for firewall hosts that protect a network (like shorewall or fwbuilder). There is yet another type of firewall application: application proxies. If you are looking into setting up an enterprise-level firewall that does packet filtering and provides a number of transparent proxies that can do fine-grain traffic analysis you should consider using zorp, which provides this in a single program. You can also manually setup this type of firewall host using the proxies available in Debian for different services like for DNS using bind (properly configured), dnsmasq, pdnsd or totd for FTP using frox or ftp-proxy, for X11 using xfwp, for IMAP using imapproxy, for mail using smtpd, or for POP3 using p3scan. For other protocols you can either use a generic TCP proxy like simpleproxy or a generic SOCKS proxy like dante-server, tsocks or socks4-server. Typically, you will also use a web caching system (like squid) and a web filtering system (like squidguard or dansguardian). 5.14.3.2. Manual init.d configuration Another possibility is to manually configure your firewall rules through an init.d script that will run all the iptables commands. Take the following steps: * Review the script below and adapt it to your needs. * Test the script and review the syslog messages to see which traffic is being dropped. If you are testing from the network you will want to either run the sample shell snippet to remove the firewall (if you don't type anything in 20 seconds) or you might want to comment out the default deny policy definitions (-P INPUT DROP and -P OUTPUT DROP) and check that the system will not drop any legitimate traffic. * Move the script to /etc/init.d/myfirewall * The below script takes advantage of Debian's use (since Squeeze) of dependency based boot sequencing. For more information see: https://wiki.debian.org/LSBInitScripts/DependencyBasedBoot and https://wiki.debian.org/LSBInitScripts. With the LSB headers set as they are in the script, insserv will automatically configure the system to start the firewall before any network is brought up, and stop the firewall after any network is brought down. # insserv myfirewall A continuación tiene un ejemplo de script cortafuegos: #!/bin/sh ### BEGIN INIT INFO # Provides: myfirewall # Required-Start: $local_fs # Required-Stop: $local_fs # Default-Start: S # Default-Stop: 0 6 # X-Start-Before: $network # X-Stop-After: $network # Short-Description: My custom firewall. ### END INIT INFO # # Sencillo ejemplo de cofiguración de un cortafuegos. # # Tenga en cuenta que: # - Esta configuraciñon se aplica en todas las interfaces de red # - Si desea restringirlo a una única interfaz utlice '-i INTERFAZ' # en cada ejecución del comando iptables # - Se permite el acceso TCP/UDP a cualquier máquina # Probablemente desee restringirlo mediante el uso de '--source'. # # chkconfig: 2345 9 91 # descripción: activa/desactiva el cortafuegos durante el inicio. # # Puede probar este script antes de instalarlo con este código. # Simplemente hace que si no escribe nada durante 10 segundos, # se borran todas las reglas del cortafuegos. #--------------------------------------------------------------- # while true; do test=""; read -t 20 -p "OK? " test ; \ # [ -z "$test" ] && /etc/init.d/myfirewall clear ; done #--------------------------------------------------------------- PATH=/bin:/sbin:/usr/bin:/usr/sbin # Services que el sistema proporciona en red TCP_SERVICES="22" # sólo SSH UDP_SERVICES="" # Services que el sistema necesita de la red.k REMOTE_TCP_SERVICES="80" # Navegación web. REMOTE_UDP_SERVICES="53" # DNS # Red mediante la que se accederá remotamente a la máquina # (si se deja en blanco, no se definirá ninguna regla) # NETWORK_MGMT=192.168.0.0/24 # Si desea tener dicha red (es decir, ha descomentado la # anterior línea), también deberá definir el puerto para SSH # descomentando la siguiente línea. Recuerde elminar el puerto SSH # en la variable TCP_SERVICES # SSH_PORT="22" if ! [ -x /sbin/iptables ]; then exit 0 fi fw_start () { # Tráfico de entrada: /sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # Servicios if [ -n "$TCP_SERVICES" ] ; then for PORT in $TCP_SERVICES; do /sbin/iptables -A INPUT -p tcp --dport ${PORT} -j ACCEPT done fi if [ -n "$UDP_SERVICES" ] ; then for PORT in $UDP_SERVICES; do /sbin/iptables -A INPUT -p udp --dport ${PORT} -j ACCEPT done fi # Acceso remoto if [ -n "$NETWORK_MGMT" ] ; then /sbin/iptables -A INPUT -p tcp --src ${NETWORK_MGMT} --dport ${SSH_PORT} -j ACCEPT fi # Pruebas remotas /sbin/iptables -A INPUT -p icmp -j ACCEPT /sbin/iptables -A INPUT -i lo -j ACCEPT /sbin/iptables -P INPUT DROP /sbin/iptables -A INPUT -j LOG # Tráfico de salida: /sbin/iptables -A OUTPUT -j ACCEPT -o lo /sbin/iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # Se permiteel tráfico de ICMP: /sbin/iptables -A OUTPUT -p icmp -j ACCEPT # También las actualizaciones de seguridad: # Puede añadir directamente la IP del servidor para evitar ataques de DNS # pero no verá cambios de IP de este servidor /sbin/iptables -A OUTPUT -p tcp -d security.debian.org --dport 80 -j ACCEPT # Igualmente para los servicios que definimos: if [ -n "$REMOTE_TCP_SERVICES" ] ; then for PORT in $REMOTE_TCP_SERVICES; do /sbin/iptables -A OUTPUT -p tcp --dport ${PORT} -j ACCEPT done fi if [ -n "$REMOTE_UDP_SERVICES" ] ; then for PORT in $REMOTE_UDP_SERVICES; do /sbin/iptables -A OUTPUT -p udp --dport ${PORT} -j ACCEPT done fi # Cualquier otra conexión se registrará mediante syslog /sbin/iptables -A OUTPUT -j LOG /sbin/iptables -A OUTPUT -j REJECT /sbin/iptables -P OUTPUT DROP # Protecciones adicionales para la red # (algunas sólo funcionan en ciertas versiones del núcleo) echo 1 > /proc/sys/net/ipv4/tcp_syncookies echo 0 > /proc/sys/net/ipv4/ip_forward echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts echo 1 > /proc/sys/net/ipv4/conf/all/log_martians echo 1 > /proc/sys/net/ipv4/ip_always_defrag echo 1 > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter echo 0 > /proc/sys/net/ipv4/conf/all/send_redirects echo 0 > /proc/sys/net/ipv4/conf/all/accept_source_route } fw_stop () { /sbin/iptables -F /sbin/iptables -t nat -F /sbin/iptables -t mangle -F /sbin/iptables -P INPUT DROP /sbin/iptables -P FORWARD DROP /sbin/iptables -P OUTPUT ACCEPT } fw_clear () { /sbin/iptables -F /sbin/iptables -t nat -F /sbin/iptables -t mangle -F /sbin/iptables -P INPUT ACCEPT /sbin/iptables -P FORWARD ACCEPT /sbin/iptables -P OUTPUT ACCEPT } case "$1" in start|restart) echo -n "Iniciando el cortafuegos.." fw_stop fw_start echo "Iniciado." ;; stop) echo -n "Deteniendo el cortafuegos.." fw_stop echo "Detenido." ;; clear) echo -n "Borrando las reglas del cortafuegos." fw_clear echo "Borradas." ;; *) echo "Uso: $0 {start|stop|restart|clear}" exit 1 ;; esac exit 0 Instead of including all of the iptables rules in the init.d script you can use the iptables-restore program to restore the rules saved using iptables-save. In order to do this you need to setup your rules, save the ruleset under a static location (such as /etc/default/firewall) 5.14.3.3. Configuring firewall rules through ifup You can use also the network configuration in /etc/network/interfaces to setup your firewall rules. For this you will need to: * Create your firewalling ruleset for when the interface is active. * Save your ruleset with iptables-save to a file in /etc, for example /etc/iptables.up.rules * Configure /etc/network/interfaces to use the configured ruleset: iface eth0 inet static address x.x.x.x [.. configuración de la interfaz..] pre-up iptables-restore < /etc/iptables.up.rules You can optionally also setup a set of rules to be applied when the network interface is down creating a set of rules, saving it in /etc/iptables.down.rules and adding this directive to the interface configuration: post-down iptables-restore < /etc/iptables.down.rules For more advanced firewall configuration scripts through ifupdown you can use the hooks available to each interface as in the *.d/ directories called with run-parts (see run-parts(8) manual page). 5.14.3.4. Probar las configuración del cortafuegos Testing your firewall configuration is as easy, and as dangerous, as just running your firewall script (or enabling the configuration you defined in your firewall configuration application). However, if you are not careful enough and you are configuring your firewall remotely (like through an SSH connection) you could lock yourself out. There are several ways to prevent this. One is running a script in a separate terminal that will remove the firewall configuration if you don't feed it input. An example of this is: $ while true; do test=""; read -t 20 -p "OK? " test ; \ [ -z "$test" ] && /etc/init.d/firewall clear ; done Another one is to introduce a backdoor in your system through an alternate mechanism that allows you to either clear the firewall system or punch a hole in it if something goes awry. For this you can use knockd and configure it so that a certain port connection attempt sequence will clear the firewall (or add a temporary rule). Even though the packets will be dropped by the firewall, since knockd binds to the interface and sees you will be able to work around the problem. Testing a firewall that is protecting an internal network is a different issue, you will want to look at some of the tools used for remote vulnerability assessment (see Sección 8.1, “Herramientas de evaluación de vulnerabilidades remotas.”) to probe the network from the outside in (or from any other direction) to test the effectiveness of the firewall configuation. ------------------------------------------------------------------------ [36] Gdm will not append -nolisten tcp if it finds a -query or -indirect on the command line since the query wouldn't work. [37] To retrieve the list of mailer daemons available in Debian try: $ apt-cache search mail-transport-agent The list will not include qmail, which is distributed only as source code in the qmail-src package. [38] A list of servers/daemons which support these protocols in Debian can be retrieved with: $ apt-cache search pop3-server $ apt-cache search imap-server [39] Note that depending on your bind version you might not have the -g option, most notably if you are using bind9 in sarge (9.2.4 version). [40] This setup has not been tested for new release of Bind yet. [41] Unless you use the instdir option when calling dpkg but then the chroot jail might be a little more complex. [42] It does try to run them under minimum priviledge which includes running daemons with their own users instead of having them run as root. [43] Available since the kernel version 2.4 (which was the default kernel in Debian 3.0). Previous kernel versions (2.2, available in even older Debian releases) used ipchains. The main difference between ipchains and iptables is that the latter is based on stateful packet inspection which provides for more secure (and easier to build) filtering configurations. Older (and now unsupported) Debian distributions using the 2.0 kernel series needed the appropriate kernel patch. [44] Unlike personal firewalls in other operating systems, Debian GNU/Linux does not (yet) provide firewall generation interfaces that can make rules limiting them per process or user. However, the iptables code can be configured to do this (see the owner module in the iptables(8) manual page). Capítulo 6. Fortalecimiento automático de sistemas Debian ========================================================= Tras leer toda la información de los capítulos anteriores podría pensar «Tengo que hacer una gran cantidad de cosas para reforzar mi sistema, ¿no podrían hacerse estas cosas de forma automática?». La respuesta es sí, pero sea cuidadoso con las herramientas de automatización. Hay gente que cree que una herramienta de fortalecimiento no elimina la necesidad de una buena administración. Por tanto, no se engañe pensando que puede automatizar el proceso completo y con eso solucionar todos los asuntos relacionados. La seguridad es siempre un proceso activo en el cual el administrador tiene que participar y no limitarse a esperar a que las herramientas hagan todo el trabajo, puesto que ninguna herramienta individual puede arreglárselas por sí misma: con todas las posibles implementaciones de las directrices de seguridad, con todos los ataques y en todos los entornos. Desde woody (Debian 3.0) hay dos paquetes específicos, útiles para reforzar la seguridad. El paquete harden que realiza una aproximación basada en las dependencias del paquete para instalar rápidamente valiosos paquetes de seguridad y eliminar otros defectuosos, la configuración de los paquetes tiene que hacerla el administrador. El paquete bastille que implementa una política de seguridad dada en el sistema local basada en configuraciones anteriores del administrador (la configuración puede hacerse mediante un procedimiento guiado en el que se deberá ir contestando sí/no a preguntas sencillas). 6.1. Harden ----------- The harden package tries to make it more easy to install and administer hosts that need good security. This package should be used by people that want some quick help to enhance the security of the system. It automatically installs some tools that should enhance security in some way: intrusion detection tools, security analysis tools, etc. Harden installs the following virtual packages (i.e. no contents, just dependencies or recommendations on others): * harden-tools: herramientas para mejorar la seguridad del sistema (comprobadores de integridad, detección de intrusos, parches del núcleo...) * harden-environment: ayuda a configurar un sistema fortalecido (actualmente vacío). * harden-servers: elimina servidores considerados inseguros por alguna razón. * harden-clients: elimina clientes considerados inseguros por alguna razón. * harden-remoteaudit: herramientas para realizar auditorías de un sistema de forma remota. * harden-nids: helps to install a network intrusion detection system. * harden-surveillance: helps to install tools for monitoring of networks and services. Useful packages which are not a dependence: * harden-doc: provides this same manual and other security-related documentation packages. * harden-development: development tools for creating more secure programs. Vaya con cuidado, porque si tiene software que le resulte necesario (y no desea desinstalarlo por alguna razón) pero entra en conflicto con alguno de los paquetes mencionados anteriormente, podría implicar limitaciones en el uso de harden. Los paquetes «harden» no hacen nada (directamente). Sin embargo, tienen conflictos intencionados con paquetes conocidos como no seguros. De esta forma, el sistema de gestión de paquetes de Debian no aprobará la instalación de estos paquetes. Por ejemplo, si intenta instalar un demonio de telnet con harden-servers, apt dirá: # apt-get install telnetd Se ELIMINARÁN los siguientes paquetes: harden-servers Se instalarán los siguientes paquetes NUEVOS: telnetd ¿Quiere continuar? [S/n] Esto debería hacer saltar la alarma en la cabeza del administrador, llevándole a reconsiderar sus acciones. 6.2. Bastille Linux ------------------- http://www.bastille-unix.org es una herramienta de fortalecimiento automático orientada originalmente a las distribuciones RedHat y Mandrake. Sin embargo, el paquete bastille suministrado con Debian (desde woody) viene parcheado con objeto de proporcionar la misma funcionalidad en los sistemas Debian GNU/Linux. «Bastille» puede utilizarse con diferentes interfaces (todas documentadas en su correspondiente página de manual en el paquete de Debian) que permiten al administrador: * Answer questions step by step regarding the desired security of your system (using InteractuveBastille(8) * Utilizar un ajuste de seguridad predeterminado (entre tres opciones: Relajada, Moderada o Paranoia) en una configuración dada (servidor o estación de trabajo) y dejar que «Bastille» decida qué política de seguridad implementar (utilizar BastilleChooser(8)) * Take a predefined configuration file (could be provided by Bastille or made by the administrator) and implement a given security policy (using AutomatedBastille(8)). Capítulo 7. Infrastructura de seguridad de Debian ================================================= 7.1. Equipo de seguridad ------------------------ Debian has a Security Team, that handles security in the stable distribution. Handling security means they keep track of vulnerabilities that arise in software (watching forums such as Bugtraq, or vuln-dev) and determine if the stable distribution is affected by it. Also, the Debian Security Team is the contact point for problems that are coordinated by upstream developers or organizations such as http://www.cert.org which might affect multiple vendors. That is, when problems are not Debian-specific. The contact point of the Security Team is mailto:team@security.debian.org which only the members of the security team read. Sensitive information should be sent to the first address and, in some cases, should be encrypted with the Debian Security Contact key (as found in the Debian keyring). Once a probable problem is received by the Security Team it will investigate if the stable distribution is affected and if it is, a fix is made for the source code base. This fix will sometimes include backporting the patch made upstream (which usually is some versions ahead of the one distributed by Debian). After testing of the fix is done, new packages are prepared and published in the http://security.debian.org site so they can be retrieved through apt (see Sección 4.2, “Ejecute una actualización de seguridad”). At the same time a Debian Security Advisory (DSA) is published on the web site and sent to public mailing lists including http://lists.debian.org/debian-security-announce and Bugtraq. Puede encontrar algunas preguntas frecuentes acerca del Equipo de Seguridad en Sección 12.3, “Preguntas con respecto al equipo de seguridad Debian”. 7.2. Avisos de seguridad de Debian ---------------------------------- Debian Security Advisories (DSAs) are made whenever a security vulnerability is discovered that affects a Debian package. These advisories, signed by one of the Security Team members, include information of the versions affected as well as the location of the updates. This information is: * version number for the fix. * problem type. * whether it is remote or locally exploitable. * short description of the package. * descripciñon del problema * descripción de la forma de explotarlo. * descripción de la solución DSAs are published both on http://www.debian.org/ and in the http://www.debian.org/security/. Usually this does not happen until the website is rebuilt (every four hours) so they might not be present immediately. The preferred channel is the debian-security-announce mailing list. Interested users can, however (and this is done in some Debian-related portals) use the RDF channel to download automatically the DSAs to their desktop. Some applications, such as Evolution (an email client and personal information assistant) and Multiticker (a GNOME applet), can be used to retrieve the advisories automatically. The RDF channel is available at http://www.debian.org/security/dsa.rdf. DSAs published on the website might be updated after being sent to the public-mailing lists. A common update is adding cross references to security vulnerability databases. Also, translations[45] of DSAs are not sent to the security mailing lists but are directly included in the website. 7.2.1. Referencias cruzadas de vulnerabilidades Debian provides a fully http://www.debian.org/security/crossreferences including all the references available for all the advisories published since 1998. This table is provided to complement the http://cve.mitre.org/cve/refs/refmap/source-DEBIAN.html. You will notice that this table provides references to security databases such as http://www.securityfocus.com/bid, http://www.cert.org/advisories/ and http://www.kb.cert.org/vuls as well as CVE names (see below). These references are provided for convenience use, but only CVE references are periodically reviewed and included. Advantages of adding cross references to these vulnerability databases are: * it makes it easier for Debian users to see and track which general (published) advisories have already been covered by Debian. * system administrators can learn more about the vulnerability and its impact by following the cross references. * this information can be used to cross-check output from vulnerability scanners that include references to CVE to remove false positives (see Sección 12.1.2.1, “Vulnerability assessment scanner X says my Debian system is vulnerable!”). 7.2.2. CVE compatibility Debian Security Advisories were http://www.debian.org/security/CVE-certificate.jpg[46] in February 24, 2004. Debian developers understand the need to provide accurate and up to date information of the security status of the Debian distribution, allowing users to manage the risk associated with new security vulnerabilities. CVE enables us to provide standardized references that allow users to develop a https://cve.mitre.org/compatible/enterprise.html. The http://cve.mitre.org project is maintained by the MITRE Corporation and provides a list of standardized names for vulnerabilities and security exposures. Debian believes that providing users with additional information related to security issues that affect the Debian distribution is extremely important. The inclusion of CVE names in advisories help users associate generic vulnerabilities with specific Debian updates, which reduces the time spent handling vulnerabilities that affect our users. Also, it eases the management of security in an environment where CVE-enabled security tools -such as network or host intrusion detection systems, or vulnerability assessment tools- are already deployed regardless of whether or not they are based on the Debian distribution. Debian provides CVE names for all DSAs released since September 1998. All of the advisories can be retrieved on the Debian web site, and announcements related to new vulnerabilities include CVE names if available at the time of their release. Advisories associated with a given CVE name can be searched directly through the Debian Security Tracker (see below). In some cases you might not find a given CVE name in published advisories, for example because: * No Debian products are affected by that vulnerability. * There is not yet an advisory covering that vulnerability (the security issue might have been reported as a http://bugs.debian.org/cgi-bin/pkgreport.cgi?tag=security but a fix has not been tested and uploaded). * An advisory was published before a CVE name was assigned to a given vulnerability (look for an update at the web site). 7.3. Security Tracker --------------------- The central database of what the Debian security teams know about vulnerabilities is the http://security-tracker.debian.org. It cross references packages, vulnerable and fixed versions for different suites, CVE names, Debian bug numbers, DSA's and miscellaneous notes. It can be searched, e.g. by CVE name to see which Debian packages are affected or fixed, or by package to show unresolved security issues. The only information missing from the tracker is confidential information that the security team received under embargo. The package debsecan uses the information in the tracker to report to the administrator of a system which of the installed packages are vulnerable, and for which updates are available to fix security issues. 7.4. Debian Security Build Infrastructure ----------------------------------------- Since Debian is currently supported in a large number of architectures, administrators sometimes wonder if a given architecture might take more time to receive security updates than another. As a matter of fact, except for rare circumstances, updates are available to all architectures at the same time. Packages in the security archive are autobuilt, just like the regular archive. However, security updates are a little more different than normal uploads sent by package maintainers since, in some cases, before being published they need to wait until they can be tested further, an advisory written, or need to wait for a week or more to avoid publicizing the flaw until all vendors have had a reasonable chance to fix it. Thus, the security upload archive works with the following procedure: * Someone finds a security problem. * Someone fixes the problem, and makes an upload to security-master.debian.org's incoming (this someone is usually a Security Team member but can be also a package maintainer with an appropriate fix that has contacted the Security Team previously). The Changelog includes a testing-security or stable-security as target distribution. * The upload gets checked and processed by a Debian system and moved into queue/accepted, and the buildds are notified. Files in here can be accessed by the security team and (somewhat indirectly) by the buildds. * Security-enabled buildds pick up the source package (prioritized over normal builds), build it, and send the logs to the security team. * The security team reply to the logs, and the newly built packages are uploaded to queue/unchecked, where they're processed by a Debian system, and moved into queue/accepted. * When the security team find the source package acceptable (i.e., that it's been correctly built for all applicable architectures and that it fixes the security hole and doesn't introduce new problems of its own) they run a script which: * installs the package into the security archive. * updates the Packages, Sources and Release files of security.debian.org in the usual way (dpkg-scanpackages, dpkg-scansources, ...). * sets up a template advisory that the security team can finish off. * forwards the packages to the appropriate proposed-updates so that it can be included in the real archive as soon as possible. This procedure, previously done by hand, was tested and put through during the freezing stage of Debian 3.0 woody (July 2002). Thanks to this infrastructure the Security Team was able to have updated packages ready for the apache and OpenSSH issues for all the supported (almost twenty) architectures in less than a day. 7.4.1. Developer's guide to security updates Debian developers that need to coordinate with the security team on fixing in issue in their packages, can refer to the Developer's Reference section http://www.debian.org/doc/manuals/developers-reference/pkgs.html#bug-security. 7.5. Firma de paquete en Debian ------------------------------- This section could also be titled "how to upgrade/update safely your Debian GNU/Linux system" and it deserves its own section basically because it is an important part of the Security Infrastructure. Package signing is an important issue since it avoids tampering of packages distributed in mirrors and of downloads with man-in-the-middle attacks. Automatic software update is an important feature but it's also important to remove security threats that could help the distribution of trojans and the compromise of systems during updates [47] FIXME: probably the Internet Explorer vulnerability handling. certificate chains has an impact on security updates on Microsoft Windows. Debian does not provide signed packages but provides a mechanism available since Debian 4.0 (codename etch) to check for downloaded package's integrity[48]. For more information, see Sección 7.5.2, “Secure apt”. This issue is better described in the http://www.cryptnet.net/fdp/crypto/strong_distro.html by V. Alex Brennen. 7.5.1. El esquema propuesto para revisiones de firma de paquete The current scheme for package signature checking using apt is: * el archivo de publicación incluye el md5sum de Paquetes.gz (este contiene el md5sums de paquetes) y será firmado. La firma es algo que pertenece a una fuente de confianza. * This signed Release file is downloaded by 'apt-get update' and stored along with Packages.gz. * Cuando un paquete va a ser instalado, primero se baja, luego el md5sum es generado. * El archivo de publicación firmado es revisado (firma correcta) y este se extrae del md5sum para el archivo Paquetes.gz, el número de comprobación de Paquetes.gz es generado y (si es correcto) el md5sum del paquete que se bajó es extraido de este. * Si el md5sum del paquete que se bajó es el mismo que el del archivo Paquetes.gz, el paquete será instalado o de lo contrario el administrador será alertado y el paquete será dejado en cache (asi el administrador puede decidir si se instala o no). Si el paquete no está en los Paquetes.gz y el administrador ha configurado el sistema para instalar únicamente los paquetes revisados, éste tampoco será instalado. Adicional a esto, la cadena de Sums MD5 apt es capaz de verificar si un paquete se origina desde una publicación específica. Este es menos flexible que firmar paquete por paquete, pero puede ser combinado con este esquema también (véase más abajo). This scheme is http://lists.debian.org/debian-devel/2003/12/msg01986.html in apt 0.6 and is available since the Debian 4.0 release. For more information see Sección 7.5.2, “Secure apt”. Packages that provide a front-end to apt need to be modified to adapt to this new feature; this is the case of aptitude which was http://lists.debian.org/debian-devel/2005/03/msg02641.html to adapt to this scheme. Front-ends currently known to work properly with this feature include aptitude and synaptic. La firma de un paquete ha sido discutida en Debian de vez en cuando, para mayor información usted puede leer: http://www.debian.org/News/weekly/2001/8/ y http://www.debian.org/News/weekly/2001/11/. http://www.debian.org/News/weekly/2001/8/yhttp://www.debian.org/News/weekly/2000/11/. 7.5.2. Secure apt The apt 0.6 release, available since Debian 4.0 etch and later releases, includes apt-secure (also known as secure apt) which is a tool that will allow a system administrator to test the integrity of the packages downloaded through the above scheme. This release includes the tool apt-key for adding new keys to apt's keyring, which by default includes only the current Debian archive signing key. These changes are based on the patch for apt (available in http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=203741) which provides this implementation. Secure apt works by checking the distribution through the Release file, as discussed in Sección 7.5.3, “Per distribution release check”. Typically, this process will be transparent to the administrator although you will need to intervene every year[49] to add the new archive key when it is rotated, for more information on the steps an administrator needs to take a look at Sección 7.5.3.7, “Añadir de forma segura una clave”. This feature is still under development, if you believe you find bugs in it, please, make first sure you are using the latest version (as this package might change quite a bit before it is finally released) and, if running the latest version, submit a bug against the apt package. You can find more information at http://wiki.debian.org/SecureApt and the official documentation: http://www.enyo.de/fw/software/apt-secure/ and https://web.archive.org/web/20070206063141/http://www.syntaxpolice.org/apt-secure/. 7.5.3. Per distribution release check This section describes how the distribution release check mechanism works, it was written by Joey Hess and is also available at the http://wiki.debian.org/SecureApt. 7.5.3.1. Conceptos básicos Here are a few basic concepts that you'll need to understand for the rest of this section. A checksum is a method of taking a file and boiling it down to a reasonably short number that uniquely identifies the content of the file. This is a lot harder to do well than it might seem, and the most commonly used type of checksum, the MD5 sum, is in the process of being broken. Public key cryptography is based on pairs of keys, a public key and a private key. The public key is given out to the world; the private key must be kept a secret. Anyone possessing the public key can encrypt a message so that it can only be read by someone possessing the private key. It's also possible to use a private key to sign a file, not encrypt it. If a private key is used to sign a file, then anyone who has the public key can check that the file was signed by that key. No one who doesn't have the private key can forge such a signature. These keys are quite long numbers (1024 to 2048 digits or longer), and to make them easier to work with they have a key id, which is a shorter, 8 or 16 digit number that can be used to refer to them. gpg is the tool used in secure apt to sign files and check their signatures. apt-key is a program that is used to manage a keyring of gpg keys for secure apt. The keyring is kept in the file /etc/apt/trusted.gpg (not to be confused with the related but not very interesting /etc/apt/trustdb.gpg). apt-key can be used to show the keys in the keyring, and to add or remove a key. 7.5.3.2. Release checksums A Debian archive contains a Release file, which is updated each time any of the packages in the archive change. Among other things, the Release file contains some MD5 sums of other files in the archive. An excerpt of an example Release file: MD5Sum: 6b05b392f792ba5a436d590c129de21f 3453 Packages 1356479a23edda7a69f24eb8d6f4a14b 1131 Packages.gz 2a5167881adc9ad1a8864f281b1eb959 1715 Sources 88de3533bf6e054d1799f8e49b6aed8b 658 Sources.gz The Release files also include SHA-1 checksums, which will be useful once MD5 sums become fully broken, however apt doesn't use them yet. Now if we look inside a Packages file, we'll find more MD5 sums, one for each package listed in it. For example: Package: uqm Priority: optional ... Filename: unstable/uqm_0.4.0-1_i386.deb Size: 580558 MD5sum: 864ec6157c1eea88acfef44d0f34d219 These two checksums can be used to verify that you have downloaded a correct copy of the Packages file, with a md5sum that matches the one in the Release file. And when it downloads an individual package, it can also check its md5sum against the content of the Packages file. If apt fails at either of these steps, it will abort. None of this is new in secure apt, but it does provide the foundation. Notice that so far there is one file that apt doesn't have a way to check: The Release file. Secure apt is all about making apt verify the Release file before it does anything else with it, and plugging this hole, so that there is a chain of verification from the package that you are going to install all the way back to the provider of the package. 7.5.3.3. Verification of the Release file To verify the Release file, a gpg signature is added for the Release file. This is put in a file named Release.gpg that is shipped alongside the Release file. It looks something like this [50] , although only gpg actually looks at its contents normally: -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) iD8DBQBCqKO1nukh8wJbxY8RAsfHAJ9hu8oGNRAl2MSmP5+z2RZb6FJ8kACfWvEx UBGPVc7jbHHsg78EhMBlV/U= =x6og -----END PGP SIGNATURE----- 7.5.3.4. Check of Release.gpg by apt Secure apt always downloads Release.gpg files when it's downloading Release files, and if it cannot download the Release.gpg, or if the signature is bad, it will complain, and will make note that the Packages files that the Release file points to, and all the packages listed therein, are from an untrusted source. Here's how it looks during an apt-get update: W: GPG error: http://ftp.us.debian.org testing Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 010908312D230C5F Note that the second half of the long number is the key id of the key that apt doesn't know about, in this case that's 2D230C5F. If you ignore that warning and try to install a package later, apt will warn again: WARNING: The following packages cannot be authenticated! libglib-perl libgtk2-perl Install these packages without verification [y/N]? If you say Y here you have no way to know if the file you're getting is the package you're supposed to install, or if it's something else entirely that somebody that can intercept the communication against the server[51] has arranged for you, containing a nasty suprise. Note that you can disable these checks by running apt with --allow-unauthenticated. It's also worth noting that newer versions of the Debian installer use the same signed Release file mechanism during their debootstrap of the Debian base system, before apt is available, and that the installer even uses this system to verify pieces of itself that it downloads from the net. Also, Debian does not currently sign the Release files on its CDs; apt can be configured to always trust packages from CDs so this is not a large problem. 7.5.3.5. How to tell apt what to trust So the security of the whole system depends on there being a Release.gpg file, which signs a Release file, and of apt checking that signature using gpg. To check the signature, it has to know the public key of the person who signed the file. These keys are kept in apt's own keyring (/etc/apt/trusted.gpg), and managing the keys is where secure apt comes in. By default, Debian systems come preconfigured with the Debian archive key in the keyring. # apt-key list /etc/apt/trusted.gpg -------------------- pub 1024D/4F368D5D 2005-01-31 [expires: 2006-01-31] uid Debian Archive Automatic Signing Key (2005) Here 4F368D5D is the key id, and notice that this key was only valid for a one year period. Debian rotates these keys as a last line of defense against some sort of security breach breaking a key. That will make apt trust the official Debian archive, but if you add some other apt repository to /etc/apt/sources.list, you'll also have to give apt its key if you want apt to trust it. Once you have the key and have verified it, it's a simple matter of running apt-key add file to add it. Getting the key and verifying it are the trickier parts. 7.5.3.6. Finding the key for a repository The debian-archive-keyring package is used to distribute keys to apt. Upgrades to this package can add (or remove) gpg keys for the main Debian archive. For other archives, there is not yet a standard location where you can find the key for a given apt repository. There's a rough standard of putting the key up on the web page for the repository or as a file in the repository itself, but no real standard, so you might have to hunt for it. The Debian archive signing key is available at https://ftp-master.debian.org/keys.html.[52] gpg itself has a standard way to distribute keys, using a keyserver that gpg can download a key from and add it to its keyring. For example: $ gpg --keyserver pgpkeys.mit.edu --recv-key 2D230C5F gpg: solicitando clave 2D230C5F de servidor hkp pgpkeys.mit.edu gpg: key 2D230C5F: clave pública "Debian Archive Automatic Signing Key (2006) " importada gpg: cantidad total procesada: 1 gpg: importada: 1 You can then export that key from your own keyring and feed it to apt-key: $ gpg -a --export 2D230C5F | sudo apt-key add - gpg: no se encuentran claves absolutamente fiables OK The "gpg: no ultimately trusted keys found" warning means that gpg was not configured to ultimately trust a specific key. Trust settings are part of OpenPGPs Web-of-Trust which does not apply here. So there is no problem with this warning. In typical setups the user's own key is ultimately trusted. 7.5.3.7. Añadir de forma segura una clave By adding a key to apt's keyring, you're telling apt to trust everything signed by the key, and this lets you know for sure that apt won't install anything not signed by the person who possesses the private key. But if you're sufficiently paranoid, you can see that this just pushes things up a level, now instead of having to worry if a package, or a Release file is valid, you can worry about whether you've actually gotten the right key. Is the key file from https://ftp-master.debian.org/keys.html mentioned above really Debian's archive signing key, or has it been modified (or this document lies). It's good to be paranoid in security, but verifying things from here is harder. gpg has the concept of a chain of trust, which can start at someone you're sure of, who signs someone's key, who signs some other key, etc., until you get to the archive key. If you're sufficiently paranoid you'll want to check that your archive key is signed by a key that you can trust, with a trust chain that goes back to someone you know personally. If you want to do this, visit a Debian conference or perhaps a local LUG for a key signing [53]. If you can't afford this level of paranoia, do whatever feels appropriate to you when adding a new apt source and a new key. Maybe you'll want to mail the person providing the key and verify it, or maybe you're willing to take your chances with downloading it and assuming you got the real thing. The important thing is that by reducing the problem to what archive keys to trust, secure apt lets you be as careful and secure as it suits you to be. 7.5.3.8. Verifiación de la integridad de la clave You can verify the fingerprint as well as the signatures on the key. Retrieving the fingerprint can be done for multiple sources, you can talk to Debian Developers on IRC, read the mailing list where the key change will be announced or any other additional means to verify the fingerprint. For example you can do this: $ GET http://ftp-master.debian.org/ziyi_key_2006.asc | gpg --import gpg: key 2D230C5F: public key "Debian Archive Automatic Signing Key (2006) " imported gpg: Total number processed: 1 gpg: imported: 1 $ gpg --check-sigs --fingerprint 2D230C5F pub 1024D/2D230C5F 2006-01-03 [expires: 2007-02-07] Key fingerprint = 0847 50FC 01A6 D388 A643 D869 0109 0831 2D23 0C5F uid Debian Archive Automatic Signing Key (2006) sig!3 2D230C5F 2006-01-03 Debian Archive Automatic Signing Key (2006) sig! 2A4E3EAA 2006-01-03 Anthony Towns sig! 4F368D5D 2006-01-03 Debian Archive Automatic Signing Key (2005) sig! 29982E5A 2006-01-04 Steve Langasek sig! FD6645AB 2006-01-04 Ryan Murray sig! AB2A91F5 2006-01-04 James Troup and then as in Sección 7.5, “Firma de paquete en Debian” check the trust path from your key (or a key you trust) to at least one of the keys used to sign the archive key. If you are sufficiently paranoid you will tell apt to trust the key only if you find an acceptable path: $ gpg --export -a 2D230C5F | sudo apt-key add - Ok Note that the key is signed with the previous archive key, so theoretically you can just build on your previous trust. 7.5.3.9. Debian archive key yearly rotation As mentioned above, the Debian archive signing key is changed each year, in January. Since secure apt is young, we don't have a great deal of experience with changing the key and there are still rough spots. In January 2006, a new key for 2006 was made and the Release file began to be signed by it, but to try to avoid breaking systems that had the old 2005 key, the Release file was signed by that as well. The intent was that apt would accept one signature or the other depending on the key it had, but apt turned out to be buggy and refused to trust the file unless it had both keys and was able to check both signatures. This was fixed in apt version 0.6.43.1. There was also confusion about how the key was distributed to users who already had systems using secure apt; initially it was uploaded to the web site with no announcement and no real way to verify it and users were forced to download it by hand. In January 2006, a new key for 2006 was made and the Release file began to be signed by it, but to try to avoid breaking systems that had the old 2005 key, the Release file was signed by that as well. In order to prevent confusion on the best distribution mechanism for users who already have systems using secure apt, the debian-archive-keyring package was introduced, which manages apt keyring updates. 7.5.3.10. Known release checking problems One not so obvious problem is that if your clock is very far off, secure apt will not work. If it's set to a date in the past, such as 1999, apt will fail with an unhelpful message such as this: W: GPG error: http://archive.progeny.com sid Release: Unknown error executing gpg Although apt-key list will make the problem plain: gpg: la clave 2D230C5F fue creada 192324901 segundos en el futuro (viaje en el tiempo o problemas con el reloj) gpg: la clave 2D230C5F fue creada 192324901 segundos en el futuro (viaje en el tiempo o problemas con el reloj) pub 1024D/2D230C5F 2006-01-03 uid Debian Archive Automatic Signing Key (2006) If it's set to a date too far in the future, apt will treat the keys as expired. Another problem you may encouter if using testing or unstable is that if you have not run apt-get update lately and apt-get install a package, apt might complain that it cannot be authenticated (why does it do this?). apt-get update will fix this. 7.5.3.11. Manual per distribution release check In case you want to add now the additional security checks and don't want or cannot run the latest apt version[54] you can use the script below, provided by Anthony Towns. This script can automatically do some new security checks to allow the user to be sure that the software s/he's downloading matches the software Debian's distributing. This stops Debian developers from hacking into someone's system without the accountability provided by uploading to the main archive, or mirrors mirroring something almost, but not quite like Debian, or mirrors providing out of date copies of unstable with known security problems. Esta muestra de código renombrada como apt-release-check, debería ser usada de la siguiente manera: # apt-get update # apt-release-check (...resultados...) # apt-get dist-upgrade Primero usted necesita: * get the keys the archive software uses to sign Release files from https://ftp-master.debian.org/keys.html and add them to ~/.gnupg/trustedkeys.gpg (which is what gpgv uses by default). gpg --no-default-keyring --keyring trustedkeys.gpg --import ziyi_key_2006.asc * remover algunas /etc/apt/sources.list líneas que no utilizanla estructura normal de distribuciones, o cambie el script de modo que este trabaje con ellas. * estar preparado para ignorar que las actualizaciones de seguridad Debian no hayan firmado archivos de publicaciones, y que los archivos de Fuente no tengan la suma de comprobaciones en el archivo de Publicación (aun). * prepárese para verificar que las fuentes apropiadas son firmadas con las llaves propicias. This is the example code for apt-check-sigs, the latest version can be retrieved from http://people.debian.org/~ajt/apt-check-sigs. This code is currently in beta, for more information read http://lists.debian.org/debian-devel/2002/07/msg00421.html. #!/bin/bash # This script is copyright (c) 2001, Anthony Towns # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. rm -rf /tmp/apt-release-check mkdir /tmp/apt-release-check || exit 1 cd /tmp/apt-release-check />OK />MISSING />NOCHECK />BAD arch=`dpkg --print-installation-architecture` am_root () { [ `id -u` -eq 0 ] } get_md5sumsize () { cat "$1" | awk '/^MD5Sum:/,/^SHA1:/' | MYARG="$2" perl -ne '@f = split /\s+/; if ($f[3] eq $ENV{"MYARG"}) { print "$f[1] $f[2]\n"; exit(0); }'} checkit () { local FILE="$1" local LOOKUP="$2" Y="`get_md5sumsize Release "$LOOKUP"`" Y="`echo "$Y" | sed 's/^ *//;s/ */ /g'`" if [ ! -e "/var/lib/apt/lists/$FILE" ]; then if [ "$Y" = "" ]; then # No file, but not needed anyway echo "OK" return fi echo "$FILE" >>MISSING echo "MISSING $Y" return fi if [ "$Y" = "" ]; then echo "$FILE" >>NOCHECK echo "NOCHECK" return fi X="`md5sum < /var/lib/apt/lists/$FILE` `wc -c < /var/lib/apt/lists/$FILE`" X="`echo "$X" | sed 's/^ *//;s/ */ /g'`" if [ "$X" != "$Y" ]; then echo "$FILE" >>BAD echo "BAD" return fi echo "$FILE" >>OK echo "OK" } echo echo "Checking sources in /etc/apt/sources.list:" echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" echo (echo "You should take care to ensure that the distributions you're downloading" echo "are the ones you think you are downloading, and that they are as up to" echo "date as you would expect (testing and unstable should be no more than" echo "two or three days out of date, stable-updates no more than a few weeks" echo "or a month)." ) | fmt echo cat /etc/apt/sources.list | sed 's/^ *//' | grep '^[^#]' | while read ty url dist comps; do if [ "${url%%:*}" = "http" -o "${url%%:*}" = "ftp" ]; then baseurl="${url#*://}" else continue fi echo "Source: ${ty} ${url} ${dist} ${comps}" rm -f Release Release.gpg wget -q -O Release "${url}/dists/${dist}/Release" if ! grep -q '^' Release; then echo " * NO TOP-LEVEL Release FILE" else origline=`sed -n 's/^Origin: *//p' Release | head -1` lablline=`sed -n 's/^Label: *//p' Release | head -1` suitline=`sed -n 's/^Suite: *//p' Release | head -1` codeline=`sed -n 's/^Codename: *//p' Release | head -1` dateline=`grep "^Date:" Release | head -1` dscrline=`grep "^Description:" Release | head -1` echo " o Origin: $origline/$lablline" echo " o Suite: $suitline/$codeline" echo " o $dateline" echo " o $dscrline" if [ "${dist%%/*}" != "$suitline" -a "${dist%%/*}" != "$codeline" ]; then echo " * WARNING: asked for $dist, got $suitline/$codeline" fi wget -q -O Release.gpg "${url}/dists/${dist}/Release.gpg" sigline="`gpgv --status-fd 3 Release.gpg Release 3>&1 >/dev/null 2>&1 | sed -n "s/^\[GNUPG:\] GOODSIG [0-9A-Fa-f]* //p"`" if [ "$sigline" ]; then echo " o Signed by: $sigline" else echo " * NO VALID SIGNATURE" >Release fi fi okaycomps="" for comp in $comps; do if [ "$ty" = "deb" ]; then X=$(checkit "`echo "${baseurl}/dists/${dist}/${comp}/binary-${arch}/Release" | sed 's,//*,_,g'`" "${comp}/binary-${arch}/Release") Y=$(checkit "`echo "${baseurl}/dists/${dist}/${comp}/binary-${arch}/Packages" | sed 's,//*,_,g'`" "${comp}/binary-${arch}/Packages") if [ "$X $Y" = "OK OK" ]; then okaycomps="$okaycomps $comp" else echo " * PROBLEMS WITH $comp ($X, $Y)" fi elif [ "$ty" = "deb-src" ]; then X=$(checkit "`echo "${baseurl}/dists/${dist}/${comp}/source/Release" | sed 's,//*,_,g'`" "${comp}/source/Release") Y=$(checkit "`echo "${baseurl}/dists/${dist}/${comp}/source/Sources" | sed 's,//*,_,g'`" "${comp}/source/Sources") if [ "$X $Y" = "OK OK" ]; then okaycomps="$okaycomps $comp" else echo " * PROBLEMS WITH component $comp ($X, $Y)" fi fi done [ "$okaycomps" = "" ] || echo " o Okay:$okaycomps" echo done echo "Results" echo "~~~~~~~" echo allokay=true cd /tmp/apt-release-check diff <(cat BAD MISSING NOCHECK OK | sort) <(cd /var/lib/apt/lists && find . -type f -maxdepth 1 | sed 's,^\./,,g' | grep '_' | sort) | sed -n 's/^> //p' />UNVALIDATEDcd /tmp/apt-release-check if grep -q ^ UNVALIDATED; then allokay=false (echo "The following files in /var/lib/apt/lists have not been validated." echo "This could turn out to be a harmless indication that this script" echo "is buggy or out of date, or it could let trojaned packages get onto" echo "your system." ) | fmt echo sed 's/^/ /' < UNVALIDATED echo fi if grep -q ^ BAD; then allokay=false (echo "The contents of the following files in /var/lib/apt/lists does not" echo "match what was expected. This may mean these sources are out of date," echo "that the archive is having problems, or that someone is actively" echo "using your mirror to distribute trojans." if am_root; then echo "The files have been renamed to have the extension .FAILED and" echo "will be ignored by apt." cat BAD | while read a; do mv /var/lib/apt/lists/$a /var/lib/apt/lists/${a}.FAILED done fi) | fmt echo sed 's/^/ /' < BAD echo fi if grep -q ^ MISSING; then allokay=false (echo "The following files from /var/lib/apt/lists were missing. This" echo "may cause you to miss out on updates to some vulnerable packages." ) | fmt echo sed 's/^/ /' < MISSING echo fi if grep -q ^ NOCHECK; then allokay=false (echo "The contents of the following files in /var/lib/apt/lists could not" echo "be validated due to the lack of a signed Release file, or the lack" echo "of an appropriate entry in a signed Release file. This probably" echo "means that the maintainers of these sources are slack, but may mean" echo "these sources are being actively used to distribute trojans." if am_root; then echo "The files have been renamed to have the extension .FAILED and" echo "will be ignored by apt." cat NOCHECK | while read a; do mv /var/lib/apt/lists/$a /var/lib/apt/lists/${a}.FAILED done fi) | fmt echo sed 's/^/ /' < NOCHECK echo fi if $allokay; then echo 'Everything seems okay!' echo fi rm -rf /tmp/apt-release-check You might need to apply the following patch for sid since md5sum adds an '-' after the sum when the input is stdin: @@ -37,7 +37,7 @@ local LOOKUP="$2" Y="`get_md5sumsize Release "$LOOKUP"`" - Y="`echo "$Y" | sed 's/^ *//;s/ */ /g'`" + Y="`echo "$Y" | sed 's/-//;s/^ *//;s/ */ /g'`" if [ ! -e "/var/lib/apt/lists/$FILE" ]; then if [ "$Y" = "" ]; then @@ -55,7 +55,7 @@ return fi X="`md5sum < /var/lib/apt/lists/$FILE` `wc -c < /var/lib/apt/lists/$FILE`" - X="`echo "$X" | sed 's/^ *//;s/ */ /g'`" + X="`echo "$X" | sed 's/-//;s/^ *//;s/ */ /g'`" if [ "$X" != "$Y" ]; then echo "$FILE" >>BAD echo "BAD" 7.5.4. Release check of non Debian sources Notice that, when using the latest apt version (with secure apt) no extra effort should be required on your part unless you use non-Debian sources, in which case an extra confirmation step will be required by apt-get. This is avoided by providing Release and Release.gpg files in the non-Debian sources. The Release file can be generated with apt-ftparchive (available in apt-utils 0.5.0 and later), the Release.gpg is just a detached signature. To generate both follow this simple procedure: $ rm -f dists/unstable/Release $ apt-ftparchive release dists/unstable > dists/unstable/Release $ gpg --sign -ba -o dists/unstable/Release.gpg dists/unstable/Release 7.5.5. Alternativa firmar esquema por paquete El esquema adicional de firmar cada uno y todos los paquetes, permite que estos sean revisados cuando no son tan referenciados por un archivo de Paquetes existentes, además, los paquetes tercera-persona donde nunca existieron Paquetes para que estos también puedan ser usados en Debian, sin embargo, no serán un esquema por defecto. This package signing scheme can be implemented using debsig-verify and debsigs. These two packages can sign and verify embedded signatures in the .deb itself. Debian already has the capability to do this now, but there is no feature plan to implement the policy or other tools since the archive signing scheme is prefered. These tools are available for users and archive administrators that would rather use this scheme instead. Latest dpkg versions (since 1.9.21) incorporate a http://lists.debian.org/debian-dpkg/2001/03/msg00024.html that provides this functionality as soon as debsig-verify is installed. NOTA: Normalmente /etc/dpkg/dpkg.cfg se desmonta con "no-debsig" como por defecto. NOTE2: Signatures from developers are currently stripped when they enter off the package archive since the currently preferred method is release checks as described previously. ------------------------------------------------------------------------ [45] Translations are available in up to ten different languages. [46] The full http://cve.mitre.org/compatible/phase2/SPI_Debian.html is available at CVE [47] Some operating systems have already been plagued with automatic-updates problems such as the http://www.cunap.com/~hardingr/projects/osx/exploit.html. [48] Older releases, such as Debian 3.1 sarge can use this feature by using backported versions of this package management tool [49] Until an automatic mechanism is developed. [50] Technically speaking, this is an ASCII-armored detached gpg signature. [51] Or has poisoned your DNS, or is spoofing the server, or has replaced the file in the mirror you are using, etc. [52] "ziyi" is the name of the tool used for signing on the Debian servers, the name is based on the name of a http://en.wikipedia.org/wiki/Zhang_Ziyi. [53] Not all apt repository keys are signed at all by another key. Maybe the person setting up the repository doesn't have another key, or maybe they don't feel comfortable signing such a role key with their main key. For information on setting up a key for a repository see Sección 7.5.4, “Release check of non Debian sources”. [54] Either because you are using the stable, sarge, release or an older release or because you don't want to use the latest apt version, although we would really appreciate testing of it. Capítulo 8. Herramientas de seguridad en Debian =============================================== ARRÉGLAME: Se necesita más contenido. Debian provides also a number of security tools that can make a Debian box suited for security purposes. These purposes include protection of information systems through firewalls (either packet or application-level), intrusion detection (both network and host based), vulnerability assessment, antivirus, private networks, etc. Since Debian 3.0 (woody), the distribution features cryptographic software integrated into the main distribution. OpenSSH and GNU Privacy Guard are included in the default install, and strong encryption is now present in web browsers and web servers, databases, and so forth. Further integration of cryptography is planned for future releases. This software, due to export restrictions in the US, was not distributed along with the main distribution but included only in non-US sites. 8.1. Herramientas de evaluación de vulnerabilidades remotas. ------------------------------------------------------------ The tools provided by Debian to perform remote vulnerability assessment are: [55] * nessus * raccess * nikto (whisker's replacement) De lejos, la herramienta más completa y actualizada es nessus, que se compone de un cliente (nessus), que es el IGU, y un servidor (nessusd), el cual lanza los ataques programados. Nessus incluye vulnerabilidades remotas para un amplio número de sistemas incluyendo aplicaciones de red, servidores ftp, servidores www, etc. Los últimos accesorios de seguridad son capaces de analizar un sitio web y tratar de descubrir, de las páginas interactivas disponibles, las que se podrían atacar. También hay clientes Java y para Win32 (no se incluyen en Debian) que se pueden usar para conectar con el servidor. nikto is a web-only vulnerability assessment scanner including anti-IDS tactics (most of which are not anti-IDS anymore). It is one of the best cgi-scanners available, being able to detect a WWW server and launch only a given set of attacks against it. The database used for scanning can be easily modified to provide for new information. 8.2. Herramientas de escáner de red ----------------------------------- Debian proporciona algunas herramientas utilizadas para el análisis remoto de anfitriones (pero sin evaluación de vulnerabilidades). Estas herramientas, en algunos casos, las utilizan los escáneres de evaluación de vulnerabilidades como el primer tipo de «ataque» ejecutado contra anfitriones remotos en un intento por determinar los servicios remotos disponibles. Actualmente Debian proporciona: * nmap * xprobe * p0f * knocker * isic * hping2 * icmpush * nbtscan (for SMB /NetBIOS audits) * fragrouter * strobe (in the netdiag package) * irpas Mientras que queso y xprobe proporcionan únicamente detección de sistemas operativos remotos (utilizando TCP/IP fingerprinting[56]), nmap y knocker realizan detección de sistemas operativos y escaneo de puertos de anfitriones remotos. Por otro lado, hping2 y icmpush se pueden utilizar en técnicas de ataques remotos ICMP. Diseñado específicamente para redes SMB, nbtscan puede utilizarse para escanear redes IP y obtener información sobre servidores con SMB habilitado, incluyendo: nombres de usuarios, nombres de red, direcciones MAC... On the other hand, fragrouter can be used to test network intrusion detection systems and see if the NIDS can be eluded by fragmentation attacks. FIXME: Check http://bugs.debian.org/153117 (ITP fragrouter) to see if it's included. FIXME add information based on https://web.archive.org/web/20040725013857/http://www.giac.org/practical/gcux/Stephanie_Thomas_GCUX.pdf which describes how to use Debian and a laptop to scan for wireless (803.1) networks (link not there any more). 8.3. Auditorías internas ------------------------ En la actualidad, tiger es la única herramienta utilizada en Debian que sirve para ejecutar auditorías internas (también llamadas «White box») de anfitriones con el fin de determinar si el sistema de ficheros está configurado correctamente, qué procesos están escuchando en el anfitrión, etc. 8.4. Auditorías de código fuente -------------------------------- Debian proporciona tres paquetes que sirven para auditar programas con código fuente C/C++ y encontrar errores de programación que pueden conducir a potenciales grietas de seguridad: * flawfinder * rats * splint * pscan 8.5. Redes virtuales privadas ----------------------------- A virtual private network (VPN) is a group of two or more computer systems, typically connected to a private network with limited public network access, that communicate securely over a public network. VPNs may connect a single computer to a private network (client-server), or a remote LAN to a private network (server-server). VPNs often include the use of encryption, strong authentication of remote users or hosts, and methods for hiding the private network's topology. Debian proporciona unos cuantos paquetes para configurar redes privadas virtuales cifradas: * vtun * tunnelv (non-US section) * cipe-source, cipe-common * tinc * secvpn * pptpd * openvpn * openswan (http://www.openswan.org/) FIXME: Update the information here since it was written with FreeSWAN in mind. Check Bug #237764 and Message-Id: <200412101215.04040.rmayr@debian.org>. The OpenSWAN package is probably the best choice overall, since it promises to interoperate with almost anything that uses the IP security protocol, IPsec (RFC 2411). However, the other packages listed above can also help you get a secure tunnel up in a hurry. The point to point tunneling protocol (PPTP) is a proprietary Microsoft protocol for VPN. It is supported under Linux, but is known to have serious security issues. For more information see the http://www.tldp.org/HOWTO/VPN-Masquerade-HOWTO.html (covers IPsec and PPTP), http://www.tldp.org/HOWTO/VPN-HOWTO.html (covers PPP over SSH), http://www.tldp.org/HOWTO/mini/Cipe+Masq.html, and http://www.tldp.org/HOWTO/mini/ppp-ssh/index.html. Also worth checking out is http://yavipin.sourceforge.net/, but no Debian packages seem to be available yet. 8.5.1. Point to Point tunneling If you want to provide a tunneling server for a mixed environment (both Microsoft operating systems and Linux clients) and IPsec is not an option (since it's only provided for Windows 2000 and Windows XP), you can use PoPToP (Point to Point Tunneling Server), provided in the pptpd package. If you want to use Microsoft's authentication and encryption with the server provided in the ppp package, note the following from the FAQ: It is only necessary to use PPP 2.3.8 if you want Microsoft compatible MSCHAPv2/MPPE authentication and encryption. The reason for this is that the MSCHAPv2/MPPE patch currently supplied (19990813) is against PPP 2.3.8. If you don't need Microsoft compatible authentication/encryption any 2.3.x PPP source will be fine. However, you also have to apply the kernel patch provided by the kernel-patch-mppe package, which provides the pp_mppe module for pppd. Take into account that the encryption in ppptp forces you to store user passwords in clear text, and that the MS-CHAPv2 protocol contains http://mopo.informatik.uni-freiburg.de/pptp_mschapv2/. 8.6. Infraestructura de clave pública (ICP). -------------------------------------------- Public Key Infrastructure (PKI) is a security architecture introduced to provide an increased level of confidence for exchanging information over insecure networks. It makes use of the concept of public and private cryptographic keys to verify the identity of the sender (signing) and to ensure privacy (encryption). Cuando se considera una ICP, usted se enfrenta a un amplia variedad de cuestiones: * una Autoridad certificadora (AC) que pueda resolver y verificar certificados, y que trabaje bajo una jerarquía dada. * un directorio para soportar los certificados públicos de usuarios * una base de datos (?) para mantener las listas de revocación de certificados (LRC) * dispositivos que interactúen con el AC con el fin de imprimir en tarjetas inteligentes/unidades USB/cualquier cosa que almacene certificados de forma segura * programas listos para usar certificados emitidos por una AC para unirse en comunicaciones cifradas y comprobar certificados contra LRC (para autenticación y soluciones completas de inicio de sesión) * una autoridad de marcas de tiempo para firmar documentos digitalmente * una consola de administración desde la cual se puedan utilizar apropiadamente todos estos (generación de certificados, control de lista de revocaciones, etc...) Debian GNU/Linux has software packages to help you with some of these PKI issues. They include OpenSSL (for certificate generation), OpenLDAP (as a directory to hold the certificates), gnupg and openswan (with X.509 standard support). However, as of the Woody release (Debian 3.0), Debian does not have any of the freely available Certificate Authorities such as pyCA, http://www.openca.org or the CA samples from OpenSSL. For more information read the http://ospkibook.sourceforge.net/. 8.7. SSL Infrastructure ----------------------- Debian does provide some SSL certificates with the distribution so that they can be installed locally. They are found in the ca-certificates package. This package provides a central repository of certificates that have been submitted to Debian and approved (that is, verified) by the package maintainer, useful for any OpenSSL applications which verify SSL connections. FIXME: read debian-devel to see if there was something added to this. 8.8. Herramientas antivirus --------------------------- There are not many anti-virus tools included with Debian GNU/Linux, probably because GNU/Linux users are not plagued by viruses. The Unix security model makes a distinction between privileged (root) processes and user-owned processes, therefore a "hostile" executable that a non-root user receives or creates and then executes cannot "infect" or otherwise manipulate the whole system. However, GNU/Linux worms and viruses do exist, although there has not (yet, hopefully) been any that has spread in the wild over any Debian distribution. In any case, administrators might want to build up anti-virus gateways that protect against viruses arising on other, more vulnerable systems in their network. Debian GNU/Linux currently provides the following tools for building antivirus environments: * http://www.clamav.net, provided since Debian sarge (3.1 release). Packages are provided both for the virus scanner (clamav) for the scanner daemon (clamav-daemon) and for the data files needed for the scanner. Since keeping an antivirus up-to-date is critical for it to work properly there are two different ways to get this data: clamav-freshclam provides a way to update the database through the Internet automatically and clamav-data which provides the data files directly. [57] * mailscanner an e-mail gateway virus scanner and spam detector. Using sendmail or exim as its basis, it can use more than 17 different virus scanning engines (including clamav). * libfile-scan-perl which provides File::Scan, a Perl extension for scanning files for viruses. This modules can be used to make platform independent virus scanners. * http://www.sourceforge.net/projects/amavis, provided in the package amavis-ng and available in sarge, which is a mail virus scanner which integrates with different MTA (Exim, Sendmail, Postfix, or Qmail) and supports over 15 virus scanning engines (including clamav, File::Scan and openantivirus). * http://packages.debian.org/sanitizer, a tool that uses the procmail package, which can scan email attachments for viruses, block attachments based on their filenames, and more. * http://packages.debian.org/amavis-postfix, a script that provides an interface from a mail transport agent to one or more commercial virus scanners (this package is built with support for the postfix MTA only). * exiscan, an e-mail virus scanner written in Perl that works with Exim. * blackhole-qmail a spam filter for Qmail with built-in support for Clamav. Some gateway daemons support already tools extensions to build antivirus environments including exim4-daemon-heavy (the heavy version of the Exim MTA), frox (a transparent caching ftp proxy server), messagewall (an SMTP proxy daemon) and pop3vscan (a transparent POP3 proxy). Debian currently provide clamav as the only antivirus scanning software in the main official distribution and it also provides multiple interfaces to build gateways with antivirus capabilities for different protocols. Some other free software antivirus projects which might be included in future Debian GNU/Linux releases:http://sourceforge.net/projects/openantivirus/ (see http://bugs.debian.org/150698 and http://bugs.debian.org/150695 ). FIXME: Is there a package that provides a script to download the latest virus signatures from http://www.openantivirus.org/latest.php? FIXME: Check if scannerdaemon is the same as the open antivirus scanner daemon (read ITPs). However, Debian will never provide propietary (non-free and undistributable) antivirus software such as: Panda Antivirus, NAI Netshield, http://www.sophos.com/, http://www.antivirus.com, or http://www.ravantivirus.com. For more pointers see the http://www.computer-networking.de/~link/security/av-linux_e.txt. This does not mean that this software cannot be installed properly in a Debian system[58]. For more information on how to set up a virus detection system read Dave Jones' article https://web.archive.org/web/20120509212938/http://www.linuxjournal.com/article/4882. 8.9. GPG agent -------------- It is very common nowadays to digitally sign (and sometimes encrypt) e-mail. You might, for example, find that many people participating on mailing lists sign their list e-mail. Public key signatures are currently the only means to verify that an e-mail was sent by the sender and not by some other person. Debian GNU/Linux provides a number of e-mail clients with built-in e-mail signing capabilities that interoperate either with gnupg or pgp: * evolution. * mutt. * kmail. * icedove (rebranded version of Mozilla's Thunderbird) through the http://enigmail.mozdev.org/ plugin. This plugin is provided by the enigmail package. * sylpheed. Depending on how the stable version of this package evolves, you may need to use the bleeding edge version, sylpheed-claws. * gnus, which when installed with the mailcrypt package, is an emacs interface to gnupg. * kuvert, which provides this functionality independently of your chosen mail user agent (MUA) by interacting with the mail transport agent (MTA). Key servers allow you to download published public keys so that you may verify signatures. One such key server is http://wwwkeys.pgp.net. gnupg can automatically fetch public keys that are not already in your public keyring. For example, to configure gnupg to use the above key server, edit the file ~/.gnupg/options and add the following line: [59] keyserver wwwkeys.pgp.net Most key servers are linked, so that when your public key is added to one server, the addition is propagated to all the other public key servers. There is also a Debian GNU/Linux package debian-keyring, that provides all the public keys of the Debian developers. The gnupg keyrings are installed in /usr/share/keyrings/. Más información en: * http://www.gnupg.org/faq.html. * http://www.gnupg.org/gph/en/manual.html. * https://web.archive.org/web/20080201103530/http://www.dewinter.com/gnupg_howto/english/GPGMiniHowto.html. * https://web.archive.org/web/20080513095235/http://www.uk.pgp.net/pgpnet/pgp-faq/. * https://web.archive.org/web/20060222110131/http://www.cryptnet.net/fdp/crypto/gpg-party.html. ------------------------------------------------------------------------ [55] Some of them are provided when installing the harden-remoteaudit package. [56] Sin embargo, la base de datos de fingerprinting de Queso es bastante antigua [57] If you use this last package and are running an official Debian, the database will not be updated with security updates. You should either use clamav-freshclam, clamav-getfiles to generate new clamav-data packages or update from the maintainers location: deb http://people.debian.org/~zugschlus/clamav-data/ / deb-src http://people.debian.org/~zugschlus/clamav-data/ / [58] Actually, there is an installer package for the F-prot antivirus, which is non-free but gratis for home users, called f-prot-installer. This installer, however, just downloads http://www.f-prot.com/products/home_use/linux/ and installs it in the system. [59] For more examples of how to configure gnupg check /usr/share/doc/mutt/examples/gpg.rc. Capítulo 9. Developer's Best Practices for OS Security ====================================================== This chapter introduces some best secure coding practices for developers writing Debian packages. If you are really interested in secure coding I recommend you read David Wheeler's http://www.dwheeler.com/secure-programs/ and http://www.securecoding.org by Mark G. Graff and Kenneth R. van Wyk (O'Reilly, 2003). 9.1. Best practices for security review and design -------------------------------------------------- Developers that are packaging software should make a best effort to ensure that the installation of the software, or its use, does not introduce security risks to either the system it is installed on or its users. In order to do so, they should make their best to review the source code of the package and detect any flaws that might introduce security bugs before releasing the software or distributing a new version. It is acknowledged that the cost of fixing bugs grows for different stages of its development, so it is easier (and cheaper) to fix bugs when designing than when the software has been deployed and is in maintenance mode (some studies say that the cost in this later phase is sixty times higher). Although there are some tools that try to automatically detect these flaws, developers should strive to learn about the different kind of security flaws in order to understand them and be able to spot them in the code they (or others) have written. The programming bugs which lead to security bugs typically include: http://en.wikipedia.org/wiki/Buffer_overflow, format string overflows, heap overflows and integer overflows (in C/C++ programs), temporary http://en.wikipedia.org/wiki/Symlink_race (in scripts), http://en.wikipedia.org/wiki/Directory_traversal and command injection (in servers) and http://en.wikipedia.org/wiki/Cross_site_scripting, and http://en.wikipedia.org/wiki/SQL_injection (in the case of web-oriented applications). For a more complete information on security bugs review Fortify's http://vulncat.fortifysoftware.com/. Some of these issues might not be easy to spot unless you are an expert in the programming language the software uses, but some security problems are easy to detect and fix. For example, finding temporary race conditions due to misuse of temporary directories can easily be done just by running grep -r "/tmp/" .. Those calls can be reviewed and replace the hardcoded filenames using temporary directories to calls to either mktemp or tempfile in shell scripts, File::Temp(3perl) in Perl scripts, or tmpfile(3) in C/C++. There are a set of tools available to assist to the security code review phase. These include rats, flawfinder and pscan. For more information, read the http://www.debian.org/security/audit/tools. When packaging software developers have to make sure that they follow common security principles, including: * The software runs with the minimum privileges it needs: * The package does install binaries setuid or setgid. Lintian will warn of http://lintian.debian.org/reports/Tsetuid-binary.html, http://lintian.debian.org/reports/Tsetgid-binary.html and http://lintian.debian.org/reports/Tsetuid-gid-binary.html binaries. * The daemons the package provide run with a low privilege user (see Sección 9.2, “Creating users and groups for software daemons”) * Programmed (i.e., cron) tasks running in the system do NOT run as root or, if they do, do not implement complex tasks. If you have to do any of the above make sure the programs that might run with higher privileges have been audited for security bugs. If you are unsure, or need help, contact the http://www.debian.org/security/audit/. In the case of setuid/setgid binaries, follow the Debian policy section regarding http://www.debian.org/doc/debian-policy/ch-files.html#s10.9 For more information, specific to secure programming, make sure you read (or point your upstream to) http://www.dwheeler.com/secure-programs/ and the https://buildsecurityin.us-cert.gov/portal/ portal. 9.2. Creating users and groups for software daemons --------------------------------------------------- If your software runs a daemon that does not need root privileges, you need to create a user for it. There are two kind of Debian users that can be used by packages: static uids (assigned by base-passwd, for a list of static users in Debian see Sección 12.1.1.12, “Usuarios y grupos del sistema operativo”) and dynamic uids in the range assigned to system users. In the first case, you need to ask for a user or group id to the base-passwd. Once the user is available there the package needs to be distributed including a proper versioned depends to the base-passwd package. In the second case, you need to create the system user either in the preinst or in the postinst and make the package depend on adduser (>= 3.11). The following example code creates the user and group the daemon will run as when the package is installed or upgraded: [...] case "$1" in install|upgrade) # If the package has default file it could be sourced, so that # the local admin can overwrite the defaults [ -f "/etc/default/packagename" ] && . /etc/default/packagename # Sane defaults: [ -z "$SERVER_HOME" ] && SERVER_HOME=server_dir [ -z "$SERVER_USER" ] && SERVER_USER=server_user [ -z "$SERVER_NAME" ] && SERVER_NAME="Server description" [ -z "$SERVER_GROUP" ] && SERVER_GROUP=server_group # Groups that the user will be added to, if undefined, then none. ADDGROUP="" # create user to avoid running server as root # 1. create group if not existing if ! getent group | grep -q "^$SERVER_GROUP:" ; then echo -n "Adding group $SERVER_GROUP.." addgroup --quiet --system $SERVER_GROUP 2>/dev/null ||true echo "..done" fi # 2. create homedir if not existing test -d $SERVER_HOME || mkdir $SERVER_HOME # 3. create user if not existing if ! getent passwd | grep -q "^$SERVER_USER:"; then echo -n "Adding system user $SERVER_USER.." adduser --quiet \ --system \ --ingroup $SERVER_GROUP \ --no-create-home \ --disabled-password \ $SERVER_USER 2>/dev/null || true echo "..done" fi # 4. adjust passwd entry usermod -c "$SERVER_NAME" \ -d $SERVER_HOME \ -g $SERVER_GROUP \ $SERVER_USER # 5. adjust file and directory permissions if ! dpkg-statoverride --list $SERVER_HOME >/dev/null then chown -R $SERVER_USER:adm $SERVER_HOME chmod u=rwx,g=rxs,o= $SERVER_HOME fi # 6. Add the user to the ADDGROUP group if test -n $ADDGROUP then if ! groups $SERVER_USER | cut -d: -f2 | \ grep -qw $ADDGROUP; then adduser $SERVER_USER $ADDGROUP fi fi ;; configure) [...] You have to make sure that the init.d script file: * Starts the daemon dropping privileges: if the software does not do the setuid(2) or seteuid(2) call itself, you can use the --chuid call of start-stop-daemon. * Stops the daemon only if the user id matches, you can use the start-stop-daemon --user option for this. * Does not run if either the user or the group do not exist: if ! getent passwd | grep -q "^ server_user :"; then echo "Server user does not exist. Aborting" >&2 exit 1 fi if ! getent group | grep -q "^ server_group :" ; then echo "Server group does not exist. Aborting" >&2 exit 1 fi If the package creates the system user it can remove it when it is purged in its postrm. This has some drawbacks, however. For example, files created by it will be orphaned and might be taken over by a new system user in the future if it is assigned the same uid[60]. Consequently, removing system users on purge is not yet mandatory and depends on the package needs. If unsure, this action could be handled by asking the administrator for the prefered action when the package is installed (i.e. through debconf). Maintainers that want to remove users in their postrm scripts are referred to the deluser/deluser --system option. Running programs with a user with limited privileges makes sure that any security issue will not be able to damage the full system. It also follows the principle of least privilege. Also consider you can limit privileges in programs through other mechanisms besides running as non-root[61]. For more information, read the http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/minimize-privileges.html chapter of the Secure Programming for Linux and Unix HOWTO book. ------------------------------------------------------------------------ [60] Some relevant threads discussing these drawbacks include http://lists.debian.org/debian-mentors/2004/10/msg00338.html and http://lists.debian.org/debian-devel/2004/05/msg01156.html [61] You can even provide a SELinux policy for it Capítulo 10. Antes del compromiso ================================= 10.1. Sistema seguro -------------------- You should strive to keep your system secure by monitoring its usage and also the vulnerabilities that might affect it, patching them as soon as patches are available. Even though you might have installed a really secure system initially you have to remember that security in a system degrades with time, security vulnerabilities might be found for exposed system services and users might expose the system security either because of lack of understanding (e.g. accessing a system remotely with a clear-text protocol or using easy to guess passwords) or because they are actively trying to subvert the system's security (e.g. install additional services locally on their accounts). 10.1.1. Tracking security vulnerabilities Although most administrators are aware of security vulnerabilities affecting their systems when they see a patch that is made available you can strive to keep ahead of attacks and introduce temporary countermeasures for security vulnerabilities by detecting when your system is vulnerable. This is specially true when running an exposed system (i.e. connected to the Internet) and providing a service. In such case the system's administrators should take care to monitor known information sources to be the first to know when a vulnerability is detected that might affect a critical service. This typically includes subscribing to the announcement mailing lists, project websites or bug tracking systems provided by the software developers for a specific piece of code. For example, Apache users should regularly review Apache's http://httpd.apache.org/security_report.html and subscribe to the http://httpd.apache.org/lists.html#http-announce mailing list. In order to track known vulnerabilities affecting the Debian distribution, the Debian Testing Security Team provides a https://security-tracker.debian.org/ that lists all the known vulnerabilities which have not been yet fixed in Debian packages. The information in that tracker is obtained through different public channels and includes known vulnerabilities which are available either through security vulnerability databases or http://www.debian.org/Bugs/. Administrators can search for the known security issues being tracked for https://security-tracker.debian.org/tracker/status/release/stable, https://security-tracker.debian.org/tracker/status/release/oldstable, https://security-tracker.debian.org/tracker/status/release/testing, or https://security-tracker.debian.org/tracker/status/release/unstable. The tracker has searchable interfaces (by http://cve.mitre.org/ name and package name) and some tools (such as debsecan, see Sección 10.1.2.4, “Automatically checking for security issues with debsecan”) use that database to provide information of vulnerabilities affecting a given system which have not yet been addressed (i.e. those who are pending a fix). Concious administrators can use that information to determine which security bugs might affect the system they are managing, determine the severity of the bug and apply (if available) temporary countermeasures before a patch is available fixing this issue. Security issues tracked for releases supported by the Debian Security Team should eventually be handled through Debian Security Advisories (DSA) and will be available for all users (see Sección 10.1.2, “Continuously update the system”). Once security issues are fixed through an advisory they will not be available in the tracker, but you will be able to search security vulnerabilities (by CVE name) using the http://www.debian.org/security/crossreferences available for published DSAs. Notice, however, that the information tracked by the Debian Testing Security Team only involves disclosed vulnerabilities (i.e. those already public). In some occasions the Debian Security Team might be handling and preparing DSAs for packages based on undisclosed information provided to them (for example, through closed vendor mailing lists or by upstream maintainers of software). So do not be surprised to find security issues that only show up as an advisory but never get to show up in the security tracker. 10.1.2. Continuously update the system You should conduct security updates frequently. The vast majority of exploits result from known vulnerabilities that have not been patched in time, as this http://www.cs.umd.edu/~waa/vulnerability.html (presented at the 2001 IEEE Symposium on Security and Privacy) explains. Updates are described under Sección 4.2, “Ejecute una actualización de seguridad”. 10.1.2.1. Manually checking which security updates are available Debian does have a specific tool to check if a system needs to be updated but many users will just want to manually check if any security updates are available for their system. If you have configured your system as described in Sección 4.2, “Ejecute una actualización de seguridad” you just need to do: # apt-get update # apt-get upgrade -s [ ... review packages to be upgraded ... ] # apt-get upgrade # checkrestart [ ... restart services that need to be restarted ... ] And restart those services whose libraries have been updated if any. Note: Read Sección 4.2, “Ejecute una actualización de seguridad” for more information on library (and kernel) upgrades. The first line will download the list of packages available from your configured package sources. The -s will do a simulation run, that is, it will not download or install the packages but rather tell you which ones should be downloaded/installed. From the output you can derive which packages have been fixed by Debian and are available as a security update. Sample: # apt-get upgrade -s Reading Package Lists... Done Building Dependency Tree... Done 2 packages upgraded, 0 newly installed, 0 to remove and 0 not upgraded. Inst cvs (1.11.1p1debian-8.1 Debian-Security:3.0/stable) Inst libcupsys2 (1.1.14-4.4 Debian-Security:3.0/stable) Conf cvs (1.11.1p1debian-8.1 Debian-Security:3.0/stable) Conf libcupsys2 (1.1.14-4.4 Debian-Security:3.0/stable) In this example, you can see that the system needs to be updated with new cvs and cupsys packages which are being retrieved from woody's security update archive. If you want to understand why these packages are needed, you should go to http://security.debian.org and check which recent Debian Security Advisories have been published related to these packages. In this case, the related DSAs are https://lists.debian.org/debian-security-announce/2003/msg00014.html (for cvs) and https://lists.debian.org/debian-security-announce/2003/msg00013.html (for cupsys). Notice that you will need to reboot your system if there has been a kernel upgrade. 10.1.2.2. Checking for updates at the Desktop Since Debian 4.0 lenny Debian provides and installs in a default installation update-notifier. This is a GNOME application that will startup when you enter your Desktop and can be used to keep track of updates available for your system and install them. It uses update-manager for this. In a stable system updates are only available when a security patch is available or at point releases. Consequently, if the system is properly configured to receive security updates as described in Sección 4.2, “Ejecute una actualización de seguridad” and you have a cron task running to update the package information you will be notified through an icon in the desktop notifcation area. The notification is not intrusive and users are not forced to install updates. From the notification icon a desktop user (with the administrator's password) can access a simple GUI to show available updates and install them. This application works by checking the package database and comparing the system with its contents. If the package database is updated periodically through a cron task then the contents of the database will be newer than the packages installed in the system and the application will notify you. Apt installs such a task (/etc/cron.d/apt) which will run based on Apt's configuration (more specifically APT::Periodic). In the GNOME environment this configuration value can be adjusted by going to System > Admin > Software origins > Updates, or running /usr/bin/software-properties. If the system is set to download the packages list daily but not download the packages themselves your /etc/apt/apt.conf.d/10periodic should look like this: APT::Periodic::Update-Package-Lists "1"; APT::Periodic::Download-Upgradeable-Packages "0"; You can use a different cron task, such as the one installed by cron-apt (see Sección 10.1.2.3, “Automatically checking for updates with cron-apt”). You can also just manually check for upgrades using this application. Users of the KDE desktop environment will probably prefer to install adept and adept-notifier instead which offers a similar functionality but is not part of the standard installation. 10.1.2.3. Automatically checking for updates with cron-apt Another method for automatic security updates is the use of cron-apt. This package provides a tool to update the system at regular intervals (using a cron job), and can also be configured to send mails to the system administrator using the local mail transport agent. It will just update the package list and download new packages by default but it can be configured to automatically install new updates. Notice that you might want to check the distribution release, as described in Sección 7.5.3, “Per distribution release check”, if you intend to automatically updated your system (even if only downloading the packages). Otherwise, you cannot be sure that the downloaded packages really come from a trusted source. More information is available at the http://www.debian-administration.org/articles/162. 10.1.2.4. Automatically checking for security issues with debsecan The debsecan program evaluates the security status of by reporting both missing security updates and security vulnerabilities. Unlike cron-apt, which only provides information related to security updates available, but this tool obtains information from the security vulnerability database maintained by the Debian Security Team which includes also information on vulnerabilities which are not yet fixed through a security update. Consequently, it is more efficient at helping administrators track security vulnerabilities (as described in Sección 10.1.1, “Tracking security vulnerabilities”). Upon installing the Debian package debsecan, and if the administrator consents to it, it will generate a cron task that will make it run and send the output to a specific user whenever it finds a vulnerable package. It will also download the information from the Internet. The location of the security database is also part of the questions ask on installation and are later defined /etc/default/debsecan, it can be easily adjusted for systems that do not have Internet access so that they all pull from a local mirror so that there is a single point that access the vulnerability database. Notice, however, that the Security Team tracks many vulnerabilities including low-risk issues which might not be fixed through a security update and some vulnerabilities initially reported as affecting Debian might, later on, upon investigation, be dismissed. Debsecan will report on all the vulnerabilities, which makes it a quite more verbose than the other tools described above. More information is available at the http://www.enyo.de/fw/software/debsecan/. 10.1.2.5. Other methods for security updates There is also the apticron, which, similarly to cron-apt will check for updates and send mails to the administrator. More information on apticron is available at the http://www.debian-administration.org/articles/491. You might also want to take a look at http://clemens.endorphin.org/secpack/ which is an unofficial program to do security updates from security.debian.org with signature checking written by Fruhwirth Clemens. Or to the Nagios Plugin http://www.unixdaemon.net/nagios_plugins.html#check_debian_packages written by Dean Wilson. 10.1.3. Avoid using the unstable branch Unless you want to dedicate time to patch packages yourself when a vulnerability arises, you should not use Debian's unstable branch for production-level systems. The main reason for this is that there are no security updates for unstable. The fact is that some security issues might appear in unstable and not in the stable distribution. This is due to new functionality constantly being added to the applications provided there, as well as new applications being included which might not yet have been thoroughly tested. In order to do security upgrades in the unstable branch, you might have to do full upgrades to new versions (which might update much more than just the affected package). Although there have been some exceptions, security patches are usually only back ported into the stable branch. The main idea being that between updates, no new code should be added, just fixes for important issues. Notice, however, that you can use the security tracker (as described in Sección 10.1.1, “Tracking security vulnerabilities”) to track known security vulnerabilities affecting this branch. 10.1.4. Security support for the testing branch If you are using the testing branch, there are some issues that you must take into account regarding the availability of security updates: * When a security fix is prepared, the Security Team backports the patch to stable (since stable is usually some minor or major versions behind). Package maintainers are responsible for preparing packages for the unstable branch, usually based on a new upstream release. Sometimes the changes happen at nearly the same time and sometimes one of the releases gets the security fix before. Packages for the stable distribution are more thoroughly tested than unstable, since the latter will in most cases provide the latest upstream release (which might include new, unknown bugs). * Security updates are available for the unstable branch usually when the package maintainer makes a new package and for the stable branch when the Security Team make a new upload and publish a DSA. Notice that neither of these change the testing branch. * If no (new) bugs are detected in the unstable version of the package, it moves to testing after several days. The time this takes is usually ten days, although that depends on the upload priority of the change and whether the package is blocked from entering testing by its dependency relationships. Note that if the package is blocked from entering testing the upload priority will not change the time it takes to enter. This behavior might change based on the release state of the distribution. When a release is almost imminent, the Security Team or package maintainers might provide updates directly to testing. Additionally, the http://secure-testing-master.debian.net can issue Debian Testing Security Advisories (DTSAs) for packages in the testing branch if there is an immediate need to fix a security issue in that branch and cannot wait for the normal procedure (or the normal procedure is being blocked by some other packages). Users willing to take advantage of this support should add the following lines to their /etc/apt/sources.list (instead of the lines described in Sección 4.2, “Ejecute una actualización de seguridad”): deb http://security.debian.org testing/updates main contrib non-free # This line makes it possible to donwload source packages too deb-src http://security.debian.org testing/updates main contrib non-free For additional information on this support please read the http://lists.debian.org/debian-devel-announce/2006/05/msg00006.html. This support officially started in http://lists.debian.org/debian-devel-announce/2005/09/msg00006.html in a separate repository and was later integrated into the main security archive. 10.1.5. Automatic updates in a Debian GNU/Linux system First of all, automatic updates are not fully recommended, since administrators should review the DSAs and understand the impact of any given security update. If you want to update your system automatically you should: * Configure apt so that those packages that you do not want to update stay at their current version, either with apt's pinning feature or marking them as hold with aptitude or dpkg. To pin the packages under a given release, you must edit /etc/apt/preferences (see apt_preferences(5)) and add: Package: * Pin: release a=stable Pin-Priority: 100 FIXME: verify if this configuration is OK. * Either use cron-apt as described in Sección 10.1.2.3, “Automatically checking for updates with cron-apt” and enable it to install downloaded packages or add a cron entry yourself so that the update is run daily, for example: apt-get update && apt-get -y upgrade The -y option will have apt assume 'yes' for all the prompts that might arise during the update. In some cases, you might want to use the --trivial-only option instead of the --assume-yes (equivalent to -y).[62] * Configure debconf so no questions will be asked during upgrades, so that they can be done non-interactively. [63] * Check the results of the cron execution, which will be mailed to the superuser (unless changed with MAILTO environment variable in the script). A safer alternative might be to use the -d (or --download-only) option, which will download but not install the necessary packages. Then if the cron execution shows that the system needs to be updated, it can be done manually. In order to accomplish any of these tasks, the system must be properly configured to download security updates as discussed in Sección 4.2, “Ejecute una actualización de seguridad”. However, this is not recommended for unstable without careful analysis, since you might bring your system into an unusable state if some serious bug creeps into an important package and gets installed in your system. Testing is slightly more secure with regard to this issue, since serious bugs have a better chance of being detected before the package is moved into the testing branch (although, you may have no security updates available whatsoever). If you have a mixed distribution, that is, a stable installation with some packages updated to testing or unstable, you can fiddle with the pinning preferences as well as the --target-release option in apt-get to update only those packages that you have updated.[64] 10.2. Do periodic integrity checks ---------------------------------- Based on the baseline information you generated after installation (i.e. the snapshot described in Sección 4.19, “Taking a snapshot of the system”), you should be able to do an integrity check from time to time. An integrity check will be able to detect filesystem modifications made by an intruder or due to a system administrators mistake. Integrity checks should be, if possible, done offline.[65] That is, without using the operating system of the system to review, in order to avoid a false sense of security (i.e. false negatives) produced by, for example, installed rootkits. The integrity database that the system is checked against should also be used from read-only media. You can consider doing integrity checks online using any of the filesystem integrity tools available (described in Sección 4.17.3, “Integridad de su sistema de archivos”) if taking offline the system is not an option. However, precaution should be taken to use a read-only integrity database and also assure that the integrity checking tool (and the operating system kernel) has not been tampered with. Some of the tools mentioned in the integrity tools section, such as aide, integrit or samhain are already prepared to do periodic reviews (through the crontab in the first two cases and through a standalone daemon in samhain) and can warn the administrator through different channels (usually e-mail, but samhain can also send pages, SNMP traps or syslog alerts) when the filesystem changes. Of course, if you execute a security update of the system, the snapshot taken for the system should be re-taken to accommodate the changes done by the security update. 10.3. Montar el descubrimiento de intrusión ------------------------------------------- Debian GNU/Linux includes tools for intrusion detection, which is the practice of detecting inappropriate or malicious activity on your local system, or other systems in your private network. This kind of defense is important if the system is very critical or you are truly paranoid. The most common approaches to intrusion detection are statistical anomaly detection and pattern-matching detection. Siempre debe darse cuenta que para mejorar realmente el sistema de seguridad con la introducción de algunas de estas herramientas, usted necesitara tener un mecanismo de alerta+respuesta, pero no use el descubrimiento de intrusión si usted no va a alertar a nadie (i.e. no malgaste su tiempo configurando cosas que mas tarde no usara). When a particular attack has been detected, most intrusion detection tools will either log the event with syslogd or send e-mail to the root user (the mail recipient is usually configurable). An administrator has to properly configure the tools so that false positives do not trigger alerts. Alerts may also indicate an ongoing attack and might not be useful, say, one day later, since the attack might have already succeeded. So be sure that there is a proper policy on handling alerts and that the technical mechanisms to implement this policy are in place. An interesting source of information is http://www.cert.org/tech_tips/intruder_detection_checklist.html 10.3.1. Detección de intrusos basadas en la máquina Network based intrusion detection tools monitor the traffic on a network segment and use this information as a data source. Specifically, the packets on the network are examined, and they are checked to see if they match a certain signature. snort is a flexible packet sniffer or logger that detects attacks using an attack signature dictionary. It detects a variety of attacks and probes, such as buffer overflows, stealth port scans, CGI attacks, SMB probes, and much more. snort also has real-time alerting capability. You can use snort for a range of hosts on your network as well as for your own host. This is a tool which should be installed on every router to keep an eye on your network. Just install it with apt-get install snort, follow the questions, and watch it log. For a little broader security framework, see http://www.prelude-ids.org. Snort en Debian está habilitado con muchos chequeos de seguridad los cuales usted debe solicitar, sin embargo, usted debe personalizar el montaje para tomarlo dentro de las consideraciones de servicios particulares en donde usted avanza sobre su sistema. Usted también tiene que solicitarlo para recuperar los chequeos adicionales y asi especificar estos servicios. There are other, simpler tools that can be used to detect network attacks. portsentry is an interesting package that can tip you off to port scans against your hosts. Other tools like ippl or iplogger will also detect some IP (TCP and ICMP) attacks, even if they do not provide the kind of advanced techniques snort does. You can test any of these tools with the Debian package idswakeup, a shell script which generates false alarms, and includes many common attack signatures. 10.3.2. Detección de intrusos basadas en la máquina Host based intrusion detection involves loading software on the system to be monitored which uses log files and/or the systems auditing programs as a data source. It looks for suspicious processes, monitors host access, and may even monitor changes to critical system files. tiger is an older intrusion detection tool which has been ported to Debian since the Woody branch. tiger provides checks of common issues related to security break-ins, like password strength, file system problems, communicating processes, and other ways root might be compromised. This package includes new Debian-specific security checks including: MD5sums checks of installed files, locations of files not belonging to packages, and analysis of local listening processes. The default installation sets up tiger to run each day, generating a report that is sent to the superuser about possible compromises of the system. Log analysis tools, such as logcheck can also be used to detect intrusion attempts. See Sección 4.13.1, “Uso y personalización de logcheck”. In addition, packages which monitor file system integrity (see Sección 4.17.3, “Integridad de su sistema de archivos”) can be quite useful in detecting anomalies in a secured environment. It is most likely that an effective intrusion will modify some files in the local file system in order to circumvent local security policy, install Trojans, or create users. Such events can be detected with file system integrity checkers. 10.4. Evitando rootkits ----------------------- 10.4.1. LKM - Loadable Kernel Modules (módulos cargables en el núcleo) Loadable kernel modules are files containing dynamically loadable kernel components used to expand the functionality of the kernel. The main benefit of using modules is the ability to add additional devices, like an Ethernet or sound card, without patching the kernel source and recompiling the entire kernel. However, crackers are now using LKMs for root-kits (knark and adore), opening up back doors in GNU/Linux systems. LKM back doors are more sophisticated and less detectable than traditional root-kits. They can hide processes, files, directories and even connections without modifying the source code of binaries. For example, a malicious LKM can force the kernel into hiding specific processes from procfs, so that even a known good copy of the binary ps would not list accurate information about the current processes on the system. 10.4.2. Detector de rootkits. There are two approaches to defending your system against LKM root-kits, a proactive defense and a reactive defense. The detection work can be simple and painless, or difficult and tiring, depending on the approach taken. 10.4.2.1. Defensa proactiva. The advantage of this kind of defense is that it prevents damage to the system in the first place. One such strategy is getting there first, that is, loading an LKM designed to protect the system from other malicious LKMs. A second strategy is to remove capabilities from the kernel itself. For example, you can remove the capability of loadable kernel modules entirely. Note, however, that there are rootkits which might work even in this case, there are some that tamper with /dev/kmem (kernel memory) directly to make themselves undetectable. Debian GNU/Linux has a few packages that can be used to mount a proactive defense: lcap - A user friendly interface to remove capabilities (kernel-based access control) in the kernel, making the system more secure. For example, executing lcap CAP_SYS_MODULE[66] will remove module loading capabilities (even for the root user).[67] There is some (old) information on capabilities at Jon Corbet's http://lwn.net/1999/1202/kernel.php3 section on LWN (dated December 1999). If you don't really need many kernel features on your GNU/Linux system, you may want to disable loadable modules support during kernel configuration. To disable loadable module support, just set CONFIG_MODULES=n during the configuration stage of building your kernel, or in the .config file. This will prevent LKM root-kits, but you lose this powerful feature of the Linux kernel. Also, disabling loadable modules can sometimes overload the kernel, making loadable support necessary. 10.4.2.2. Defensa Reactiva. The advantage of a reactive defense is that it does not overload system resources. It works by comparing the system call table with a known clean copy in a disk file, System.map. Of course, a reactive defense will only notify the system administrator after the system has already been compromised. Detection of some root-kits in Debian can be accomplished with the chkrootkit package. The http://www.chkrootkit.org program checks for signs of several known root-kits on the target system, but is not a definitive test. 10.5. Ideas geniales/paranóicas — qué debe hacer ------------------------------------------------ This is probably the most unstable and funny section, since I hope that some of the "duh, that sounds crazy" ideas might be realized. The following are just some ideas for increasing security - maybe genius, paranoid, crazy or inspired depending on your point of view. * Jugando alrededor con PAM. Como se dijo en el articulo phrack 56 PAM , lo agradable con PAM es que "usted está limitado únicamente por lo que pueda pensar" es verdad, imagine la raíz del inicio de sesión únicamente posible con revisión de impresión o eyescan o cryptocard (porque yo aqui hago una conjunción OR y no AND). * Iniciación de sesión fascista. Yo diria que que todo lo que nosotros hemos hablado acerca de login es "un sueve inicio de sesión". si usted quiere ejecutar una sesión real, tome una impresora con papel fanfold y registre todo lo complicado para imprimir sobre el.Los sonidos divertidos, son confiables y no pueden ser removidos. * CD distribution. This idea is very easy to realize and offers pretty good security. Create a hardened Debian distribution, with proper firewall rules. Turn it into a boot-able ISO image, and burn it on a CDROM. Now you have a read-only distribution, with about 600 MB space for services. Just make sure all data that should get written is done over the network. It is impossible for intruders to get read/write access on this system, and any changes an intruder does make can be disabled with a reboot of the system. * El Switch de capacidad del modulo apagado. Cuando desconecta el uso de modulos del núcleo en un tiempo compilado del núcleo, muchos núcleo se basan en puertas traseras imposibles para poder implementarlas, ya que muchos de ellos estan basados en la instalación de modulos modificados del núcleo. * Entrando a través del cable serial (contribuido por Gaby Schilders). Dado que que los servidores aun tienen puertos en serie, imagínese tener una máquina de registro de bitácoras desconectada de su red en la mitad con un puerto serial multiplexor (antiquisimo o algo similar). Ahora todos sus servidores registrando a sus puertos seriales. Con sólo escritura. la máquina de registo únicamente acepta texto plano como entrada sobre sus puertos seriales y únicamente escribe en un archivo de registro. Enganche un cd/dvd writer. Cuando el registro del archivo está cerca de 600 MB lo copia al cd-rom. Ahora si pudieran hacer quemadoras con auto-cambiadores ... No copia tan dura como la impreosra, pero que puede manejar largos volúmenes y los cd no toman mucho espacio de almacenamiento. * Change file attributes using chattr (taken from the Tips-HOWTO, written by Jim Dennis). After a clean install and initial configuration, use the chattr program with the +i attribute to make files unmodifiable (the file cannot be deleted, renamed, linked or written to). Consider setting this attribute on all the files in /bin, /sbin/, /usr/bin, /usr/sbin, /usr/lib and the kernel files in root. You can also make a copy of all files in /etc/, using tar or the like, and mark the archive as immutable. La razón para todo es limitar el daño que usted pueda ocasionar cuando se registyra como root. Usted no podra sobreescribir archivos con un desviado operador de redirecciones, usted no podra hacer del sitema algo inusual con un desviado espacio dentro de un comando rm -fr (usted puede permancer haciendo lo suficiente con los daños de sus datos - pero sus binarios y librerías estarán seguros). Ésta también emplea una variedad de seguridad y rechazo de servicios de cualquier imposible explosión o algo de mayor dificultad (ya que muchos de ellos confian en sobre copiar archivos a través de las acciones de algun programa SUIDque no suministra arbitrariamente una interfase de comandos) El único inconveniente de este es cuando se construye y se hace su make install sobre varias clases de sistemas binarios. Sobre la otra mano también previene la instalación desde los archivos sobre escritos. Cuando usted olvida leer el Makefile y chattr -i los archivos que pueden ser sobre escritos fallan con el make (y los directorios para los cuales usted necesita para añadir archivos), usted solo use el comando chattr y regrese. Usted también puede tener la oportuinidad de mover sus viejos bins, libs o lo que sea dentro de un old/directory o puede renombrar, marcar o lo que sea. Note que esto lo previene de hacer una actualización de los paquetes de su sistema. Dado que los archivos que ellos suministran no pueden ser sobre escritos, y usted debe tener un mecanismo para desactivar la bandera de inmutable sobre todos los binarios antes de un apt-get update. * Play with UTP cabling in a way that you cut 2 or 4 wires and make the cable one-way traffic only. Then use UDP packets to send information to the destination machine which can act as a secure log server or a credit card storage system. 10.5.1. Construyendo un equipo trampa A honeypot is a system designed to teach system administrators how crackers probe for and exploit a system. It is a system setup with the expectation and goal that the system will be probed, attacked and potentially exploited. By learning the tools and methods employed by the cracker, a system administrator can learn to better protect their own systems and network. Debian GNU/Linux systems can easily be used to setup a honeynet, if you dedicate the time to implement and monitor it. You can easily setup the fake honeypot server as well as the firewall[68] that controls the honeynet and some sort of network intrusion detector, put it on the Internet, and wait. Do take care that if the system is exploited, you are alerted in time (see Sección 4.13, “La importancia de logs y alarmas”) so that you can take appropriate measures and terminate the compromise when you've seen enough. Here are some of the packages and issues to consider when setting up your honeypot: * la tecnología del cortafuegos usted la debera necesitar (suministrado por Linux Kernel). * syslog-ng, useful for sending logs from the honeypot to a remote syslog server. * snort para montar la captura de todo la llegada del trafico de red para honeypot y para detectar ataques. * osh, a SETUID root, security enhanced, restricted shell with logging (see Lance Spitzner's article below). * Of course, all the daemons you will be using for your fake server honeypot. Depending on what type of attacker you want to analyse you will or will not harden the honeypot and keep it up to date with security patches. * Chequeadores integrales (vea check-integ) y los toolkit de Coroners y (tct) para hacer una auditoria de post ataque. * honeyd and farpd to setup a honeypot that will listen to connections to unused IP addresses and forward them to scripts simulating live services. Also check out iisemulator. * tinyhoneypot to setup a simple honeypot server with fake services. If you cannot use spare systems to build up the honeypots and the network systems to protect and control it you can use the virtualisation technology available in xen or uml (User-Mode-Linux). If you take this route you will need to patch your kernel with either kernel-patch-xen or kernel-patch-uml. You can read more about building honeypots in Lanze Spitzner's excellent article http://www.net-security.org/text/articles/spitzner/honeypot.shtml (from the Know your Enemy series). Also, the http://project.honeynet.org/ provides valuable information about building honeypots and auditing the attacks made on them. ------------------------------------------------------------------------ [62] You may also want to use the --quiet (-q) option to reduce the output of apt-get, which will stop the generation of any output if no packages are installed. [63] Note that some packages might not use debconf and updates will stall due to packages asking for user input during configuration. [64] This is a common issue since many users want to maintain a stable system while updating some packages to unstable to gain the latest functionality. This need arises due to some projects evolving faster than the time between Debian's stable releases. [65] An easy way to do this is using a Live CD, such as http://www.knoppix-std.org/ which includes both the file integrity tools and the integrity database for your system. [66] There are over 28 capabilities including: CAP_BSET, CAP_CHOWN, CAP_FOWNER, CAP_FSETID, CAP_FS_MASK, CAP_FULL_SET, CAP_INIT_EFF_SET, CAP_INIT_INH_SET, CAP_IPC_LOCK, CAP_IPC_OWNER, CAP_KILL, CAP_LEASE, CAP_LINUX_IMMUTABLE, CAP_MKNOD, CAP_NET_ADMIN, CAP_NET_BIND_SERVICE, CAP_NET_RAW, CAP_SETGID, CAP_SETPCAP, CAP_SETUID, CAP_SYS_ADMIN, CAP_SYS_BOOT, CAP_SYS_CHROOT, CAP_SYS_MODULE, CAP_SYS_NICE, CAP_SYS_PACCT, CAP_SYS_PTRACE, CAP_SYS_RAWIO, CAP_SYS_RESOURCE, CAP_SYS_TIME, and CAP_SYS_TTY_CONFIG. All of them can be de-activated to harden your kernel. [67] You don't need to install lcap to do this, but it's easier than setting /proc/sys/kernel/cap-bound by hand. [68] You will typically use a bridge firewall so that the firewall itself is not detectable, see Sección B.4, “Setting up a bridge firewall ”. Capítulo 11. After the compromise (incident response) ===================================================== 11.1. Comportamiento general ---------------------------- If you are physically present when an attack is happening, your first response should be to remove the machine from the network by unplugging the network card (if this will not adversely affect any business transactions). Disabling the network at layer 1 is the only true way to keep the attacker out of the compromised box (Phillip Hofmeister's wise advice). However, some tools installed by rootkits, trojans and, even, a rogue user connected through a back door, might be capable of detecting this event and react to it. Seeing a rm -rf / executed when you unplug the network from the system is not really much fun. If you are unwilling to take the risk, and you are sure that the system is compromised, you should unplug the power cable (all of them if more than one) and cross your fingers. This may be extreme but, in fact, will avoid any logic-bomb that the intruder might have programmed. In this case, the compromised system should not be re-booted. Either the hard disks should be moved to another system for analysis, or you should use other media (a CD-ROM) to boot the system and analyze it. You should not use Debian's rescue disks to boot the system, but you can use the shell provided by the installation disks (remember, Alt+F2 will take you to it) to analyze [69] the system. The most recommended method for recovering a compromised system is to use a live-filesystem on CD-ROM with all the tools (and kernel modules) you might need to access the compromised system. You can use the mkinitrd-cd package to build such a CD-ROM[70]. You might find the http://www.caine-live.net/ (Computer Aided Investigative Environment) CD-ROM useful here too, since it's also a live CD-ROM under active development with forensic tools useful in these situations. There is not (yet) a Debian-based tool such as this, nor an easy way to build the CD-ROM using your own selection of Debian packages and mkinitrd-cd (so you'll have to read the documentation provided with it to make your own CD-ROMs). If you really want to fix the compromise quickly, you should remove the compromised host from your network and re-install the operating system from scratch. Of course, this may not be effective because you will not learn how the intruder got root in the first place. For that case, you must check everything: firewall, file integrity, log host, log files and so on. For more information on what to do following a break-in, see http://www.cert.org/tech_tips/root_compromise.html or SANS's https://www.sans.org/white-papers/. Some common questions on how to handle a compromised Debian GNU/Linux system are also available in. 11.2. Realizar copia de seguridad del sistema --------------------------------------------- Recuerde que si está seguro de que el sistema ha estado comprometido, no puede fiarse del software instalado ni de ninguna información que este le devuelva. Las aplicaciones podrían contener un troyano, podrían instalarse módulos del núcleo, etc. Lo mejor que puede hacer es una copia de seguridad del sistema de archivos completo (utilizando dd) tras arrancar desde un medio seguro. Los CDROMs de Debian GNU/Linux pueden venir bien para esto, puesto que proporcionan una shell en consola cuando arranca la instalación (acceda a ella utilizando Alt+2 y pulsando Enter). Desde esta shell, copie la información que quiera salvar en otro ordenador, si es posible (quizás a un servidor de archivos de red por medio de NFS/FTP). Luego puede llevar a cabo cualquier análisis del compromiso o la reinstalación mientras el sistema afectado está desconectado. Si está seguro de que el único compromiso es un módulo troyano del núcleo, puede intentar arrancar la imagen del núcleo desde el CDROM de Debian en modo rescue (N. del T.: modo rescate). Asegúrese de arrancar en modo monousuario, de modo que no se ejecute otro proceso troyano después del núcleo. 11.3. Contact your local CERT ----------------------------- The CERT (Computer and Emergency Response Team) is an organization that can help you recover from a system compromise. There are CERTs worldwide [71] and you should contact your local CERT in the event of a security incident which has lead to a system compromise. The people at your local CERT can help you recover from it. Providing your local CERT (or the CERT coordination center) with information on the compromise even if you do not seek assistance can also help others since the aggregate information of reported incidents is used in order to determine if a given vulnerability is in wide spread use, if there is a new worm aloft, which new attack tools are being used. This information is used in order to provide the Internet community with information on the http://www.cert.org/current/, and to publish http://www.cert.org/incident_notes/ and even http://www.cert.org/advisories/. For more detailed information read on how (and why) to report an incident read http://www.cert.org/tech_tips/incident_reporting.html. You can also use less formal mechanisms if you need help for recovering from a compromise or want to discuss incident information. This includes the http://marc.theaimsgroup.com/?l=incidents and the http://marc.theaimsgroup.com/?l=intrusions. 11.4. Análisis forense ---------------------- If you wish to gather more information, the tct (The Coroner's Toolkit from Dan Farmer and Wietse Venema) package contains utilities which perform a post mortem analysis of a system. tct allows the user to collect information about deleted files, running processes and more. See the included documentation for more information. These same utilities and some others can be found in http://www.sleuthkit.org/ by Brian Carrier, which provides a web front-end for forensic analysis of disk images. In Debian you can find both sleuthkit (the tools) and autopsy (the graphical front-end). Recuerde también que los análisis forenses deberían hacerse siempre sobre una copia de seguridad de los datos, nunca sobre los datos mismos, por si se alteran los datos durante el análisis y se pierde la evidencia. You will find more information on forensic analysis in Dan Farmer's and Wietse Venema's http://www.porcupine.org/forensics/forensic-discovery/ book (available online), as well as in their http://www.porcupine.org/forensics/column.html and their http://www.porcupine.org/forensics/handouts.html. Brian Carrier's newsletter http://www.sleuthkit.org/informer/index.php is also a very good resource on forensic analysis tips. Finally, the http://www.honeynet.org/misc/chall.html are an excellent way to hone your forensic analysis skills as they include real attacks against honeypot systems and provide challenges that vary from forensic analysis of disks to firewall logs and packet captures. For information about available forensics packages in Debian visit https://salsa.debian.org and search for forensic. FIXME: This paragraph will hopefully provide more information about forensics in a Debian system in the coming future. FIXME: Talk on how to do a debsums on a stable system with the MD5sums on CD and with the recovered file system restored on a separate partition. FIXME: Add pointers to forensic analysis papers (like the Honeynet's reverse challenge or http://staff.washington.edu/dittrich/). 11.5. Analysis of malware ------------------------- Some other tools that can be used for forensic analysis provided in the Debian distribution are: strace and ltrace Any of these packages can be used to analyze rogue binaries (such as back doors), in order to determine how they work and what they do to the system. Some other common tools include ldd (in libc6), strings and objdump (both in binutils). If you try to do forensic analysis with back doors or suspected binaries retrieved from compromised systems, you should do so in a secure environment (for example in a bochs or xen image or a chroot'ed environment using a user with low privileges[72]). Otherwise your own system can be back doored/r00ted too! If you are interested in malware analysis then you should read the http://www.porcupine.org/forensics/forensic-discovery/chapter6.html chapter of Dan Farmer's and Wietse Venema's forensics book. ------------------------------------------------------------------------ [69] >If you are adventurous, you can login to the system and save information on all running processes (you'll get a lot from /proc/nnn/). It is possible to get the whole executable code from memory, even if the attacker has deleted the executable files from disk. Then pull the power cord. [70] >In fact, this is the tool used to build the CD-ROMs for the http://www.gibraltar.at/ project (a firewall on a live CD-ROM based on the Debian distribution). [71] > This is a list of some CERTs, for a full list look at the http://www.first.org/about/organization/teams/index.html (FIRST is the Forum of Incident Response and Security Teams): http://www.auscert.org.au (Australia), http://www.unam-cert.unam.mx/ (Mexico) http://www.cert.funet.fi (Finland), http://www.dfn-cert.de (Germany), http://cert.uni-stuttgart.de/ (Germany), http://security.dico.unimi.it/ (Italy), http://www.jpcert.or.jp/ (Japan), http://cert.uninett.no (Norway), http://www.cert.hr (Croatia) http://www.cert.pl (Poland), http://www.cert.ru (Russia), http://www.arnes.si/si-cert/ (Slovenia) http://www.rediris.es/cert/ (Spain), http://www.switch.ch/cert/ (Switzerland), http://www.cert.org.tw (Taiwan), and http://www.cert.org (US). [72] >Be very careful if using chroots, since if the binary uses a kernel-level exploit to increase its privileges it might still be able to infect your system Capítulo 12. Preguntas Frecuentes ================================= Este capítulo introduce algunas de las preguntas más comunes de la lista de seguridad de Debian. Debería leerlas antes de preguntar o la gente posiblemente le diga RTFM (N.T. Read The Fucking Manual - Lea el P*to Manual). 12.1. La seguridad en el sistema operativo Debian ------------------------------------------------- 12.1.1. ¿Es más seguro Debian que X? Un sistema es sólo tan seguro como su administrador es capaz de hacerlo. La instalación predeterminada de Debian de servicios trata de ser segura, pero puede no ser tan paranoica como la de otros sistemas operativos que instalan todos los servicios deshabilitados de manera predeterminada. En cualquier caso, el administrador del sistema necesita adaptar la seguridad del sistema a su política de seguridad local. Para ver una recopilación de datos acerca de vulnerabilidades de seguridad de muchos sistemas operativos mire en http://securityfocus.com/vulns/stats.shtml. ¿Le son útiles estos datos? El servidor lista varios factores a considerar cuando se interpretan los datos y avisa de que los datos no pueden usarse para comparar las vulnerabilidades de un sistema operativo frente a otro.[73]Tenga también en mente que alguna de las vulnerabilidades de BugTraq que afectan a Debian se aplican sólo a la rama unstable. For a collection of data regarding security vulnerabilities for many operating systems, see the http://www.cert.org/stats/cert_stats.html or generate stats using the http://nvd.nist.gov/statistics.cfm (formerly ICAT) Is this data useful? There are several factors to consider when interpreting the data, and it is worth noticing that the data cannot be used to compare the vulnerabilities of one operating system versus another.[74] Also, keep in mind that some reported vulnerabilities regarding Debian apply only to the unstable (i.e. unreleased) branch. 12.1.1.1. Is Debian more secure than other Linux distributions (such as Red Hat, SuSE...)? There are not really many differences between Linux distributions, with exceptions to the base installation and package management system. Most distributions share many of the same applications, with differences mainly in the versions of these applications that are shipped with the distribution's stable release. For example, the kernel, Bind, Apache, OpenSSH, Xorg, gcc, zlib, etc. are all common across Linux distributions. For example, Red Hat was unlucky and shipped when foo 1.2.3 was current, which was then later found to have a security hole. Debian, on the other hand, was lucky enough to ship foo 1.2.4, which incorporated the bug fix. That was the case in the big http://www.cert.org/advisories/CA-2000-17.html problem from a couple years ago. There is a lot of collaboration between the respective security teams for the major Linux distributions. Known security updates are rarely, if ever, left unfixed by a distribution vendor. Knowledge of a security vulnerability is never kept from another distribution vendor, as fixes are usually coordinated upstream, or by http://www.cert.org. As a result, necessary security updates are usually released at the same time, and the relative security of the different distributions is very similar. One of Debian's main advantages with regards to security is the ease of system updates through the use of apt. Here are some other aspects of security in Debian to consider: * Debian provides more security tools than other distributions, see Capítulo 8, Herramientas de seguridad en Debian. * Debian's standard installation is smaller (less functionality), and thus more secure. Other distributions, in the name of usability, tend to install many services by default, and sometimes they are not properly configured (remember the http://www.sophos.com/virusinfo/analyses/linuxlion.html http://www.sophos.com/virusinfo/analyses/linuxramen.html). Debian's installation is not as limited as OpenBSD (no daemons are active per default), but it's a good compromise. [75] * Debian documents best security practices in documents like this one. 12.1.1.2. Hay muchos errores de Debian en Bugtraq. ¿Significa eso que es muy vulnerable? The Debian distribution boasts a large and growing number of software packages, probably more than provided by many proprietary operating systems. The more packages installed, the greater the potential for security issues in any given system. Más y más personas están examinando el código fuente en busca de debilidades. Hay muchos avisos acerca de auditorías del código fuente de los componentes más importantes de Debian. Cuando esas auditorías de código fuente descubren vulnerabilidades, se solucionan y se envía un aviso a las listas y a Bugtraq. Bugs that are present in the Debian distribution usually affect other vendors and distributions as well. Check the "Debian specific: yes/no" section at the top of each advisory (DSA). 12.1.1.3. Does Debian have any certification related to security? Short answer: no. Long answer: certification costs money (specially a serious security certification), nobody has dedicated the resources in order to certify Debian GNU/Linux to any level of, for example, the http://niap.nist.gov/cc-scheme/st/. If you are interested in having a security-certified GNU/Linux distribution, try to provide the resources needed to make it possible. There are currently at least two linux distributions certified at different http://en.wikipedia.org/wiki/Evaluation_Assurance_Level levels. Notice that some of the CC tests are being integrated into the http://ltp.sourceforge.net which is available in Debian in the ltp. 12.1.1.4. ¿Hay algún programa de securización para Debian? Sí. http://www.bastille-unix.org, originalmente orientado hacia otras distribuciones de Linux (RedHat y Mandrake), actualmente funciona para Debian. Los pasos están siendo tomados para integrar los cambios hechos a la versión original al paquete Debian llamado bastille. Sin embargo, algunas personas creen que una herramienta de securización no elimina la necesidad de una buena administración. 12.1.1.5. I want to run XYZ service, which one should I choose? One of Debian's great strengths is the wide variety of choice available between packages that provide the same functionality (DNS servers, mail servers, ftp servers, web servers, etc.). This can be confusing to the novice administrator when trying to determine which package is right for you. The best match for a given situation depends on a balance between your feature and security needs. Here are some questions to ask yourself when deciding between similar packages: * Is the software maintained upstream? When was the last release? * Is the package mature? The version number really does not tell you about its maturity. Try to trace the software's history. * Is the software bug-ridden? Have there been security advisories related to it? * Does the software provide all the functionality you need? Does it provide more than you really need? 12.1.1.6. Quiero ejecutar el servicio XYZ, ¿cuál debería elegir? Una de las mayores fortalezas de Debian es la gran variedad de elecciones posibles entre paquetes que proporcionan la misma funcionalidad (servidores de DNS, servidores de correo, servidores de FTP, servidores WEB, etc.). Eso puede resultar confuso para el administrador novel al tratar de determinar que paquete es el adecuado. La mejor opción para una situación concreta se basa en el compromiso entre su funcionalidad y los requerimientos de seguridad. Hay algunas preguntas que debe contestar antes de decidir entre paquetes similares: 12.1.1.7. How can I remove all the banners for services? If you do not like users connecting to your POP3 daemon, for example, and retrieving information about your system, you might want to remove (or change) the banner the service shows to users. [76] Doing so depends on the software you are running for a given service. For example, in postfix, you can set your SMTP banner in /etc/postfix/main.cf: smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU) Other software is not as easy to change. ssh will need to be recompiled in order to change the version that it prints. Take care not to remove the first part (SSH-2.0) of the banner, which clients use to identify which protocol(s) is supported by your package. 12.1.1.8. ¿Son seguros todos los paquetes de Debian? The Debian security team cannot possibly analyze all the packages included in Debian for potential security vulnerabilities, since there are just not enough resources to source code audit the whole project. However, Debian does benefit from the source code audits made by upstream developers. De todas formas un desarrollador Debian podría distribuir un troyano en un paquete y no habría forma posible de comprobarlo. Incluso si se introduce en una rama de Debian, podría ser imposible cubrir todas las posibles situaciones en las que un troyano puede ejecutarse. Esa es la razón por la que Debian tiene una cláusula de "no garantías" en su licencia. Aun así, los usuarios de Debian tiene confianza en el hecho de que el código estable tiene una gran audiencia y la mayoría de los problemas pueden descubrirse con el uso. Instalar programas no probados no es recomendable en un sistema crítico (si no puede hacer la auditoría de código necesaria). En cualquier caso, si se introduce una vulnerabilidad de seguridad en una distribución, el proceso que se usa para incluir paquetes (usando firma digital) asegura que el problema puede seguirse hasta el desarrollador. El proyecto Debian no se ha tomado a la ligera este tema. 12.1.1.9. Why are some log files/configuration files world-readable, isn't this insecure? Of course, you can change the default Debian permissions on your system. The current policy regarding log files and configuration files is that they are world readable unless they provide sensitive information. Be careful if you do make changes since: * Processes might not be able to write to log files if you restrict their permissions. * Some applications may not work if the configuration file they depend on cannot be read. For example, if you remove the world-readable permission from /etc/samba/smb.conf, the smbclient program will not work when run by a normal user. FIXME: Check if this is written in the Policy. Some packages (i.e. ftp daemons) seem to enforce different permissions. 12.1.1.10. Why does /root/ (or UserX) have 755 permissions? As a matter of fact, the same questions stand for any other user. Since Debian's installation does not place any file under that directory, there's no sensitive information to protect there. If you feel these permissions are too broad for your system, consider tightening them to 750. For users, read Sección 4.11.19.1, “Limitar el acceso a los datos de otros usuarios”. This Debian security mailing list http://lists.debian.org/debian-devel/2000/11/msg00783.html has more on this issue. 12.1.1.11. After installing a grsec/firewall, I started receiving many console messages! How do I remove them? If you are receiving console messages, and have configured /etc/syslog.conf to redirect them to either files or a special TTY, you might be seeing messages sent directly to the console. The default console log level for any given kernel is 7, which means that any message with lower priority will appear in the console. Usually, firewalls (the LOG rule) and some other security tools log lower that this priority, and thus, are sent directly to the console. To reduce messages sent to the console, you can use dmesg (-n option, see dmseg(8)), which examines and controls the kernel ring buffer. To fix this after the next reboot, change /etc/init.d/klogd from: KLOGD="" para: KLOGD="-c 4" Use a lower number for -c if you are still seeing them. A description of the different log levels can be found in /usr/include/sys/syslog.h: #define LOG_EMERG 0 /* system is unusable */ #define LOG_ALERT 1 /* action must be taken immediately */ #define LOG_CRIT 2 /* critical conditions */ #define LOG_ERR 3 /* error conditions */ #define LOG_WARNING 4 /* warning conditions */ #define LOG_NOTICE 5 /* normal but significant condition */ #define LOG_INFO 6 /* informational */ #define LOG_DEBUG 7 /* debug-level messages */ 12.1.1.12. Usuarios y grupos del sistema operativo 12.1.1.12.1. ¿Son necesarios todos los usuarios del sistema? Yes and no. Debian comes with some predefined users (user id (UID) < 99 as described in http://www.debian.org/doc/debian-policy/ or /usr/share/doc/base-passwd/README) to ease the installation of some services that require that they run under an appropriate user/UID. If you do not intend to install new services, you can safely remove those users who do not own any files in your system and do not run any services. In any case, the default behavior is that UID's from 0 to 99 are reserved in Debian, and UID's from 100 to 999 are created by packages on install (and deleted when the package is purged). To easily find users who don't own any files, execute the following command[77] (run it as root, since a common user might not have enough permissions to go through some sensitive directories): cut -f 1 -d : /etc/passwd | \ while read i; do find / -user "$i" | grep -q . || echo "$i"; done Estos usuarios son del paquete base-passwd. Mire en su documentación si quiere más información acerca de cómo se gestionan estos usuarios en Debian. La lista de usuarios predeterminados (con su grupo correspondiente) es la siguiente: * root: Root es (típicamente) el super usuario. * daemon: Algunos demonios sin privilegios que necesitan escribir en archivos del del disco se ejecutan como daemon.daemon (p.e., portmap, atd, y probablemente otros). Los demonios que no necesitan tener ningún archivo corren como nobody.nogroup, algunos otros demonios más complejos se ejecutan con usuarios dedicados. El usuario del demonio es también útil para demonios instalados localmente. * bin: mantenido por razones históricas. * sys: igual que bin. Aun así, /dev/vcs* y /var/spool/cups son del usuario y grupo sys. * sync: La shell del usuario sync es /bin/sync. Aun así si su contraseña se pone fácil de adivinar (como ""), cualquiera puede sincronizar el sistema en la consola incluso si no tiene cuenta. * games: Muchos juegos tienen SETGID de manera que puedan escribir sus propios archivos de puntuación más alta. Se explica en la política. * man: El programa man (a veces) se ejecuta con el usuario man, para que pueda escribir páginas en /var/cache/man. * lp: Usado por los demonios de impresión. * mail: los buzones de /var/mail son del grupo mail, como se explica en la política. El usuario y grupo se usan también con otros propósitos por varios MTAs. * news: Varios servidores de noticias y programas asociados (como suck) usan el usuario y grupo news de varias formas. Los archivos en la cola news son habitualmente del usuario y grupo news. Programas como inews que pueden usarse para enviar noticias son típicamente noticias con SETGID. * uucp: El usuario y grupo uucp es usado por el subsistema UUCP. Tiene su propia cola y archivos de configuración. Los usuarios en el grupo uucp pueden ejecutar uucico. * proxy: Como daemon, este usuario y grupo lo usan algunos demonios (especialmente demonios de proxy) que no tienen usuarios dedicados y necesitan tener archivos. Por ejemplo el grupo proxy lo usan pdnsd, y squid. * majordom: Majordomo tiene un UID estático en sistemas Debian por razones históricas. No se instala en sistemas nuevos. * postgres: Las bases de datos de Postgresql son de este usuario y grupo. Todos los archvos de /var/lib/postgresql son de este usuario para reforzar la seguridad. * www-data: Algunos servidores web corren como www-data. El contenido *no* debe ser de este usuario o un servidor comprometido podría reescribir el web. Los datos escritos por el servidor web incluyendo los archivos de registro, deben ser de www-data. * backup: Muchas funciones de copia/restauración pueden ser delegadas a alguien sin privilegios completos de root. * operator: Operator es históricamente (y prácticamente) el único 'usuario' que puede acceder al sistema de forma remota y no depende de NIS/NFS. * list: Los archivos de listas de correo y sus datos son de este usuario y grupo. Algunos programas de listas de correo pueden ejecutarse también con este usuario. * irc: Usado por demonios de IRC. Un usuario determinado se necesita únicamente por un error de ircd, que hace SETUID()s de si mismo a un UID determinado en el arranque. * gnats. * nobody, nogroup: Los demonios que no necesitan ningún archivo se ejecutan con el usuario nobody y grupo nogroup. Así que no debería existir ningún archivo de este usuario o grupo en el sistema. Otros grupos que no tienen un usuario asociado: * adm: El grupo adm se usa para tareas de monitorización del sistema. Los miembros de este grupo pueden leer muchos de los archivos de /var/log, y pueden usar xconsole. Históricamente /var/log eran /usr/adm (y más tarde /var/adm), del mismo grupo. * tty: Los dispositivos TTY son de este grupo. Lo usan write y wall para escribir en los TTYs de otras personas. * disk: Acceso directo a disco. Mayormente equivalente al acceso de root. * kmem: /dev/kmem y archivos similares son accesibles en modo lectura por este grupo. Esto es, mayormente, una reliquia de BSD pero algunos programas siguen necesitando acceso directo de lectura a la memoria del sistema que se hace con SETGID kmem. * dialout: Acceso directo y completo a los puertos serie. Los miembros de este grupo pueden reconfigurar el módem, llamar a cualquier parte, etc. * dip: El nombre del grupo viene de "Dial-up IP", y ser de ese grupo le permite usar herramientas como ppp, dip, wvdial, etc. para comenzar una conexión. La mayoría de los usuarios de este grupo no pueden configurar el módem, pero pueden ejecutar programas que lo usa. * fax: Permite a los miembros usar el programa de fax para enviar / recibir faxes. * voice: Voicemail, usado por sistemas que usan módems como contestadores. * cdrom: Este grupo puede ser usado localmente para dar acceso al CDROM a los usuarios. * floppy: Este grupo puede ser usado localmente para dar acceso a la disquetera a los usuarios. * tape: Este grupo puede ser usado localmente para dar acceso a la cinta a los usuarios. * sudo: Los miembros de este grupo no necesitan teclear la contraseña cuando usen el programa sudo. Mire /usr/share/doc/sudo/OPTIONS. * audio: Este grupo puede ser usado localmente para dar acceso a los usuarios al dispositivo de audio. * src: Este grupo tiene el código fuente incluyendo los archivos de /usr/src. Puede usarse para darle al usuario la capacidad de gestionar el sistema de código fuente. * shadow: /etc/shadow es de lectura para este grupo. Algunos programas que necesitan acceso a este archivo tienen SETGID shadow. * utmp: Este grupo puede escribir en /var/run/utmp y archivos similares. Los programas que necesitan escribir ahí tienen SETGID utmp. * video: Este grupo puede ser usado para dar a los usuarios acceso al dispositivo de video. * staff: Permite a los usuarios añadir modificaciones locales al sistema (/usr/local, /home) sin necesidad de tener privilegios de root. Comparar con el grupo "adm", que está más relacionado con monitorización/seguridad. * users: Mientras los sistemas Debian usan el sistema de usuarios privados de forma predeterminada (cada usuario tiene su propio grupo), algunos prefieren un sistema de grupos más tradicional, en el que cada usuario es miembro de este grupo. 12.1.1.12.2. I removed a system user! How can I recover? If you have removed a system user and have not made a backup of your password and group files you can try recovering from this issue using update-passwd (see update-passwd(8)). 12.1.1.12.3. ¿Qué diferencia hay entre el grupo adm y el staff? The 'adm' group are usually administrators, and this group permission allows them to read log files without having to su. The 'staff' group are usually help-desk/junior sysadmins, allowing them to work in /usr/local and create directories in /home. 12.1.1.13. Why is there a new group when I add a new user? (or Why does Debian give each user one group?) The default behavior in Debian is that each user has its own, private group. The traditional UN*X scheme assigned all users to the users group. Additional groups were created and used to restrict access to shared files associated with different project directories. Managing files became difficult when a single user worked on multiple projects because when someone created a file, it was associated with the primary group to which they belong (e.g. 'users'). Debian's scheme solves this problem by assigning each user to their own group; so that with a proper umask (0002) and the SETGID bit set on a given project directory, the correct group is automatically assigned to files created in that directory. This makes it easier for people who work on multiple projects, because they will not have to change groups or umasks when working on shared files. You can, however, change this behavior by modifying /etc/adduser.conf. Change the USERGROUPS variable to 'no', so that a new group is not created when a new user is created. Also, set USERS_GID to the GID of the users group which all users will belong to. 12.1.1.14. Cuestiones sobre servicios en ejecución y puertos abiertos. 12.1.1.14.1. ¿Por qué están todos los servicios activados tras la instalación? Es una aproximación al problema de, por una parte la seguridad y por otra la usabilidad. Al contrario que como OpenBSD, deshabilita los servicios a no ser que los habilite el administrador, Debian GNU/Linux habilitará todos los servicios instalados a no ser que se desactiven (mire en Sección 3.5.1, “Deshabilitar servicios” para ver más información). Después de todo usted instaló el servicio ¿no es así? There has been much discussion on Debian mailing lists (both at debian-devel and at debian-security) regarding which is the better approach for a standard installation. However, as of this writing (March 2002), there still isn't a consensus. 12.1.1.14.2. Can I remove inetd? Inetd no es fácil de eliminar porque netbase depende del paquete que lo provee (netkit-inetd). Si quiere deshabilitarlo (mire disableserv o elimine el paquete usando el paquete equivs). 12.1.1.14.3. ¿Por qué tengo abierto el puerto 111? El puerto 111 es el portmapper de sunrpc y se instala de manera predeterminada como parte del sistema base de Debian porque no se sabe cuando un programa de usuario necesitará usar RPC para funcionar correctamente. En cualquier caso, se usa mayormente en NFS. Si no lo necesita, elimínelo tal y como se explica en rpc. In versions of the portmap package later than 5-5 you can actually have the portmapper installed but listening only on localhost (by modifying /etc/default/portmap) 12.1.1.14.4. What use is identd (port 113) for? Identd service is an authentication service that identifies the owner of a specific TCP/IP connection to the remote server accepting the connection. Typically, when a user connects to a remote host, inetd on the remote host sends back a query to port 113 to find the owner information. It is often used by mail, FTP and IRC servers, and can also be used to track down which user in your local system is attacking a remote system. There has been extensive discussion on the security of identd (See http://lists.debian.org/debian-security/2001/08/msg00297.html). In general, identd is more helpful on a multi-user system than on a single user workstation. If you don't have a use for it, disable it, so that you are not leaving a service open to the outside world. If you decide to firewall the identd port, please use a reject policy and not a deny policy, otherwise a connection to a server utilizing identd will hang until a timeout expires (see http://logi.cc/linux/reject_or_deny.php3). 12.1.1.14.5. I have services using port 1 and 6, what are they and how can I remove them? If you have run the command netstat -an and receive: Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name raw 0 0 0.0.0.0:1 0.0.0.0:* 7 - raw 0 0 0.0.0.0:6 0.0.0.0:* 7 - You are not seeing processes listening on TCP/UDP port 1 and 6. In fact, you are seeing a process listening on a raw socket for protocols 1 (ICMP) and 6 (TCP). Such behavior is common to both legitimate software like intrustion detection systems, such as iplogger and portsentry, but some trojans have also been known yo use them. If you have the mentioned packages simply remove them to close the port. If you do not, try netstat's -p (process) option to see which process is running these listeners. 12.1.1.14.6. I found the port XYZ open, can I close it? Por supuesto que puede, usted puede ir dejando los portales abiertos en su sitio de política, fortaleciendo los servicios públicos disponibles para otros sistemas. Revise si estos son abiertos por inetd (observe Sección 3.5.2, “Disabling inetd or its services”) o por otros paquetes instalados y tómelo en medidas apropiadas (configure inetd, remueva el paquete, anule el funcionamiento en bootup...). 12.1.1.14.7. Will removing services from /etc/services help secure my box? No, /etc/services solo suministra un mapping desde un nombre virtual a un acceso numérico dado, removiendo nombres desde (usualmente) donde no haya que impedir servicios al ser iniciados. Algunos demonios no podrán funcionar si /etc/services ha sido modificado, pero ésta no es la norma y no es la vía recomendable para hacerlo, observe disableserv. 12.1.1.15. Common security issues 12.1.1.15.1. ¡¡He perdido mi password y no puedo tener acceso al sistema!! Usted necesita seguir unos pasos para recuperar su password y este depende desi usted ha aplicado o no el procedimiento para limitar el acceso a Lilo y BIOS. Si usted ha limitado a ambos. Necesita desactivar las características de BIOS (hágalo solo desde el disco duro) antes de proceder, además, si usted olvida el password de BIOS, tendrá que abrir el sistema y eliminar la batería BIOS manualmente. Once you have enabled booting from a CD-ROM or diskette enable, try the following: * inicie desde un disco de rescate e inicie el kernel. * desplácese hasta la consola virtual (Alt+F2) * monte el disco duro, en donde está su /root * edite (El disco de rescate Debian 2.2, viene con ae, Debian 3.0 viene con nano-tiny, el cual es similar a vi) /etc/shadow y modifique la línea: root:asdfjl290341274075:XXXX:X:XXXX:X::: (X=cualquier número) para: root::XXXX:X:XXXX:X::: This will remove the forgotten root password, contained in the first colon separated field after the user name. Save the file, reboot the system and login with root using an empty password. Remember to reset the password. This will work unless you have configured the system more tightly, i.e. if you have not allowed users to have null passwords or not allowed root to login from the console. Si usted ha introducido también estas características, usted necesitará entrar en el modo single. LILO no necesita ser limitado si usted ha hecho esto también, necesitará reiniciar lilo justo después que el administrador lo reajusta. Esto es totalmente difícil desde que su /etc/lilo.conf necesite ser atrapado por tener un / sistema de archivo, que es un disco de la memoria ram y no del verdadero disco duro. Once LILO is unrestricted, try the following: * Presionar Alt, shift o la tecla Control, antes que el sistema BIOS finalice, usted debería obtener la entrada LILO. * Type linux single, linux init=/bin/sh or linux 1 at the prompt. * usted debería obtener una entrada a interfaz de comando en el modo singleuser (este solicitará la clave, aunque usted ya la conozca). * Re-mount read/write the root (/) partition, using the mount command. # mount -o remount,rw / * Cambiar la clave del superusuario con passwd (desde que usted sea el superusuario, no se le solicitará la clave anterior). 12.1.1.16. How do I accomplish setting up a service for my users without giving out shell accounts? For example, if you want to set up a POP service, you don't need to set up a user account for each user accessing it. It's best to set up directory-based authentication through an external service (like Radius, LDAP or an SQL database). Just install the appropriate PAM library (libpam-radius-auth, libpam-ldap, libpam-pgsql or libpam-mysql), read the documentation (for starters, see Sección 4.11.1, “Uso de la autentificación: PAM”) and configure the PAM-enabled service to use the back end you have chosen. This is done by editing the files under /etc/pam.d/ for your service and modifying the auth required pam_unix_auth.so shadow nullok use_first_pass to, for example, ldap: auth required pam_ldap.so In the case of LDAP directories, some services provide LDAP schemas to be included in your directory that are required in order to use LDAP authentication. If you are using a relational database, a useful trick is to use the where clause when configuring the PAM modules. For example, if you have a database with the following table attributes: (user_id, user_name, realname, shell, password, UID, GID, homedir, sys, pop, imap, ftp) By making the services attributes boolean fields, you can use them to enable or disable access to the different services just by inserting the appropriate lines in the following files: * /etc/pam.d/imap:where=imap=1. * /etc/pam.d/qpopper:where=pop=1. * /etc/nss-mysql*.conf:users.where_clause = user.sys = 1;. * /etc/proftpd.conf: SQLWhereClause "ftp=1". 12.1.2. My system is vulnerable! (Are you sure?) 12.1.2.1. Vulnerability assessment scanner X says my Debian system is vulnerable! Many vulnerability assessment scanners give false positives when used on Debian systems, since they only use version checks to determine if a given software package is vulnerable, but do not really test the security vulnerability itself. Since Debian does not change software versions when fixing a package (many times the fix made for newer releases is back ported), some tools tend to think that an updated Debian system is vulnerable when it is not. If you think your system is up to date with security patches, you might want to use the cross references to security vulnerability databases published with the DSAs (see Sección 7.2, “Avisos de seguridad de Debian”) to weed out false positives, if the tool you are using includes CVE references. 12.1.2.2. I've seen an attack in my system's logs. Is my system compromised? A trace of an attack does not always mean that your system has been compromised, and you should take the usual steps to determine if the system is indeed compromised (see Capítulo 11, After the compromise (incident response)). Even if your system was not vulnerable to the attack that was logged, a determined attacker might have used some other vulnerability besides the ones you have detected. 12.1.2.3. I have found strange 'MARK' lines in my logs: Am I compromised? You might find the following lines in your system logs: Dec 30 07:33:36 debian -- MARK -- Dec 30 07:53:36 debian -- MARK -- Dec 30 08:13:36 debian -- MARK -- This does not indicate any kind of compromise, and users changing between Debian releases might find it strange. If your system does not have high loads (or many active services), these lines might appear throughout your logs. This is an indication that your syslogd daemon is running properly. From syslogd(8): -m interval The syslogd logs a mark timestamp regularly. The default interval between two -- MARK -- lines is 20 minutes. This can be changed with this option. Setting the interval to zero turns it off entirely. 12.1.2.4. I found users using 'su' in my logs: Am I compromised? Usted puede encontrar líneas en sus bitácoras como: Apr 1 09:25:01 server su[30315]: + ??? root-nobody Apr 1 09:25:01 server PAM_unix[30315]: (su) session opened for user nobody by (UID=0) No se preocupe tanto, revise si esto se debe a un trabajo en funcionamiento a través de cron (usualmente con /etc/cron.daily/find o logrotate): $ grep 25 /etc/crontab 25 6 * * * root test -e /usr/sbin/anacron || run-parts --report /etc/cron.daily $ grep nobody /etc/cron.daily/* find:cd / || updatedb --localuser=nobody 2>/dev/null 12.1.2.5. I have found 'possible SYN flooding' in my logs: Am I under attack? If you see entries like these in your logs: May 1 12:35:25 linux kernel: possible SYN flooding on port X. Sending cookies. May 1 12:36:25 linux kernel: possible SYN flooding on port X. Sending cookies. May 1 12:37:25 linux kernel: possible SYN flooding on port X. Sending cookies. May 1 13:43:11 linux kernel: possible SYN flooding on port X. Sending cookies. Check if there is a high number of connections to the server using netstat, for example: linux:~# netstat -ant | grep SYN_RECV | wc -l 9000 This is an indication of a denial of service (DoS) attack against your system's X port (most likely against a public service such as a web server or mail server). You should activate TCP syncookies in your kernel, see Sección 4.18.2, “Configuring syncookies”. Note, however, that a DoS attack might flood your network even if you can stop it from crashing your systems (due to file descriptors being depleted, the system might become unresponsive until the TCP connections timeout). The only effective way to stop this attack is to contact your network provider. 12.1.2.6. I have found strange root sessions in my logs: Am I compromised? You might see these kind of entries in your /var/log/auth.log file: May 2 11:55:02 linux PAM_unix[1477]: (cron) session closed for user root May 2 11:55:02 linux PAM_unix[1476]: (cron) session closed for user root May 2 12:00:01 linux PAM_unix[1536]: (cron) session opened for user root by (UID=0) May 2 12:00:02 linux PAM_unix[1536]: (cron) session closed for user root These are due to a cron job being executed (in this example, every five minutes). To determine which program is responsible for these jobs, check entries under: /etc/crontab, /etc/cron.d, /etc/crond.daily and root's crontab under /var/spool/cron/crontabs. 12.1.2.7. He sufrido una interrupción, ¿qué debo hacer? There are several steps you might want to take in case of a break-in: * Check if your system is up to date with security patches for published vulnerabilities. If your system is vulnerable, the chances that the system is in fact compromised are increased. The chances increase further if the vulnerability has been known for a while, since there is usually more activity related to older vulnerabilities. Here is a link to http://www.sans.org/top20/. * Read this document, especially the Capítulo 11, After the compromise (incident response) section. * Ask for assistance. You might use the debian-security mailing list and ask for advice on how to recover/patch your system. * Notify your local http://www.cert.org (if it exists, otherwise you may want to consider contacting CERT directly). This might or might not help you, but, at the very least, it will inform CERT of ongoing attacks. This information is very valuable in determining which tools and attacks are being used by the blackhat community. 12.1.2.8. ¿Cómo puedo encontrar el origen de un ataque? Observando las bitácoras (si ellas no han sido cambiadas), usando sistemas de detección de intrusión (observe intrusion-detect), traceroute, whois y herramientas similares (incluyendo análisis forense), usted puede encontrar un ataque a la fuente. La manera como usted debería reaccionar frente a esta información depende, solamente del uso apropiado que usted le de a la política de seguridad y que usted considere lo que es un ataque. ¿Es un scanner remoto un ataque? ¿Un ataque es una prueba de vulnerabilidad? 12.1.2.9. Cualquier programa en Debian es vulnerable ¿Qué debo hacer? Tómese un momento. Primero, observe si la vulnerabilidad ha sido anunciada en listas de correo de seguridad pública (como Bugtraq) u otros foros, el equipo de seguridad Debian permanece actualizado con estas listas, de manera que ellos ya pueden estar enterados del problema. No ejecute ningunas acciones remotas si usted ya observa algún anuncio en http://security.debian.org. If no information seems to be published, please send e-mail about the affected package(s), as well as a detailed description of the vulnerability (proof of concept code is also OK), to mailto:team@security.debian.org. This will get you in touch with Debian's security team. 12.1.2.10. El número de versión para un paquete indica que todavía estoy corriendo una versión vulnerable En lugar de actualizar una nueva descarga, podemos fijar la seguridad en backport, a la versión que fue enviada en la descarga establecida. La razón de esto es asegurarnos que una descarga cambie posiblemente un poco algunas cosas o que se interrumpan repentinamente, como un resultado de la seguridad fija. Usted puede chequear si está corriendo una versión segura de un paquete, observando el paquete changelog o comparando su número de versión exacta (versión upstream -slash- descargar debian)el número de la versión exacta con la versión indicada en el Asesor de seguridad Debian. 12.2. Software específico ------------------------- 12.2.1. Proftpd es vulnerable a un ataque en el servicio Denial. Agregue DenyFilter \*.*/ a su archivo de configuración, para más información observe http://www.proftpd.org/critbugs.html. 12.2.2. After installing portsentry, there are a lot of ports open. That's just the way portsentry works. It opens about twenty unused ports to try to detect port scans. 12.3. Preguntas con respecto al equipo de seguridad Debian ---------------------------------------------------------- The security team keeps its list of Frequently Asked Questions at the http://www.debian.org/security/faq. Please refer to that web page for up to date information. ------------------------------------------------------------------------ [73] Por ejemplo, teniendo en cuenta los datos de Securityfocus, puede parecer que Windows NT es más seguro que Linux, lo que es una afirmación cuestionable. Después de todo, las distribuciones de Linux proporcionan habitualmente muchas más aplicaciones comparadas con Windows NT de Microsoft. [74] For example, based on some data, it might seem that Windows NT is more secure than Linux, which is a questionable assertion. After all, Linux distributions usually provide many more applications compared to Microsoft's Windows NT. This counting vulnerabilities issues are better described in http://www.dwheeler.com/oss_fs_why.html#security by David A. Wheeler [75] >Without diminishing the fact that some distributions, such as Red Hat or Mandrake, are also taking into account security in their standard installations by having the user select security profiles, or using wizards to help with configuration of personal firewalls. [76] >Note that this is 'security by obscurity', and will probably not be worth the effort in the long term. [77] Be careful, as this will traverse your whole system. If you have a lot of disk and partitions you might want to reduce it in scope. Apéndice A. Historia de revisiones ================================== Historial de revisiones Revisión 3-19.2 Sun May 19 2024 Holger Wansing Translation files synchronised with XML sources 3-19 Revisión 3-19.1 Mon May 1 2017 Marcos Fouces Translation files synchronised with XML sources 3-19 Revisión 3-19 April 2017 Marcos Fouces Migrate to Docbook XML. Build with Publican. No longer use custom Makefile. Migrate svn repository to git. Import chinese, italian, spanish, portuguese, japanese, russian, french and german translations to PO format. Revisión 3-18 February 2015 Thijs Kinkhorst Clarify FAQ on raw sockets. Update section 4.5 on GRUB2. Replace example postrm user removal code with advice to use deluser/delgroup --system Revisión 3-17 January 2015 Thijs Kinkhorst Remove mention of MD5 shadow passwords. Do not recommend dselect for holding packages. No longer include the Security Team FAQ verbatim, because it duplicates information documented elsewhere and is hence perpetually out of date. Update section on restart after library upgrades to mention needrestart. Avoid gender-specific language. Patch by Myriam. Use LSB headers for firewall script. Patch by Dominic Walden. Revisión 3-16 January 2013 Javier Fernández-Sanguino Peña. Indicate that the document is not updated with latest versions. Update pointers to current location of sources. Update information on security updates for newer releases. Point information for Developers to online sources instead of keeping the information in the document, to prevent duplication. Extend the information regarding securing console access, including limiting the Magic SysRq key. Update the information related to PAM modules including how to restrict console logins, use cracklib and use the features avialable in /etc/pam.d/login. Remove the references to obsolete variables in /etc/login.defs. Reference some of the PAM modules available to use double factor authentication, for administrators that want to stop using passwords altogether. Fix shell script example in Appendix. Fix reference errors. Point to the Basille sourceforge project instead of the bastille-unix.org site as it is not responding. Revisión 3-15 December 2010 Javier Fernández-Sanguino Peña Change reference to Log Analysis' website as this is no longer available. Revisión 3-14 March 2009 Javier Fernández-Sanguino Peña Change the section related to choosing a filesystem: note that ext3 is now the default. Change the name of the packages related to enigmail to reflect naming changes introduced in Debian. Revisión 3-13 February 2008 Javier Fernández-Sanguino Peña Change URLs pointing to Bastille Linux to www.Bastille-UNIX.org since the domain has been http://bastille-linux.sourceforge.net/press-release-newname.html. Fix pointers to Linux Ramen and Lion worms. Use linux-image in the examples instead of the (old) kernel-image packages. Fix typos spotted by Francesco Poli. Revisión 3-12 August 2007 Javier Fernández-Sanguino Peña Update the information related to security updates. Drop the text talking about Tiger and include information on the update-notifier and adept tools (for Desktops) as well as debsecan. Also include some pointers to other tools available. Divide the firewall applications based on target users and add fireflier to the Desktop firewall applications list. Remove references to libsafe, it's not in the archive any longer (was removed January 2006). Fix the location of syslog's configuration, thanks to John Talbut. Revisión 3-11 January 2007 Javier Fernández-Sanguino Peña Thanks go to Francesco Poli for his extensive review of the document. Remove most references to the woody release as it is no longer available (in the archive) and security support for it is no longer available. Describe how to restrict users so that they can only do file transfers. Added a note regarding the debian-private declasiffication decision. Updated link of incident handling guides. Added a note saying that development tools (compilers, etc.) are not installed now in the default 'etch' installation. Added a note saying that development tools (compilers, etc.) are not installed now in the default 'etch' installation. Fix references to the master security server. Add pointers to additional APT-secure documentation. Improve the description of APT signatures. Comment out some things which are not yet final related to the mirror's official public keys. Fixed name of the Debian Testing Security Team. Remove reference to sarge in an example. Update the antivirus section, clamav is now available on the release. Also mention the f-prot installer. Removes all references to freeswan as it is obsolete. Describe issues related to ruleset changes to the firewall if done remotely and provide some tips (in footnotes). Update the information related to the IDS installation, mention BASE and the need to setup a logging database. Rewrite the "running bind as a non-root user" section as this no longer applies to Bind9. Also remove the reference to the init.d script since the changes need to be done through /etc/default. Remove the obsolete way to setup iptables rulesets as woody is no longer supported. Revert the advice regarding LOG_UNKFAIL_ENAB it should be set to 'no' (as per default). Added more information related to updating the system with desktop tools (including update-notifier) and describe aptitude usage to update the system. Also note that dselect is deprecated. Updated the contents of the FAQ and remove redundant paragraphs. Review and update the section related to forensic analysis of malware. Remove or fix some dead links. Fix many typos and gramatical errors reported by Francesco Poli. Revisión 3-10 November 2006 Javier Fernández-Sanguino Peña Provide examples using apt-cache's rdepends as suggested by Ozer Sarilar. Fix location of Squid's user's manual because of its relocation as notified by Oskar Pearson (its maintainer). Fix information regarding umask, it's logins.defs (and not limits.conf) where this can be configured for all login connections. Also state what is Debian's default and what would be a more restrictive value for both users and root. Thanks to Reinhard Tartler for spotting the bug. Revisión 3-9 October 2006 Javier Fernández-Sanguino Peña Add information on how to track security vulnerabilities and add references to the Debian Testing Security Tracker. Add more information on the security support for testing. Fix a large number of typos with a patch provided by Simon Brandmair. Added section on how to disable root prompt on initramfs provided by Max Attems. Remove references to queso. Note that testing is now security-supported in the introduction. Revisión 3-8 July 2006 Javier Fernández-Sanguino Peña Rewrote the information on how to setup ssh chroots to clarify the different options available, thank to Bruce Park for bringing up the different mistakes in this appendix. Fix lsof call as suggested by Christophe Sahut. Include patches for typo fixes from Uwe Hermann. Fix typo in reference spotted by Moritz Naumann. Revisión 3-7 April 2006 Javier Fernández-Sanguino Peña Add a section on Debian Developer's best practices for security. Ammended firewall script with comments from WhiteGhost. Revisión 3-6 March 2006 Javier Fernández-Sanguino Peña Included a patch from Thomas Sjögren which describes that noexec works as expected with "new" kernels, adds information regarding tempfile handling, and some new pointers to external documentation. Add a pointer to Dan Farmer's and Wietse Venema's forensic discovery web site, as suggested by Freek Dijkstra, and expanded a little bit the forensic analysis section with more pointers. Fixed URL of Italy's CERT, thanks to Christoph Auer. Reuse Joey Hess' information at the wiki on secure apt and introduce it in the infrastructure section. Review sections referring to old versions (woody or potato). Fix some cosmetic issues with patch from Simon Brandmair. Included patches from Carlo Perassi: acl patches are obsolete, openwall patches are obsolete too, removed fixme notes about 2.2 and 2.4 series kernels, hap is obsolete (and not present in WNPP), remove references to Immunix (StackGuard is now in Novell's hands), and fix a FIXME about the use of bsign or elfsign. Updated references to SElinux web pages to point to the Wiki (currently the most up to date source of information). Include file tags and make a more consistent use of "MD5 sum" with a patch from Jens Seidel. Patch from Joost van Baal improving the information on the firewall section (pointing to the wiki instead of listing all firewall packages available) (Closes: #339865). Review the FAQ section on vulnerability stats, thanks to Carlos Galisteo de Cabo for pointing out that it was out of date. Use the quote from the Social Contract 1.1 instead of 1.0 as suggested by Francesco Poli. Revisión 3-5 November 2005 Javier Fernández-Sanguino Peña Note on the SSH section that the chroot will not work if using the nodev option in the partition and point to the latest ssh packages with the chroot patch, thanks to Lutz Broedel for pointing these issues out. Fix typo spotted by Marcos Roberto Greiner (md5sum should be sha1sum in code snippet). Included Jens Seidel's patch fixing a number of package names and typos. Slightly update of the tools section, removed tools no longer available and added some new ones. Rewrite parts of the section related to where to find this document and what formats are available (the website does provide a PDF version). Also note that copies on other sites and translations might be obsolete (many of the Google hits for the manual in other sites are actually out of date). Revisión 3-4 August-September 2005 Javier Fernández-Sanguino Peña Improved the after installation security enhancements related to kernel configuration for network level protection with a sysctl.conf file provided by Will Moy. Improved the gdm section, thanks to Simon Brandmair. Typo fixes from Frédéric Bothamy and Simon Brandmair. Improvements in the after installation sections related to how to generate the MD5 (or SHA-1) sums of binaries for periodic review. Updated the after installation sections regarding checksecurity configuration (was out of date). Revisión 3-3 June 2005 Javier Fernández-Sanguino Peña Added a code snippet to use grep-available to generate the list of packages depending on Perl. As requested in #302470. Rewrite of the section on network services (which ones are installed and how to disable them). Added more information to the honeypot deployment section mentioning useful Debian packages. Revisión 3-2 March 2005 Javier Fernández-Sanguino Peña Expanded the PAM configuration limits section. Added information on how to use pam_chroot for openssh (based on pam_chroot's README). Fixed some minor issues reported by Dan Jacobson. Updated the kernel patches information partially based on a patch from Carlo Perassi and also by adding deprecation notes and new kernel patches available (adamantix). Included patch from Simon Brandmair that fixes a sentence related to login failures in terminal. Added Mozilla/Thunderbird to the valid GPG agents as suggested by Kapolnai Richard. Expanded the section on security updates mentioning library and kernel updates and how to detect when services need to be restarted. Rewrote the firewall section, moved the information that applies to woody down and expand the other sections including some information on how to manually set the firewall (with a sample script) and how to test the firewall configuration. Added some information preparing for the 3.1 release. Added more detailed information on kernel upgrades, specifically targeted at those that used the old installation system. Added a small section on the experimental apt 0.6 release which provides package signing checks. Moved old content to the section and also added a pointer to changes made in aptitude. Typo fixes spotted by Frédéric Bothamy. Revisión 3-1 January 2005 Javier Fernández-Sanguino Peña Added clarification to ro /usr with patch from Joost van Baal. Apply patch from Jens Seidel fixing many typos. FreeSWAN is dead, long live OpenSWAN. Added information on restricting access to RPC services (when they cannot be disabled) also included patch provided by Aarre Laakso. Update aj's apt-check-sigs script. Apply patch Carlo Perassi fixing URLs. Apply patch from Davor Ocelic fixing many errors, typos, urls, grammar and FIXMEs. Also adds some additional information to some sections. Rewrote the section on user auditing, highlight the usage of script which does not have some of the issues associated to shell history. Revisión 3-0 December 2004 Javier Fernández-Sanguino Peña Rewrote the user-auditing information and include examples on how to use script. Revisión 2-99 March 2004 Javier Fernández-Sanguino Peña Added information on references in DSAs and CVE-Compatibility. Added information on apt 0.6 (apt-secure merge in experimental). Fixed location of Chroot daemons HOWTO as suggested by Shuying Wang. Changed APACHECTL line in the Apache chroot example (even if its not used at all) as suggested by Leonard Norrgard. Added a footnote regarding hardlink attacks if partitions are not setup properly. Added some missing steps in order to run bind as named as provided by Jeffrey Prosa. Added notes about Nessus and Snort out-of-dateness in woody and availability of backported packages. Added a chapter regarding periodic integrity test checks. Clarified the status of testing regarding security updates (Debian bug 233955). Added more information regarding expected contents in securetty (since it's kernel specific). Added pointer to snoopylogger (Debian bug 179409). Added reference to guarddog (Debian bug 170710). apt-ftparchive is in apt-utils, not in apt (thanks to Emmanuel Chantreau for pointing this out). Removed jvirus from AV list. Revisión 2-98 Javier Fernández-Sanguino Peña Fixed URL as suggested by Frank Lichtenheld. Fixed PermitRootLogin typo as suggested by Stefan Lindenau. Revisión 2-97 September 2003 Javier Fernández-Sanguino Peña Added those that have made the most significant contributions to this manual (please mail me if you think you should be in the list and are not). Added some blurb about FIXME/TODOs. Moved the information on security updates to the beginning of the section as suggested by Elliott Mitchell. Added grsecurity to the list of kernel-patches for security but added a footnote on the current issues with it as suggested by Elliott Mitchell. Removed loops (echo to 'all') in the kernel's network security script as suggested by Elliott Mitchell. Added more (up-to-date) information in the antivirus section. Rewrote the buffer overflow protection section and added more information on patches to the compiler to enable this kind of protection. Revisión 2-96 August 2003 Javier Fernández-Sanguino Peña Removed (and then re-added) appendix on chrooting Apache. The appendix is now dual-licensed. Revisión 2-95 June 2003 Javier Fernández-Sanguino Peña Fixed typos spotted by Leonard Norrgard. Added a section on how to contact CERT for incident handling (Capítulo 11, After the compromise (incident response)). More information on setting up a Squid proxy. Added a pointer and removed a FIXME thanks to Helge H. F. Fixed a typo (save_inactive) spotted by Philippe Faes. Fixed several typos spotted by Jaime Robles. Revisión 2-94 April 2003 Javier Fernández-Sanguino Peña Following Maciej Stachura's suggestions I've expanded the section on limiting users. Fixed typo spotted by Wolfgang Nolte. Fixed links with patch contributed by Ruben Leote Mendes Added a link to David Wheeler's excellent document on the footnote about counting security vulnerabilities. Revisión 2-93 March 2003 Frédéric Schütz rewrote entirely the section of ext2 attributes (lsattr/chattr) Revisión 2-92 February 2003 Javier Fernández-Sanguino Peña, Frédéric Schütz Merge section 9.3 ("useful kernel patches") into section 4.13 ("Adding kernel patches"), and added some content. Added a few more TODOs. Added information on how to manually check for updates and also about cron-apt. That way Tiger is not perceived as the only way to do automatic update checks. Slightly rewrite of the section on executing a security updates due to Jean-Marc Ranger comments. Added a note on Debian's installation (which will suggest the user to execute a security update right after installation). Revisión 2-91 January/February 2003 Javier Fernández-Sanguino Peña Added a patch contributed by Frédéric Schütz. Added a few more references on capabilities thanks to Frédéric. Slight changes in the bind section adding a reference to BIND's 9 online documentation and proper references in the first area (Hi Pedro!). Fixed the changelog date - new year :-). Added a reference to Colin's articles for the TODOs. Removed reference to old ssh+chroot patches. More patches from Carlo Perassi. Typo fixes (recursive in Bind is recursion), pointed out by Maik Holtkamp. Revisión 2-9 December 2002 Javier Fernández-Sanguino Peña Reorganized the information on chroot (merged two sections, it didn't make much sense to have them separated). Added the notes on chrooting Apache provided by Alexandre Ratti. Applied patches contributed by Guillermo Jover. Revisión 2-8 Javier Fernández-Sanguino Peña Applied patches from Carlo Perassi, fixes include: re-wrapping the lines, URL fixes, and fixed some FIXMEs. Updated the contents of the Debian security team FAQ. Added a link to the Debian security team FAQ and the Debian Developer's reference, the duplicated sections might (just might) be removed in the future. Fixed the hand-made auditing section with comments from Michal Zielinski. Added links to wordlists (contributed by Carlo Perassi). Fixed some typos (still many around). Fixed TDP links as suggested by John Summerfield. Revisión 2-7 Javier Fernández-Sanguino Peña Some typo fixes contributed by Tuyen Dinh, Bartek Golenko and Daniel K. Gebhart. Note regarding /dev/kmem rootkits contributed by Laurent Bonnaud. Fixed typos and FIXMEs contributed by Carlo Perassi. Revisión 2-6 September 2002 Cris Tillman Changed around to improve grammar/spelling. s/host.deny/hosts.deny/ (1 place). Applied Larry Holish's patch (quite big, fixes a lot of FIXMEs). Revisión 2-5.1 September 2002 Javier Fernández-Sanguino Peña Fixed minor typos submitted by Thiemo Nagel. Added a footnote suggested by Thiemo Nagel. Fixed an URL link. Revisión 2-5.0 August 2002 Javier Fernández-Sanguino Peña Applied a patch contributed by Philipe Gaspar regarding the Squid which also kills a FIXME. Yet another FAQ item regarding service banners taken from the debian-security mailing list (thread "Telnet information" started 26th July 2002). Added a note regarding use of CVE cross references in the How much time does the Debian security team... FAQ item. Added a new section regarding ARP attacks contributed by Arnaud "Arhuman" Assad. New FAQ item regarding dmesg and console login by the kernel. Small tidbits of information to the signature-checking issues in packages (it seems to not have gotten past beta release). New FAQ item regarding vulnerability assessment tools false positives. Added new sections to the chapter that contains information on package signatures and reorganized it as a new Debian Security Infrastructure chapter. New FAQ item regarding Debian vs. other Linux distributions. New section on mail user agents with GPG/PGP functionality in the security tools chapter. Clarified how to enable MD5 passwords in woody, added a pointer to PAM as well as a note regarding the max definition in PAM. Added a new appendix on how to create chroot environments (after fiddling a bit with makejail and fixing, as well, some of its bugs), integrated duplicate information in all the appendix. Added some more information regarding SSH chrooting and its impact on secure file transfers. Some information has been retrieved from the debian-security mailing list (June 2002 thread: secure file transfers). New sections on how to do automatic updates on Debian systems as well as the caveats of using testing or unstable regarding security updates. New section regarding keeping up to date with security patches in the Before compromise section as well as a new section about the debian-security-announce mailing list. Added information on how to automatically generate strong passwords. New section regarding login of idle users. Reorganized the securing mail server section based on the Secure/hardened/minimal Debian (or "Why is the base system the way it is?") thread on the debian-security mailing list (May 2002). Reorganized the section on kernel network parameters, with information provided in the debian-security mailing list (May 2002, syn flood attacked? thread) and added a new FAQ item as well. New section on how to check users passwords and which packages to install for this. New section on PPTP encryption with Microsoft clients discussed in the debian-security mailing list (April 2002). Added a new section describing what problems are there when binding any given service to a specific IP address, this information was written based on the Bugtraq mailing list in the thread: Linux kernel 2.4 "weak end host" issue (previously discussed on debian-security as "arp problem") (started on May 9th 2002 by Felix von Leitner). Added information on ssh protocol version 2. Added two subsections related to Apache secure configuration (the things specific to Debian, that is). Added a new FAQ related to raw sockets, one related to /root, an item related to users' groups and another one related to log and configuration files permissions. Added a pointer to a bug in libpam-cracklib that might still be open... (need to check). Added more information regarding forensics analysis (pending more information on packet inspection tools such as tcpflow). Changed the "what should I do regarding compromise" into a bullet list and included some more stuff. Added some information on how to set up the Xscreensaver to lock the screen automatically after the configured timeout. Added a note related to the utilities you should not install in the system. Included a note regarding Perl and why it cannot be easily removed in Debian. The idea came after reading Intersect's documents regarding Linux hardening. Added information on lvm and journalling file systems, ext3 recommended. The information there might be too generic, however. Added a link to the online text version (check). Added some more stuff to the information on firewalling the local system, triggered by a comment made by Hubert Chan in the mailing list. Added more information on PAM limits and pointers to Kurt Seifried's documents (related to a post by him to Bugtraq on April 4th 2002 answering a person that had ``discovered'' a vulnerability in Debian GNU/Linux related to resource starvation). As suggested by Julián Muñoz, provided more information on the default Debian umask and what a user can access if given a shell in the system (scary, huh?). Included a note in the BIOS password section due to a comment from Andreas Wohlfeld. Included patches provided by Alfred E. Heggestad fixing many of the typos still present in the document. Added a pointer to the changelog in the Credits section since most people who contribute are listed here (and not there). Added a few more notes to the chattr section and a new section after installation talking about system snapshots. Both ideas were contributed by Kurt Pomeroy. Added a new section after installation just to remind users to change the boot-up sequence. Added some more TODO items provided by Korn Andras. Added a pointer to the NIST's guidelines on how to secure DNS provided by Daniel Quinlan. Added a small paragraph regarding Debian's SSL certificates infrastructure. Added Daniel Quinlan's suggestions regarding ssh authentication and exim's relay configuration. Added more information regarding securing bind including changes suggested by Daniel Quinlan and an appendix with a script to make some of the changes commented on in that section. Added a pointer to another item regarding Bind chrooting (needs to be merged). Added a one liner contributed by Cristian Ionescu-Idbohrn to retrieve packages with tcpwrappers support. Added a little bit more info on Debian's default PAM setup. Included a FAQ question about using PAM to provide services without shell accounts. Moved two FAQ items to another section and added a new FAQ regarding attack detection (and compromised systems). Included information on how to set up a bridge firewall (including a sample Appendix). Thanks to Francois Bayart who sent this to me in March. Added a FAQ regarding the syslogd's MARK heartbeat from a question answered by Noah Meyerhans and Alain Tesio in December 2001. Included information on buffer overflow protection as well as some information on kernel patches. Added more information (and reorganized) the firewall section. Updated the information regarding the iptables package and the firewall generators available. Reorganized the information regarding log checking, moved logcheck information from host intrusion detection to that section. Added some information on how to prepare a static package for bind for chrooting (untested). Added a FAQ item regarding some specific servers/services (could be expanded with some of the recommendations from the debian-security list). Added some information on RPC services (and when it's necessary). Added some more information on capabilities (and what lcap does). Is there any good documentation on this? I haven't found any documentation on my 2.4 kernel. Se corrigieron algunos errores ortográficos. Revisión 2-4 June 2002 Javier Fernández-Sanguino Peña Reescrita la parte de la sección BIOS. Revisión 2-3.1 April 2002 Javier Fernández-Sanguino Peña La mayoría de los archivos se encuentran marcados con la etiqueta file. Fallo de ortografía observado por Edi Stojicevi. La sección de herramientas de auditoría remota se ha modificado ligeramente. Se añadieron algunas piezas de PORHACER. Se añadió más información con respecto a impresoras y los archivos de configuración de cups (tomado de un hilo en debian-security). Se añadió un parche suministrado por Jesus Climent relacionado con el acceso de usuarios válidos del sistema en Proftpd cuando se ha configurado como servidor anónimo. Pequeños cambios sobre divisiones de esquemas para el caso especial de servidores de correo. Se añadió Hacking Linux Exposed para la sección de los libros. Error en directorio notificado por Eduardo Pérez Ureta. Error ortográfico /etc/ssh en la checklist notificado por Edi Stojicevi. Revisión 2-3.0 April 2002 Javier Fernández-Sanguino Peña Cambio de ubicación del fichero de configuración de dpkg. Alexander eliminado de la información de contacto. Se añadieron direcciones de correo alternativas. Se arregló la dirección de correo de Alexander (aún entre comentarios). Se arregló la ubicación de la llave publicada de la distribución (gracias a Pedro Zorzenon por señalarlo). Revisión 2-2 April 2002 Javier Fernández-Sanguino Peña Se arreglaron errores ortográficos gracias a Jamin W. Collins. Se añadió una referencia a la página de manual de apt-extracttemplate (documenta la configuración APT::ExtracTemplate). Se añadió la sección sobre SSH restringido. Información basada en los correos enviados por Mark Janssen, Christian G. Warden y Emmanuel Lacour en la lista de correo debian-security. Se añadió información sobre programas antivirus. Se añadió un FAQ: las bitácoras de su debido al cron que se ejecuta como root. Revisión 2-1 April 2002 Javier Fernández-Sanguino Peña Se eliminó el ARREGLAME de lshell gracias a Oohara Yuuma. Se agregó un paquete para sXid y se eliminaron comentarios desde que éste se encuentra disponible. Se corrigieron algunos fallos ortográficos descubiertos por Oohara Yuuma. ACID está ahora disponible en Debian (en el paquete acidlab). Gracias a Oohara Yuuma por notificarlo. Se arreglaron los URLs de seguridad de Linux (gracias a Dave Wreski por comentarlo). versión 2.0 cuando todos los ARREGLAMEs estaban cambiados, pero los eliminé de los números 1.9X :( Revisión 2-0 March 2002 Javier Fernández-Sanguino Peña Se convirtió el HOWTO a un manual (ahora puedo decir apropiadamente LEJM). Se añadió más información con respecto a los tcpwrappers y a Debian (ahora muchos servicios están compilados con soporte para ellos, así que ya no es problema de inetd). Se aclaró la información sobre como deshabilitar el servicio rpc para hacerlo más consistente (la información rpc hacía referencia a update-rc.d). Se añadieron pequeñas notas sobre lprng. Se agregó alguna información sobre servidores comprometidos (aún muy rústico). Se corrigieron fallos ortográficos detectados por Mark Bucciarelli. Se añadieron algunos pasos en la recuperación de password para proteger los casos en que el administrador tiene paranoid-mode=on. Se añadió información para colocar paranoid-mode=on cuando el login está en la consola. Nuevo párrafo para introducir las configuraciones de servicios. Se reorganizó la sección Después de la instalación. Además ésta se descompone en varios temas más, facilitando la lectura. Se escribió información sobre como montar un cortafuegos con el montaje estándar de Debian 3.0 (paquete iptables). Un pequeño párrafo explicando por qué la instalación estando conectado a Internet no es buena idea y cómo evitar esto usando las herramientas Debian. Un pequeño párrafo referenciando a un trabajo publicado en el IEEE sobre como aplicar a tiempo parches de seguridad. Un apéndice sobre como montar una máquina snort Debian basada en lo que Vladimir envió a la lista de seguridad de debian-security (3 de septiembre de 2001). Información sobre como logcheck se monta en Debian y como puede ser usado en el sistema HIDS. Información sobre la contabilidad del usuario y los beneficios de los análisis. Se incluyó la configuración apt.conf para leer únicamente /usr copiado del correo de Olaf Meeuwissen a la lista de correos debian-security. Nueva sección en VPN con algunas indicaciones y paquetes disponibles en Debian (se necesita contenido de como establecer VPNs y problemas específicos de Debian), basado en los envíos de Jaroslaw Tabor y Samuli Suonpaa a la lista debian-security. Una corta nota con respecto a algún programa que automáticamente construye jaulas para el cambio de directorio raíz. Nuevo artículo FAQ con respecto a identd basado en una discusión en la lista de correo debian-security (febrero 2002, empezado por Johannes Weiss). Nuevo artículo FAQ con respecto al inetd basada en una discusión en la lista de correo debian-security (febrero 2002). Se introdujo una nota en rcconf en la sección "deshabilitar servicios". Varió el enfoque con respecto a LKM, gracias a Philipe Gaspar. Se añadieron enlaces a documentos del CERT y fuentes de información de Couterpane. Revisión 1-99 January 2002 Javier Fernández-Sanguino Peña Se añadió un nuevo FAQ con respecto al tiempo de arreglo de vulnerabilidades de seguridad. Secciones FAQ reorganizadas. Se comenzó a escribir la sección con respecto al firewalling en Debian GNU/Linux (podría ser ampliado un poco). Eliminados errores ortográficos detectados por Matt Kraai. Cambiada la información de DNS. Se agregó información sobre whisker y nbtscan para la sección de auditoría. Se modificó algún URL erróneo. Revisión 1-98 January 2002 Javier Fernández-Sanguino Peña Se añadió una nueva sección con respecto a la auditoría usando Debian GNU/Linux. Se añadió información con respecto al demonio finger tomada de la lista de correo de seguridad. Revisión 1-97 January 2002 Javier Fernández-Sanguino Peña Se cambió el enlace a Linux Trustees. Se corrigieron fallos ortográficos (parches de Oohara Yuuma y Pedro Zorzenon). Revisión 1-96 December 2001 Javier Fernández-Sanguino Peña Se reorganizó el servicio de instalación y se añadieron y eliminaron algunas notas. Se añadieron algunas notas con respecto al uso de sistemas de comprobación de integridad como herramientas de detección de intrusos. Se añadió un capítulo con respecto firmas de paquetes. Revisión 1-95 December 2001 Javier Fernández-Sanguino Peña Se añadieron notas con respecto a la seguridad de Squid enviadas por Philipe Gaspar. Cambios de enlaces sobre rookits gracias a Philipe Gaspar. Revisión 1-94 November 2001 Javier Fernández-Sanguino Peña Se añadieron algunas notas con respecto a Apache y Lpr/lpng. Se añadió alguna información con respecto a noexec y particiones de acceso aleatorio. Reescritura de como puede el usuario ayudar en los asuntos de seguridad Debian (FAQ). Revisión 1-93 November 2001 Javier Fernández-Sanguino Peña Se arregló el sitio donde se encuentra el programa de correo. Se añadieron algunos nuevos elementos a las FAQ. Revisión 1-92 October 2001 Javier Fernández-Sanguino Peña Añadió una pequeña sección de como se maneja la seguridad en Debian. Clarificación sobre las contraseñas MD5 (gracias a `rocky'). Añadida un poco más de información con respecto a harden-X de Stephen Egmond. Se añadieron algunos nuevos elementos a las FAQ. Revisión 1-91 October 2001 Javier Fernández-Sanguino Peña Añadida un poco de información forense enviada por Yotam Rubin. Añadió información de como construir una red trampa con Debian GNU/Linux. Añadidas unas cosas a hacer más. Corrección de más errores ortográficos (gracias a Yotam). Revisión 1-9 October 2001 Javier Fernández-Sanguino Peña Se añadió un parche para arreglar errores de ortografía y un poco de nueva información (contribuido por Yotam Rubin). Se añadieron referencias a otra documentación en línea (y no en línea) tanto en una única sección (vea Sección 2.2, “Sea consciente de los problemas de seguridad general”) como dentro de algunas secciones. Añadida alguna información sobre como configurar opciones de bind para restringir el acceso al servidor de DNS. Agregada información de como bastionar un sistema de Debian automáticamente (con respecto al paquete harden y bastille). Eliminados algunos PORHACER hechos y añadidos otros nuevos. Revisión 1-8 October 2001 Javier Fernández-Sanguino Peña Se añadió la lista de usuario/grupo por defecto proporcionada por Joey Hess (enviada a la lista de correo debian-security). Se añadió información sobre los rootkits LKM (Sección 10.4.1, “LKM - Loadable Kernel Modules (módulos cargables en el núcleo)”) contribuida por Philipe Gaspar. Se agregó información sobre Proftp contribuida por Emmanuel Lacour. Se recuperó el apéndice checklist de Era Eriksson. Se añadieron algunos artículos nuevos al PORHACER y se arreglaron otros. Se incluyeron manualmente los parches de Era dado que no se habían incluido en la versión anterior. Revisión 1-7 September 2001 Javier Fernández-Sanguino Peña, Era Eriksson Se arreglaron errores ortográficos y se cambiaron algunas palabras. Cambios menores de las etiquetas para seguir removiendo las tt, y sustituirlas por las etiquetas de prgn/package. Revisión 1-6 August 2001 Javier Fernández-Sanguino Peña Se añadió el enlace al documento como se publicó en el DDP (debería reemplazar el original en el futuro cercano). Comenzó un mini-FAQ (debería extenderse) con algunas preguntas recuperadas de mi buzón. Se añadió información general a considerar cuando se está bastionando. Se añadió un párrafo con respecto al envío de correo local (entrante). Se añadieron enlaces de información. Se añadió información con respecto al servicio de impresión. Se añadió una lista de chequeo de bastionado. Se reorganizó información de NIS y RPC. Se añadieron algunas notas tomadas mientras está leyendo este documento en mi nuevo visor :) Se arreglaron algunas líneas mal formateadas. Se corrigieron algunos errores ortográficos. Se añadieron ideas Geniales/Paranoícas contribuidas por Gaby Schilders. Revisión 1-5 May 2001 Javier Fernández-Sanguino Peña, Josip Rodin Se añadieron párrafos relacionados con bind y algunos ARREGLAMEs. Revisión 1-4 May 2001 Javier Fernández-Sanguino Peña Se revisaron algunos setuid pequeños. Cambios menores. Se averiguó como usar sgml2txt -f para la versión txt. Revisión 1-3 March 2001 Javier Fernández-Sanguino Peña Se añadió una actualización de seguridad después del párrafo de la instalación. Se añadió un párrafo del proftpd. En ésta ocasión se escribió algo sobre XDM, disculpas por el anterior. Revisión 1-2 December 2000 Javier Fernández-Sanguino Peña Muchas correcciones de gramática por James Treacy, nuevo párrafo de XDM. Revisión 1-1 December 2000 Javier Fernández-Sanguino Peña Errores ortográficos, cambios varios. Revisión 1-0 December 2000 Javier Fernández-Sanguino Peña Versión inicial. Apéndice B. Appendix ==================== B.1. El proceso de fortalecimiento es manejado paso a paso ---------------------------------------------------------- Below is a post-installation, step-by-step procedure for hardening a Debian 2.2 GNU/Linux system. This is one possible approach to such a procedure and is oriented toward the hardening of network services. It is included to show the entire process you might use during configuration. Also, see Sección B.2, “Lista de chequeo de la configuración”. * Install the system, taking into account the information regarding partitioning included earlier in this document. After base installation, go into custom install. Do not select task packages. * Vaya através de dselect y remueva lo que no es necesario, si no selecciono paquetes antesv de ser (I)instalados. Deje la menor cantidad de programas necesarios en el servidor. * Actualice todo el software desde los utimos paquetes disponibles en security.debian.org como se expuso previamente en update. * implemente las sugerencias presentadas en este manual , considerando las cuotas del usuario, definiciones de login y lilo. * Make a list of services currently running on your system. Try: $ ps -aux $ netstat -pn -l -A inet # /usr/sbin/lsof -i | grep LISTEN Necesitará instalar lsof-2.2 para que el tercer comando funcione (corralo como root). Debería ser consiente que lsof puede transladar la palabra LISTEN a su configuraciones de los locales. * In order to remove unnecessary services, first determine what package provides the service and how it is started. This can be accomplished by checking the program that listens in the socket. The following shell script, which uses the programs lsof and dpkg, does just that: #!/bin/sh # ARREGLAME: this is quick and dirty; replace with a more robust script snippet for i in `sudo lsof -i | grep LISTEN | cut -d " " -f 1 |sort -u` ; do pack=`dpkg -S $i |grep bin |cut -f 1 -d : | uniq` echo "Service $i is installed by $pack"; init=`dpkg -L $pack |grep init.d/ ` if [ ! -z "$init" ]; then echo "and is run by $init" fi done * Once you find any unwanted services, remove the associated package (with dpkg --purge), or disable the service from starting automatically at boot time using update-rc.d (see Sección 3.5.1, “Deshabilitar servicios”). * For inetd services (launched by the superdaemon), check which services are enabled in /etc/inetd.conf using: $ grep -v "^#" /etc/inetd.conf | sort -u Then disable those services that are not needed by commenting out the line that includes them in /etc/inetd.conf, removing the package, or using update-inetd. * Si se tienen servicios de cubierta (usando estos /usr/sbin/tcpd) revise que los /etc/hosts.allow y /etc/hosts.deny estén configurados acorde a su política de servicios. * If the server uses more than one external interface, depending on the service, you may want to limit the service to listen on a specific interface. For example, if you want internal FTP access only, make the FTP daemon listen only on your management interface, not on all interfaces (i.e, 0.0.0.0:21). * Reinicie la máquina, o cámbiela para entrar a single user y vuelva a multiusuario con # init 1 (....) # init 2 * Revise los servicios disponibles actualmente, y si es necesario repita estos pasos de nuevo. * Instale, ahora los servicios necesarios, si usted todavia no lo ha hecho, y configurelos apropiadamente. * Use the following shell command to determine what user each available service is running as: # for i in `/usr/sbin/lsof -i |grep LISTEN |cut -d " " -f 1 |sort -u`; \ > do user=`ps ef |grep $i |grep -v grep |cut -f 1 -d " "` ; \ > echo "Service $i is running as user $user"; done Consider changing these services to a specific user/group and maybe chroot'ing them for increased security. You can do this by changing the /etc/init.d scripts which start the service. Most services in Debian use start-stop-daemon, which has options (--change-uid and --chroot) for accomplishing this. A word of warning regarding the chroot'ing of services: you may need to put all the files installed by the package (use dpkg -L) providing the service, as well as any packages it depends on, in the chroot'ed environment. Information about setting up a chroot environment for the ssh program can be found in Sección B.7, “Chroot environment for SSH”. * Repita los pasos anteriores para revisar que los solamente los servicios deseados corran, y que lo hagan como el usuario o grupo desea. * Pruebe la instalación de servicios para saber si trabajan como se esperaba. * Compruebe el sistema usando un revisor de aseguramiento de vulnerabilidades (como nessus) para determinar las vulnerabilidades del sistema (configuraciones erróneas, servicios viejos o innecesarios) * Install network and host intrusion measures like snort and logcheck. * Repita el paso del revisor de red y verifique que los sistemas de detección de intrusiónd trabajan correctamente. para los verdaderos paranoicos, considere también lo siguiente: * Agregar capacidades de cortafuegos al sistema, aceptando conexiones entrantes solamente para los servicios ofrecidos y limite conexiones salientes para los autorizados. * Vuelva a revisar la instalación con una nueva herramienta de revisión de vulnerabilidades. * Using a network scanner, check outbound connections from the system to an outside host and verify that unwanted connections do not find their way out. ARREGLAME: Este procedimiento considera el servicio de fortelecimiento, pero no el sistema de fortalecimiento a nivel de usuario, incluir informaciones con respecto al chequeo de permisos del usuario, archivos setuid y paros en el sistema usando el sistema de archivos. B.2. Lista de chequeo de la configuración ----------------------------------------- Este apéndice reitera puntos de otras secciones de este manual condensando en un formato de lista de chequeo. El propósito es ser un resumen para quienes ya han leído el manual. También hay otras buenas listas de chequeo disponibles, Kurt Seifried tiene una configuración basada en un curso en http://seifried.org/security/os/linux/20020324-securing-linux-step-by-step.h tml. ARREGLAME: esto es basado en v1.4 del manual, y podría necesitar actualizarse. * límitar la entrada para un acceso físico. * Enable a password in the BIOS. * Disable floppy/cdrom/... booting in the system's BIOS. * enviar una contraseña LILO o GRUB (/etc/lilo.conf o /boot/grub/menu.lst, respectivamente); revisar que la configuración de los archivos LILO o GRUB sea de lectura-protegida. * partitura * Separe los datos del suscriptor, no sistema de datos, y cambiar rápaidamente los datos del tiempo de recorrido de sus datos de particón. * enviar nosuid,noexec,nodev montar opciones en /etc/fstab sobre la partición ext2 tal como /tmp. * Higiene de las contraseñas y aseguramiento a la entrada * Defina una buena contraseña para el administrador * Instale y use PAM * Agregue MD5 para soportar PAM y asegúrese que: (en términos generales) las entradas en el archivo /etc/pam.d/ que permiten acceso a la máquina, tengan en el segundo campo del archivo pam.d definidoc com "requisite" o "required". * Cambie /etc/pam.d/login para permitir solamente entradas locales al administrador. * también marque las tty: atuorizadas en /etc/security/access.conf y generalmente configurar este archivo para limitar la entrada del administrador tanto como sea posible. * Agregue pam_limits.so si usted desea habilitar límites para usuarios. * Cambie /etc/pam.d/passwd: especifique un tamaño mínimo de contraseña.(podrían ser 6 caracteres) y habilite md5 * agregue un grupo wheel a /etc/group si desea, agregue pam_wheel. para entrar a /etc/pam.d/su * para especificar controles por usuario iniciales, use pam_listfile cuando sea apropiado. * tenga un archivo /etc/pam.d/othery montarlo con seguridad alta. * ponga límites en /etc/security/limits.conf (note que /etc/limits no es usado si usted está utilizando PAM) * Restrinja /etc/login.defs; también, si usted habilita MD5 y/o PAM, asegurese que usted hace los cambios carrespondientes ahí también. * Tighten up /etc/pam.d/login * inhabilite el acceso a root por ftp en /etc/ftpusers * Disable network root login; use su(1) or sudo(1). (consider installing sudo) * Use PAM para hacer cumplir las restrinciones adicionales sobre logins? * Otros asuntos de la seguridad local. * Cambios de Kernel (ver kernel-conf) * Parches del Kernel (ver kernel-patches) * restrinja los permisos de los archivos de bitácora (/var/log/{last,fail}log, Apache logs) * Verifique que la revisión de setuid está habilitada en /etc/checksecurity.conf * Considere hacer algunos archivos log append-only y configurar archivos inmutables usando chattr (ext2 filesystems únicamente) * Active integridad de archivos (vea check-integ). instale debsums * Enviar bitácoras a una impresora local? * Queme su configuración sobre un CD de arranque y e inicie la máquina desde este? * incapacitar módulos del kernel? * Limite el acceso a la red * Instale y configure ssh (se sugiere PermitRootLogin No /etc/ssh/sshd_config, PermitEmptyPasswords No; note que hay otras sugerencias en este texto) * Disable or remove in.telnetd, if installed * Generalmente, inhabilite los servicios gratuitos en /etc/inetd.conf usando update-inetd --disable (or inhabilite todo inetd, o use un reemplazo como xinetd or rlinetd) * Disable other gratuitous network services; ftp, DNS, WWW etc should not be running if you do not need them and monitor them regularly. In most cases mail should be running but configured for local delivery only. * Para los servicios que necesite, no use solamente los programas comunes, busque más versiones seguras enviadas por Debian (o busque otros recursos). Para cualquier servicio que usted termine usando, asegúrese de entender los riesgos. * Monte celdas de directorio raíz distintos para usuarios externos y demonios. * Configure firewall and tcpwrappers (i.e. hosts_access(5)); note trick for /etc/hosts.deny in text. * si usted corre ftp, monte su servidor ftpd y siempre corra chrooted para el directorio raíz del usuario * Si usted corre X, inhabilite la autenticación xhost y use ssh a cambio, mejor aún, inhabilite X remoto si usted puede (adicione -nolisten tcp a X desde la línea de comandos y apague XDMCP en /etc/X11/xdm/xdm-config configurando requestPort a 0) * Inhabilite el acceso externo a impresoras. * Use tunel para sesiones de IMAP o POP a través de SSL o ssh; instale stunnel si usted quiere proporcionar este servicio a usuarios de correo remoto * Monte un loghost y configure otras máquinas para enviar logs a ésta (/etc/syslog.conf) * asegure BIND, Sendmail, y otros demonios complejos (Configure una celda de cambio de directorio ; corra como non-root pseudo-user) * Install tiger or a similar network intrusion detection tool. * Install snort or a similar network intrusion detection tool.v * Prescinda de NIS y RPC si usted puede (inhabilite portmap). * Políticas * Eduque a los usuarios acerca de los porque y los como de sus políticas. Cuando usted ha prohibido algo que normalmente está disponible en otros sistemas, suministre documenteción que explique como conseguir resultados similares usando otros medios más seguros. * Prohiba el uso de protocolos que usa claves en texto plano (telnet, rsh y friends; ftp, imap, http, ...). * Prohiba programas comoVGAlib. * Use quotas de disco. * manténegase informado sobre asuntos de seguridad * Subscríbase a la lista de correo de seguridad * Subscríbase a las actualizaciones de seguridad, adicione a /etc/apt/sources.list una entrada (o entradas) a http://security.debian.org/debian-security * Además recuerde correr periódicamente apt-get update ; apt-get upgrade (tal vez instalar un cron job?) como se explicó en Sección 4.2, “Ejecute una actualización de seguridad”. B.3. Montar un IDS aislado -------------------------- You can easily set up a dedicated Debian system as a stand-alone Intrusion Detection System using snort and a web-based interface to analyse the intrusion detection alerts: * Instale una base de sistema Debian y no seleccione paquetes adicionales. * Install one of the Snort versions with database support and configure the IDS to log alerts into the database. * Download and install BASE (Basic Analysis and Security Engine), or ACID (Analysis Console for Intrusion Databases). Configure it to use the same database than Snort. * Download and install the necessary packages[78]. BASE is currently packaged for Debian in acidbase and ACID is packaged as acidlab[79]. Both provide a graphical WWW interface to Snort's output. Besides the base installation you will also need a web server (such as apache), a PHP interpreter and a relational database (such postgresql or mysql) where Snort will store its alerts. This system should be set up with at least two interfaces: one interface connected to a management LAN (for accessing the results and maintaining the system), and one interface with no IP address attached to the network segment being analyzed. You should configure the web server to listen only on the interface connected to the management LAN. You should configure both interfaces in the standard Debian /etc/network/interfaces configuration file. One (the management LAN) address can be configured as you would normally do. The other interface needs to be configured so that it is started up when the system boots, but with no interface address. You can use the following interface definition: auto eth0 iface eth0 inet manual up ifconfig $IFACE 0.0.0.0 up up ip link set $IFACE promisc on down ip link set $IFACE promisc off down ifconfig $IFACE down The above configures an interface to read all the traffic on the network in a stealth-type configuration. This prevents the NIDS system to be a direct target in a hostile network since the sensors have no IP address on the network. Notice, however, that there have been known bugs over time in sensors part of NIDS (for example see https://lists.debian.org/debian-security-announce/2003/msg00087.html related to Snort) and remote buffer overflows might even be triggered by network packet processing. You might also want to read the http://www.faqs.org/docs/Linux-HOWTO/Snort-Statistics-HOWTO.html and the documentation available at the https://www.snort.org/#documents. B.4. Setting up a bridge firewall --------------------------------- This information was contributed by Francois Bayart in order to help users set up a Linux bridge/firewall with the 2.4.x kernel and iptables. Kernel patches are no more needed as the code was made standard part of the Linux kernel distribution. To configure the kernel with necessary support, run make menuconfig or make xconfig. In the section Networking options, enable the following options: [*] Network packet filtering (replaces ipchains) [ ] Network packet filtering debugging (NEW) <*> 802.1d Ethernet Bridging [*] netfilter (firewalling) support (NEW) Caution: you must disable this if you want to apply some firewalling rules or else iptables will not work: [ ] Network packet filtering debugging (NEW) Next, add the correct options in the section IP: Netfilter Configuration. Then, compile and install the kernel. If you want to do it the Debian way, install kernel-package and run make-kpkg to create a custom Debian kernel package you can install on your server using dpkg. Once the new kernel is compiled and installed, install the bridge-utils package. Once these steps are complete, you can complete the configuration of your bridge. The next section presents two different possible configurations for the bridge, each with a hypothetical network map and the necessary commands. B.4.1. A bridge providing NAT and firewall capabilities The first configuration uses the bridge as a firewall with network address translation (NAT) that protects a server and internal LAN clients. A diagram of the network configuration is shown below: Internet ---- router ( 62.3.3.25 ) ---- bridge (62.3.3.26 gw 62.3.3.25 / 192.168.0.1) | | |---- WWW Server (62.3.3.27 gw 62.3.3.25) | | LAN --- Zipowz (192.168.0.2 gw 192.168.0.1) The following commands show how this bridge can be configured. # Create the interface br0 /usr/sbin/brctl addbr br0 # Add the Ethernet interface to use with the bridge /usr/sbin/brctl addif br0 eth0 /usr/sbin/brctl addif br0 eth1 # Start up the Ethernet interface /sbin/ifconfig eth0 0.0.0.0 /sbin/ifconfig eth1 0.0.0.0 # Configure the bridge ethernet # The bridge will be correct and invisible ( transparent firewall ). # It's hidden in a traceroute and you keep your real gateway on the # other computers. Now if you want you can config a gateway on your # bridge and choose it as your new gateway for the other computers. /sbin/ifconfig br0 62.3.3.26 netmask 255.255.255.248 broadcast 62.3.3.31 # I have added this internal IP to create my NAT ip addr add 192.168.0.1/24 dev br0 /sbin/route add default gw 62.3.3.25 B.4.2. Añadir capacidades al cortafuegos A second possible configuration is a system that is set up as a transparent firewall for a LAN with a public IP address space. Internet ---- router (62.3.3.25) ---- bridge (62.3.3.26) | | |---- WWW Server (62.3.3.28 gw 62.3.3.25) | | |---- Mail Server (62.3.3.27 gw 62.3.3.25) The following commands show how this bridge can be configured. # Create the interface br0 /usr/sbin/brctl addbr br0 # Add the Ethernet interface to use with the bridge /usr/sbin/brctl addif br0 eth0 /usr/sbin/brctl addif br0 eth1 # Start up the Ethernet interface /sbin/ifconfig eth0 0.0.0.0 /sbin/ifconfig eth1 0.0.0.0 # Configure the bridge Ethernet # The bridge will be correct and invisible ( transparent firewall ). # It's hidden in a traceroute and you keep your real gateway on the # other computers. Now if you want you can config a gateway on your # bridge and choose it as your new gateway for the other computers. /sbin/ifconfig br0 62.3.3.26 netmask 255.255.255.248 broadcast 62.3.3.31 If you traceroute the Linux Mail Server, you won't see the bridge. If you want access to the bridge with ssh, you must have a gateway or you must first connect to another server, such as the "Mail Server", and then connect to the bridge through the internal network card. B.4.3. Basic IPtables rules This is an example of the basic rules that could be used for either of these setups. Ejemplo B.1. Reglas Iptables iptables -F FORWARD iptables -P FORWARD DROP iptables -A FORWARD -s 0.0.0.0/0.0.0.0 -d 0.0.0.0/0.0.0.0 -m state --state INVALID -j DROP iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT # Some funny rules but not in a classic Iptables sorry ... # Limit ICMP # iptables -A FORWARD -p icmp -m limit --limit 4/s -j ACCEPT # Match string, a good simple method to block some VIRUS very quickly # iptables -I FORWARD -j DROP -p tcp -s 0.0.0.0/0 -m string --string "cmd.exe" # Block all MySQL connection just to be sure iptables -A FORWARD -p tcp -s 0/0 -d 62.3.3.0/24 --dport 3306 -j DROP # Linux Mail Server Rules # Allow FTP-DATA (20), FTP (21), SSH (22) iptables -A FORWARD -p tcp -s 0.0.0.0/0 -d 62.3.3.27/32 --dport 20:22 -j ACCEPT # Allow the Mail Server to connect to the outside # Note: This is *not* needed for the previous connections # (remember: stateful filtering) and could be removed. iptables -A FORWARD -p tcp -s 62.3.3.27/32 -d 0/0 -j ACCEPT # WWW Server Rules # Allow HTTP ( 80 ) connections with the WWW server iptables -A FORWARD -p tcp -s 0.0.0.0/0 -d 62.3.3.28/32 --dport 80 -j ACCEPT # Allow HTTPS ( 443 ) connections with the WWW server iptables -A FORWARD -p tcp -s 0.0.0.0/0 -d 62.3.3.28/32 --dport 443 -j ACCEPT # Allow the WWW server to go out # Note: This is *not* needed for the previous connections # (remember: stateful filtering) and could be removed. iptables -A FORWARD -p tcp -s 62.3.3.28/32 -d 0/0 -j ACCEPT B.5. Sample script to change the default Bind installation. ----------------------------------------------------------- This script automates the procedure for changing the bind version 8 name server's default installation so that it does not run as the superuser. Notice that bind version 9 in Debian already does this by default [80] , and you are much better using that version than bind version 8. This script is here for historical purposes and to show how you can automate this kind of changes system-wide. The script will create the user and groups defined for the name server and will modify both /etc/default/bind and /etc/init.d/bind so that the program will run with that user. Use with extreme care since it has not been tested thoroughly. You can also create the users manually and use the patch available for the default init.d script attached to http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=157245. #!/bin/sh # Change the default Debian bind v8 configuration to have it run # with a non-root user and group. # # DO NOT USER this with version 9, use debconf for configure this instead # # WARN: This script has not been tested thoroughly, please # verify the changes made to the INITD script # (c) 2002 Javier Fernandez-Sanguino Pena # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 1, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # Please see the file `COPYING' for the complete copyright notice. # restore() { # Just in case, restore the system if the changes fail echo "WARN: Restoring to the previous setup since I'm unable to properly change it." echo "WARN: Please check the $INITDERR script." mv $INITD $INITDERR cp $INITDBAK $INITD } USER=named GROUP=named INITD=/etc/init.d/bind DEFAULT=/etc/default/bind INITDBAK=$INITD.preuserchange INITDERR=$INITD.changeerror AWKS="awk ' /\/usr\/sbin\/ndc reload/ { print \"stop; sleep 2; start;\"; noprint = 1; } /\\\\$/ { if ( noprint != 0 ) { noprint = noprint + 1;} } /^.*$/ { if ( noprint != 0 ) { noprint = noprint - 1; } else { print \$0; } } '" [ `id -u` -ne 0 ] && { echo "This program must be run by the root user" exit 1 } RUNUSER=`ps eo user,fname |grep named |cut -f 1 -d " "` if [ "$RUNUSER" = "$USER" ] then echo "WARN: The name server running daemon is already running as $USER" echo "ERR: This script will not do any changes to your setup." exit 1 fi if [ ! -f "$INITD" ] then echo "ERR: This system does not have $INITD (which this script tries to change)" RUNNING=`ps eo fname |grep named` [ -z "$RUNNING" ] && \ echo "ERR: In fact the name server daemon is not even running (is it installed?)" echo "ERR: No changes will be made to your system" exit 1 fi # Check if there are options already setup if [ -e "$DEFAULT" ] then if grep -q ^OPTIONS $DEFAULT; then echo "ERR: The $DEFAULT file already has options set." echo "ERR: No changes will be made to your system" fi fi # Check if named group exists if [ -z "`grep $GROUP /etc/group`" ] then echo "Creating group $GROUP:" addgroup $GROUP else echo "WARN: Group $GROUP already exists. Will not create it" fi # Same for the user if [ -z "`grep $USER /etc/passwd`" ] then echo "Creating user $USER:" adduser --system --home /home/$USER \ --no-create-home --ingroup $GROUP \ --disabled-password --disabled-login $USER else echo "WARN: The user $USER already exists. Will not create it" fi # Change the init.d script # First make a backup (check that there is not already # one there first) if [ ! -f $INITDBAK ] then cp $INITD $INITDBAK fi # Then use it to change it cat $INITDBAK | eval $AWKS > $INITD # Now put the options in the /etc/default/bind file: cat >>$DEFAULT < bash ./etc: total 24 drwxr-xr-x 2 root root 4096 Mar 15 16:13 . drwxr-xr-x 8 guest guest 4096 Mar 15 16:53 .. -rw-r--r-- 1 root root 54 Mar 15 13:23 group -rw-r--r-- 1 root root 428 Mar 15 15:56 hosts -rw-r--r-- 1 root root 44 Mar 15 15:53 passwd -rw-r--r-- 1 root root 52 Mar 15 13:23 shells ./lib: total 1848 drwxr-xr-x 2 root root 4096 Mar 18 13:37 . drwxr-xr-x 8 guest guest 4096 Mar 15 16:53 .. -rwxr-xr-x 1 root root 92511 Mar 15 12:49 ld-linux.so.2 -rwxr-xr-x 1 root root 1170812 Mar 15 12:49 libc.so.6 -rw-r--r-- 1 root root 20900 Mar 15 13:01 libcrypt.so.1 -rw-r--r-- 1 root root 9436 Mar 15 12:49 libdl.so.2 -rw-r--r-- 1 root root 248132 Mar 15 12:48 libncurses.so.5 -rw-r--r-- 1 root root 71332 Mar 15 13:00 libnsl.so.1 -rw-r--r-- 1 root root 34144 Mar 15 16:10 libnss_files.so.2 -rw-r--r-- 1 root root 29420 Mar 15 12:57 libpam.so.0 -rw-r--r-- 1 root root 105498 Mar 15 12:51 libpthread.so.0 -rw-r--r-- 1 root root 25596 Mar 15 12:51 librt.so.1 -rw-r--r-- 1 root root 7760 Mar 15 12:59 libutil.so.1 -rw-r--r-- 1 root root 24328 Mar 15 12:57 libwrap.so.0 ./usr: total 16 drwxr-xr-x 4 root root 4096 Mar 15 13:00 . drwxr-xr-x 8 guest guest 4096 Mar 15 16:53 .. drwxr-xr-x 2 root root 4096 Mar 15 15:55 bin drwxr-xr-x 2 root root 4096 Mar 15 15:37 lib ./usr/bin: total 340 drwxr-xr-x 2 root root 4096 Mar 15 15:55 . drwxr-xr-x 4 root root 4096 Mar 15 13:00 .. -rwxr-xr-x 1 root root 10332 Mar 15 15:55 env -rwxr-xr-x 1 root root 13052 Mar 15 13:13 id -r-xr-xr-x 1 root root 25432 Mar 15 12:40 scp -rwxr-xr-x 1 root root 43768 Mar 15 15:15 sftp -r-sr-xr-x 1 root root 218456 Mar 15 12:40 ssh -rwxr-xr-x 1 root root 9692 Mar 15 13:17 tty ./usr/lib: total 852 drwxr-xr-x 2 root root 4096 Mar 15 15:37 . drwxr-xr-x 4 root root 4096 Mar 15 13:00 .. -rw-r--r-- 1 root root 771088 Mar 15 13:01 libcrypto.so.0.9.6 -rw-r--r-- 1 root root 54548 Mar 15 13:00 libz.so.1 -rwxr-xr-x 1 root root 23096 Mar 15 15:37 sftp-server B.7.2. Chrooting the ssh server If you create a chroot which includes the SSH server files in, for example /var/chroot/ssh, you would start the ssh server chroot'ed with this command: # chroot /var/chroot/ssh /sbin/sshd -f /etc/sshd_config That would make startup the sshd daemon inside the chroot. In order to do that you have to first prepare the contents of the /var/chroot/ssh directory so that it includes both the SSH server and all the utilities that the users connecting to that server might need. If you are doing this you should make certain that OpenSSH uses Privilege Separation (which is the default) having the following line in the configuration file /etc/ssh/sshd_config: UsePrivilegeSeparation yes That way the remote daemon will do as few things as possible as the root user so even if there is a bug in it it will not compromise the chroot. Notice that, unlike the case in which you setup a per-user chroot, the ssh daemon is running in the same chroot as the users so there is at least one potential process running as root which could break out of the chroot. Notice, also, that in order for SSH to work in that location, the partition where the chroot directory resides cannot be mounted with the nodev option. If you use that option, then you will get the following error: PRNG is not seeded, because /dev/urandom does not work in the chroot. B.7.2.1. Setup a minimal system (the really easy way) You can use debootstrap to setup a minimal environment that just includes the ssh server. In order to do this you just have to create a chroot as described in the http://www.debian.org/doc/manuals/reference/ch09#_chroot_system document. This method is bound to work (you will get all the necessary componentes for the chroot) but at the cost of disk space (a minimal installation of Debian will amount to several hundred megabytes). This minimal system might also include setuid files that a user in the chroot could use to break out of the chroot if any of those could be use for a privilege escalation. B.7.2.2. Automatically making the environment (the easy way) You can easily create a restricted environment with the makejail package, since it automatically takes care of tracing the server daemon (with strace), and makes it run under the restricted environment. The advantage of programs that automatically generate chroot environments is that they are capable of copying any package to the chroot environment (even following the package's dependencies and making sure it's complete). Thus, providing user applications is easier. To set up the environment using makejail's provided examples, just create /var/chroot/sshd and use the command: # makejail /usr/share/doc/makejail/examples/sshd.py This will setup the chroot in the /var/chroot/sshd directory. Notice that this chroot will not fully work unless you: * Mount the procfs filesystem in /var/chroot/sshd/proc. Makejail will mount it for you but if the system reboots you need to remount it running: # mount -t proc proc /var/chroot/sshd/proc You can also have it be mounted automatically by editing /etc/fstab and including this line: proc-ssh /var/chroot/sshd/proc proc none 0 0 * Have syslog listen to the device /dev/log inside the chroot. In order to do this you have modify /etc/default/syslogd and add -a /var/chroot/sshd/dev/log to the SYSLOGD variable definition. Read the sample file to see what other changes need to be made to the environment. Some of these changes, such as copying user's home directories, cannot be done automatically. Also, limit the exposure of sensitive information by only copying the data from a given number of users from the files /etc/shadow or /etc/group. Notice that if you are using Privilege Separation the sshd user needs to exist in those files. The following sample environment has been (slightly) tested in Debian 3.0 and is built with the configuration file provided in the package and includes the fileutils package: . |-- bin | |-- ash | |-- bash | |-- chgrp | |-- chmod | |-- chown | |-- cp | |-- csh -> /etc/alternatives/csh | |-- dd | |-- df | |-- dir | |-- fdflush | |-- ksh | |-- ln | |-- ls | |-- mkdir | |-- mknod | |-- mv | |-- rbash -> bash | |-- rm | |-- rmdir | |-- sh -> bash | |-- sync | |-- tcsh | |-- touch | |-- vdir | |-- zsh -> /etc/alternatives/zsh | `-- zsh4 |-- dev | |-- null | |-- ptmx | |-- pts | |-- ptya0 (...) | |-- tty | |-- tty0 (...) | `-- urandom |-- etc | |-- alternatives | | |-- csh -> /bin/tcsh | | `-- zsh -> /bin/zsh4 | |-- environment | |-- hosts | |-- hosts.allow | |-- hosts.deny | |-- ld.so.conf | |-- localtime -> /usr/share/zoneinfo/Europe/Madrid | |-- motd | |-- nsswitch.conf | |-- pam.conf | |-- pam.d | | |-- other | | `-- ssh | |-- passwd | |-- resolv.conf | |-- security | | |-- access.conf | | |-- chroot.conf | | |-- group.conf | | |-- limits.conf | | |-- pam_env.conf | | `-- time.conf | |-- shadow | |-- shells | `-- ssh | |-- moduli | |-- ssh_host_dsa_key | |-- ssh_host_dsa_key.pub | |-- ssh_host_rsa_key | |-- ssh_host_rsa_key.pub | `-- sshd_config |-- home | `-- userX |-- lib | |-- ld-2.2.5.so | |-- ld-linux.so.2 -> ld-2.2.5.so | |-- libc-2.2.5.so | |-- libc.so.6 -> libc-2.2.5.so | |-- libcap.so.1 -> libcap.so.1.10 | |-- libcap.so.1.10 | |-- libcrypt-2.2.5.so | |-- libcrypt.so.1 -> libcrypt-2.2.5.so | |-- libdl-2.2.5.so | |-- libdl.so.2 -> libdl-2.2.5.so | |-- libm-2.2.5.so | |-- libm.so.6 -> libm-2.2.5.so | |-- libncurses.so.5 -> libncurses.so.5.2 | |-- libncurses.so.5.2 | |-- libnsl-2.2.5.so | |-- libnsl.so.1 -> libnsl-2.2.5.so | |-- libnss_compat-2.2.5.so | |-- libnss_compat.so.2 -> libnss_compat-2.2.5.so | |-- libnss_db-2.2.so | |-- libnss_db.so.2 -> libnss_db-2.2.so | |-- libnss_dns-2.2.5.so | |-- libnss_dns.so.2 -> libnss_dns-2.2.5.so | |-- libnss_files-2.2.5.so | |-- libnss_files.so.2 -> libnss_files-2.2.5.so | |-- libnss_hesiod-2.2.5.so | |-- libnss_hesiod.so.2 -> libnss_hesiod-2.2.5.so | |-- libnss_nis-2.2.5.so | |-- libnss_nis.so.2 -> libnss_nis-2.2.5.so | |-- libnss_nisplus-2.2.5.so | |-- libnss_nisplus.so.2 -> libnss_nisplus-2.2.5.so | |-- libpam.so.0 -> libpam.so.0.72 | |-- libpam.so.0.72 | |-- libpthread-0.9.so | |-- libpthread.so.0 -> libpthread-0.9.so | |-- libresolv-2.2.5.so | |-- libresolv.so.2 -> libresolv-2.2.5.so | |-- librt-2.2.5.so | |-- librt.so.1 -> librt-2.2.5.so | |-- libutil-2.2.5.so | |-- libutil.so.1 -> libutil-2.2.5.so | |-- libwrap.so.0 -> libwrap.so.0.7.6 | |-- libwrap.so.0.7.6 | `-- security | |-- pam_access.so | |-- pam_chroot.so | |-- pam_deny.so | |-- pam_env.so | |-- pam_filter.so | |-- pam_ftp.so | |-- pam_group.so | |-- pam_issue.so | |-- pam_lastlog.so | |-- pam_limits.so | |-- pam_listfile.so | |-- pam_mail.so | |-- pam_mkhomedir.so | |-- pam_motd.so | |-- pam_nologin.so | |-- pam_permit.so | |-- pam_rhosts_auth.so | |-- pam_rootok.so | |-- pam_securetty.so | |-- pam_shells.so | |-- pam_stress.so | |-- pam_tally.so | |-- pam_time.so | |-- pam_unix.so | |-- pam_unix_acct.so -> pam_unix.so | |-- pam_unix_auth.so -> pam_unix.so | |-- pam_unix_passwd.so -> pam_unix.so | |-- pam_unix_session.so -> pam_unix.so | |-- pam_userdb.so | |-- pam_warn.so | `-- pam_wheel.so |-- sbin | `-- start-stop-daemon |-- usr | |-- bin | | |-- dircolors | | |-- du | | |-- install | | |-- link | | |-- mkfifo | | |-- shred | | |-- touch -> /bin/touch | | `-- unlink | |-- lib | | |-- libcrypto.so.0.9.6 | | |-- libdb3.so.3 -> libdb3.so.3.0.2 | | |-- libdb3.so.3.0.2 | | |-- libz.so.1 -> libz.so.1.1.4 | | `-- libz.so.1.1.4 | |-- sbin | | `-- sshd | `-- share | |-- locale | | `-- es | | |-- LC_MESSAGES | | | |-- fileutils.mo | | | |-- libc.mo | | | `-- sh-utils.mo | | `-- LC_TIME -> LC_MESSAGES | `-- zoneinfo | `-- Europe | `-- Madrid `-- var `-- run |-- sshd `-- sshd.pid 27 directories, 733 files For Debian release 3.1 you have to make sure that the environment includes also the common files for PAM. The following files need to be copied over to the chroot if makejail did not do it for you: $ ls /etc/pam.d/common-* /etc/pam.d/common-account /etc/pam.d/common-password /etc/pam.d/common-auth /etc/pam.d/common-session B.7.2.3. Manually creating the environment (the hard way) It is possible to create an environment, using a trial-and-error method, by monitoring the sshd server traces and log files in order to determine the necessary files. The following environment, contributed by José Luis Ledesma, is a sample listing of files in a chroot environment for ssh in Debian woody (3.0): [86] .: total 36 drwxr-xr-x 9 root root 4096 Jun 5 10:05 ./ drwxr-xr-x 11 root root 4096 Jun 3 13:43 ../ drwxr-xr-x 2 root root 4096 Jun 4 12:13 bin/ drwxr-xr-x 2 root root 4096 Jun 4 12:16 dev/ drwxr-xr-x 4 root root 4096 Jun 4 12:35 etc/ drwxr-xr-x 3 root root 4096 Jun 4 12:13 lib/ drwxr-xr-x 2 root root 4096 Jun 4 12:35 sbin/ drwxr-xr-x 2 root root 4096 Jun 4 12:32 tmp/ drwxr-xr-x 2 root root 4096 Jun 4 12:16 usr/ ./bin: total 8368 drwxr-xr-x 2 root root 4096 Jun 4 12:13 ./ drwxr-xr-x 9 root root 4096 Jun 5 10:05 ../ -rwxr-xr-x 1 root root 109855 Jun 3 13:45 a2p* -rwxr-xr-x 1 root root 387764 Jun 3 13:45 bash* -rwxr-xr-x 1 root root 36365 Jun 3 13:45 c2ph* -rwxr-xr-x 1 root root 20629 Jun 3 13:45 dprofpp* -rwxr-xr-x 1 root root 6956 Jun 3 13:46 env* -rwxr-xr-x 1 root root 158116 Jun 3 13:45 fax2ps* -rwxr-xr-x 1 root root 104008 Jun 3 13:45 faxalter* -rwxr-xr-x 1 root root 89340 Jun 3 13:45 faxcover* -rwxr-xr-x 1 root root 441584 Jun 3 13:45 faxmail* -rwxr-xr-x 1 root root 96036 Jun 3 13:45 faxrm* -rwxr-xr-x 1 root root 107000 Jun 3 13:45 faxstat* -rwxr-xr-x 1 root root 77832 Jun 4 11:46 grep* -rwxr-xr-x 1 root root 19597 Jun 3 13:45 h2ph* -rwxr-xr-x 1 root root 46979 Jun 3 13:45 h2xs* -rwxr-xr-x 1 root root 10420 Jun 3 13:46 id* -rwxr-xr-x 1 root root 4528 Jun 3 13:46 ldd* -rwxr-xr-x 1 root root 111386 Jun 4 11:46 less* -r-xr-xr-x 1 root root 26168 Jun 3 13:45 login* -rwxr-xr-x 1 root root 49164 Jun 3 13:45 ls* -rwxr-xr-x 1 root root 11600 Jun 3 13:45 mkdir* -rwxr-xr-x 1 root root 24780 Jun 3 13:45 more* -rwxr-xr-x 1 root root 154980 Jun 3 13:45 pal2rgb* -rwxr-xr-x 1 root root 27920 Jun 3 13:46 passwd* -rwxr-xr-x 1 root root 4241 Jun 3 13:45 pl2pm* -rwxr-xr-x 1 root root 2350 Jun 3 13:45 pod2html* -rwxr-xr-x 1 root root 7875 Jun 3 13:45 pod2latex* -rwxr-xr-x 1 root root 17587 Jun 3 13:45 pod2man* -rwxr-xr-x 1 root root 6877 Jun 3 13:45 pod2text* -rwxr-xr-x 1 root root 3300 Jun 3 13:45 pod2usage* -rwxr-xr-x 1 root root 3341 Jun 3 13:45 podchecker* -rwxr-xr-x 1 root root 2483 Jun 3 13:45 podselect* -r-xr-xr-x 1 root root 82412 Jun 4 11:46 ps* -rwxr-xr-x 1 root root 36365 Jun 3 13:45 pstruct* -rwxr-xr-x 1 root root 7120 Jun 3 13:45 pwd* -rwxr-xr-x 1 root root 179884 Jun 3 13:45 rgb2ycbcr* -rwxr-xr-x 1 root root 20532 Jun 3 13:45 rm* -rwxr-xr-x 1 root root 6720 Jun 4 10:15 rmdir* -rwxr-xr-x 1 root root 14705 Jun 3 13:45 s2p* -rwxr-xr-x 1 root root 28764 Jun 3 13:46 scp* -rwxr-xr-x 1 root root 385000 Jun 3 13:45 sendfax* -rwxr-xr-x 1 root root 67548 Jun 3 13:45 sendpage* -rwxr-xr-x 1 root root 88632 Jun 3 13:46 sftp* -rwxr-xr-x 1 root root 387764 Jun 3 13:45 sh* -rws--x--x 1 root root 744500 Jun 3 13:46 slogin* -rwxr-xr-x 1 root root 14523 Jun 3 13:46 splain* -rws--x--x 1 root root 744500 Jun 3 13:46 ssh* -rwxr-xr-x 1 root root 570960 Jun 3 13:46 ssh-add* -rwxr-xr-x 1 root root 502952 Jun 3 13:46 ssh-agent* -rwxr-xr-x 1 root root 575740 Jun 3 13:46 ssh-keygen* -rwxr-xr-x 1 root root 383480 Jun 3 13:46 ssh-keyscan* -rwxr-xr-x 1 root root 39 Jun 3 13:46 ssh_europa* -rwxr-xr-x 1 root root 107252 Jun 4 10:14 strace* -rwxr-xr-x 1 root root 8323 Jun 4 10:14 strace-graph* -rwxr-xr-x 1 root root 158088 Jun 3 13:46 thumbnail* -rwxr-xr-x 1 root root 6312 Jun 3 13:46 tty* -rwxr-xr-x 1 root root 55904 Jun 4 11:46 useradd* -rwxr-xr-x 1 root root 585656 Jun 4 11:47 vi* -rwxr-xr-x 1 root root 6444 Jun 4 11:45 whoami* ./dev: total 8 drwxr-xr-x 2 root root 4096 Jun 4 12:16 ./ drwxr-xr-x 9 root root 4096 Jun 5 10:05 ../ crw-r--r-- 1 root root 1, 9 Jun 3 13:43 urandom ./etc: total 208 drwxr-xr-x 4 root root 4096 Jun 4 12:35 ./ drwxr-xr-x 9 root root 4096 Jun 5 10:05 ../ -rw------- 1 root root 0 Jun 4 11:46 .pwd.lock -rw-r--r-- 1 root root 653 Jun 3 13:46 group -rw-r--r-- 1 root root 242 Jun 4 11:33 host.conf -rw-r--r-- 1 root root 857 Jun 4 12:04 hosts -rw-r--r-- 1 root root 1050 Jun 4 11:29 ld.so.cache -rw-r--r-- 1 root root 304 Jun 4 11:28 ld.so.conf -rw-r--r-- 1 root root 235 Jun 4 11:27 ld.so.conf~ -rw-r--r-- 1 root root 88039 Jun 3 13:46 moduli -rw-r--r-- 1 root root 1342 Jun 4 11:34 nsswitch.conf drwxr-xr-x 2 root root 4096 Jun 4 12:02 pam.d/ -rw-r--r-- 1 root root 28 Jun 4 12:00 pam_smb.conf -rw-r--r-- 1 root root 2520 Jun 4 11:57 passwd -rw-r--r-- 1 root root 7228 Jun 3 13:48 profile -rw-r--r-- 1 root root 1339 Jun 4 11:33 protocols -rw-r--r-- 1 root root 274 Jun 4 11:44 resolv.conf drwxr-xr-x 2 root root 4096 Jun 3 13:43 security/ -rw-r----- 1 root root 1178 Jun 4 11:51 shadow -rw------- 1 root root 80 Jun 4 11:45 shadow- -rw-r----- 1 root root 1178 Jun 4 11:48 shadow.old -rw-r--r-- 1 root root 161 Jun 3 13:46 shells -rw-r--r-- 1 root root 1144 Jun 3 13:46 ssh_config -rw------- 1 root root 668 Jun 3 13:46 ssh_host_dsa_key -rw-r--r-- 1 root root 602 Jun 3 13:46 ssh_host_dsa_key.pub -rw------- 1 root root 527 Jun 3 13:46 ssh_host_key -rw-r--r-- 1 root root 331 Jun 3 13:46 ssh_host_key.pub -rw------- 1 root root 883 Jun 3 13:46 ssh_host_rsa_key -rw-r--r-- 1 root root 222 Jun 3 13:46 ssh_host_rsa_key.pub -rw-r--r-- 1 root root 2471 Jun 4 12:15 sshd_config ./etc/pam.d: total 24 drwxr-xr-x 2 root root 4096 Jun 4 12:02 ./ drwxr-xr-x 4 root root 4096 Jun 4 12:35 ../ lrwxrwxrwx 1 root root 4 Jun 4 12:02 other -> sshd -rw-r--r-- 1 root root 318 Jun 3 13:46 passwd -rw-r--r-- 1 root root 546 Jun 4 11:36 ssh -rw-r--r-- 1 root root 479 Jun 4 12:02 sshd -rw-r--r-- 1 root root 370 Jun 3 13:46 su ./etc/security: total 32 drwxr-xr-x 2 root root 4096 Jun 3 13:43 ./ drwxr-xr-x 4 root root 4096 Jun 4 12:35 ../ -rw-r--r-- 1 root root 1971 Jun 3 13:46 access.conf -rw-r--r-- 1 root root 184 Jun 3 13:46 chroot.conf -rw-r--r-- 1 root root 2145 Jun 3 13:46 group.conf -rw-r--r-- 1 root root 1356 Jun 3 13:46 limits.conf -rw-r--r-- 1 root root 2858 Jun 3 13:46 pam_env.conf -rw-r--r-- 1 root root 2154 Jun 3 13:46 time.conf ./lib: total 8316 drwxr-xr-x 3 root root 4096 Jun 4 12:13 ./ drwxr-xr-x 9 root root 4096 Jun 5 10:05 ../ -rw-r--r-- 1 root root 1024 Jun 4 11:51 cracklib_dict.hwm -rw-r--r-- 1 root root 214324 Jun 4 11:51 cracklib_dict.pwd -rw-r--r-- 1 root root 11360 Jun 4 11:51 cracklib_dict.pwi -rwxr-xr-x 1 root root 342427 Jun 3 13:46 ld-linux.so.2* -rwxr-xr-x 1 root root 4061504 Jun 3 13:46 libc.so.6* lrwxrwxrwx 1 root root 15 Jun 4 12:11 libcrack.so -> libcrack.so.2.7* lrwxrwxrwx 1 root root 15 Jun 4 12:11 libcrack.so.2 -> libcrack.so.2.7* -rwxr-xr-x 1 root root 33291 Jun 4 11:39 libcrack.so.2.7* -rwxr-xr-x 1 root root 60988 Jun 3 13:46 libcrypt.so.1* -rwxr-xr-x 1 root root 71846 Jun 3 13:46 libdl.so.2* -rwxr-xr-x 1 root root 27762 Jun 3 13:46 libhistory.so.4.0* lrwxrwxrwx 1 root root 17 Jun 4 12:12 libncurses.so.4 -> libncurses.so.4.2* -rwxr-xr-x 1 root root 503903 Jun 3 13:46 libncurses.so.4.2* lrwxrwxrwx 1 root root 17 Jun 4 12:12 libncurses.so.5 -> libncurses.so.5.0* -rwxr-xr-x 1 root root 549429 Jun 3 13:46 libncurses.so.5.0* -rwxr-xr-x 1 root root 369801 Jun 3 13:46 libnsl.so.1* -rwxr-xr-x 1 root root 142563 Jun 4 11:49 libnss_compat.so.1* -rwxr-xr-x 1 root root 215569 Jun 4 11:49 libnss_compat.so.2* -rwxr-xr-x 1 root root 61648 Jun 4 11:34 libnss_dns.so.1* -rwxr-xr-x 1 root root 63453 Jun 4 11:34 libnss_dns.so.2* -rwxr-xr-x 1 root root 63782 Jun 4 11:34 libnss_dns6.so.2* -rwxr-xr-x 1 root root 205715 Jun 3 13:46 libnss_files.so.1* -rwxr-xr-x 1 root root 235932 Jun 3 13:49 libnss_files.so.2* -rwxr-xr-x 1 root root 204383 Jun 4 11:33 libnss_nis.so.1* -rwxr-xr-x 1 root root 254023 Jun 4 11:33 libnss_nis.so.2* -rwxr-xr-x 1 root root 256465 Jun 4 11:33 libnss_nisplus.so.2* lrwxrwxrwx 1 root root 14 Jun 4 12:12 libpam.so.0 -> libpam.so.0.72* -rwxr-xr-x 1 root root 31449 Jun 3 13:46 libpam.so.0.72* lrwxrwxrwx 1 root root 19 Jun 4 12:12 libpam_misc.so.0 -> libpam_misc.so.0.72* -rwxr-xr-x 1 root root 8125 Jun 3 13:46 libpam_misc.so.0.72* lrwxrwxrwx 1 root root 15 Jun 4 12:12 libpamc.so.0 -> libpamc.so.0.72* -rwxr-xr-x 1 root root 10499 Jun 3 13:46 libpamc.so.0.72* -rwxr-xr-x 1 root root 176427 Jun 3 13:46 libreadline.so.4.0* -rwxr-xr-x 1 root root 44729 Jun 3 13:46 libutil.so.1* -rwxr-xr-x 1 root root 70254 Jun 3 13:46 libz.a* lrwxrwxrwx 1 root root 13 Jun 4 12:13 libz.so -> libz.so.1.1.3* lrwxrwxrwx 1 root root 13 Jun 4 12:13 libz.so.1 -> libz.so.1.1.3* -rwxr-xr-x 1 root root 63312 Jun 3 13:46 libz.so.1.1.3* drwxr-xr-x 2 root root 4096 Jun 4 12:00 security/ ./lib/security: total 668 drwxr-xr-x 2 root root 4096 Jun 4 12:00 ./ drwxr-xr-x 3 root root 4096 Jun 4 12:13 ../ -rwxr-xr-x 1 root root 10067 Jun 3 13:46 pam_access.so* -rwxr-xr-x 1 root root 8300 Jun 3 13:46 pam_chroot.so* -rwxr-xr-x 1 root root 14397 Jun 3 13:46 pam_cracklib.so* -rwxr-xr-x 1 root root 5082 Jun 3 13:46 pam_deny.so* -rwxr-xr-x 1 root root 13153 Jun 3 13:46 pam_env.so* -rwxr-xr-x 1 root root 13371 Jun 3 13:46 pam_filter.so* -rwxr-xr-x 1 root root 7957 Jun 3 13:46 pam_ftp.so* -rwxr-xr-x 1 root root 12771 Jun 3 13:46 pam_group.so* -rwxr-xr-x 1 root root 10174 Jun 3 13:46 pam_issue.so* -rwxr-xr-x 1 root root 9774 Jun 3 13:46 pam_lastlog.so* -rwxr-xr-x 1 root root 13591 Jun 3 13:46 pam_limits.so* -rwxr-xr-x 1 root root 11268 Jun 3 13:46 pam_listfile.so* -rwxr-xr-x 1 root root 11182 Jun 3 13:46 pam_mail.so* -rwxr-xr-x 1 root root 5923 Jun 3 13:46 pam_nologin.so* -rwxr-xr-x 1 root root 5460 Jun 3 13:46 pam_permit.so* -rwxr-xr-x 1 root root 18226 Jun 3 13:46 pam_pwcheck.so* -rwxr-xr-x 1 root root 12590 Jun 3 13:46 pam_rhosts_auth.so* -rwxr-xr-x 1 root root 5551 Jun 3 13:46 pam_rootok.so* -rwxr-xr-x 1 root root 7239 Jun 3 13:46 pam_securetty.so* -rwxr-xr-x 1 root root 6551 Jun 3 13:46 pam_shells.so* -rwxr-xr-x 1 root root 55925 Jun 4 12:00 pam_smb_auth.so* -rwxr-xr-x 1 root root 12678 Jun 3 13:46 pam_stress.so* -rwxr-xr-x 1 root root 11170 Jun 3 13:46 pam_tally.so* -rwxr-xr-x 1 root root 11124 Jun 3 13:46 pam_time.so* -rwxr-xr-x 1 root root 45703 Jun 3 13:46 pam_unix.so* -rwxr-xr-x 1 root root 45703 Jun 3 13:46 pam_unix2.so* -rwxr-xr-x 1 root root 45386 Jun 3 13:46 pam_unix_acct.so* -rwxr-xr-x 1 root root 45386 Jun 3 13:46 pam_unix_auth.so* -rwxr-xr-x 1 root root 45386 Jun 3 13:46 pam_unix_passwd.so* -rwxr-xr-x 1 root root 45386 Jun 3 13:46 pam_unix_session.so* -rwxr-xr-x 1 root root 9726 Jun 3 13:46 pam_userdb.so* -rwxr-xr-x 1 root root 6424 Jun 3 13:46 pam_warn.so* -rwxr-xr-x 1 root root 7460 Jun 3 13:46 pam_wheel.so* ./sbin: total 3132 drwxr-xr-x 2 root root 4096 Jun 4 12:35 ./ drwxr-xr-x 9 root root 4096 Jun 5 10:05 ../ -rwxr-xr-x 1 root root 178256 Jun 3 13:46 choptest* -rwxr-xr-x 1 root root 184032 Jun 3 13:46 cqtest* -rwxr-xr-x 1 root root 81096 Jun 3 13:46 dialtest* -rwxr-xr-x 1 root root 1142128 Jun 4 11:28 ldconfig* -rwxr-xr-x 1 root root 2868 Jun 3 13:46 lockname* -rwxr-xr-x 1 root root 3340 Jun 3 13:46 ondelay* -rwxr-xr-x 1 root root 376796 Jun 3 13:46 pagesend* -rwxr-xr-x 1 root root 13950 Jun 3 13:46 probemodem* -rwxr-xr-x 1 root root 9234 Jun 3 13:46 recvstats* -rwxr-xr-x 1 root root 64480 Jun 3 13:46 sftp-server* -rwxr-xr-x 1 root root 744412 Jun 3 13:46 sshd* -rwxr-xr-x 1 root root 30750 Jun 4 11:46 su* -rwxr-xr-x 1 root root 194632 Jun 3 13:46 tagtest* -rwxr-xr-x 1 root root 69892 Jun 3 13:46 tsitest* -rwxr-xr-x 1 root root 43792 Jun 3 13:46 typetest* ./tmp: total 8 drwxr-xr-x 2 root root 4096 Jun 4 12:32 ./ drwxr-xr-x 9 root root 4096 Jun 5 10:05 ../ ./usr: total 8 drwxr-xr-x 2 root root 4096 Jun 4 12:16 ./ drwxr-xr-x 9 root root 4096 Jun 5 10:05 ../ lrwxrwxrwx 1 root root 7 Jun 4 12:14 bin -> ../bin// lrwxrwxrwx 1 root root 7 Jun 4 11:33 lib -> ../lib// lrwxrwxrwx 1 root root 8 Jun 4 12:13 sbin -> ../sbin// B.7.3. Chroot environment for Apache B.7.3.1. Introducción The chroot utility is often used to jail a daemon in a restricted tree. You can use it to insulate services from one another, so that security issues in a software package do not jeopardize the whole server. When using the makejail script, setting up and updating the chrooted tree is much easier. FIXME: Apache can also be chrooted using http://www.modsecurity.org which is available in libapache-mod-security (for Apache 1.x) and libapache2-mod-security (for Apache 2.x). B.7.3.1.1. Licensing This document is copyright 2002 Alexandre Ratti. It has been dual-licensed and released under the GPL version 2 (GNU General Public License) the GNU-FDL 1.2 (GNU Free Documentation Licence) and is included in this manual with his explicit permission. B.7.3.2. Installing the server This procedure was tested on Debian GNU/Linux 3.0 (Woody) with makejail 0.0.4-1 (in Debian/testing). * Log in as root and create a new jail directory: $ mkdir -p /var/chroot/apache * Create a new user and a new group. The chrooted Apache server will run as this user/group, which isn't used for anything else on the system. In this example, both user and group are called chrapach. $ adduser --home /var/chroot/apache --shell /bin/false \ --no-create-home --system --group chrapach FIXME: is a new user needed? (Apache already runs as the apache user) * Install Apache as usual on Debian: apt-get install apache * Set up Apache (e.g. define your subdomains, etc.). In the /etc/apache/httpd.conf configuration file, set the Group and User options to chrapach. Restart Apache and make sure the server is working correctly. Now, stop the Apache daemon. * Install makejail (available in Debian/testing for now). You should also install wget and lynx as they will be used by makejail to test the chrooted server: apt-get install makejail wget lynx * Copy the sample configuration file for Apache to the /etc/makejail directory: # cp /usr/share/doc/makejail/examples/apache.py /etc/makejail/ * Edit /etc/makejail/apache.py. You need to change the chroot, users and groups options. To run this version of makejail, you can also add a packages option. See the http://www.floc.net/makejail/current/doc/. A sample is shown here: chroot="/var/chroot/apache" testCommandsInsideJail=["/usr/sbin/apachectl start"] processNames=["apache"] testCommandsOutsideJail=["wget -r --spider http://localhost/", "lynx --source https://localhost/"] preserve=["/var/www", "/var/log/apache", "/dev/log"] users=["chrapach"] groups=["chrapach"] packages=["apache", "apache-common"] userFiles=["/etc/password", "/etc/shadow"] groupFiles=["/etc/group", "/etc/gshadow"] forceCopy=["/etc/hosts", "/etc/mime.types"] FIXME: some options do not seem to work properly. For instance, /etc/shadow and /etc/gshadow are not copied, whereas /etc/password and /etc/group are fully copied instead of being filtered. * Create the chroot tree: makejail /etc/makejail/apache.py * If /etc/password and /etc/group were fully copied, type: $ grep chrapach /etc/passwd > /var/chroot/apache/etc/passwd $ grep chrapach /etc/group > /var/chroot/apache/etc/group to replace them with filtered copies. * Copy the Web site pages and the logs into the jail. These files are not copied automatically (see the preserve option in makejail's configuration file). # cp -Rp /var/www /var/chroot/apache/var # cp -Rp /var/log/apache/*.log /var/chroot/apache/var/log/apache * Edit the startup script for the system logging daemon so that it also listen to the /var/chroot/apache/dev/log socket. In /etc/default/syslogd, replace: SYSLOGD="" with SYSLOGD=" -a /var/chroot/apache/dev/log" and restart the daemon (/etc/init.d/sysklogd restart). * Edit the Apache startup script (/etc/init.d/apache). You might need to make some changes to the default startup script for it to run properly with a chrooted tree. Such as: * set a new CHRDIR variable at the top of the file; * edit the start, stop, reload, etc. sections; * add a line to mount and unmount the /proc filesystem within the jail. #! /bin/bash # # apache Start the apache HTTP server. # CHRDIR=/var/chroot/apache NAME=apache PATH=/bin:/usr/bin:/sbin:/usr/sbin DAEMON=/usr/sbin/apache SUEXEC=/usr/lib/apache/suexec PIDFILE=/var/run/$NAME.pid CONF=/etc/apache/httpd.conf APACHECTL=/usr/sbin/apachectl trap "" 1 export LANG=C export PATH test -f $DAEMON || exit 0 test -f $APACHECTL || exit 0 # ensure we don't leak environment vars into apachectl APACHECTL="env -i LANG=${LANG} PATH=${PATH} chroot $CHRDIR $APACHECTL" if egrep -q -i "^[[:space:]]*ServerType[[:space:]]+inet" $CONF then exit 0 fi case "$1" in start) echo -n "Starting web server: $NAME" mount -t proc proc /var/chroot/apache/proc start-stop-daemon --start --pidfile $PIDFILE --exec $DAEMON \ --chroot $CHRDIR ;; stop) echo -n "Stopping web server: $NAME" start-stop-daemon --stop --pidfile "$CHRDIR/$PIDFILE" --oknodo umount /var/chroot/apache/proc ;; reload) echo -n "Reloading $NAME configuration" start-stop-daemon --stop --pidfile "$CHRDIR/$PIDFILE" \ --signal USR1 --startas $DAEMON --chroot $CHRDIR ;; reload-modules) echo -n "Reloading $NAME modules" start-stop-daemon --stop --pidfile "$CHRDIR/$PIDFILE" --oknodo \ --retry 30 start-stop-daemon --start --pidfile $PIDFILE \ --exec $DAEMON --chroot $CHRDIR ;; restart) $0 reload-modules exit $? ;; force-reload) $0 reload-modules exit $? ;; *) echo "Usage: /etc/init.d/$NAME {start|stop|reload|reload-modules|force-reload|restart}" exit 1 ;; esac if [ $? == 0 ]; then echo . exit 0 else echo failed exit 1 fi FIXME: should the first Apache process be run as another user than root (i.e. add --chuid chrapach:chrapach)? Cons: chrapach will need write access to the logs, which is awkward. * Replace in /etc/logrotate.d/apache/var/log/apache/*.log with /var/chroot/apache/var/log/apache/*.log * Start Apache (/etc/init.d/apache start) and check what is it reported in the jail log (/var/chroot/apache/var/log/apache/error.log). If your setup is more complex, (e.g. if you also use PHP and MySQL), files will probably be missing. if some files are not copied automatically by makejail, you can list them in the forceCopy (to copy files directly) or packages (to copy full packages and their dependencies) option the /etc/makejail/apache.py configuration file. * Type ps aux | grep apache to make sure Apache is running. You should see something like: root 180 0.0 1.1 2936 1436 ? S 04:03 0:00 /usr/sbin/apache chrapach 189 0.0 1.1 2960 1456 ? S 04:03 0:00 /usr/sbin/apache chrapach 190 0.0 1.1 2960 1456 ? S 04:03 0:00 /usr/sbin/apache chrapach 191 0.0 1.1 2960 1456 ? S 04:03 0:00 /usr/sbin/apache chrapach 192 0.0 1.1 2960 1456 ? S 04:03 0:00 /usr/sbin/apache chrapach 193 0.0 1.1 2960 1456 ? S 04:03 0:00 /usr/sbin/apache * Make sure the Apache processes are running chrooted by looking in the /proc filesystem: ls -la /proc/process_number/root/. where process_number is one of the PID numbers listed above (2nd column; 189 for instance). The entries for a restricted tree should be listed: drwxr-sr-x 10 root staff 240 Dec 2 16:06 . drwxrwsr-x 4 root staff 72 Dec 2 08:07 .. drwxr-xr-x 2 root root 144 Dec 2 16:05 bin drwxr-xr-x 2 root root 120 Dec 3 04:03 dev drwxr-xr-x 5 root root 408 Dec 3 04:03 etc drwxr-xr-x 2 root root 800 Dec 2 16:06 lib dr-xr-xr-x 43 root root 0 Dec 3 05:03 proc drwxr-xr-x 2 root root 48 Dec 2 16:06 sbin drwxr-xr-x 6 root root 144 Dec 2 16:04 usr drwxr-xr-x 7 root root 168 Dec 2 16:06 var To automate this test, you can type:ls -la /proc/`cat /var/chroot/apache/var/run/apache.pid`/root/. FIXME: Add other tests that can be run to make sure the jail is closed? The reason I like this is because setting up the jail is not very difficult and the server can be updated in just two lines: apt-get update && apt-get install apache makejail /etc/makejail/apache.py B.7.4. See also If you are looking for more information you can consider these sources of information in which the information presented is based: http://www.floc.net/makejail/, this program was written by Alain Tesio ------------------------------------------------------------------------ [78] Typically the needed packages will be installed through the dependencies [79] It can also be downloaded from http://www.cert.org/kb/acid/, http://acidlab.sourceforge.net or http://www.andrew.cmu.edu/~rdanyliw/snort/. [80] Since version 9.2.1-5. That is, since Debian release sarge. [81] Such as knockd. Alternatively, you can open a different console and have the system ask for confirmation that there is somebody on the other side, and reset the firewall chain if no confirmation is given. The following test script could be of use: #!/bin/bash while true; do read -n 1 -p "Are you there? " -t 30 ayt if [ -z "$ayt" ] ; then break fi done # Reset the firewall chain, user is not available echo echo "Resetting firewall chain!" iptables -F iptables -P INPUT ACCEPT iptables -P FORWARD ACCEPT iptables -P OUTPUT ACCEPT exit 1 [82] You can use the debug option to have it send the progress of the module to the authpriv.notice facility [83] You can create a very limited bash environment with the following python definition for makejail, just create the directory /var/chroots/users/foo and a file with the following contents and call it bash.py: chroot="/var/chroots/users/foo" cleanJailFirst=1 testCommandsInsideJail=["bash ls"] And then run makejail bash.py to create the user environment at /var/chroots/users/foo. To test the environment run: # chroot /var/chroots/users/foo/ ls bin dev etc lib proc sbin usr [84] In some occasions you might need the /dev/ptmx and /dev/pty* devices and the /dev/pts/ subdirectory. Running MAKEDEV in the /dev directory of the chrooted environment should be sufficient to create them if they do not exist. If you are using kernels (version 2.6) which dynamically create device files you will need to create the /dev/pts/ files yourself and grant them the proper privileges. [85] If you are using a kernel that implements Mandatory Access Control (RSBAC/SElinux) you can avoid changing this configuration just by granting the sshd user privileges to make the chroot() system call. [86] Notice that there are no SETUID files. This makes it more difficult for remote users to escape the chroot environment. However, it also prevents users from changing their passwords, since the passwd program cannot modify the files /etc/passwd or /etc/shadow.