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/. 摘要 本文档主要涉及 Debian 项目的安全部分. 其源于让 Debian GNU/Linux 发行的版缺省安装过程更加安全和强壮. 同时也涉及一些常见的使用 Debian GNU/Linux 配置安全网络环境的任务, 提供了很多安全工具的附加信息, 并且对 Debian 安全小组如何加强安全策略进行讨论. ------------------------------------------------------------------------ 第 1 章 介绍 ======== 撰写安全文档, 最难莫过于每个案例都是相互独立的. 需要着重考虑站点, 主机, 或网络所处环境和安全需求. 例如, 家庭用户的安全需求则与网络银行完全不同. 家庭用户所要面对的主要威胁来自骇客的脚本陷阱. 网络银行所必须担心的则是直接攻击. 另外, 银行必须保证其用户数据的精确性. 简而言之, 用户必须在安全性和易用性之间作出妥协. 注意本手册只涉及与软件相关部分. 即使是世界上最好的软件也无法保护可以物理接触的计算机. 您可以把计算机置于工作台下, 或者重兵把守的堡垒里. 然而一个正确配置的台式计算机可能比被重兵保护的充满安全漏洞的计算机更安(从软件观点来看). 很明显, 这两个方面您都要考虑. 本手册仅仅在增加 Debian GNU/Linux 系统的安全方面作简要介绍. 如果您浏览过有关 Linux 安全的其它文档, 会发现一些通用性问题可能与本手册重复. 当然, 本手册并不试图作为您的最后信息源, 而只是设法在同样的问题上提供更适合 Debian GNU/Linux 系统的信息. 不同的发行版处理问题的方式不同(守护进程的启动就是一例); 您将发现本手册是针对 Debian 程序和工具的. 1.1. 作者 ------- 本手册的当前维护者是 Javier Fernández-Sanguino Peña。如有关本手册任何的评论、添加或建议,请和他联系,他们将会考虑添加到本手册。 本手册最初只是 Alexander Reelsen 撰写的一篇 HOWTO文档。在互联网上发布后,Javier Fernández-Sanguino Peña 将其整合到 Debian 文档项目 中。许多人为手册作出了贡献(所有贡献都在更新记录中列出)。需要特别指出以下人员做出了重要的贡献(完成了完整的章、节或附录): * Stefano Canepa * Era Eriksson * Carlo Perassi * Alexandre Ratti * Jaime Robles * Yotam Rubin * Frederic Schutz * Pedro Zorzenon Neto * Oohara Yuuma * Davor Ocelic 1.2. 在哪里获取手册(以及可用的格式) --------------------- 您可以从 Debian 文档项目的网页上下载或查看本 Debian 安全手册的最新版本。如果您正在其它站点阅读本文档的副本,请先检查网页上提供的正式主版本是否提供了更新的信息。如果您正在阅读翻译版本,请检查翻译的版本是否对应了可用的原文最新版。如果您的版本更旧,请考虑使用原始副本或检查新版存在哪些改动。 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. 组织信息与反馈 ------------ 这是手册的正式部分. 此时,我(Alexander Reelsen)撰写了本手册的主要部分, 但是就我看来不应该停滞于此. 自由软件伴随我成长与生活, 它是我日常使用的一部分,我猜您也如此. 任何人都可以将其反馈, 附加提示或任何其它建议寄发给我. If you think, you can maintain a certain section or paragraph better, then write to the document maintainer and you are welcome to do it. Especially if you find a section marked as FIXME, that means the authors did not have the time yet or the needed knowledge about the topic. Drop them a mail immediately. 本手册的主题清楚的表明及时更新相当重要, 如果您可以做到. 请贡献. 1.4. 预备知识 --------- The installation of Debian GNU/Linux is not very difficult and you should have been able to install it. If you already have some knowledge about Linux or other Unices and you are a bit familiar with basic security, it will be easier to understand this manual, as this document cannot explain every little detail of a feature (otherwise this would have been a book instead of a manual). If you are not that familiar, however, you might want to take a look at for where to find more in-depth information. 1.5. 需要添加一些内容(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 (第 1.1 节 “作者”). * 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. * 考虑添加关于如何构建基于 Debian 的网络应用的部分(以及如基本系统, equivs 和 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. * 增加使用 Debian GNU/Linux 配置防火墙的内容. 此部分假定要保护的是单系统(不保护其他...)并就如何测试设定进行讨论. * 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). * 使用 file-rc 进行服务配置的内容。 * 检查所有参考 URL, 删除/修正不再可用的部分. * 增加关于对一般服务器进行功能限制性替换方面的内容(Debian)。例如: * 用 cups(软件包)本地打印? * 用 lpr 远程打印 * 用 dnrd/maradns 替代 bind * 用 dhttpd/thttpd/wn(tux?) 替代 apache * 用 ssmtpd/smtpd/postfix 替代 exim/sendmail * 用 tinyproxy 替代 squid * 用 oftpd/vsftp 替代 ftpd * ... * Debian 中更多有关内核安全补丁的内容, 包括上边提到的和具体如何使用这些补丁应用到 Debian 系统中的内容. * Linux 入侵检测 (kernel-patch-2.4-lids) * Linux Trustees (在 trustees 软件包中) * NSA Enhanced Linux * linux-patch-openswan * ... * 禁用不必要的网络服务(包括 inetd )的内容, 这属于程序安全化部分, 但可以涉及的更广一点. * 有关口令转换的内容,这与策略关系更密切. * 策略,和用户培训策略。 * 更多关于 tcpwrappers, 和 wrappers 的内容? * hosts.equiv 以及其它主要安全漏洞. * 文件共享服务方面的问题如 Samba 和 NFS? * suidmanager/dpkg-statoverrides. * lpr 和 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. * 更多关于日志分析软件的内容 (即 logcheck 和 logcolorise). * 'advanced' routing (traffic policing is security related). * 限制 ssh 对于某些运行命令的访问. * dpkg-statoverride 的使用。 * 对用户共享 CD 刻录机的安全方法. * 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). * 安全的网络浏览器. * 设置经由 ssh 的 FTP。 * 使用加密回环文件系统。 * 加密整个文件系统。 * steganographic tools. * 为一个组织设置 PKA。 * 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. * 添加有关虚拟服务器(如 Xen 等)的作用的章节。 * Explain how to use some integrity checkers (AIDE, integrit or samhain). The basics are simple and could even explain some configuration improvements. 1.6. 荣誉与致谢! ----------- * Alexander Reelsen 撰写了原始文档。 * 向原始文档添加了更多信息。 * Robert van der Meulen 提供了 quota 章节和很多好主意。 * Ethan Benson 校正了 PAM 章节并提供了一些好的建议。 * Dariusz Puchalak 为一些章节提供一些信息。 * Gaby Schilders 提供了一个很棒的 Genius/Paranoia 主意. * Era Eriksson 弄顺了许多地方的语法并提供了附录清单。 * Philipe Gaspar 撰写了 LKM 部分。 * Yotam Rubin contributed fixes for many typos as well as information regarding bind versions and MD5 passwords. * 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 第 1.2 节 “在哪里获取手册(以及可用的格式)”). * (Alexander) All the folks who encouraged me to write this HOWTO (which was later turned into a manual). * 整个 Debian 项目。 第 2 章 开始之前 ========== 2.1. 系统用途 --------- Debian 的安全配置与其它系统没有太大的不同; 要正确的考虑 Debian 系统安全问题, 首先要确定系统的用途. 然后, 如果需要一个真正安全的系统, 必须考虑下边的步骤. 您会发现本手册从基础写起, 也就是说, 是在 Debian 系统安装之前, 安装过程中, 和安装之后, 应当阅读的一些任务信息,这些任务是: * 确定哪些服务是您需要的, 哪些是应当限制的. 这包括禁用/卸载不必要的服务, 添加防火墙过滤, 或 tcp 伪装. * 系统中用户权限的设置. * 增强提供的服务安全性, 即使出现问题, 也应将影响降到最小. * 使用适当的工具, 确保及时发现未经授权的使用, 以便能采取适当的措施. 2.2. 应当知道的一般性安全问题 ----------------- 下边在为什么一些内容了涉及安全问题上(通常)将不做细节性探讨. 因此, 你最好有 UNIX 和(特别是) linux 安全知识背景, 您遇到不同选择的时候, 花点时间阅读一些安全文档是个明智的决定. Debian GNU/Linux 是基于 linux 内核的, 因此很多有关 Linux 的信息, 以及其它发行版和一般性 Unix 安全同样也适用于它(即使使用工具或程序有所不同). 一些有用的文档: * 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. * In http://www.tldp.org/links/p_books.html#securing_linux you can find a similar document to this manual but related to Red Hat, some of the issues are not distribution-specific and also apply to 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. In any case, there is more information regarding the services explained here (NFS, NIS, SMB...) in many of the HOWTOs of the http://www.tldp.org/. Some of these documents speak on the security side of a given service, so be sure to take a look there too. The HOWTO documents from the Linux Documentation Project are available in Debian GNU/Linux through the installation of the doc-linux-text (text version) or doc-linux-html (HTML version). After installation these documents will be available at the /usr/share/doc/HOWTO/en-txt and /usr/share/doc/HOWTO/en-html directories, respectively. 其它一些推荐文档: * Linux 安全最大化 : 一个黑客在保护您的 Linux服务和网络方面给出的指导. Anonymous. Paperback - 829 pages. Sams Publishing. ISBN: 0672313413. July 1999. * Linux Security By John S. Flowers. New Riders; ISBN: 0735700354. March 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 其它一些图书 (与一般性 UNIX 安全问题相关,而不是针对 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. * 防火墙与入侵检测 Cheswick, William R. and Bellovin, Steven M.; Addison-Wesley; 1994; ISBN 0-201-63357-4; 320pp. Some useful web sites to keep up to date regarding security: * 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. Debian 对安全问题的态度 -------------------- 如果你对 Debian GNU/Linux 的安全问题有一个大概的了解, 你就应该注意到为了提供一个全面安全系统, Debian 处理问题的不同: * 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 follows security issues closely. The security team checks many security related sources, the most important being http://www.securityfocus.com/cgi-bin/vulns.pl, on the lookout for packages with security issues that might be included in Debian. * Security updates are the first priority. When a security problem arises in a Debian package, the security update is prepared as fast as possible and distributed for our stable, testing and unstable releases, including all architectures. * 有关安全的信息被集中在一个站点, http://security.debian.org/. * Debian 一直通过启动新项目努力改善发行版的整体安全性, 如自动软件包签名验证机制. * Debian 为系统管理和监控提供许多有用的有关安全的工具. 为了更好的实施本地安全策略, 开发者努力将这些工具与发行版紧密的结合在一起. 这些工具包括: 集中认证,审核工具,加固工具,防火墙工具,入侵察觉工具,等等. * 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 第 1.4 节 “预备知识”), 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. 第 3 章 安装前和安装过程中 =============== 3.1. 选择一个 BIOS 密码 ----------------- Before you install any operating system on your computer, set up a BIOS password. After installation (once you have enabled bootup from the hard disk) you should go back to the BIOS and change the boot sequence to disable booting from floppy, CD-ROM and other devices that shouldn't boot. Otherwise a cracker only needs physical access and a boot disk to access your entire system. 没有密码就无法引导相对要好一点. 如果您运行的是一个服务器, 这将非常有效, 因为不需要经常重起. 在此情况下, 重起时需要人工干预, 如果机器不是很容易接触, 则可能变得很不方便. 注: 很多 BIOS 都有广为人知的默认密码, 并且有些程序还可以从 BIOS 中获取密码. 推论: 不要依靠这种方法来保证控制台访问的安全. 3.2. 系统分区 --------- 3.2.1. 选择明智的分区方案 一份明智的分区方案依赖于机器的用途. 合理使用分区是一条不错的经验, 并注意一下因素: * 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] * 变化较大的分区, /var (特别是 /var/log)/var 应该放在一个独立的分区上. 在 Debian 系统中, 您创建的 /var 应当比在其它系统中稍大一点, 因为下载的软件包( apt 缓存) 存放于 /var/cache/apt/archives 目录下. * 您打算安装 non-distribution 软件的任何分区都应是是独立的. 根据文件层次标准, 应当是 /opt 或 /usr/local 目录. 如果这些在独立分区上, (必须)重装 Debian 系统时将不会被删除. * 从安全的角度考虑, 应当将静态数据放在独立的分区上, 并将此分区以只读的方式挂载. 将这些数据存放在只读介质上会更好. 后边会详细讲解. 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). 某些情况下您可能无法确定是否需要独立的分区, 可以安装逻辑卷管理器(Logical Volume Manager) (lvm-common 和您的内核所需的二进制程序, 可能是 lvm10, lvm6, 或 lvm5), 使用 lvm 可以创造扩展多物理容量的卷组. 3.2.2. 选择合适的文件系统 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: * 为膝上电脑安装任何文件系统. 在意外的电池耗尽或因为硬件问题(如一般的 X 配置问题) 引起系统锁死, 重起后可能丢失数据. * 对于存放大量数据的系统来说(象邮件服务器, ftp服务器, 网络文件系统...)推荐使用这些分区格式. 这样, 系统出现故障的时候, 系统用于恢复和检查文件系统的时间就会大大缩短, 同时数据丢失的可能也会降低. 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. 无论怎样, 在 ext3 下数据完整性也许更好,因为它是真正的文件-数据记录, 而其它的仅仅是元-数据记录, 参见 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. 准备好前不要连入互联网 ---------------- 系统在安装过程中不应该被连入互联网. 这听起来很蠢, 因为网络安装是最常用的方法. 系统安装后服务马上被激活, 如果系统连入互联网但服务没有被正确配置,那么您将面临着被攻击. 同时应当注意到您所安装软件包中的一些服务可能存在着未被修复的安全漏洞. 如果您的系统是由老版本安装的, 通常会是如此(象 CD ROM). 在这种情况下,安装完成前您的系统是非常脆弱的! 因为 Debian 的安装和升级可以通过互联网来完成, 可能您认为使用它的这个特性进行安装是个不错的主意. 如果系统用于直接连入互联网(且没有防火墙或 NAT 的保护), 那么安装过程最好不要与互联网相连, 而是使用本地软件 包镜象进行安装和安全升级. 您可以使用 Debian 的工具(如果是 Debian 系统)在其它和互联网相连的系统上设置 软件包镜象, 譬如 apt-move 或 apt-proxy, 或其它的常见镜象工具, 来提供安装源. 如果不能实现, 您可以通过设置防火墙规则, 来限制在安装过程中对系统的访问 (参见 第 B.6 节 “防火墙保护下的安全更新”). 3.4. 设置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 第 4.11.20 节 “生成用户密码”). 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. 运行最少服务需求 ------------- 服务就是程序, 如 ftp 服务器和 web 服务. 因为它们必需 侦听 连接请求, 并响应服务, 这样外部计算机就可以和您的计算机建立连接. 服务器有时候是非常脆弱的(即, 可能在遭受一次攻击后瘫痪), 因此存在安全风险. 您不应该在您的机器安装不需要的服务. 每个安装的服务都可能在您的计算机上产生新的,或许不明显(或不知道)的安全漏洞. 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 第 5.13 节 “增强 RPC 服务的安全性” for more information on how to secure or disable RPC services. 当您在 Debian GNU/Linux 系统中安装一个新的网络相关的服务(守护进程), 有两种方式将其激活: 通过 inetd 超级守护进程(即在 /etc/inetd.conf 中加入一行)或 通过一个独立的程序将自身与您的网络接口绑定. 独立程序由 /etc/init.d 目录下的文件控制, 通过 SysV 机制在启动时使用 /etc/rc?.d/* 下的连接来启用相应的服务 (更多信息参阅 /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 第 3.5.1 节 “禁用守护进程服务”. 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. 禁用守护进程服务 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 . Where XX is a number that determines when the stop action for that service will be executed. Please note that, if you are not using file-rc, update-rc.d -f service remove will not work properly, since all links are removed, upon re-installation or upgrade of the package these links will be re-generated (probably not what you wanted). If you think this is not intuitive you are probably right (see http://bugs.debian.org/67095). From the manpage: If any files /etc/rcrunlevel.d/[SK]??name already exist then update-rc.d does nothing. This is so that the system administrator can rearrange the links, provided that they leave at least one link remaining, without having their configuration overwritten. 如果您使用 file-rc 则关于服务启动的所有信息由一个共同的配置文件处理和维护, 既使软件包从系统中删除. 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. Unlike other (UNIX) operating systems, services in Debian cannot be disabled by modifying files in /etc/default/service_name. FIXME: Add more information on handling daemons using file-rc. 3.5.2. 禁用 inetd 服务 现在, 您应当检查一下是否真的需要 inetd 守护进程. inetd 一直是对内核不足的一个补偿, 但是那些问题已经在最新的内核中得到了解决. 可能会因为 inetd 而存在拒绝服务(它将会极大的增加机器的负载), 并且很多人喜欢直接使用守护进程而不是通过 inetd 加载. 如果您仍然想使用 inetd 类的服务, 请使用更加结构化的 inet 守护进程 如 xinetd 或 rlinetd 或 rlinetd. 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). 您可以通过直接编辑/etc/inetd.conf 来禁用服务, 但 Debian 提供一个更好的选择: update-inetd(当您要启用服务的时候会更方便). 您可以通过执行下边的命令来改变文件设置并重起守护进程以删除 telnet 服务(这样 telnet 就被禁用了): /usr/sbin/update-inetd --disable telnet 如果您想保留一项服务, 但又不想让其监听您的主机的所有IP地址, 那么您可以使用 inetd 的非归档特性 (服务名称用 service@ip 代替)或者使用其他的 inetd 守护进程如 xinetd. 3.6. 安装最少数量的需求软件 ---------------- 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. 您已经知道了系统的用途(不是吗?), 因此应该只安装真正需要的软件. 安装的任何多余的工具都可能被试图破坏系统的用户或外部入侵者所利用(或通过可利用服务执行远端代码). 例如, 开发工具( C 编译器)或解释型语言(譬如 perl, python, tcl..., 其中 perl 在后面还会讲到) 可以帮助攻击者破坏系统做很多事情: * 允许他提升权限. 这非常容易, 例如,如果装有调试器和编译器,就可以在本地系统运行 exploits, 并进行调试 ! * providing tools that could help the attacker to use the compromised system as a base of attack against other systems. [7] 当然, 一个入侵者通过本地 shell 下载他们的工具并运行, 即使是 shell 本身也能做出复杂的程序. 删除不必要的软件并不能 避免 问题的发生, 但是可以增加入侵者入侵的难度(并且有可能放弃它转而寻找更容易的目标). 因此, 如果在生产系统中安装了用于远程攻击的工具(参阅 第 8.1 节 “远程风险评估工具”), 就不要期望入侵者不会利用它. 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. 删除 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] 哪些程序使用 perl? 运行下边的命令您自己可以看到: $ for i in /bin/* /sbin/* /usr/bin/* /usr/sbin/*; do [ -f $i ] && { type=`file $i | grep -il perl`; [ -n "$type" ] && echo $i; }; done 输出的程序是的优先级是 required 或 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. 因此, 没有Perl, 除非你在 shell 脚本里重新编制这些程序, 否则您将不能处理任何软件包 (因此您将不能升级系统, 这不是一件好事情). 如果您确定从 Debian 基本系统中删除 Perl, 并且您有比较宽松的时间, 递交错误报告, 以及 shell 脚本程序作为以前的软件包(作为补丁)的替代. 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. 阅读 Debian 的安全邮件列表 ---------------------- 浏览一下 debian 安全公告的邮件列表, 此处 Debian 安全小组发布对已发行软件包的公告和修正, 或发邮件给mailto:debian-security@lists.debian.org, 您可以参与 Debian 安全相关问题的讨论, 并不属于浪费时间. In order to receive important security update alerts, send an email to mailto:debian-security-announce-request@lists.debian.org with the word "subscribe" in the subject line. You can also subscribe to this moderated email list via the web page at http://www.debian.org/MailingLists/subscribe. This mailing list has very low volume, and by subscribing to it you will be immediately alerted of security updates for the Debian distribution. This allows you to quickly download new packages with security bug fixes, which is very important in maintaining a secure system (see 第 4.2 节 “进行安全更新” for details on how to do this). ------------------------------------------------------------------------ [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. 第 4 章 After installation ======================== 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 第 4.3 节 “修改 BIOS (再次)”,第 4.4 节 “设置 LILO 或 GRUB 密码”, 第 4.6 节 “取消 root 的提示等待”, 第 4.7 节 “限制控制台登录”, and 第 4.8 节 “限制系统通过控制台重起”. 在连入任何网络前, 特别是将要连入公网之前, 至少应该执行一次安全更新(参阅 第 4.2 节 “进行安全更新”). 最好, 您能对系统进行系统快照(参阅 第 4.19 节 “生成系统快照”). 4.1. Subscribe to the Debian Security Announce mailing list ----------------------------------------------------------- 您可以通过订阅 debian-security-announce 邮件列表,接收 Debian 的安全公告(DSAs), 关于 Debian 安全小组的更多内容, 参阅 第 7.1 节 “Debian 安全小组”. 如何订阅邮件列表参见 http://lists.debian.org. 由 Debian 安全小组签署的 DSAs 也可以从 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. 进行安全更新 ----------- 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 第 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 第 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. * 如果使用 dselect, 那么, 首先[U]pdate, 然后 [I]nstall 最后, [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. 修改 BIOS (再次) ----------------- 还记得 第 3.1 节 “选择一个 BIOS 密码” 吗? 很好, 当你不必从可移动介质启动的时候, 应当更改 BIOS 的默认设置,使之只能从硬盘引导. 确保不会丢失 BIOS 密码, 否则, 硬盘启动失败的时候您将不能回到 BIOS 和更改设置, 例如从 CD-ROM 启动. 其它不太安全但很方便的方式是, 设置系统从硬盘引导, 失败后则尝试从可移动介质引导. 通常是这样设置的, 因为 BIOS 密码不常使用, 很容易忘记. 4.4. 设置 LILO 或 GRUB 密码 ---------------------- Anybody can easily get a root-shell and change your passwords by entering init=/bin/sh at the boot prompt. After changing the passwords and rebooting the system, the person has unlimited root-access and can do anything he/she wants to the system. After this procedure you will not have root access to your system, as you do not know the root password. 您应该为启动加载器设置一个密码以确保这类事情不会发生. 您可以选择设置全局密码或为某个影像设置密码. For LILO you need to edit the config file /etc/lilo.conf and add a password and restricted line as in the example below. 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. If you use GRUB instead of LILO, edit /boot/grub/menu.lst and add the following two lines at the top (substituting, of course hackme with the desired password). This prevents users from editing the boot items. timeout 3 specifies a 3 second delay before grub boots the default item. timeout 3 password hackme To further harden the integrity of the password, you may store the password in an encrypted form. The utility grub-md5-crypt generates a hashed password which is compatible with GRUB's encrypted password algorithm (MD5). To specify in grub that an MD5 format password will be used, use the following directive: timeout 3 password --md5 $1$bw0ez$tljnxxKLfMzmnDVaQWgjP0 The --md5 parameter was added to instruct grub to perform the MD5 authentication process. The provided password is the MD5 encrypted version of hackme. Using the MD5 password method is preferable to choosing its clear-text counterpart. More information about grub passwords may be found in the grub-doc package. 4.5. Disable root prompt on the initramfs ----------------------------------------- Note: This applies to the default kernels provided for releases after Debian 3.1 Linux2.4 kernel 在加载了 cramfs 文件系统后, 提供一个访问 root shell 的方法, 加载cramf文件系统后, 将要启动的时候, 出现提示信息, 此时允许管理员输入具有 root 权限的可执行 shell 命令, 通常用于自动检测失败后手动装载模块. 缺省为 initrd 的 linuxrc. 随后出现如下信息: "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. 取消 root 的提示等待 ------------------ 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. Linux 2.4 kernels provide a way to access a root shell while booting which will be presented just after loading the cramfs file system. A message will appear to permit the administrator to enter an executable shell with root permissions, this shell can be used to manually load modules when autodetection fails. This behavior is the default for initrd's linuxrc. The following message will appear: Press ENTER to obtain a shell (waits 5 seconds) 可以通过编辑 /etc/mkinitrd/mkinitrd.conf 做如下设置, 来修改这一特性: # DELAY The number of seconds the linuxrc script should wait to # allow the user to interrupt it before the system is brought up DELAY=0 然后重新生成您的 ramdisk image. 例如您可以这样做: # cd /boot # mkinitrd -o initrd.img-2.4.18-k7 /lib/modules/2.4.18-k7 或 (推荐): # dpkg-reconfigure -plow kernel-image-2.4.x-yz 4.7. 限制控制台登录 ------------ Some security policies might force administrators to log in to the system through the console with their user/password and then become superuser (with su or sudo). This policy is implemented in Debian by editing the /etc/pam.d/login and the /etc/securetty when using PAM: /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 使用 PAM 时, 可以通过配置 /etc/pam.d/login 文件来完成对于登录过程的其他更改, 这可能包括用户和组给定时间的约束. 很重要的一个特性是, 可以禁止空密码. 这一特性可以通过把下行中的 nullok 删除来实现: auth required pam_unix.so nullok 4.8. 限制系统通过控制台重起 ---------------- 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. 正确的挂接分区 ------------- 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 You see the difference in the options sections. The option nosuid ignores the setuid and setgid bits completely, while noexec forbids execution of any program on that mount point, and nodev ignores device files. This sounds great, but it: * only applies to ext2 or ext3 file systems * 很容易绕过 The noexec option prevents binaries from being executed directly, but was easily circumvented in earlier versions of the kernel: 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 However, many script kiddies have exploits which try to create and execute files in /tmp. If they do not have a clue, they will fall into this pit. In other words, a user cannot be tricked into executing a trojanized binary in /tmp e.g. when /tmp is accidentally added into the local PATH. Also be forewarned, some script might depend on /tmp being executable. Most notably, Debconf has (had?) some issues regarding this, for more information see http://bugs.debian.org/116448. 下边是一个更加详尽的例子. 注意, 虽然: /var 可以被设为 noexec, 但一些软件[15]把它们的程序存放在 /var 目录下. nosuid 选项也是一样. /dev/sda6 /usr ext3 defaults,ro,nodev 0 2 /dev/sda12 /usr/share ext3 defaults,ro,nodev,nosuid 0 2 /dev/sda7 /var ext3 defaults,nodev,usrquota,grpquota 0 2 /dev/sda8 /tmp ext3 defaults,nodev,nosuid,noexec,usrquota,grpquota 0 2 /dev/sda9 /var/tmp ext3 defaults,nodev,nosuid,noexec,usrquota,grpquota 0 2 /dev/sda10 /var/log ext3 defaults,nodev,nosuid,noexec 0 2 /dev/sda11 /var/account ext3 defaults,nodev,nosuid,noexec 0 2 /dev/sda13 /home ext3 rw,nosuid,nodev,exec,auto,nouser,async,usrquota,grpquota 0 2 /dev/fd0 /mnt/fd0 ext3 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. 将 /tmp 设为 noexec Be careful if setting /tmp noexec when you want to install new software, since some programs might use it for installation. apt is one such program (see http://bugs.debian.org/116448) if not configured properly APT::ExtractTemplates::TempDir (see apt-extracttemplates(1)). You can set this variable in /etc/apt/apt.conf to another directory with exec privileges other than /tmp. 4.10.2. 设置 /usr 为只读 If you set /usr read-only you will not be able to install new packages on your Debian GNU/Linux system. You will have to first remount it read-write, install the packages and then remount it read-only. apt can be configured to run commands before and after installing packages, so you might want to configure it properly. 修改 /etc/apt/apt.conf 并加入: 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. 提供安全的用户访问 --------------- 4.11.1. 用户认证: 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). 每个带有PAM支持的服务在 /etc/pam.d/ 下都有一个配置文件, 可以通过修改它来完成配置: * 认证使用什么样的后端. * 会话使用什么样的后端. * 如何进行密码检测. 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 offers you the possibility to go through several authentication steps at once, without the user's knowledge. You could authenticate against a Berkeley database and against the normal passwd file, and the user only logs in if the authentication succeeds in both. You can restrict a lot with PAM, just as you can open your system doors very wide. So be careful. A typical configuration line has a control field as its second element. Generally it should be set to requisite, which returns a login failure if one module fails. 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 This definition: * 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: # Be sure to install libpam-cracklib first or you will not be able to log in 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. User access control in PAM 可以在 /etc/pam.d/login 中加入一下行, 以确保 root 用户只能从本地终端登录: 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 第 4.7 节 “限制控制台登录”). 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. User limits in PAM The following line should be enabled in /etc/pam.d/login to set up user resource limits. session required pam_limits.so This restricts the system resources that users are allowed (see below in 第 4.11.8 节 “资源的限制使用: limits.conf 文件”). For example, you could restrict the number of concurrent logins (of a given group of users, or system-wide), number of processes, memory size etc. 4.11.5. Control of su in PAM If you want to protect su, so that only some people can use it to become root on your system, you need to add a new group "wheel" to your system (that is the cleanest way, since no file has such a group permission yet). Add root and the other users that should be able to su to the root user to this group. Then add the following line to /etc/pam.d/su: auth requisite pam_wheel.so group=wheel debug 以确保只有组 "wheel" 的用户可以使用 su 成为root. 其它用户不能成为 root. 事实上如果他们试图成为 root 将会得到一条拒绝信息. If you want only certain users to authenticate at a PAM service, this is quite easy to achieve by using files where the users who are allowed to login (or not) are stored. Imagine you only want to allow users 'ref' to log in via ssh. So you put them into /etc/sshusers-allowed and write the following into /etc/pam.d/ssh: auth required pam_listfile.so item=user sense=allow file=/etc/sshusers-allowed onerr=fail 4.11.6. Temporary directories in 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. Configuration for undefined PAM applications Finally, but not least, create /etc/pam.d/other and enter the following lines: 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 这些内容为所有的支持 PAM 的应用程序提供了很不错的默认设置(默认访问拒绝). 4.11.8. 资源的限制使用: 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 And these are the limits for an administrative user: $ 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 更多信息请阅读: * 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. 用户登录: 编辑 /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 如果您使用这个变量, 将会记录失败的登录. 这对跟踪尝试暴力攻击者非常重要. 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 启用这个参数将在 syslog 中记录试图 su 的操作. 对于重要的机器这相当重要, 同时也要注意这可能引起保密性问题. 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. 限制ftp: 编辑 /etc/ftpusers 文件 /etc/ftpusers 包含不允许使用 ftp 登录主机的用户名单. 如果你真的想允许 ftp 就使用这个文件(通常不推荐使用, 因为它使用明文传送密码). 如果您的守护进程支持 PAM, 您也可用它来定义某些服务对用户的允许和拒绝. FIXME(BUG): 这是一个缺陷,Debian 中缺省的 ftpusers 不包括所有管理员用户(在 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. 使用 su 如果您真的需要系统中的用户变为超级用户, 例如, 安装软件包或增加用户, 您可以使用 su 命令来改变身份. 您应该设法避免任何人使用 root 登录系统, 而应当使用su. 实际上, 最好的解决办法是删除 su, 而是使用 sudo, 因为它比 su 有更多特点. 但是, su 在类unix系统上 更具通用性. 4.11.13. 使用 sudo sudo allows the user to execute defined commands under another user's identity, even as root. If the user is added to /etc/sudoers and authenticates correctly, the commands defined in /etc/sudoers get enabled. Violations, such as incorrect passwords or trying to run a program you don't have permission for, are logged and mailed to root. 4.11.14. 禁止管理员远程访问 您应当修改 /etc/security/access.conf 以禁止管理员远程登录. 这样用户就需要使用 su (或 sudo), 无论本地用户什么时候使用管理员权限, 就都可以进行跟踪了. 您需要在 /etc/security/access.conf 中加入如下行, 缺省的 Debian 配置文件中这一行被注释掉了: -: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. 限制用户访问 有时候您也许认为需要创建本地用户以执行特定的服务(pop3 邮件服务或 ftp). 动手前, 首先记得, Debian GNU/Linux 系统中的 PAM 工具允许使用各种外部地址服务器提供的 libpam 软件包来认证用户(radius, ldap, 等等). If users need to be created and the system can be accessed remotely take into account that users will be able to log in to the system. You can fix this by giving users a null (/dev/null) shell (it would need to be listed in /etc/shells). If you want to allow users to access the system but limit their movements, you can use the /bin/rbash, equivalent to adding the -r option in bash (RESTRICTED SHELL see bash(1) ). Please note that even with restricted shell, a user that access an interactive program (that might allow execution of a subshell) could be able to bypass the limits of the 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] 如果您要对通过 ssh 访问你的系统的用户有所限制, 可以按照自己的需求来编辑 /etc/security/access.conf . 关于 chroot 用户如何通过 ssh 服务访问系统的内容参见第 B.7 节 “Chroot environment for SSH”. 4.11.16. 用户检测 如果您是个偏执狂, 也许希望添加一个系统范围的配置文件来来检测用户在您的系统里所做的操作. 本部分提供一些不同工具使用的小窍门. 4.11.16.1. 输入输出检测脚本 您可以使用本 script 命令来审核用户运行的命令和这些命令的输出. 您不能把 script 配置为一个 shell(即使您把它添加到 /etc/shells 中). 但是您可以配置 shell 的初始化程序运行下边的内容: umask 077 exec script -q -a "/var/log/sessions/$USER" 当然, 如果您要在系统范围内设置, 那就意味着 shell不嗯个连续的读取个人初始化文件(因为 shell已经被 script 修改). 另一种可用的方法是在用户的初始化文件中完成这一工作(但, 这样的话用户就可能将其删除, 参阅下边的内容) 您还需要在检测目录中(这个例子中是 /var/log/sessions/)配置此文件, 这样用户就可写入内容, 但是不能删除. 例如, 可以通过预先创建用户会话文件, 并用 chattr 设置 append-only 标志来完成这一配置. 另一个对系统管理有用的方案, 其包括日期信息: umask 077 exec script -q -a "/var/log/sessions/$USER-`date +%Y%m%d`" 4.11.16.2. 使用 shell 的历史记录文件 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. 使用帐号工具完成用户检测 前边的例子是一个配置用户检测的简单方法, 但是对于复杂系统或用户根本就不(或很少)使用 shell 的系统, 用处不大. 如果碰到这种情况, 您需要求助于acct, 这个帐号检测工具. 这个工具会在空闲磁盘上记录用户或系统进程运行的所有命令. 当启用的帐号, 所有的有关进程和用的信息保存在 /var/account/ 目录下, 更确切的是在 pacct 中. 这个帐号软件包包括一些分析这些数据的工具(sa 和 ac). 4.11.16.4. 其它的用户检测方法 为 .profile 文件设置 inmutable 标志位(同样用到 chattr)是个不错的选择 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. 检查用户的 profile 如果您要查看用户通常在做些什么, 可以在用户连入时使用包括所有登录信息的 wtmp 数据库. 有几个工具可以处理这个文件, 其中 sac 可以对每个用户产生一个 profile 文件,显示此用户经常登录的时间段. 如果您启用了记账系统, 您还可以用其提供的工具来确定用户的登录时间和执行的命令. 4.11.18. 设置用户的 umask 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. 限制用户查看/访问的内容 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. 如果您需要授予用户通过 shell 访问系统的权限, 应该仔细考虑清楚. 一个用户, 除非是在非常苛刻的环境下(如 chroot jail) ,可以查看有关您系统的许多信息,包括: * 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. * 通过查看软件包数据库, 或者查看/usr/share/doc目录, 或通过查看您系统中的二进制文件和库, 来猜测您所安装的软件包. * 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 ). 一个用户在您的系统里可以看到什么? 可能许多东西, 试试这个(先做一下深呼吸): 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. 限制用户对于其他用户信息的访问 如果您允许用户通过 shell 访问, 但是想限制其对于其他用户信息的查看. 用户通过 shell 访问会在其主目录下产生很多文件: 邮箱, 个人文件, X/GNOME/KDE 应用程序的配置文件... 在Debian中每个用户创建是都产生一个附加组, 并且没有两个用户属于同一个组. 这是缺省设置: 当 userX 创建时, 产生一个他所属的名为 userX 组. 这样可以避免因为用户组的概念, 难以对其他用户隐藏信息. 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. 生成用户密码 很多情况下, 管理员需要创建多个账号, 并为其设置密码. 当然, 管理员可以简单的将其设为与用户账号相同, 但是这是非常不明智的. 一个比较好的办法是使用密码生成程序. Debian提供了 makepasswd, apg 和 pwgen 软件包(程序名与包名相同). Makepasswd 可以产生注重于安全而不是可读性的真正的随机密码, pwgen 则试图产生无意义但具有可读性的密码. apg 则同时提供了这两种算法 (这个程序还有个C/S版本, 但其并不在 Debian 软件包中提供). 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. 用户密码检查 有时用户密码可能是一个特定系统的安全中最弱的一环. 这归结于一些用户为他们的账户选择了弱密码 (越弱,则被攻击的可能性越大). 既使您创建了使用 cracklib PAM 模块的检测和密码限制,如在 第 4.11.1 节 “用户认证: PAM” 中所述. 用户仍然可以使用弱密码. 因为访问也许包括远程 shell 访问(ssh, 希望是), 一个远程攻击(在他们用其他的方法做过用户枚举之后)无法猜测用户密码是非常重要的, 特别是如果他们不知什么原因收集到了类似用户名甚至 passwd 和 shadow 文件本身等重要信息. 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. 注销闲置的用户 闲置用户通常是一个安全隐患, 用户闲置, 可能因为他外出午餐, 或远程连接断掉, 但是没有重新建立. 无论什么原因,闲置用户可能导致系统受到威胁: * 因为用户的控制台或许没有锁定,可能被入侵者所利用. * 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). 一些远程系统甚至因为闲置的(分离的)屏幕而受到威胁. 强制断开闲置的用户是本地安全策略的一部分. 有以下几种方式: * 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. * 安装 timeoutd 并根据您的本地安全策略配置 /etc/timeouts. 守护进程将监视闲置用户,在 shell 之外对其记时. * 安装 autolog 并配置其删除闲置用户. 使用 timeoutd 或 autolog 守护进程是不错的方法, 因为, 终究, 用户可以修改其缺省 shell,或运行默认 shell 以后,切换到其他的(未受控制的) shell. 4.12. 使用 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. Debian 中安装的很多服务可以: * 通过 tcpwrapper(tcpd)服务加载 * 通过编入libwrapper 来内建支持. 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 考虑到 tcpchk(非常有用的 CP wrappers 配置文件规则和符号检查器)的运行. 当您在 hosts.deny 和 hosts.allow 文件中添加独立的服务时(它们时 wrapper 库的符号连接), tcpdchk会因找不到那些服务而发出警告, 因为它通过 /etc/inetd.conf 查找(联机手册 不是很准确). Now, here comes a small trick, and probably the smallest intrusion detection system available. In general, you should have a decent firewall policy as a first line, and tcp wrappers as the second line of defense. One little trick is to set up a SPAWN [26] command in /etc/hosts.deny that sends mail to root whenever a denied service triggers wrappers: 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) & 当心: 上边的例子对于短时间内建立许多连接的 Dos 攻击是开放的. 很多邮件就意味着很少的数据包就会浪费大量的文件 I/O. 4.13. 日志与警告的重要性 --------------- 显而易见, 日志和警告对于一个安全的系统非常重要. 假设一个系统配置的非常完美并且 99% 的安全, 当 1% 的攻击发生时, 如果没有到位的安全工具, 首先, 检测到, 其次, 发出警告, 那么这个系统根本就不安全. 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. 使用和定制 logcheck 在 Debian中, logcheck 分为三部分, logcheck(主程序), logcheck-database(程序的正则表达式库)和 logtail (打印未读的日志内容). 在 Debian 中缺省(/etc/cron.d/logcheck)logcheck 系统空闲时每小说运行一次和系统重起时运行一次. 如果配置合适, 这个工具可能对于管理员发现系统的异常事件相当有用. Logcheck 可以设置为, 从日志中发现值得注意的事件, 并发送邮件. 默认安装的profile忽略事件和违规策略, 分为三种不同的设定 (workstation, server, paranoid). Debian的软件包包括一个/etc/logcheck/logcheck.conf, 源自程序,用于定义检查给哪些用户发送邮件. 它还为软件包在以下目录下实现新的策略提供了一种方法: /etc/logcheck/cracking.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_, 和 /etc/logcheck/ignore.d.workstation/_packagename_. 但是, 并非当前的包都是如此. 如果您有一种对其他用户有用的策略. 请将其作为对应软件包的一个问题报告提交 (作为一个wishlist问题). 更多信息请参阅/usr/share/doc/logcheck/README.Debian. 最佳的配置 logcheck 的方式是安装后, 编辑其配置文件 /etc/logcheck/logcheck.conf 将缺省用户(root)修改为邮件接收者. 您还需要设置报告级别:logcheck-database有三种报告级别: workstation, server, paranoid. "server" 为缺省级别, paranoid 只有在运行着尽可能少的服务的高安全性机器上才需要, workstation 使用于, 受保护的安全性不高的机器. 如果您想补充日志文件, 将其加入/etc/logcheck/logcheck.logfiles即可. 这对于默认的 syslog 安装来说是适宜的. 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. 配置警告发送地 Debian comes with a standard syslog configuration (in /etc/syslog.conf) that logs messages to the appropriate files depending on the system facility. You should be familiar with this; have a look at the syslog.conf file and the documentation if not. If you intend to maintain a secure system you should be aware of where log messages are sent so they do not go unnoticed. 例如, 发送信息至控制台就是一个很棒的设定, 对生产系统很有用. 但是为多个这种系统增加一台设备作为日志主机(即从其他系统接收日志)也是非常重要. 也应当被考虑 root 的邮件, 许多安全控制台(象 snort) 发送警告信息到 root 的邮箱. 这个邮箱通常是指系统创建的第一个用户(检查 /etc/aliases). 注意要把 root 的邮件发送到他能接收的地方(本地或远程). 在您的系统里还有其他的角色账号和别名. 在一个小型系统里, 将所有这类别名指向 root 账号并将给 root 的邮件转送的系统管理员的个人邮箱应当非常简单. FIXME: It would be interesting to tell how a Debian system can send/receive SNMP traps related to security problems (jfs). Check: snmptrapfmt, snmp and snmpd. 4.13.3. 使用日志主机 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="" 改为 SYSLOGD="-r" 其次, 配置其它机器发送数据到日志主机. 在/etc/syslog.conf 中增加如下类似内容: facility.level @your_loghost 查找文献, 看用什么可以替代 facility 和 level (它们不应当象这样逐字输入). 如果您要纪录远程的所有信息, 仅需这样写: *.* @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. 日志文件的权限 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. 系统安装后, 一些日志文件的权限并不理想(但这当然取决于你的本地安全策略). 首先 /var/log/lastlog 和 /var/log/faillog 对于普通用户不应当是可读的. 在 lastlog 文件中您会看到最近谁登录了, 在 faillog 中, 您则能看到失败的登录列表. 作者推荐修改两个文件chmod 660. 检查一下您的日志文件,然后谨慎的确定对哪个 UID 不为0且不属于 'adm' 或 '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) 为了定制日志文件的创建, 您可能需要定制生成它们的程序. 如果日志文件是轮换的, 您则需要定制创建和轮换性能. 4.14. 增加内核补丁 ------------ Debian GNU/Linux 为 Linux 内核提供了一些增强其安全性的补丁。 它们包括: * 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. 保护免受缓冲溢出 -------------- 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. 主要有四中方法保护免受缓冲溢出: * patch the kernel to prevent stack execution. You can use either: Exec-shield, OpenWall or PaX (included in the Grsecurity and Adamantix patches). * 使用工具查找源码中易受攻击的片断, 并修正它. * 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. 内核补丁对缓冲溢出的保护 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 第 4.14 节 “增加内核补丁”. 4.15.2. 程序的溢出测试 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. 文件的安全传送 ------------- 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. 当然, 这些方法都需要特殊的客户端. Debian 提供了这类客户端,如 ssh 提供了 scp. 其使用如 rcp, 但是是完全加密的, 因此那些坏家伙 甚至不能发现您在复制什么. 还有一个对应的服务器的 ftp-ssl 客户端软件包. 您可以找到这些软件的客户端, 甚至是基于其他操作系统(非Unix), putty 和 winscp 是基于微软操作系统任何版本的安全复制工具. 注意, 用户可以使用 scp 对所有文件系统进行访问, 除非使用了如第 5.1.1 节 “Chrooting ssh”中描述的 chroot. FTP访问可以设置为 chroot, 基于您选择的守护进程或许更容易,如第 5.3 节 “FTP 安全化”中所述. 如果担心用户浏览您的本地文件, 并想进行加密通讯, 您可以使用带有 SSL 支持的 ftp 守护进程, 或结合明码通信的 ftp 和 VPN 的设定(参阅 第 8.5 节 “虚拟专用网”). 4.17. File system limits and control ------------------------------------ 4.17.1. 使用配额 有一个好的配额策略是很重要的,因为它可以防止用户填满硬盘. 您可以使用两个不同的配额系统: 用户配额和组配额. 就象您所猜到的, 用户配额是指限制用户磁盘空间的占用量, 组配额则是限制组的. 在你设置配额时这一点要记清楚. 在设置配额时有几个需要考虑的关键点: * 使得配额尽量小, 防止用户吃光您的硬盘空间. * 使得配额足够大,防止用户抱怨或邮件配额使他们可以长时间的保留邮件. * 在所有用户可写范围内使用配额, /home 以及 /tmp. 用户具有完全写权限的每个分区和目录都应该启用配额设置. 结合实用性和安全性, 来计算和分配这些分区和目录的可用配额大小. 那么, 现在您想使用配额了. 首先, 需要检查您是否在内核中启用配额支持. 如果没有, 您需要重新编译内核. 然后, 是否安装了控制 quota 的软件包. 如果没有请安装. Enabling quota for the respective file systems is as easy as modifying the defaults setting to defaults,usrquota in your /etc/fstab file. If you need group quota, substitute usrquota to grpquota. You can also use them both. Then create empty quota.user and quota.group files in the roots of the file systems you want to use quotas on (e.g. 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. For more information about quotas, read the quota man page, and the quota mini-howto (/usr/share/doc/HOWTO/en-html/mini/Quota.html). You may also want to look at pam_limits.so. 4.17.2. The ext2 filesystem specific attributes (chattr/lsattr) 除了通常Unix的权限, ext2 和 ext3 文件系统还提供了一套特别的属性用于控制您的文件和系统. 不同于基本的权限, 这些属性并不能通过 ls -l 命令显示出来, 也不能使用chmod命令修改, 您需要额外的两个工具 lsattr 和 chattr (在e2fsprogs 包中)来管理它们. 注意, 这意味着, 您在备份系统时, 通常不能保存这些属性, 所以, 如果您对它们做了任何修改, 也许可以将其有价值部分 对应的chattr命令写入脚本, 这样就可以在以后必需恢复系统时重新设置. 在所有的属性中, 对于增强安全性最有价值的是参考字符 'i' 和 'a', 它们只能由超级用户设定(或删除): * 'i' 属性 ('immutable'): 带有此属性的文件, 不能被修改, 删除或重命名, 建立连接, 即使是超级用户也不能. * 'a' 属性 ('append'): 除了您能以附加的方式打开此文件外,此属性与 immutable 属性具有同样的效果. 这意味着, 您仍可以在文件中增加更多的内容, 但是不能修改以前的内容. 这个属性对于存储于 /var/log/ 目录的日志文件特别有用, 尽管应该考虑到有时候根据日志循环脚本, 它们有可能被移动. 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 第 10.4.2.1 节 “主动防护”. 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: * 对您选定的文件设置 'a' and 'i' 属性; * Add the command lcap CAP_LINUX_IMMUTABLE (as well as lcap CAP_SYS_MODULE, as suggested in 第 10.4.2.1 节 “主动防护”) to one of the startup scripts; * 为此脚本和其他配置文件设置'i'属性, 包括 lcap 二进制文件本身; * 手工执行上述命令(或重新起动您的系统确定一切如设想的一样运行). 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. 文件系统的完整性检查 几个月后, 您能肯定硬盘上的 /bin/login 仍然是您安装的那个吗? 如果是一个被黑的版本, 其将输入的密码存储到隐藏的文件中, 或者以明文方式通过邮件发送到网上呢? The only method to have some kind of protection is to check your files every hour/day/month (I prefer daily) by comparing the actual and the old md5sum of this file. Two files cannot have the same md5sum (the MD5 digest is 128 bits, so the chance that two different files will have the same md5sum is roughly one in 3.4e3803), so you're on the safe site here, unless someone has also hacked the algorithm that creates md5sums on that machine. This is, well, extremely difficult and very unlikely. You really should consider this auditing of your binaries as very important, since it is an easy way to recognize changes at your binaries. 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 第 10.2 节 “周期性入侵检测” and 第 4.19 节 “生成系统快照”. 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. 设置 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. The default behavior does not send this information to the superuser but, instead keeps daily copies of the changes in /var/log/setuid.changes. You should set the MAILTO variable (in /etc/checksecurity.conf) to 'root' to have this information mailed to the superuser. See checksecurity(8) manual page for more configuration info. 4.18. 安全的网络访问 ------------- FIXME: More (Debian-specific) content needed. 4.18.1. 配置内核的网络特性 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. 如果您想拦截系统里所有的 ICMP 回送请求, 启用这个配置选项: net/ipv4/icmp_echo_ignore_all = 1 记录您网络中的地址不可用的数据包(由于错误路由): /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 这个选项是一把双刃剑. 一方面它保护您的系统免受 syn 湮灭; 另一方面它违背了定义的标准(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 此选项只有编译内核时启用 CONFIG_SYNCOOKIES 才会有效. 所有的 Debian 内核都是内置此选项编译的, 您可以运行下边的命令来确认: $ sysctl -A |grep syncookies net/ipv4/tcp_syncookies = 1 有关 TCP syncookies 的更多信息, 参阅 http://cr.yp.to/syncookies.html. 4.18.3. 增强启动时网络的安全性 当设置了您需要的内核网络选项后, 那么每次重起时这些参数都会被加载. 下边的例子启用了很多前边提到的选项和其他有用的选项. 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. # IP spoofing protection. 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 # Disable source routed packets. 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. 配置防火墙 In order to have firewall capabilities, either to protect the local system or others behind it, the kernel needs to be compiled with firewall capabilities. The standard Debian 2.2 kernel (Linux 2.2) provides the packet filter ipchains firewall, Debian 3.0 standard kernel (Linux 2.4) provides the stateful packet filter iptables (netfilter) firewall. In any case, it is pretty easy to use a kernel different from the one provided by Debian. You can find pre-compiled kernels as packages you can easily install in the Debian system. You can also download the kernel sources using the kernel-source-X and build custom kernel packages using make-kpkg from the kernel-package package. 在 第 5.14 节 “增加防火墙” 处有关于在 Debian 中配置防火墙的更详细的讨论. 4.18.5. 禁用弱客户主机问题 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. 在 2.2 (和更早)的内核中, 可以做如下修正: # 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 ..... 在最新的内核中, 还可以做如下操作: * 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: 提交一个 netbas 的错误, 使得 routing fix 成为Debian标准的动作? 4.18.6. 保护系统免受 ARP 攻击 当您不再信任您的局域网内(经常会出现这种情况, 因为这才是安全的态度)的其他系统时, 您需要保护自己免受各种各样的 ARP 攻击. 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/. 但是, 总有一个解决办法: * 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...). * 实行确认主机MAC地址的IP通讯过滤. 4.19. 生成系统快照 ------------ 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 第 11 章 攻陷之后(事件响应)). 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). 下边的脚本将创建这样的快照: #!/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 第 11 章 攻陷之后(事件响应). 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 一旦生成了快照完, 您应当确保其被存储于只读介质上. 您也可以存储其备份, 将其置于磁盘上,用于每晚的 cron 检查比较. 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 第 10.2 节 “周期性入侵检测”. 4.20. 其它建议 ---------- 4.20.1. 不要使用基于 svgalib 的软件 SVGAlib 非常受控制台爱好者的喜爱, 比如我. 但是, 过去它已被多次证明是不安全的. 发布的基于 zgv 的 Exploits, 很容易获取root权限. 只要可能尽量避免使用 SVGAlib 程序 . ------------------------------------------------------------------------ [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] 这包括软件包管理工具 dpkg 因为安装 (post,pre) 和删除 (post,pre) 脚本在 /var/lib/dpkg/ 下 和 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] be sure to use uppercase 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. 第 5 章 增强系统上运行服务的安全性 =================== 有两种方式来增强系统中运行的服务的安全性: * 使其只能通过它们应当所在的访问点(接口)访问. * 正确配置, 使其只能由合法的用户使用授权方式访问. Restricting services so that they can only be accessed from a given place can be done by restricting access to them at the kernel (i.e. firewall) level, configure them to listen only on a given interface (some services might not provide this feature) or using some other methods, for example the Linux vserver patch (for 2.4.16) can be used to force processes to use only one interface. 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 } 以下部分将详细介绍如何根据其用途正确的配置各项服务. 5.1. ssh 安全化 ------------ 如果您仍然使用 telnet, 而不是 ssh, 则需要改变对本手册的阅读方式. 应当用 ssh 来取代所有的 telnet 远程登录. 任何时候通过嗅探互联网通讯来获取明文密码都是相当简单的, 您应该采用使用加密算法的协议. 那么, 现在在你的系统上执行 apt-get install ssh . 鼓励您系统上的所有用户使用 ssh 取代 telnet, 或者更进一步, 卸载 telnet/telnetd. 另外您应该避免使用 ssh 以 root 身份登录, 其替代的方法是使用 su 或 sudo 转换成 root 用户. 最后, /etc/ssh 目录下的 sshd_config 文件, 应当作如下修改, 以增强安全性: * ListenAddress 192.168.0.1 Have ssh listen only on a given interface, just in case you have more than one (and do not want ssh available on it) or in the future add a new network card (and don't want ssh connections from it). * PermitRootLogin no Try not to permit Root Login wherever possible. If anyone wants to become root via ssh, now two logins are needed and the root password cannot be brute forced via 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. * AllowGroups wheel admin Allow only certain group members to have access via ssh to this machine. AllowGroups and AllowUsers have equivalent directives for denying access to a machine. Not surprisingly they are called "DenyUsers" and "DenyGroups". * PasswordAuthentication yes It is completely your choice what you want to do. It is more secure to only allow access to the machine from users with ssh-keys placed in the ~/.ssh/authorized_keys file. If you want so, set this one to "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 最后, 应当注意那些存放 OpenSSH 配置文件的目录. 现在, 有三种常用的 SSH 守护进程, ssh1, ssh2, 和 OpenBSD 用户使用的 OpenSSH. ssh1 是第一个可以使用的 ssh 守护进程, 并且仍然有很大的用户群(甚至谣传有windows版本). ssh2 和 ssh1 相比有更多高级特性, 但是它是基于保留源代码协议的. OpenSSH 是完全自由的 ssh 守护进程, 它支持 ssh1, 和 ssh2. OpenSSH 是在 Debian 系统中选择安装的 ssh 软件包. 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 当前的 OpenSSH 没有提供用户连接后自动完成 chroot 的方法(商业版本提供这种功能). 但是有个项目为 OpenSSH 提供这种功能,参见http://chrootssh.sourceforge.net, 尽管它不在当前 Debian 的软件包中. 然而, 您可以使用 pam_chroot 模块,如 第 4.11.15 节 “限制用户访问” 所述. In 第 B.7 节 “Chroot environment for SSH” you can find several options to make a chroot environment for SSH. 5.1.2. ssh 客户端 如果您使用的 SSH 客户端不能访问 SSH 服务器, 则需要确认是否支持在服务器端被强制执行的协议. 例如, 如果您使用了只支持 version 1 协议的 mindterm 软件包. 但是 sshd 服务器默认配置为只接受 version 2 协议(基于安全的原因). 5.1.3. 禁止文件传送 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: * 禁止用户通过 login 登录 ssh 服务器(如上所述或通过配置文件或PAM 配置). * 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. 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 eveyone icp_access allow all 您还应当基于系统资源来配置 Squid, 包括高速缓存(cache_mem项), 本地缓存文件, 及其占用的空间大小(cache_dir项). 注意, 如果配置不当, 某些人也许可以通过 Squid 传递邮件消息, 因为HTTP和SMTP协议设计的非常相似. Squid 的默认配置文件拒绝访问 25 端口. 如果您希望允许连接 25 端口, 仅需要将其加入 Safe_ports 列表即可. 但是, 这里推荐 NOT. Setting and configuring the proxy/cache server properly is only part of keeping your site secure. Another necessary task is to analyze Squid's logs to assure that all things are working as they should be working. There are some packages in Debian GNU/Linux that can help an administrator to do this. The following packages are available in Debian 3.0 and Debian 3.1 (sarge): * calamaris - Squid 或 Oops 代理的日志分析工具. * modlogan - 日志分析工具组件. * sarg - Squid Analysis Report Generator. * squidtaild - Squid 日志监控程序. 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. FTP 安全化 ------------ 如果您真的必须使用 FTP(没有使用 sslwarp 或插入 SSL 或使用 SSH 通道), 则应当 chroot ftp 为 ftp 用户的主目录, 这样用户就不会看到其目录以外的东西. 否则他们就可以遍历您的文件系统, 就象他们拥有这样的 shell 一样. 您应当在 proftpd.conf 中的global 部分增加以下行以启用 chroot 的这个特点: DefaultRoot ~ Restart ProFTPd by /etc/init.d/proftpd restart and check whether you can escape from your homedir now. To prevent ProFTPd DoS attacks using ../../.., add the following line in /etc/proftpd.conf: DenyFilter \*.*/ Always remember that FTP sends login and authentication passwords in clear text (this is not an issue if you are providing an anonymous public service) and there are better alternatives in Debian for this. For example, sftp (provided by ssh). There are also free implementations of SSH for other operating systems: http://www.chiark.greenend.org.uk/~sgtatham/putty/ and http://www.cygwin.com for example. However, if you still maintain the FTP server while making users access through SSH you might encounter a typical problem. Users accessing anonymous FTP servers inside SSH-secured systems might try to log in the FTP server. While the access will be refused, the password will nevertheless be sent through the net in clear form. To avoid that, ProFTPd developer TJ Saunders has created a patch that prevents users feeding the anonymous FTP server with valid SSH accounts. More information and patch available at: http://www.castaglia.org/proftpd/#Patches. This patch has been reported to Debian too, see http://bugs.debian.org/145669. 5.4. 对 X 窗口系统的安全访问 ------------------ 今天, 越来越多的使用一台服务器带多台工作站的公司会使用 X 终端. 这可能是很危险的, 因为您需要允许文件服务器连接到客户端(从 X 的观点来看就是 X 服务器. X 的关键词是客户和服务器). 如果听从大多数(糟糕的)文档的建议, 在您的机器上键入 xhost +. 这将允许任何 X 客户端连接您的机器. 基于安全的考虑, 您则应当使用 xhost +hostname 命令, 仅允许指定的主机连接. 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. For best security, if you do not need X access from other machines, switch off the binding on TCP port 6000 simply by typing: $ startx -- -nolisten tcp This is the default behavior in Xfree 4.1.0 (the Xserver provided in Debian 3.0 and 3.1). If you are running Xfree 3.3.6 (i.e. you have Debian 2.2 installed) you can edit /etc/X11/xinit/xserverrc to have it something along the lines of: #!/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]. 您还可以为xscreensaver锁设置默认系统超时. 既使用户能忽略它, 您应该编辑 /etc/X11/app-defaults/XScreenSaver 配置文件, 修改锁定行: *lock: False (在Debian中是默认设置) 为: *lock: True FIXME: Add information on how to disable the screensavers which show the user desktop (which might have sensitive information). Read more on X Window security in http://www.tldp.org/HOWTO/XWindow-User-HOWTO.html (/usr/share/doc/HOWTO/en-txt/XWindow-User-HOWTO.txt.gz). FIXME: 增加debian-security 线程关于修改 XFree 3.3.6 的配置文件信息. 5.4.1. 检查您的显示管理器 如果您只想安装一个用于本地应用的显示管理器(拥有友好的图形登录界面), 应确保 XDMCP (X管理控制协议)被禁用. 在XDM中您可以在 /etc/X11/xdm/xdm-config 中加入如下行: DisplayManager.requestPort: 0 For GDM there should be in your gdm.conf: [xdmcp] Enable=false 通常, 在 Debian 中所有显示管理器缺省被配置成不启用始XDMCP. 5.5. Securing printing access (the lpd and lprng issue) ------------------------------------------------------- 想象一下, 您刚开始工作, 打印机就开始无休止的往外吐纸, 这是因为某些人控制了打印守护进程. 很讨厌,不是吗? In any UNIX printing architecture, there has to be a way to get the client's data to the host's print server. In traditional lpr and lp, the client command copies or symlinks the data into the spool directory (which is why these programs are usually SUID or SGID). In order to avoid any issues you should keep your printer servers especially secure. This means you need to configure your printer service so it will only allow connections from a set of trusted servers. In order to do this, add the servers you want to allow printing to your /etc/hosts.lpd. 但是, 即便如此, lpr 守护进程仍会接收任何对 515 端口的连接. 您应当考虑屏蔽来自 networks/hosts 的连接, 他们是不允许使用打印服务的(lpr 守护进程不能设定为只监听指定 IP 地址). 和lpr相比, Lprng 应当是更好的选择,因为它可以配置为遵从IP存取控制. 并且可以指定绑定端口(虽然有些古怪). If you are using a printer in your system, but only locally, you will not want to share this service over a network. You can consider using other printing systems, like the one provided by cups or http://pdq.sourceforge.net/ which is based on user permissions of the /dev/lp0 device. In cups, the print data is transferred to the server via the HTTP protocol. This means the client program doesn't need any special privileges, but does require that the server is listening on a port somewhere. 但是, 如果您仅希望在本地使用 cups, 则可以通过修改/etc/cups/cupsd.conf 以将其绑定到回送端口: Listen 127.0.0.1:631 此配置文件有许多诸如允许或禁止网络和主机的其他安全选项. 然而, 如果您并不需要这些, 则仅需要限制监听端口即可. Cups 也是通过 HTTP 端口来传送文档数据, 如果您不想对外部攻击者透露潜在有用信息的话(端口是开放的), 可以增加如下行: Order Deny,Allow Deny From All Allow From 127.0.0.1 This configuration file can be modified to add some more features including SSL/TLS certificates and crypto. The manuals are available at http://localhost:631/ or at http://cups.org. FIXME: Add more content (the article on http://www.rootprompt.org provides some very interesting views). FIXME: 检查在 Debian 中 PDG 的可用性, 如果可以, 建议其做好更好的打印系统. FIXME: 检查 Farmer/Wietse 是否可以作为打印守护进程的替代, 以及其是否在 Debian 系统中可用. 5.6. 邮件服务的安全化 ------------- 如果您的服务器并不是一个邮件系统, 那么您并不需要一个邮件守护进程监听传入连接, 但是也许您希望本地邮件能够有序的分发,比如,为 root 用户接收从报警系统传来的邮件. 如果您安装了exim, 并不需要其作为守护进程, 因为标准 cron 任务可以刷新邮件队列. 配置方法, 参阅第 3.5.1 节 “禁用守护进程服务”. 5.6.1. 配置 Nullmailer 也许您需要一个本地邮件守护进程, 以便可以将本地邮件发送到其他系统. 当您管理几个系统, 并且不想连到每个系统去阅读本地邮件时, 那么这是很普通的需求. 所有单个系统的登录可以通过一台中央 syslog 服务器集中起来, 邮件被发送到一台中央邮件服务器. 这就需要正确的配置一个只读系统. 守护进程配置为仅监听回送地址. 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 并将邮件守护进程配置为仅监听回送接口. 在 exim 中(缺省的MTA) 您可以通过编辑 /etc/exim.conf 加入如下行来完成配置: local_interfaces = "127.0.0.1" 重起两个守护进程(inetd 和 exim)后, exim 将只对 127.0.0.1:25 监听. 注意, 要首先禁用 inted, 否则 exim 将不能启用, 因为 inetd 守护进程仍然处理传入连接. 对于 postfix 来说应当编辑 /etc/postfix/main.conf: inet_interfaces = localhost 如果您只是希望处理本地邮件, 这种方法比 tcp-wrapping 邮件或增加防火墙规则来限制访问更好. 但是, 如果您仍需要监听其他接口, 则应当考虑由 inetd 装载并增加一个 tcp wrapper, 并用 /etc/hosts.allow 和 /etc/hosts.deny 来限制访问. 并且, 如果你正确的设置了日志纪录, 则当未被授权的访问试图攻击您的邮件守护进程时,将会被告知. 无论如何, 在 SMTP 级别拒绝邮件转发, 您应当编辑 /etc/exim/exim.conf 加入如下行: receiver_verify = true 既使您的邮件服务器不会转发信息, 这种配置对于中转测试器来说也是必须的, 可以通过 http://www.abuse.net/relay.html 来检测您的服务器有无中转能力. 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. 提供对邮箱的安全访问 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. 例如, 可以尝试配置您的 inbox 路径为 {server.com}/etc/passwd, 如果可以成功, 则说明您的 IMAP 守护进程没有正确的配置以阻止此类访问. 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. 安全的接收邮件 Reading/receiving mail is the most common clear-text protocol. If you use either POP3 or IMAP to get your mail, you send your clear-text password across the net, so almost anyone can read your mail from now on. Instead, use SSL (Secure Sockets Layer) to receive your mail. The other alternative is SSH, if you have a shell account on the box which acts as your POP or IMAP server. Here is a basic fetchmailrc to demonstrate this: 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' The preconnect is the important line. It fires up an ssh session and creates the necessary tunnel, which automatically forwards connections to localhost port 1236 to the IMAP mail server, but encrypted. Another possibility would be to use fetchmail with the SSL feature. 如果您想象 POP 和 IMAP 一样提供加密邮件, apt-get install stunnel, 然后用如下方式启动您的守护进程: stunnel -p /etc/ssl/certs/stunnel.pem -d pop3s -l /usr/sbin/popd This command wraps the provided daemon (-l) to the port (-d) and uses the specified SSL certificate (-p). 5.7. 增强 BIND 的安全性 ----------------- 有很多不同的方式用于完成域名服务器守护进程的安全化, 这仅与考虑方式有关: * configuring the daemon itself properly so it cannot be misused from the outside (see 第 5.7.1 节 “配置Bind以防误用”). This includes limiting possible queries from clients: zone transfers and recursive queries. * limit the access of the daemon to the server itself so if it is used to break in, the damage to the system is limited. This includes running the daemon as a non-privileged user (see 第 5.7.2 节 “管理 BIND 用户”) and chrooting it (see 第 5.7.3 节 “使名称服务器运行于 chroot 环境”). 5.7.1. 配置Bind以防误用 You should restrict some of the information that is served from the DNS server to outside clients so that it cannot be used to retrieve valuable information from your organization that you do not want to give away. This includes adding the following options: allow-transfer, allow-query, allow-recursion and version. You can either limit this on the global section (so it applies to all the zones served) or on a per-zone basis. This information is documented in the bind-doc package, read more on this on /usr/share/doc/bind/html/index.html once the package is installed. 设想一下, 您的服务器同时与互联网和您的内部(您的内部IP是192.168.1.2)网(一台基本的 multi-homed 服务器)相连, 您不想为互联网提供任何服务, 而只是为内部主机提供 DNS 查询服务. 您可以在 /etc/bind/named.conf 中加入如下内容, 以实现这种限制: options { allow-query { 192.168.1/24; } ; allow-transfer { none; } ; allow-recursion { 192.168.1/24; } ; listen-on { 192.168.1.2; } ; forward { only; } ; forwarders { A.B.C.D; } ; }; listen-on 选项使 DNS 仅绑定到内部地址接口, 但即使此接口和与互联网相连的相同(例如, 您正在使用 NAT), 也只会接收源自您的内部网络的主机的查询. 如果系统有多个接口, 并且没有指定listen-on项, 以确保只有内部用户可以查询, 那么因为此端口外部攻击者也可以访问,所以他们将设法对 DNS 服务器攻击(或利用缓冲溢出攻击). 因此如果 DNS 服务器只为自身提供服务, 则应当配置其只监听 127.0.0.1. The version.bind record in the chaos class contains the version of the currently running bind process. This information is often used by automated scanners and malicious individuals who wish to determine if one's bind is vulnerable to a specific attack. By providing false or no information in the version.bind record, one limits the probability that one's server will be attacked based on its published version. To provide your own version, use the version directive in the following manner: options { ... various options here ... version "Not available."; }; 改变 version.bind 的记录并不能对避免攻击提供实质性的保护. 但是可以被认为是一个有用的保障. 下边是一个 named.conf 配置文件的例子: 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. 管理 BIND 用户 Regarding limiting BIND's privileges you must be aware that if a non-root user runs BIND, then BIND cannot detect new interfaces automatically, for example when you put a PCMCIA card into your laptop. Check the README.Debian file in your named documentation (/usr/share/doc/bind/README.Debian) directory for more information about this issue. There have been many recent security problems concerning BIND, so switching the user is useful when possible. We will detail here the steps needed in order to do this, however, if you want to do this in an automatic way you might try the script provided in 第 B.5 节 “修改Bind默认安装的示例脚本.”. 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. 为了可以使用其它用户来运行 BIND, 首先应为此创建一个单独的用户和组 (每个非root运行的服务都使用 nobody 或 bogroup 不是一个好主意). 在下边的例子中, 将会使用named这个用户和组. 键入如下内容: addgroup named adduser --system --home /home/named --no-create-home --ingroup named \ --disabled-password --disabled-login named 注意, 用户 named 将会是一个限制. 如果您需要, 或者其它的原因, 有一个较少的限制的设定: adduser --system --ingroup named named Now you can either edit /etc/init.d/bind with your favorite editor and change the line beginning with 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" 修改 Bind 所使用文件的权限, 这包括 /etc/bind/rndc.key: -rw-r----- 1 root named 77 Jan 4 01:02 rndc.key 在 bind 创建 pidfile 的地方,使用, 例如 /var/run/named 来替代 /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 to: reload) $0 stop sleep 1 $0 start 注意: 您也许还需要修改 restart 行, 这与您的 Debian 的版本有关. 这在 Debian 的 bind 1:8.3.1-2 版中对此做了修正. All you need to do now is to restart bind via /etc/init.d/bind restart, and then check your syslog for two entries like this: 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. 使名称服务器运行于 chroot 环境 To achieve maximum BIND security, now build a chroot jail (see 第 5.10 节 “常用 chroot 和 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 Bind 守护进程必须对 named 文件有访问权限才能正常运行. 因为这些配置文件通常都在 /etc/named/ 目录下, 所以这很容易办到. 应当考虑到,对于区域文件只需要有只读权限,除非这是第二或缓存名称服务器. 如果是这样,您则需要给必要的区域以写权限(以便从主服务器进行区域转换). 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.3.6.so lib/libc-2.3.6.so lib/ld-linux.so.2 - symlinked to ld-2.3.6.so lib/libc.so.6 - symlinked to libc-2.3.6.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. 如果您想避免动态链接库的问题, 您可以静态编译 bind. 可以使用 apt-get 带 source 选项下载. 这样可以下载所需正确编译的软件包. 您需要做类似如下操作: $ 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. 有关如何设定chroot的更多信息,参见 第 5.10 节 “常用 chroot 和 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. 增加 Apache 的安全性 ------------------- FIXME: 增加内容: 有关 Apache 正常安装时提供的模块(在 /usr/lib/apache/X.X/mod_* 处) 和可能被安装的在 ibapache-mod-XXX 软件包中的模块. You can limit access to the Apache server if you only want to use it internally (for testing purposes, to access the doc-central archive, etc.) and do not want outsiders to access it. To do this use the Listen or BindAddress directives in /etc/apache/http.conf. 使用监听: Listen 127.0.0.1:80 使用地址绑定: BindAddress 127.0.0.1 然后通过 /etc/init.d/apache restart 重启 Apache, 您会发现它只监听回送接口. 无论如何, 如果您并不使用 Apache 提供的全部功能, 您可以考虑一下 Debian 中提供的其它 web 服务器, 如dhttpd. The http://httpd.apache.org/docs/misc/security_tips.html provides information regarding security measures to be taken on Apache web server (this same information is provided in Debian by the apache-doc package). 第 B.7.3 节 “Chroot environment for Apache” 提供了更多的有关设置 chroot jail 以对 Apache 实现更多限制的信息. 5.8.1. 禁止用户发布 web 内容 在 Debian 中缺省的 Apache 安装允许用户在 $HOME/public_html 目录下发布 web 内容. 此内容可以远程通过形如 http://your_apache_server/~user 的 URL 检索到. 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. 日志文件权限 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. 发布 web 文件 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. 增强 finger 的安全性 ------------------- 如果您想要运行finger服务, 首先考虑一下这是不是必须的. 检查一下, 您会发现 Debian 提供了很多 finger 守护进程 (主要源自 apt-cache search fingerd 的输出): * cfingerd - 可配置的 finger 守护进程 * efingerd - unix 下的另一个 finger守护进程, 对输出做了优化. * ffingerd - 一个安全的 finger 守护进程 * fingerd - 远程用户信息服务器. * xfingerd - BSD-like finger daemon with qmail support. 如果您打算将 finger 守护进程用于公共服务, 推荐使用 ffingerd. 无论如何, 当您通过 inetd, xinetd 或 tcpserver 配置它时, 建议您: 限制同时运行进程数, 限制指定主机(使用 tcp wrappers)对 finger 守护进程的访问, 使它只监听您需要的接口. 5.10. 常用 chroot 和 suid ---------------------- chroot is one of the most powerful possibilities to restrict a daemon or a user or another service. Just imagine a jail around your target, which the target cannot escape from (normally, but there are still a lot of conditions that allow one to escape out of such a jail). You can eventually create a modified root environment for the user or service you do not trust. This can use quite a bit of disk space as you need to copy all needed executables, as well as libraries, into the jail. But then, even if the user does something malicious, the scope of the damage is limited to the jail. 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 第 5.7 节 “增强 BIND 的安全性”). 但是, Debian 确实提供了一些用于设置 chroot 环境的软件, 参阅 第 5.10.1 节 “自动配置 chroot 环境”. 无论如何, 如果您在您的系统上运行一项服务, 都需要尽可能的保证其安全性, 这包括取消其 root 权限, 在限制的环境下运行(如 chroot jail)或者用更安全的方法. 但是, 应当注意的是, 以root用户运行的 chroot jail 是有可能被破坏的. 因此, 应当确保服务以非特权用户运行. 通过限制其环境, 您可以限制服务可访问文件的读/执行权限, 因此您也就限制了利用本地系统的漏洞提升权限的可能性. 即使如此您也无法确保一个聪明的攻击者以某种方法突破 chroot jail. 只有使用公认的安全性好的服务器, 才是增加安全性的很好的手段. 即使一个很小的漏洞, 如开放文件句柄, 也可能被熟练的攻击者利用来攻破系统. 最后, chroot 并不是设计作为一个安全工具, 而是一个测试工具. 5.10.1. 自动配置 chroot 环境 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. 明文密码 ---------- 您应当设法避免在网络中象 FTP/Telnet/NIS/RPC 一样接收和发送明文密码. 作者建议大家使用 ssh 代替 telnet 和 ftp. 记住, 从 telnet 转到 ssh, 但是仍然使用其它的明文协议并不能为您增加任何安全性! 最好的办法是删除 ftp, telnet, pop, imap, http, 而是用他们各自的使用加密的服务. 您可以考虑将它们删除, 而使用它们的 SSL 版本, ftp-ssl, telnet-ssl, pop-ssl, https ... 以上的大多数提示适用于每个 unix 系统(您会在阅读其它的 Linux 和类 Unix 的安全文档时发现您会发现这些提示). 5.12. 禁用 NIS ------------ You should not use NIS, the Network Information Service, if possible, because it allows password sharing. This can be highly insecure if your setup is broken. If you need password sharing between machines, you might want to consider using other alternatives. For example, you can setup an LDAP server and configure PAM on your system in order to contact the LDAP server for user authentication. You can find a detailed setup in the http://www.tldp.org/HOWTO/LDAP-HOWTO.html (/usr/share/doc/HOWTO/en-txt/LDAP-HOWTO.txt.gz). You can read more about NIS security in the http://www.tldp.org/HOWTO/NIS-HOWTO.html (/usr/share/doc/HOWTO/en-txt/NIS-HOWTO.txt.gz). FIXME (jfs): Add info on how to set this up in Debian. 5.13. 增强 RPC 服务的安全性 ------------------- 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. Disabling RPC services completely Disabling portmap is quite simple. There are several different methods. The simplest one in a Debian 3.0 system and later releases is to uninstall the portmap package. If you are running an older Debian version you will have to disable the service as seen in 第 3.5.1 节 “禁用守护进程服务”, because the program is part of the netbase package (which cannot be de-installed without breaking the system). 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. Limiting access to RPC services 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 第 5.14 节 “增加防火墙”). * Block access to these services using tcp wrappers, since the portmapper (and some RPC services) are compiled with libwrap (see 第 4.12 节 “使用 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, 第 4.18.5 节 “禁用弱客户主机问题”). 5.14. 增加防火墙 ----------- 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. 为本地系统构建放火墙 You can use firewall rules as a way to secure the access to your local system and, even, to limit the outbound communications made by it. Firewall rules can also be used to protect processes that cannot be properly configured not to provide services to some networks, IP addresses, etc. 然而, 本手册中, 此方法的提出, 主要是因为其保护一个系统并不仅仅是基于防火墙的性能, 一个系统的安全源于多个层面, 一旦所有的服务完成安全化设置, 防火墙应该是最后一层. 您应该很容易的设想, 如果一个系统的保护仅仅基于一个内置防火墙, 一旦管理员不管出于什么原因, 删除了防火墙规则(可能因为设置, 喜好, 人为错误), 如果在此系统中没有其它保护措施的话, 这个系统将完全对攻击者敞开. 另一方面, 本地系统拥有防火墙规则还能防止其它一些破坏性事情发生. 即使提供的服务做了安全化配置, 一个防火墙也能为错误的配置或者新安装的 还未来得及配置的服务提供保护, 并且一个紧凑的配置, 除非防火墙的代码被删除, 将会防止木马侵害. 注意, 入侵者并不一定要超级用户权限才能控制装有木马的系统(因为对于绑定端口, 如果它不是私有端口, 并且没有被禁用, 这将是允许的. 因而,一个合适的防火墙设置应该带有默认的拒绝策略,即: * 只允许许可的机器访问本地许可的服务. * outgoing connections are only allowed to services used by your system (DNS, web browsing, POP, email...).[44] * forward 规则设为拒绝(除非您有其它系统的保护, 参阅下边). * 其它的连入连出都是禁止的. 5.14.2. 使用防火墙保护其它系统 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 第 B.4 节 “设定网桥防火墙” for more information on how to set this up in a Debian GNU/Linux system. 5.14.3. Setting up a firewall 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 第 5.14.3.1 节 “Using firewall packages”). 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. 记住: 仅仅安装 iptables(或者旧版的防火墙代码)并不能给您任何保护, 只不过是提供了一个软件. 要想拥有一个防火墙, 您就必须配置它! If you do not have a clue on how to set up your firewall rules manually consult the Packet Filtering HOWTO and NAT HOWTO provided by iptables for offline reading at /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 第 1.4 节 “预备知识” for more (general) pointers on firewalls. Another good iptables tutorial is http://iptables-tutorial.frozentux.net/iptables-tutorial.html. 5.14.3.1. Using firewall packages 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. Debian 系统中可用于设定防火墙规则的一些软件: * For desktop systems: * 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 第 6 章 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 This is the sample firewall script: #!/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 # # Simple example firewall configuration. # # Caveats: # - This configuration applies to all network interfaces # if you want to restrict this to only a given interface use # '-i INTERFACE' in the iptables calls. # - Remote access for TCP/UDP services is granted to any host, # you probably will want to restrict this using '--source'. # # chkconfig: 2345 9 91 # description: Activates/Deactivates the firewall at boot time # # You can test this script before applying with the following shell # snippet, if you do not type anything in 10 seconds the firewall # rules will be cleared. #--------------------------------------------------------------- # 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 that the system will offer to the network TCP_SERVICES="22" # SSH only UDP_SERVICES="" # Services the system will use from the network REMOTE_TCP_SERVICES="80" # web browsing REMOTE_UDP_SERVICES="53" # DNS # Network that will be used for remote mgmt # (if undefined, no rules will be setup) # NETWORK_MGMT=192.168.0.0/24 # If you want to setup a management network (i.e. you've uncommented # the above line) you will need to define the SSH port as well (i.e. # uncomment the below line.) Remember to remove the SSH port from the # TCP_SERVICES string. # SSH_PORT="22" if ! [ -x /sbin/iptables ]; then exit 0 fi fw_start () { # Input traffic: /sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # Services 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 # Remote management if [ -n "$NETWORK_MGMT" ] ; then /sbin/iptables -A INPUT -p tcp --src ${NETWORK_MGMT} --dport ${SSH_PORT} -j ACCEPT fi # Remote testing /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 # Output: /sbin/iptables -A OUTPUT -j ACCEPT -o lo /sbin/iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # ICMP is permitted: /sbin/iptables -A OUTPUT -p icmp -j ACCEPT # So are security package updates: # Note: You can hardcode the IP address here to prevent DNS spoofing # and to setup the rules even if DNS does not work but then you # will not "see" IP changes for this service: /sbin/iptables -A OUTPUT -p tcp -d security.debian.org --dport 80 -j ACCEPT # As well as the services we have defined: 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 # All other connections are registered in syslog /sbin/iptables -A OUTPUT -j LOG /sbin/iptables -A OUTPUT -j REJECT /sbin/iptables -P OUTPUT DROP # Other network protections # (some will only work with some kernel versions) 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 "Starting firewall.." fw_stop fw_start echo "done." ;; stop) echo -n "Stopping firewall.." fw_stop echo "done." ;; clear) echo -n "Clearing firewall rules.." fw_clear echo "done." ;; *) echo "Usage: $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 [.. interface configuration ..] 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. Testing your firewall configuration 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 第 8.1 节 “远程风险评估工具”) 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). 第 6 章 Debian 系统安全配置的自动化 ======================= After reading through all the information in the previous chapters you might be wondering "I have to do quite a lot of things in order to harden my system, couldn't these things be automated?". The answer is yes, but be careful with automated tools. Some people believe, that a hardening tool does not eliminate the need for good administration. So do not be fooled to think that you can automate the whole process and will fix all the related issues. Security is an ever-ongoing process in which the administrator must participate and cannot just stand away and let the tools do all the work since no single tool can cope with all the possible security policy implementations, all the attacks and all the environments. Since woody (Debian 3.0) there are two specific packages that are useful for security hardening. The harden package which takes an approach based on the package dependencies to quickly install valuable security packages and remove those with flaws, configuration of the packages must be done by the administrator. The bastille package that implements a given security policy on the local system based on previous configuration by the administrator (the building of the configuration can be a guided process done with simple yes/no questions). 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: tools to enhance system security (integrity checkers, intrusion detection, kernel patches...) * harden-environment: helps configure a hardened environment (currently empty). * harden-servers: removes servers considered insecure for some reason. * harden-clients: removes clients considered insecure for some reason. * harden-remoteaudit: tools to remotely audit a system. * 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. Be careful because if you have software you need (and which you do not wish to uninstall for some reason) and it conflicts with some of the packages above you might not be able to fully use harden. The harden packages do not (directly) do a thing. They do have, however, intentional package conflicts with known non-secure packages. This way, the Debian packaging system will not approve the installation of these packages. For example, when you try to install a telnet daemon with harden-servers, apt will say: # apt-get install telnetd The following packages will be REMOVED: harden-servers The following NEW packages will be installed: telnetd Do you want to continue? [Y/n] 这应当在管理员的头脑中引起一些警惕,考虑一下您的操作. 6.2. Bastille Linux ------------------- http://bastille-linux.sourceforge.net/ is an automatic hardening tool originally oriented towards the Red Hat and Mandrake Linux distributions. However, the bastille package provided in Debian (since woody) is patched in order to provide the same functionality for Debian GNU/Linux systems. 管理员可以使用 Bastille 不同的前端(在其联机手册中提及), 来完成: * Answer questions step by step regarding the desired security of your system (using InteractuveBastille(8) * Use a default setting for security (amongst three: Lax, Moderate or Paranoia) in a given setup (server or workstation) and let Bastille decide which security policy to implement (using 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)). 第 7 章 Debian 的安全机制 ================== 7.1. Debian 安全小组 ---------------- 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 第 4.2 节 “进行安全更新”). 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. 其它有关 Debian 安全小组的常见问题可以参阅第 12.3 节 “有关 Debian 安全小组的问题”. 7.2. 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: * 问题软件的版本号. * 问题类型. * 是会被远程攻击还是本地. * 软件包的简短描述. * 问题描述. * 攻击描述. * 修复描述. 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. 然而感兴趣的用户可以, (需要通过一些 Debian 相关端口来完成)使用 RDF 频道去自动下载 DSAs 到他们的计算机. 一些应用程序,譬如 Evolution (电子邮件客户和个人信息助理) 和 Multiticker (一个GNOME附属程序),可以用来自动获取公告. RDF 频道可以由 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. 漏洞的交叉参考 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. * 这些信息也可用于漏洞扫描器的交叉检测输出, 其包括参考 CVE 删除错误信息 (参见 第 12.1.2.1 节 “某个漏洞评估扫描工具说我的 Debian 系统存在漏洞!”). 7.2.2. CVE 兼容性 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 相信为用户提供影响 Debian 发行版的安全问题的附加信息是非常重要的. 在公告中 CVE 名称有助于用户了解漏洞与某个 Debian 安全更新的关系, 这有助于减少花费在处理影响我们用户的漏洞上的时间. 同时, 也使得对于部署了支持 CVE 的安全工具的环境的安全问题的管理变得简单 - 譬如基于网络或主机的入侵检测系统, 或漏洞评估工具, 不管它是不是基于 Debian 发行版的. 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 安全构建机制 ------------------ 因为当前的 Debian 支持大多数的平台, 管理员有时想知道是不是某一平台的安全更新比其它平台需要更多的时间. 事实上除了极罕见的情况外, 所有平台都是同事更新的. 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 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. * 提交由一个 Debian 系统完成检查和处理, 然后将其转移到 queue/accepted, 并在 buildds 上通告. 这些文件可由安全小组和(间接的) buildds 访问. * Security-enabled buildds 对源码包进行整理, 打包, 然后将日志发送给安全小组. * 安全小组对日志做出回应, 最新构建的软件包将被上载到 queue/unchecked, 在这里它们由 Debian 系统统一处理, 然后转移到 queue/accepted. * 当安全小组发现源码包可以接受时(即,它可以在各种平台正确的构建, 并且修复了安全漏洞, 而自身不会产生新的问题), 他们将会运行一个脚本来完成: * 软件包安装到安全归档区. * updates the Packages, Sources and Release files of security.debian.org in the usual way (dpkg-scanpackages, dpkg-scansources, ...). * 设定安全小组完成的模板通告. * forwards the packages to the appropriate proposed-updates so that it can be included in the real archive as soon as possible. 早先由手工完成的这些工作, 被测试后进入处于冻结阶段的 Debian 3.0 woody(2002年7月). 感谢这种机制, 使得安全小组可以在不到一天的时间内为所有的(大约二十种)平台更新 apache 和 OpenSSH. 7.4.1. 安全更新的开发指南 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. 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 第 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. The current scheme for package signature checks 当前使用 apt 进行软件包签名检测的计划是: * the Release file includes the MD5 sum of Packages.gz (which contains the MD5 sums of packages) and will be signed. The signature is one of a trusted source. * This signed Release file is downloaded by 'apt-get update' and stored along with Packages.gz. * When a package is going to be installed, it is first downloaded, then the MD5 sum is generated. * The signed Release file is checked (signature ok) and it extracts from it the MD5 sum for the Packages.gz file, the Packages.gz checksum is generated and (if ok) the MD5 sum of the downloaded package is extracted from it. * If the MD5 sum from the downloaded package is the same as the one in the Packages.gz file the package will be installed, otherwise the administrator will be alerted and the package will be left in the cache (so the administrator can decide whether to install it or not). If the package is not in the Packages.gz and the administrator has configured the system to only install checked packages it will not be installed either. 下边的 MD5 sums apt 可以完成对于源自某个发行版的单个的软件包的校检. 这与对每个软件包签名相比不太灵活, 也许会与这个计划结合(参见下面). 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 第 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. 在Debian]中的软件包签名已经被讨论了相当一段时间了, 更多信息参见: http://www.debian.org/News/weekly/2001/8/ 和 http://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 第 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 第 7.5.3.7 节 “Safely adding a key”. 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. Basic concepts 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: requesting key 2D230C5F from hkp server pgpkeys.mit.edu gpg: key 2D230C5F: public key "Debian Archive Automatic Signing Key (2006) " imported gpg: Total number processed: 1 gpg: imported: 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 ultimately trusted keys found 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. Safely adding a key 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. Verifying key integrity 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 第 7.5 节 “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: key 2D230C5F was created 192324901 seconds in the future (time warp or clock problem) gpg: key 2D230C5F was created 192324901 seconds in the future (time warp or clock problem) 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. 示例代码,将其命名为 apt-check-sigs, 可以通过下边的方法使用: # apt-get update # apt-check-sigs (...results...) # apt-get dist-upgrade 首先, 您需要: * 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 * 删除 /etc/apt/sources.list 中所有没有正常使用 "dists" 的行, 或者修改脚本,以便对它们有效. * be prepared to ignore the fact that Debian security updates don't have signed Release files, and that Sources files don't have appropriate checksums in the Release file (yet). * 准备用正确的公钥检查对应的源码. 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 # 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 | cut -d\ -f1` `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 lynx -reload -dump "${url}/dists/${dist}/Release" >/dev/null 2>&1 wget -q -O Release "${url}/dists/${dist}/Release" if ! grep -q '^' Release; then echo " * NO TOP-LEVEL Release FILE" >Release 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 lynx -reload -dump "${url}/dists/${dist}/Release.gpg" >/dev/null 2>&1 wget -q -O Release.gpg "${url}/dists/${dist}/Release.gpg" gpgv --status-fd 3 Release.gpg Release 3>&1 >/dev/null 2>&1 | sed -n "s/^\[GNUPG:\] //p" | (okay=0; err=""; while read gpgcode rest; do if [ "$gpgcode" = "GOODSIG" ]; then if [ "$err" != "" ]; then echo " * Signed by ${err# } key: ${rest#* }" else echo " o Signed by: ${rest#* }" okay=1 fi err="" elif [ "$gpgcode" = "BADSIG" ]; then echo " * BAD SIGNATURE BY: ${rest#* }" err="" elif [ "$gpgcode" = "ERRSIG" ]; then echo " * COULDN'T CHECK SIGNATURE BY KEYID: ${rest %% *}" err="" elif [ "$gpgcode" = "SIGREVOKED" ]; then err="$err REVOKED" elif [ "$gpgcode" = "SIGEXPIRED" ]; then err="$err EXPIRED" fi done if [ "$okay" != 1 ]; then 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' >UNVALIDATED cd /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. 可供选种的软包签名方案 The additional scheme of signing each and every packages allows packages to be checked when they are no longer referenced by an existing Packages file, and also third-party packages where no Packages ever existed for them can be also used in Debian but will not be default scheme. 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. 注: 当前 /etc/dpkg/dpkg.cfg 引入 "no-debsig" 为缺省值. 注2: 来自开发者的签名署名当它们进入软包的时候被剥离, 因为当前首选的方法还是使用前边描述的那种方法. ------------------------------------------------------------------------ [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 第 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. 第 8 章 Debian 中的安全工具 =================== FIXME: 需要更多内容. 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. 从 Debian 3.0(woody) 开始, 发行版就具有了将密码软件集成到主发行版中的特点. 缺省安装包括 OpenSSH 和 GPG(GNU Privacy Guard), 在浏览器, web服务器, 数据库, 等等中也出现了高强度加密. 计划在未来的发行版中, 进一步集成数据加密. 由于美国的出口限制, 这种软件是不允许随主发行版发布的, 只能包含在 non-US 站点上. 8.1. 远程风险评估工具 ------------- The tools provided by Debian to perform remote vulnerability assessment are: [55] * nessus * raccess * nikto (whisker's replacement) 显然, 最完善和最新的工具是 nessus, 它由一个GUI客户端(nessus), 和一个负责攻击的服务器端(nessusd)组成. Nessus 包括许多系统的远程漏洞如网络工具, ftp 服务器, www 服务器, 等等. 最新版本甚至可以解析网站, 并设法发现可以用于攻击的交互式页面. 并且还提供(没有包含在 Debian 中)用于连接管理服务器的 java 和 Win32 客户端. 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. 网络扫描器工具 ------------ Debian 确实提供了一些工具用于远程扫描主机(并不是风险评估). 这些工具在某些情况下被用作风险评估扫描器, 而不是当做攻击工具用于扫描以发现远程可用服务. Debian 当前提供: * nmap * xprobe * p0f * knocker * isic * hping2 * icmpush * nbtscan (for SMB /NetBIOS audits) * fragrouter * strobe (in the netdiag package) * irpas While xprobe provide only remote operating system detection (using TCP/IP fingerprinting, nmap and knocker do both operating system detection and port scanning of the remote hosts. On the other hand, hping2 and icmpush can be used for remote ICMP attack techniques. Designed specifically for SMB networks, nbtscan can be used to scan IP networks and retrieve name information from SMB-enabled servers, including: usernames, network names, MAC addresses... 另一方面, fragrouter 可以用于测试网络的入侵检测系统, 检查攻击者是否能绕过 NIDS. 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. 内部审计 --------- 当前, 在 Debian 系统中只有 tiger 工具可用于完成主机的内部(也称作白盒)审计, 以确定文件系统是否设置正确, 这个过程进行主机监听, 等等. 8.4. 源代码的审核 ----------- Debian provides several packages that can be used to audit C/C++ source code programs and find programming errors that might lead to potential security flaws: * flawfinder * rats * splint * pscan 8.5. 虚拟专用网 ---------- 一个虚拟专用网(VPN)至少由两台以上计算机系统组成, 典型的通过公网访问私有网络, 实现在公网的安全通信. VPNs 可能是将单机连入一个私有网络(客户端-服务器), 也可能是将一个远程局域网与一个私有网络相连(服务器-服务器). VPNs 通常包括使用加密, 远程用户或主机的强认证, 和隐藏私有网络拓扑结构的方法. Debian 提供一些软件包用于设置虚拟专用网的加密: * 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. 点对点隧道 如果您想为混合环境(微软操作系统和 linux 客户端)提供隧道服务, 并且不能选 IPsec(它是基于 Windows 2000 和 Windows XP 的), 那么可以使用 pptpd 软件包中提供的 PoPToP (点对点隧道服务). 如果您想使用 PPP 包中提供的微软的认证和加密服务, 注意下边的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. 然而, 您还必须使用 kernel-patch-mppe 软件包提供的内核补丁才行, 它为 pppd 提供了 pp_mppe 模块. 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. 公钥机制 (PKI) --------------- 公钥机制(PKI)是在不安全的网络上, 用于增加信息通讯的安全信心级别的安全平台. 它利用公钥和私钥的概念来核实发送者(签名)的身份以确保保密性(加密). 就 PKI 而言, 您要面对各种各样的问题: * a Certificate Authority (CA) that can issue and verify certificates, and that can work under a given hierarchy. * a Directory to hold user's public certificates. * a Database (?) to maintain Certificate Revocation Lists (CRL). * devices that interoperate with the CA in order to print out smart cards/USB tokens/whatever to securely store certificates. * certificate-aware applications that can use certificates issued by a CA to enroll in encrypted communication and check given certificates against CRL (for authentication and full Single Sign On solutions). * a Time stamping authority to digitally sign documents. * a management console from which all of this can be properly used (certificate generation, revocation list control, 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 机制 ----------- Debian 在发行版中提供一些用于安装到本地的 SSL 证书. 您可以在 ca-certificates 包中找到它们. 此软件包提供了一个重要的证书仓库, 它已由软件包维护者认可(就是校验)的, 并被提交到了Debian, 对任何一个使用 SSL 校验连接的 OpenSSL 应用程序都非常有用. FIXME: 查看 debian-devel 中是否有些东西需要添加到这里. 8.8. 病毒工具 --------- 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 提供如下用于构建防火墙环境的工具: * 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. [56] * 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 提供 File::Scan 一个扫描病毒的 perl 扩展. 此模块可用于制作 plataform 独立病毒扫描器. * 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, 一个用 perl 写的基于 Exim 的电子邮件病毒扫描器. * blackhole-qmail 一个 Qmail 的垃圾过滤器, 内置支持 Clamav. 一些网关守护进程已经支持工具扩展, 以构建防病毒环境, 其包括 exim4-daemon-heavy (Exim MTA 的 heavy 版), frox(一个透明缓存的 ftp 代理服务器), messagewall(一个 SMTP 代理守护进程), 和 pop3vscan (透明的 POP3 代理). 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[57]. 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 代理 ----------- 现在对一个邮件进行数字签名(有时是加密)非常普遍. 例如, 您可能发现邮件列表上的很多人对其列表邮件进行签名. 公钥签名是现在唯一的核实一个邮件是由其发送者发送, 而不是其他人仿冒的唯一手段. Debian GNU/Linux 提供了很多内置可以与 gnupg 或 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. 基于此软件包的稳定版本的演变, 您可能需要使用 bleeding edge version, sylpheed-claws. * gnus, 当其与 mailcrypt 软件包一起安装时, 是一个 gnupg 的 emacs 接口. * kuvert, 其由于和邮件传输代理( MTA )的融合, 可以提供独立于邮件用户代理( MUA )的功能. 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: [58] keyserver wwwkeys.pgp.net 很多 key server 是相互连接的, 因为当您的公钥加入一个服务器时, 它也将附加的蔓延到其它 key server 上. Debian GNU/Linux 也提供了一个 debian-keyring 软件包, 提供了 Debian 开发者的所有公钥. gnupg keyrings 被安装在 /usr/share/keyrings/ 目录下. 更多信息: * 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] 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/ / [57] 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. [58] For more examples of how to configure gnupg check /usr/share/doc/mutt/examples/gpg.rc. 第 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 第 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 第 12.1.1.12 节 “操作系统的用户与组”) 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[59]. 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[60]. 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. ------------------------------------------------------------------------ [59] 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 [60] You can even provide a SELinux policy for it 第 10 章 被攻陷之前 ============ 10.1. Keep your system secure ----------------------------- 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 第 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 第 10.1.2 节 “系统的及时更新”). 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. 系统的及时更新 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 第 4.2 节 “进行安全更新”. 10.1.2.1. 手动检查有效的安全更新 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. 如果您如 第 4.2 节 “进行安全更新” 所述, 配置了系统. 那么, 仅需要: # 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 第 4.2 节 “进行安全更新” for more information on library (and kernel) upgrades. 第一行将从您配置的源下载可用软件包列表. -s 将做一个模拟运行, 即并不真的下载, 并安装软件包, 而只是告诉您将会下载/安装哪些. 从输出中, 您可以知道 Debian 对哪些软件包做了修补, 可以做为一个安全更新. 例如: # 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 第 4.2 节 “进行安全更新” 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 第 10.1.2.3 节 “使用 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. 使用 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 第 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 第 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. 避免使用 unstable 分支 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. 为了对 unstable 分支进行安全更新, 您可能必须全部更新到新版本(其影响远远不止对软件包). 尽管存在一些例外, 安全补丁通常只进入 stable 分支. 其主要想法是在更新之间不再加入新的代码, 主要进行修补重大问题. Notice, however, that you can use the security tracker (as described in 第 10.1.1 节 “Tracking security vulnerabilities”) to track known security vulnerabilities affecting this branch. 10.1.4. Security support for the testing branch 如果您正在使用 testing 分支,那么您则必须考虑一些有关可用安全更新的问题: * 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). * 通常也有用于 unstable 的更新, 当软件包的维护者制作了一个新的软件包, 并且当安全小组制作了新的上载, 并公布了 DSA. 注意这两者都不会更改 testing 分支 * 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. 根据发行版的发行状态, 这种方式可能会改变. 当一个发行版将要放出时, 安全小组或软件包维护者可能对 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 第 4.2 节 “进行安全更新”): 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. 自动完成 Debian GNU/Linux 系统的更新 首先,并不十分推荐自动更新, 因为管理员应当查阅 DSA, 并了解每次安全更新的影响. 如果要自动完成系统的更新, 您应该: * 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: 检查这种配置的正确性. * Either use cron-apt as described in 第 10.1.2.3 节 “使用 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).[61] * Configure debconf so no questions will be asked during upgrades, so that they can be done non-interactively. [62] * 检查 cron 的执行结果, 它将会通过mail发送给超级用户(除非修改了与 MAILTO 环境变量相关的脚本). 使用 -d(或 --download-only)选项也许会更加安全, 这样只下载所需的软件包, 而并不安装. 然后如果 cron 执行的结果显示系统需要更新, 就手动完成. 为了完成这些工作, 需要正确配置系统以下载安全更新如第 4.2 节 “进行安全更新”中建议的. 但是,如果没有经过仔细的分析, 并不推荐在 unstable 中这样做, 因为如果您安装到系统中的一个重要的软件包中存在严重 bug, 可能会使系统崩溃. 对于这种问题, testing 相对要好一点. 因为严重的 bug 在进入 testing 分支前有更多机会被检测出来.(尽管,您可能没有任何安全更新可用). 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.[63] 10.2. 周期性入侵检测 ------------- 通常完成安装后, 一条基本准则是(即, 如 第 4.19 节 “生成系统快照” 所描述)应当经常进行系统完整性检查. 完整性检查有助于发现入侵者对文件系统的改动, 或系统管理的操作失误. Integrity checks should be, if possible, done offline.[64] 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. 您可以考虑使用有效的文件系统完整性检查工具(如 ref id="check-integ" /> 中所述)在线完成完整性检查, 如果离线完成这一工作不太可能. 但是, 除了使用只读数据库这一预防措施, 还要确保完整性检查工具(和操作系统内核)未被篡. 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. 当然, 如果您对系统进行了安全更新, 应当重新制作系统快照, 以包容安全更新所产生的改动. 10.3. 设置入侵检测 ------------ 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. 谨记, 为了使用介绍的工具真正改善系统的安全性, 您需要到位的报警和响应机制. 如果没有报警, 入侵检测将会非常费时. 当检测到一次特殊的攻击时, 多数的入侵检测工具要么使用 syslogd 记录事件, 要么要么发送邮件到 root 用户(邮件接收者是可以配置的). 管理员必须正确的配置这些工具, 以便错误的信息不会触发报警. 报警也许还表明当一次持续的攻击, 也许一天以后已经没用了, 因为攻击可能已经成功了. 因此要确保正确的处理报警的策略以及相应的技术机制应当到位. An interesting source of information is http://www.cert.org/tech_tips/intruder_detection_checklist.html 10.3.1. 基于网络的入侵检测 基于网络的入侵检测工具监测在网络上传送的数据段, 并将其作为数据源. 具体就是审查网上的数据包, 看是否与某些特征匹配. 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. Debian's snort package has many security checks enabled by default. However, you should customize the setup to take into account the particular services you run on your system. You may also want to seek additional checks specific to these services. 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. 基于主机的入侵检测 基于主机的入侵检测包括在被检测的系统中加载软件, 其使用日志文件和/或系统的检测程序作为数据源. 它搜寻可疑的进程, 监视主机的访问, 也许甚至监控对重要文件的修改. 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 第 4.13.1 节 “使用和定制 logcheck”. 另外,用于监测文件系统完整性的软件包(参见 第 4.17.3 节 “文件系统的完整性检查”)在检查一个安全系统的异常现象时也非常有用. 一个有效的侵入很可能会 修改一些本地文件系统中的文件以绕过本地安全策略, 安装木马, 或创建用户. 这些事件通常可以通过使用文件系统完整性检查工具检测到. 10.4. 避免 root-kits ------------------ 10.4.1. 可加载内核模块 (LKM) 可加载内核模块是指包含动态可加载内核组件的文件, 用于扩展内核功能. 使用模块最大的好处是在添加另外的设备时, 如网卡或声卡, 不必修补内核源码, 并重新编译整个内核. 然而, 现在黑客将 LKMs 用于 root-kits(knark 和 adore),在 GNU/Linux 系统中开启后门. LKM 后门比传统的 root-kits 更加先进和隐蔽. 可以隐藏进程, 文件, 目录, 甚至连接而不必修改二进制源码. 例如, 一个恶意的 LKM 可以迫使内核隐藏源自 procfs 的进程, 这样即使是著名的 ps 也不能列出关于系统的当前进程的准确信息. 10.4.2. 检测 root-kits 有两种方法保护您的系统免受 LKM 伤害, 主动防护和被动防护. 检测工作可能是简单和轻松的, 或是麻烦和繁重的, 这和采取的方法有关. 10.4.2.1. 主动防护 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 仅提供很少的软件包用于挂载一个主动防御防护: 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[65] will remove module loading capabilities (even for the root user).[66] There is some (old) information on capabilities at Jon Corbet's http://lwn.net/1999/1202/kernel.php3 section on LWN (dated December 1999). 如果您的 GNU/Linux 系统确实不需要那么多的内核特性, 您可能想在内核配置阶段取消可加载模块支持. 禁用可加载模块支持, 只要在构建内核的配置阶段或者在 .config 文件中设置 CONFIG_MODULES=n 就可以了. 这将能防止 LKM root-kits, 但是你也将丧失 Linux 内核的强大特性. 同时, 有时对可加载的支持是必须的, 禁用可加载模块可能会引起内核过载. 10.4.2.2. 被动防护 被动防护的优点是不必重载系统资源. 其通过将系统与一个已知干净系统的清单 System.map 相比较. 当然, 被动防护只能在系统被攻克以后通知管理员. 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. Genius/Paranoia Ideas - what you could do ----------------------------------------------- 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. * 轻率的对待可插入认证模块 (PAM). 就象文章 Phrack 56 PAM 中说的一样, PAM 最好是"您只是受您思维的限制", 这是真的, 设想一下 root 通过指纹或眼睛扫描或 加密卡认证登陆(为什么我使用 或 连接词来代替 和 ?). * 法西斯式记录. 我把前面所做的关于日志的讨论称作"软件日志". 如果您想完成真正的日志, 就配置一台打印机, 并把所有的日志打印出来. 这听起来很滑稽, 但这样才可靠, 不会被篡改或删除. * 光盘版本. 这个想法很好实现, 并更具安全性. 构建一个安全化的 Debian 发行版, 并带有合适的防火墙规则. 把它转换成可引导 ISO 影像, 然后烧录成光盘. 这样您就拥有了一个只读版本, 大约有600M空间用于服务. 只要确保所有需要写入的数据都是通过网络完成的就行了. 这样入侵者就不可能拥有系统的读/写权限, 并且入侵者的任何修改都不会影像重起后的系统. * 禁用模块切换能力. 就象前边所谈论的, 当您在编译阶段禁用掉模块, 许多基于内核的后门就不可能实现, 因为它们中的大部分基于安装时对内核模块的修改. * Logging through serial cable (contributed by Gaby Schilders). As long as servers still have serial ports, imagine having one dedicated logging system for a number of servers. The logging system is disconnected from the network, and connected to the servers via a serial-port multiplexer (Cyclades or the like). Now have all your servers log to their serial ports, write only. The log-machine only accepts plain text as input on its serial ports and only writes to a log file. Connect a CD/DVD-writer, and transfer the log file to it when the log file reaches the capacity of the media. Now if only they would make CD writers with auto-changers... Not as hard copy as direct logging to a printer, but this method can handle larger volumes and CD-ROMs use less storage space. * 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. This strategy will help limit the damage that you can do when logged in as root. You won't overwrite files with a stray redirection operator, and you won't make the system unusable with a stray space in a rm -fr command (you might still do plenty of damage to your data - but your libraries and binaries will be safer). 这个策略也可使系统免受拒绝服务攻击(DoS), 或使其更加困难(因为大多数基于通过激活一些 SETUID 程序, 来重写一个文件,这并不能避免随意的 shell 命令). One inconvenience of this strategy arises during building and installing various system binaries. On the other hand, it prevents the make install from over-writing the files. When you forget to read the Makefile and chattr -i the files that are to be overwritten, (and the directories to which you want to add files) - the make command fails, and you just use the chattr command and rerun it. You can also take that opportunity to move your old bin's and libs out of the way, into a .old/ directory or tar archive for example. 注意这个策略将会使您无法升级系统, 因为被更新的文件是无法重写的. 您也许需要一个脚本或机制使得在 apt-get update 前取消所有程序的不可修改标志. * 使用 UTP 电缆时, 去掉2根或4根线, 使其只能进行 one-way 传输. 这样, 使用 UDP 包向做为安全日志服务器或信用卡存储系统的机器发送信息包. 10.5.1. 构建蜜罐 蜜罐(honeypot)是一个设计来让系统管理员用于学习黑客如何探测和利用一个系统的系统. 这个系统的设置目的是希望被探测, 攻击, 和潜在的利用. 通过学习黑客使用的工具和方法, 系统管理员可以更好的保护他们的系统和网络. 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[67] 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 第 4.13 节 “日志与警告的重要性”) 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: * 您要使用的防火墙技术(由 Linux 内核提供). * syslog-ng, useful for sending logs from the honeypot to a remote syslog server. * snort, to set up capture of all the incoming network traffic to the honeypot and detect the attacks. * 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. * Integrity checkers (see 第 4.17.3 节 “文件系统的完整性检查”) and The Coroner's Toolkit (tct) to do post-attack audits. * 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. ------------------------------------------------------------------------ [61] 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. [62] Note that some packages might not use debconf and updates will stall due to packages asking for user input during configuration. [63] 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. [64] 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. [65] 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. [66] You don't need to install lcap to do this, but it's easier than setting /proc/sys/kernel/cap-bound by hand. [67] You will typically use a bridge firewall so that the firewall itself is not detectable, see 第 B.4 节 “设定网桥防火墙”. 第 11 章 攻陷之后(事件响应) ================= 11.1. 常见方法 ---------- 假设您受到攻击时, 你的第一反应应该是拔掉网线(如果不会影响到商业事务), 切断同互联网的物理连接. 在第一层禁用网络, 隔绝攻击者, 这是唯一正确选择(Phillip Hofmeister 的忠告). 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 [68] 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[69]. 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. 备份系统 ---------- Remember that if you are sure the system has been compromised you cannot trust the installed software or any information that it gives back to you. Applications might have been trojanized, kernel modules might be installed, etc. The best thing to do is a complete file system backup copy (using dd) after booting from a safe medium. Debian GNU/Linux CD-ROMs can be handy for this since they provide a shell in console 2 when the installation is started (jump to it using Alt+2 and pressing Enter). From this shell, backup the information to another host if possible (maybe a network file server through NFS/FTP). Then any analysis of the compromise or re-installation can be performed while the affected system is offline. If you are sure that the only compromise is a Trojan kernel module, you can try to run the kernel image from the Debian CD-ROM in rescue mode. Make sure to startup in single user mode, so no other Trojan processes run after the kernel. 11.3. 联系您当地的 CERT ----------------- The CERT (Computer and Emergency Response Team) is an organization that can help you recover from a system compromise. There are CERTs worldwide [70] 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. 事故分析 ---------- 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). Remember that forensics analysis should be done always on the backup copy of the data, never on the data itself, in case the data is altered during analysis and the evidence is lost. 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: 希望将来本段增加更多有关在 Debian 系统中事故分析的信息. 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[71]). 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. ------------------------------------------------------------------------ [68] >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. [69] >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). [70] > 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). [71] >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 第 12 章 常见问题解答 (FAQ) =================== 本章介绍源自 Debian 安全邮件列表中的一些常见问题, 当您准备发送邮件, 甚至别人告诉您去 RTFM 时, 您可以阅读它们. 12.1. Debian 操作系统的安全 -------------------- 12.1.1. Debian 比 X 更安全吗? A system is only as secure as its administrator is capable of making it. Debian's default installation of services aims to be secure, but may not be as paranoid as some other operating systems which install all services disabled by default. In any case, the system administrator needs to adapt the security of the system to the local security policy. 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.[72] 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. Debian 在安全方面主要的优势在于系统通过 apt 完成升级非常简单. Debian 在安全方面还有以下方面值得考虑: * Debian 比其它发行版提供更多的安全工具, 参见 第 8 章 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. [73] * 提供了最佳的安全实践文档, 就象本篇. 12.1.1.2. 在 Bugtraq 中有很多 Debian bug. 这是否意味着它很脆弱吗? Debian 发行版号称拥有最多的软件包, 可能比任何一个操纵系统都多. 安装的软件包越多, 潜在的安全问题就越大. 越来越多的人测试原代码的缺陷. 在 Debian 中许多公告与主要软件组件的源码审计有关. 每当诸如此类的源码审计出现漏洞, 它们将会被修复, 并向如 Bugtraq 的列表发送一个公告. 通常在 Debian 中发现的 bug 同样会影响到其它发行版和开发商. 检查每个公告 (DSA) 顶端的 "Debian specific: yes/no" 部分. 12.1.1.3. Debian 有与安全相关的证书吗? 简短的回答: 没有. 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. 有针对 Debian 的安全化程序吗? Yes. http://bastille-linux.sourceforge.net/, originally oriented toward other Linux distributions (Red Hat and Mandrake), it currently works also for Debian. Steps are being taken to integrate the changes made to the upstream version into the Debian package, named bastille. 但是, 有些人认为一个安全设置工具并不能满足一个好的管理员的需求. 12.1.1.5. 我想要运行 XYZ 服务, 应当选择哪个? Debian 的一个强大之处在于对于相同功能( DNS 服务器, 邮件服务器, ftp服务器, web 服务器, 等等) 有很多软件包可供选择. 对于新管理员确定哪个软件包更适合来说很容易被搞糊涂. 对于给定条件的最好的选择是基于您的特点与安全需求之间的平衡. 当您在相似的软件包之间作选择时, 应当问自己这么几个问题: * 上游仍在维护这个软件吗? 什么时候发行的最新版? * 软件包成熟吗? 版本号并不能告诉您它的成熟度. 设法查看软件的开发历史. * 软件 bug-ridden 吗? 有与其相关的安全公告吗? * 软件是否提供您所需要的所有功能? 是否多于您的真正需求? 12.1.1.6. 在 Debian 中如何使 XYZ 服务更安全? 在本文档中您会找到一些在 Debian GNU/Linux 中使一些服务(FTP,Bind)更安全的方法. 这里所没有提供的, 您可以查看程序的文档, 或常用的 Linux 信息. 大多数的用于 Unix 系统的安全指南同样适用于 Debian. 很多情况下, Debian 中服务 X 的安全设置于在其它 Linu x发行版相同行(或 Un*x ,就此而言). 12.1.1.7. 如何删除服务的所有标语? 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. [74] 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. 所有的 Debian 软件包都安全吗? Debian 安全小组不可能分析 Debian 中所有的软件包的潜在漏洞, 因为没有足够的资金用于整个项目的源代码的安全审计. 但是, Debian 可受益于上游开发者. 实际上,Debian 开发者可能发布一个含有木马的软件包, 并且无法将其检查出来. 即使将其引入 Debian 的一个分支, 也不可能报告出木马可能运行的所有可能的状况. 这就是为什么 Debian 含有"无保证"条件许可的原因. 但是,Debian 用户事实上应当对有广泛用户的稳定版本有足够的信心, 其多数问题可以通过使用被发现. 对于一个重要的系统并不推荐安装未经测试的软件(如果无法提供必要的代码审计). 无论如何, 如果含有安全漏洞的软件被引入发行版, 通过包含软件包确认的使用过程, 这种问题最终可能将追踪到开发者. Debian 项目不轻易采取了这种方法. 12.1.1.9. 为什么一些日志文件/配置文件设为完全可读(world-readable), 这样不是不安全吗? 当然,您可以修改系统的缺省 Debian 许可. 当前关于日志文件和配置文件的策略是完全可读(world readable), 除非它们提供的是高度机密的信息. 如果您作修改,那么就要小心: * 进程也许不能写入日志, 如果您限制了它们的权限. * 一些软件可能不能工作了, 如果它们依靠的配置文件不可读. 例如, 如果您移除了 /etc/samba/smb.conf 的完全可读权限, 普通用户将无法运行 smbclient 程序. FIXME: 检查策略里的写权限部分. 一些软件包(即, ftp 守护进程)似乎强制执行不同的权限. 12.1.1.10. 为什么 /root/(或 UserX)的权限是755? 实际上,其他用户存在同样的问题. 因为 Debian 的安装不在这个目录下放置任何文件, 那里没有任何需要保护的机密信息. 对于您的系统来说, 如果您觉得权限过于宽松, 可以考虑设为750. 对于其他用户,参阅 第 4.11.19.1 节 “限制用户对于其他用户信息的访问”. This Debian security mailing list http://lists.debian.org/debian-devel/2000/11/msg00783.html has more on this issue. 12.1.1.11. 在安装 grsec/防火墙后,我开始接收到许多控制信息! 怎么删除他们? 如果您正在接受控制台信息, 并已经配置了 /etc/syslog.conf 将日志信息转向其他文件或指定 TTY, 那么您可能会看到直接发送到控制台的信息. 任何一个内核的缺省控制台日志级别都为 7, 这意味着任何低优先级信息都会出现在控制台. 通常, 防火墙(日志规则)和一些其它的安全工具的日志优先级较低, 因此, 会被直接发送到控制台. 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="" 为: KLOGD="-c 4" 如果仍然出现, 为 -c 设置更小的数字. 在 /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. 操作系统的用户与组 12.1.1.12.1. 所有系统用户都是必需的吗? 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[75] (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 These users are provided by base-passwd. Look in its documentation for more information on how these users are handled in Debian. The list of default users (with a corresponding group) follows: * root: Root 是(典型的) 超级用户. * daemon: 一些非特权守护进程运行时需要象 daemon.daemon (如, portmap, atd, 或许还有其它)一样对磁盘文件进行写操作. 守护进程以 nobody.nogroup 运行时不需要拥有任何文件. 更复杂或更安全的守护进程以指定用户运行. daemon 用户也可用于本地安装 daemon. * bin: 因为历史的原因被保留下来. * sys: 同 bin. 但是,sys 组拥有 /dev/vcs* 和 /var/spool/cups. * sync: 用户 sync 的 shell 是 /bin/sync. 因而,如果它的密码被设置对容易事猜测(譬如 "" ) ,任何人都可以通过控制台 sync 系统. 既使他们没有帐户. * games: 许多游戏被 SETGID 为 games, 这样就可以对它们的高分值文件进行写操作. 这是策略里边的解释. * man: 程序(有时)以用户 man 运行, 这样可以将 cat 的页面写入 /var/cache/man. * lp: 由打印机守护进程使用. * mail: /var/mail 目录下的信箱由 mail 组拥有, 这是策略中的解释. 用户和组同时也被其它各种各样的 MTA 使用. * news: 各种各样的新闻服务器以及其它相关的程序(譬如 suck)以各种各样的方式使用 news 用户和组. 在 news spool 中的文件通常为 news 用户和组拥有. 用于投递新闻的程序,如 inews 就是典型的 SETGID news. * uucp: uucp 用户和组由 UUCP 子系统使用. 其拥有 spool 和配置文件. 属于 uucp 组的用户,可以运行 uucico. * proxy: 如 daemon, 此用户和组由一些没有指定用户id, 但是需要拥有文件的守护进程(具体的, proxy 守护进程)使用. 例如, proxy 组由 pdnsd 使用, squid 以proxy用户运行. * majordom: 在Debian系统中, 因为历史的原因, Majordomo 有一个静态分配的 UID. 新的系统中没有. * postgres: Postgresql 数据库由这个用户和组拥有. 因为安全的原因, 目录 /var/lib/postgresql 下的所有文件由此用户拥有. * www-data: Some web servers run as www-data. Web content should not be owned by this user, or a compromised web server would be able to rewrite a web site. Data written out by web servers, including log files, will be owned by www-data. * backup: 这样, 备份/恢复的任务可以委派没有完全 root 权限的用户. * operator: operator 是过去(和现在)唯一可以不依赖于 NIS/NFS 远程登陆而'用户'账号. * list: 邮件列表文件和数据由此用户和组拥有. 一些邮件列表程序也是以此用户运行. * irc: 由 irc 守护进程使用. 因为 ircd 的一个 bug, 需要分配一个静态用户, 启动时, 它将自身 SETUID() 给一个指定 UID. * gnats. * nobody, nogroup: 不需要拥有任何文件的守护进程以用户 nobody 和组 nogroup 的方式运行. 因此, 此用户和组在一个系统上不会拥有任何文件. 其它没有相关用户的组: * adm: adm 组由系统监控任务使用. 这个组的成员对 /var/log 下的许多日志文件有读权限. 并且可以使用 xconsole. 过去, /var/log 就是 /usr/adm(后来是 /var/adm). 这是这个组名字的由来. * tty: TTY 设备由这个组拥有. 这样可以将 write 和 wall 操作传到其它人的 TTY 上. * disk: raw 对磁盘的访问, 等同于 root 的访问. * kmem: 此组可以读取 /dev/kmem 和类似的文件, 这是BSD的一个主要遗留痕迹, 任何需要直接读去系统内存的程序都需要 SETGID 为 kmem. * dialout: 对串口的全部和直接访问. 此组的成员可以对调制解调器, dial anywhere 等进行再配置. * dip: 此组的标准名称为"Dial-up IP", 此组的成员允许使用ppp, dip, wvdial, 等一类的工具, 进行拨号连接. 这个组的用户不允许配置调制解调器, 但是可以运行使用它的程序. * fax: 允许成员使用fax软件收/发传真. * voice: Voicemail, 对于使用调制解调器作为电话答录机的系统非常有用. * cdrom: 这个组可以用来在本地分配给用户对 CDROM 的访问权限. * floppy: 这个组可以用来在本地分配给用户对软驱的访问权限. * tape: 这个组可以用来在本地分配给用户对磁带机的访问权限. * sudo: 当使用 sudo 时, 这个组的成员不需要键入密码. 参阅 /usr/share/doc/sudo/OPTIONS. * audio: 这个组可以用来在本地分配给用户对 audio 设备的访问权限. * src: 这个组拥有源代码,包括 /usr/src 目录下的文件. 可以用来在本地给用户分配管理系统源代码的能力. * shadow: 这个组可以读取 /etc/shadow. 需要访问这个文件的一些程序需要 SETGID 为 shadow. * utmp: 这个组可以对 /var/run/utmp 和类似的文件进行写操作. 需要对此类文件进行写操作的程序需要 SETGID 为 utmp. * video: This group can be used locally to give a set of users access to a video device. * staff: 允许用户添加对系统((/usr/local, /home)的本地修改, 而不需要特权. 与 "adm" 组相比, 更 monitoring/security. * users: 当 Debian 系统使用默认的私有用户组系统(每个用户都有他们自己的组)时, 有些更愿使用传统的组系统, 所有用户都是此组的一个成员. 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. adm 组和 staff 组之间有什么区别? 'adm' 组的成员通常为管理员, 这个组的权限允许他们不用 su 就能读取日志文件. 'staff' 组则通常为 help-desk/junior sysadmins, 允许成员在 /usr/local 目录下操作, 和在 /home 目录下创建目录. 12.1.1.13. 为什么我创建新用户时, 会同时出现一个新组?(或为什么 Debian 为每个用户创建一个所属组?) 在 Debian 中, 缺省设置为每个用户都有一个私有组. 传统的 UN*X 方案为每个用户指定了用户组. 创建的其它的组用于限制对不同项目目录下的共享文件的访问. 当单个用户操作多个项目时, 如果某个用户创建了一个文件, 文件的管理将变的困难, 它同它所属的主要组联系在一起(如,'users'). Debian 的方案是通过为每个用户指定一个他们自己的组解决了这一问题; 这样可以带有一个合适的 umask(0002)并且对给定项目目录设置了 SETGID 位, 在此目录下创建的文件都被正确的指定了组. 这使得处理多个项目更加简单, 因为不必切换所属的组或 umask. 然而, 您也可以通过修改 /etc/adduser.conf 来改变这一特性. 修改 USERGROUPS 变量为 'no', 这样当创建用户时就不会伴随产生一个新组了. 也可以设置 USERS_GID 为所有用户都属于的组的GID. 12.1.1.14. Questions regarding services and open ports 12.1.1.14.1. 为什么所有的服务安装后都被激活了? 这只是解决问题的一种方法, 既考虑到了安全性, 又兼顾对用户的友好. 除非管理员将其激活, OpenBSD 将禁用所服务. 与此不同除非将其禁用, Debian GNU/Linux 会激活所有安装的服务(更多信息参见 第 3.5.1 节 “禁用守护进程服务”). 在您安装了服务之后, 不是这样吗? 对于标准安装, 哪个是更好的解决方案, 在 Debian 的邮件列表(debian-devel 和 debian-security)上有更多的讨论, 然而, 到目前为止(2002年3月), 仍然没有达成共识. 12.1.1.14.2. 我能删除 inetd 吗? Inetd is not easy to remove since netbase depends on the package that provides it (netkit-inetd). If you want to remove it, you can either disable it (see 第 3.5.1 节 “禁用守护进程服务”) or remove the package by using the equivs package. 12.1.1.14.3. 为什么我的111端口是打开的? 端口111是 sunrpc 的 portmapper,它是 Debian 的基本安装的默认部分, 因为不必知道何时用户的程序需要 RPC 才能正确运行. 无论如何, 它主要由 NFS 使用. 如果您不需要它, 您可以依照 第 5.13 节 “增强 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. identd(port 113)的主要用途是什么? Identd 服务是一个认证服务, 用于鉴别某个 TCP/IP 远程服务连接的拥有者的身份. 一个典型的例子, 当用户连接到远程主机, 远程主机上的 inetd 向113端口发回一个查询到, 索取用户信息, 通常由 mail, FTP 和 IRC 服务器使用, 也可用于跟踪您本地系统中的哪个用户试图攻击一个远程系统. 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. 使用 1 到 6 端口的是什么服务,如果删除? 运行命令 netstat -an, 您会看到: 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. 我发现端口 XYZ 打开了, 可以将其关闭吗? 是的,当然可以. 您所开放的端口应当遵循您的个人站点关于对其它网络提供公共服务的策略. 检查由 inetd 打开的端口(参见 第 3.5.2 节 “禁用 inetd 服务”), 或由于安装的其它软件包打开的端口, 并采取适当的措施(即,配置 inetd, 删除这个软件包, 避免其启动时运行). 12.1.1.14.7. 从 /etc/services 中删除服务, 是否对我的主机的安全有帮助? 否, /etc/services 只是在真实名称和指定端口号之间提供一种映射. 从此文件中删除服务名并不能(通常)阻止运行的服务. /etc/services 修改后一些守护进程可能不能运行了, 但这样做并不规范. 正确的禁用服务的方法, 参见 第 3.5.1 节 “禁用守护进程服务”. 12.1.1.15. 常见安全问题 12.1.1.15.1. 我的密码丢了,无法访问系统了! 您所需要做的恢复步骤与您是否采纳了限制访问 lilo 和系统的 BIOS 的建议有关. 如果您两个都做了限制, 则进行下一步前, 您需要禁用只能从硬盘启动的 BIOS 设定. 如果你连 BIOS 的密码也忘了, 就需要打开机箱, 取下BIOS 的电池, 将 BIOS 的设置复位. 一旦您设定了从 CD-ROM 或软盘启动,尝试以下步骤: * 由救援盘启动内核 * 转到虚拟控制台(Alt+F2) * 挂接 /root 所在硬盘分区 * 编辑(Debian2.2 救援盘提供 ae 编辑器, Debian3.0 提供与 vi 很相似的 nano-tiny)/etc/shadow 并修改: root:asdfjl290341274075:XXXX:X:XXXX:X::: (X=any number) 为: root::XXXX:X:XXXX:X::: 这将删除遗忘的 root 密码, 包含在用户名之后第一个冒号分割的部分. 保存修改, 重起系统, 以 root 使用空密码登录. 记得重新设置密码. 这样就可行了, 除非您更严谨的配置了系统, 即您不允许用户使用空密码登录, 或不允许 root 由控制台登录. 如果使用这些特性, 则您将需要以单用户模式进入. 如果对 LILO 做了限制, 则您需要在 root 重新设置了上述之后再次运行 lilo. 这相当棘手, 因为你的 /etc/lilo.conf 需要根据 root(/)文件系统来调整, 而不是真正的硬盘 一旦没有了 LILO 限制,尝试以下步骤: * 在系统 BIOS 完成之前按下 Alt, shift 或 Control 键, 您会得到 LILO 提示符. * 在提示符后键入 linux single, linux init=/bin/sh 或 linux 1. * 这样您会得到一个单用户模式下的 shell 提示符(将提示键入密码, 但是您已经知道了) * 使用 mount 命令, 重新以 read/write 模式挂接 root(/) 分区. # mount -o remount,rw / * 使用 passwd 命令修改超级用户密码(因为您就是超级用户, 所有不会要求您提供原密码). 12.1.1.16. 如何配置不需要分配用户 shell 账号的服务? 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 第 4.11.1 节 “用户认证: 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 为, 例如, 对于 ldap 来说: auth required pam_ldap.so 就 LDAP 目录而论,为了使用 LDAP 认证, 一些服务需要在您的目录中提供 LDAP 方案. 如果您使用关系数据库,可以在配置 PAM 模块时, 使用一个有趣的设定. 例如, 如果您有一个带有如下表属性的数据库: (user_id, user_name, realname, shell, password, UID, GID, homedir, sys, pop, imap, ftp) 通过标记服务的属性布尔字段, 就可以启用或禁用对于不同服务的访问, 仅仅需要在下列文件插入合适的内容: * /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. 我的系统存在漏洞!(您确认吗?) 12.1.2.1. 某个漏洞评估扫描工具说我的 Debian 系统存在漏洞! 许多漏洞评估扫描器在 Debian 系统上使用不能给予肯定的回答, 因为它们通过版本检查来确定给定软件包是否存在漏洞, 并不真正的进行安全漏洞测试. 因为 Debian 在修正软件漏洞后并不修改软件版本信息 (很多时候, 修复一个更新版本仅仅是移植), 一些工具认为一个更新了的 Debian 系统是存在漏洞的, 即使并不是这样. 如果您认为您的系统已经更新了最新的安全补丁, 可以与 DSA(参见 第 7.2 节 “Debian 安全公告”) 公布的安全漏洞数据库相参考, 识别虚假信息, 如果您使用的工具包括 CVE 参考. 12.1.2.2. 我在系统日志中看到一次攻击. 我的系统被入侵了吗? 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 第 11 章 攻陷之后(事件响应)). 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. 我在日志中发现了奇怪的 'MARK' 行: 我被入侵了吗?? 您也许在系统日志中发现了如下内容: 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. 在日志中发现有用户使用'su': 我被入侵了? 有可能您在日志中发现如下类似内容: 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) 不必太担心. 检查这些内容是否与 cron 有关 (通常为 /etc/cron.daily/find 或 logrotate): $ grep 25 /etc/crontab 25 9 * * * 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? 如果您在日志中发现了如下类似内容: 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. 用 netstat 检查服务器是否存在大量的连接, 例如: linux:~# netstat -ant | grep SYN_RECV | wc -l 9000 这表明对您的系统的 X 端口(通常是对应公共服务, 如 web 服务器, 或邮件服务器)进行了拒绝服务(DoS)攻击. 您应当激活内核中的 TCP syncookies, 参阅 第 4.18.2 节 “Configuring syncookies”. 但是, 应当注意, 这样即使您能避免系统被搞瘫, 一个 DoS 攻击仍能湮没您的网络(由于资源标示被耗尽, 系统也许暂时无法应答 TCP 连接, 直至超时). 最有效的解决方法是联系您的网络提供商. 12.1.2.6. 在日志中发现了奇怪的 root 会话: 我被入侵了? 在 /var/log/auth.log 文件中, 也许您会发现如下类似内容: 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 这与执行的 cron 任务有关(在这个例子中,每5分钟一次). 确定哪个程序对应这些任务, 检查如下目录中的内容: /etc/crontab, /etc/cron.d, /etc/crond.daily 和 root 的 crontab 目录. 12.1.2.7. 我被入侵了, 怎么办? 这种情况下,也许您应当采取如下措施: * 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/. * 阅读本文档, 尤其 第 11 章 攻陷之后(事件响应) 部分. * 寻求帮助. 您可以使用 Debian 安全邮件列表, 寻求如何恢复/修补您的系统的建议. * 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. 如何跟踪攻击? 查看日志(如果还未被篡改), 使用入侵检测系统(参见 第 10.3 节 “设置入侵检测”), traceroute, whois 和其它简单的工具(包括事故分析), 您也许能跟踪到攻击源. 这种方法是否有效与您的安全策略, 以及您认为什么是攻击有关. 远程扫描是攻击吗? 漏洞探测是攻击吗? 12.1.2.9. Debian 系统中的程序 X 存在漏洞, 我该怎么办? First, take a moment to see if the vulnerability has been announced in public security mailing lists (like Bugtraq) or other forums. The Debian Security Team keeps up to date with these lists, so they may also be aware of the problem. Do not take any further actions if you see an announcement at 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. 软件包的版本号表明,我正在运行一个存在漏洞的版本! Instead of upgrading to a new release, Debian backports security fixes to the version that was shipped in the stable release. The reason for this is to make sure that the stable release changes as little as possible, so that things will not change or break unexpectedly as a result of a security fix. You can check if you are running a secure version of a package by looking at the package changelog, or comparing its exact (upstream version -slash- debian release) version number with the version indicated in the Debian Security Advisory. 12.2. 特定软件 ---------- 12.2.1. proftpd is vulnerable to a Denial of Service attack. Add DenyFilter \*.*/ to your configuration file, and for more information see http://www.proftpd.org/bugs.html. 12.2.2. After installing portsentry, there are a lot of ports open. 这是 portsentry 的工作方式. 它打开大约二十个未使用的端口用于确定端口扫描. 12.3. 有关 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. ------------------------------------------------------------------------ [72] 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 [73] >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. [74] >Note that this is 'security by obscurity', and will probably not be worth the effort in the long term. [75] 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. 附录 A. 修订历史 ========== 修订历史 修订 3-19.2 Sun May 19 2024 Holger Wansing Translation files synchronised with XML sources 3-19 修订 3-19.1 Mon May 1 2017 Marcos Fouces Translation files synchronised with XML sources 3-19 修订 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. 修订 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 修订 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. 修订 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. 修订 3-15 December 2010 Javier Fernández-Sanguino Peña Change reference to Log Analysis' website as this is no longer available. 修订 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. 修订 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. 修订 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. 修订 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. 修订 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. 修订 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. 修订 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. 修订 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. 修订 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. 修订 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). 修订 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). 修订 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. 修订 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. 修订 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. 修订 3-0 December 2004 Javier Fernández-Sanguino Peña Rewrote the user-auditing information and include examples on how to use script. 修订 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. 修订 2-98 Javier Fernández-Sanguino Peña Fixed URL as suggested by Frank Lichtenheld. Fixed PermitRootLogin typo as suggested by Stefan Lindenau. 修订 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. 修订 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. 修订 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 (第 11 章 攻陷之后(事件响应)). 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. 修订 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. 修订 2-93 March 2003 Frédéric Schütz rewrote entirely the section of ext2 attributes (lsattr/chattr) 修订 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). 修订 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. 修订 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. 修订 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. 修订 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. 修订 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). 修订 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. 修订 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. Fixed some typos. 修订 2-4 June 2002 Javier Fernández-Sanguino Peña Rewritten part of the BIOS section. 修订 2-3.1 April 2002 Javier Fernández-Sanguino Peña Wrapped most file locations with the file tag. Fixed typo noticed by Edi Stojicevi. Slightly changed the remote audit tools section. Added some todo items. Added more information regarding printers and cups config file (taken from a thread on debian-security). Added a patch submitted by Jesus Climent regarding access of valid system users to Proftpd when configured as anonymous server. Small change on partition schemes for the special case of mail servers. Added Hacking Linux Exposed to the books section. Fixed directory typo noticed by Eduardo Pérez Ureta. Fixed /etc/ssh typo in checklist noticed by Edi Stojicevi. 修订 2-3.0 April 2002 Javier Fernández-Sanguino Peña Fixed location of dpkg conffile. Remove Alexander from contact information. Added alternate mail address. Fixed Alexander mail address (even if commented out). Fixed location of release keys (thanks to Pedro Zorzenon for pointing this out). 修订 2-2 April 2002 Javier Fernández-Sanguino Peña Fixed typos, thanks to Jamin W. Collins. Added a reference to apt-extracttemplate manpage (documents the APT::ExtractTemplate config). Added section about restricted SSH. Information based on that posted by Mark Janssen, Christian G. Warden and Emmanuel Lacour on the debian-security mailing list. Added information on antivirus software. Added a FAQ: su logs due to the cron running as root. 修订 2-1 April 2002 Javier Fernández-Sanguino Peña Changed FIXME from lshell thanks to Oohara Yuuma. Added package to sXid and removed comment since it *is* available. Fixed a number of typos discovered by Oohara Yuuma. ACID is now available in Debian (in the acidlab package) thanks to Oohara Yuuma for noticing. Fixed LinuxSecurity links (thanks to Dave Wreski for telling). 修订 2-0 March 2002 Javier Fernández-Sanguino Peña Converted the HOWTO into a Manual (now I can properly say RTFM). Added more information regarding tcp wrappers and Debian (now many services are compiled with support for them so it's no longer an inetd issue). Clarified the information on disabling services to make it more consistent (rpc info still referred to update-rc.d). Added small note on lprng. Added some more info on compromised servers (still very rough). Fixed typos reported by Mark Bucciarelli. Added some more steps in password recovery to cover the cases when the admin has set paranoid-mode=on. Added some information to set paranoid-mode=on when login in console. New paragraph to introduce service configuration. Reorganized the After installation section so it is more broken up into several issues and it's easier to read. Wrote information on how to set up firewalls with the standard Debian 3.0 setup (iptables package). Small paragraph explaining why installing connected to the Internet is not a good idea and how to avoid this using Debian tools. Small paragraph on timely patching referencing to IEEE paper. Appendix on how to set up a Debian snort box, based on what Vladimir sent to the debian-security mailing list (September 3rd 2001). Information on how logcheck is set up in Debian and how it can be used to set up HIDS. Information on user accounting and profile analysis. Included apt.conf configuration for read-only /usr copied from Olaf Meeuwissen's post to the debian-security mailing list. New section on VPN with some pointers and the packages available in Debian (needs content on how to set up the VPNs and Debian-specific issues), based on Jaroslaw Tabor's and Samuli Suonpaa's post to debian-security. Small note regarding some programs to automatically build chroot jails. New FAQ item regarding identd based on a discussion in the debian-security mailing list (February 2002, started by Johannes Weiss). New FAQ item regarding inetd based on a discussion in the debian-security mailing list (February 2002). Introduced note on rcconf in the "disabling services" section. Varied the approach regarding LKM, thanks to Philipe Gaspar. Added pointers to CERT documents and Counterpane resources. 修订 1-99 January 2002 Javier Fernández-Sanguino Peña Added a new FAQ item regarding time to fix security vulnerabilities. Reorganized FAQ sections. Started writing a section regarding firewalling in Debian GNU/Linux (could be broadened a bit). Fixed typos sent by Matt Kraai. Fixed DNS information. Added information on whisker and nbtscan to the auditing section. Fixed some wrong URLs. 修订 1-98 January 2002 Javier Fernández-Sanguino Peña Added a new section regarding auditing using Debian GNU/Linux. Added info regarding finger daemon taken from the security mailing list. 修订 1-97 January 2002 Javier Fernández-Sanguino Peña Fixed link for Linux Trustees. Fixed typos (patches from Oohara Yuuma and Pedro Zorzenon). 修订 1-96 December 2001 Javier Fernández-Sanguino Peña Reorganized service installation and removal and added some new notes. Added some notes regarding using integrity checkers as intrusion detection tools. Added a chapter regarding package signatures. 修订 1-95 December 2001 Javier Fernández-Sanguino Peña Added notes regarding Squid security sent by Philipe Gaspar. Fixed rootkit links thanks to Philipe Gaspar. 修订 1-94 November 2001 Javier Fernández-Sanguino Peña Added some notes regarding Apache and Lpr/lpng. Added some information regarding noexec and read-only partitions. Rewrote how users can help in Debian security issues (FAQ item). 修订 1-93 November 2001 Javier Fernández-Sanguino Peña Fixed location of mail program. Added some new items to the FAQ. 修订 1-92 October 2001 Javier Fernández-Sanguino Peña Added a small section on how Debian handles security. Clarified MD5 passwords (thanks to `rocky'). Added some more information regarding harden-X from Stephen van Egmond. Added some new items to the FAQ. 修订 1-91 October 2001 Javier Fernández-Sanguino Peña Added some forensics information sent by Yotam Rubin. Added information on how to build a honeynet using Debian GNU/Linux. Added some more TODOS. Fixed more typos (thanks Yotam!). 修订 1-9 October 2001 Javier Fernández-Sanguino Peña Added patch to fix misspellings and some new information (contributed by Yotam Rubin). Added references to other online (and offline) documentation both in a section (see 第 2.2 节 “应当知道的一般性安全问题”) by itself and inline in some sections. Added some information on configuring Bind options to restrict access to the DNS server. Added information on how to automatically harden a Debian system (regarding the harden package and bastille). Removed some done TODOs and added some new ones. 修订 1-8 October 2001 Javier Fernández-Sanguino Peña Added the default user/group list provided by Joey Hess to the debian-security mailing list. Added information on LKM root-kits (第 10.4.1 节 “可加载内核模块 (LKM)”) contributed by Philipe Gaspar. Added information on Proftp contributed by Emmanuel Lacour. Recovered the checklist Appendix from Era Eriksson. Added some new TODO items and removed other fixed ones. Manually included Era's patches since they were not all included in the previous version. 修订 1-7 September 2001 Javier Fernández-Sanguino Peña, Era Eriksson Typo fixes and wording changes. Minor changes to tags in order to keep on removing the tt tags and substitute prgn/package tags for them. 修订 1-6 August 2001 Javier Fernández-Sanguino Peña Added pointer to document as published in the DDP (should supersede the original in the near future). Started a mini-FAQ (should be expanded) with some questions recovered from my mailbox. Added general information to consider while securing. Added a paragraph regarding local (incoming) mail delivery. Added some pointers to more information. Added information regarding the printing service. Added a security hardening checklist. Reorganized NIS and RPC information. Added some notes taken while reading this document on my new Visor :). Fixed some badly formatted lines. Fixed some typos. Added a Genius/Paranoia idea contributed by Gaby Schilders. 修订 1-5 May 2001 Javier Fernández-Sanguino Peña, Josip Rodin Added paragraphs related to BIND and some FIXMEs. 修订 1-4 May 2001 Javier Fernández-Sanguino Peña Small setuid check paragraph Various minor cleanups. Found out how to use sgml2txt -f for the txt version. 修订 1-3 March 2001 Javier Fernández-Sanguino Peña Added a security update after installation paragraph. Added a proftpd paragraph. This time really wrote something about XDM, sorry for last time. 修订 1-2 December 2000 Javier Fernández-Sanguino Peña Lots of grammar corrections by James Treacy, new XDM paragraph. 修订 1-1 December 2000 Javier Fernández-Sanguino Peña Typo fixes, miscellaneous additions. 修订 1-0 December 2000 Javier Fernández-Sanguino Peña Initial release. 附录 B. Appendix ============== B.1. 循序渐进安全化 ------------ 下边是安装完成后, 来循序渐进的增强 Debian 2.2 GNU/Linux 系统的安全性. 对于增强网络服务的安全性, 这是一种可行的方法. 这包括展示您的整个配置过程. 更多信息参见 第 B.2 节 “配置清单”. * 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. * 使用 dselect, 删除在前边使用 [I]nstall 时安装了但是并不需要的软件包. 使得系统安装的软件包最少. * 如前边 第 4.2 节 “进行安全更新” 阐明的, 从 security.debian.org 更新所有的软件包. * 实现本手册前边提出的建议, 特边是用户限额, 登录定义和 lilo * 构建一个系统当前运行服务的列表. 尝试: $ ps aux $ netstat -pn -l -A inet # /usr/sbin/lsof -i | grep LISTEN You will need to install lsof-2.2 for the third command to work (run it as root). You should be aware that lsof can translate the word LISTEN to your locale settings. * 为了删除多余的服务, 首先应当确定服务是由什么软件包提供的, 它是如何启动的. 这可以通过检查程序监听的 socket 来确定. 下边使用了 lsof 和 dpkg 程序的脚本可以完成这一任务: #!/bin/sh # FIXME: 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 * 一旦发现了您不需要的任务, 删除相关软件包(使用 dpkg --purge), 或使用 update-rc.d(参阅 第 3.5.1 节 “禁用守护进程服务”) 禁止服务在启动时自动运行. * 对于 inetd 服务(由超级用户装入的), 检查在 /etc/inetd.conf 中启用了哪些服务: $ grep -v "^#" /etc/inetd.conf | sort -u 然后通过注释掉 /etc/inetd.conf 中的对应行, 将其禁用, 删除对应软件包, 或使用 update-inetd. * 如果您使用了 wrapped 服务(它们使用 /usr/sbin/tcpd), 根据您的服务策略, 检查 /etc/hosts.allow 和 /etc/hosts.deny 文件的配置. * 如果服务器使用了多个外部接口, 根据服务, 您可以限制服务只监听特定的接口. 例如, 如果您只允许内网访问 FTP, 那么就配置 FTP 守护进程只监听您管理的接口, 而不是所有接口(即, 0.0.0.0:21). * Re-boot the machine, or switch to single user mode and then back to multiuser using the commands: # init 1 (....) # init 2 * 检查现在的服务, 并, 如果需要, 重复上边的步骤. * 现在, 安装所需服务, 如果, 您还没有做好, 正确的配置它们... * 使用下边的 shell 命令, 确定服务是以什么用户运行的: # 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 考虑用指定的用户/组运行这些服务, 为了增强安全性, 也可为它们设置 chroot. 您可以通过修改启动服务的脚本 /etc/init.d 达到这个目的. Debian 中许多服务使用 start-stop-daemon, 它们都有完成这种设置的选项 (--change-uid 和 --chroot). 有关为服务设置 chroot 的警告信息: 您可能需要将服务对应软件包(使用 dpkg -L)所安装的所有文件, 以及其依赖的软件包, 置于 chroot 环境中. 有关配置 ssh 的 chroot 环境的信息, 参阅 第 B.7 节 “Chroot environment for SSH”. * 重复上边的步骤, 直至只有所希望的服务运行, 并且与希望的用户/组绑定. * 测试安装的服务是否与期望相符. * Check the system using a vulnerability assessment scanner (like nessus), in order to determine vulnerabilities in the system (i.e., misconfiguration, old services or unneeded services). * Install network and host intrusion measures like snort and logcheck. * 重复进行网络扫描和入侵检测校验, 直至确定系统运行正常. 下边是更加偏执的做法: * 提高系统防火墙的性能, 只接受对所提供服务的连入访问, 并限制连出访问, 只允许授权的连接通行. * 使用网络扫描器, 再次对系统进行漏洞评估. * 使用网络扫描器, 检查系统指向外部站点的出站连接, 确保没有多余的连出连接. FIXME: 这个过程只是考虑增强服务的安全性, 而不是在用户级别上增强系统的安全性, 包括检查用户权限的信息, SETUID 文件和使用 ext2 文件系统的冻结修改. B.2. 配置清单 --------- This appendix briefly reiterates points from other sections in this manual in a condensed checklist format. This is intended as a quick summary for someone who has already read the manual. There are other good checklists available, including Kurt Seifried's http://seifried.org/security/os/linux/20020324-securing-linux-step-by-step.html and http://www.cert.org/tech_tips/usc20_full.html. FIXME: 这些内容基于手册的 1.4 版, 也许需要更新了.. * 限制物理访问和启动 * Enable a password in the BIOS. * Disable floppy/cdrom/... booting in the system's BIOS. * 设置 LILO 或 GRUB 密码(/etc/lilo.conf 或 /boot/grub/menu.lst, 分别); 检查LILO 或 GRUB 配置文件是否为只读保护. * 分区 * 用户可写数据, 非系统数据, 和运行时频繁改变的数据与安装分区分离. * Set nosuid,noexec,nodev mount options in /etc/fstab on ext2/3 partitions that should not hold binaries such as /home or /tmp. * 密码学和登陆安全 * 设置一个好的 root 密码 * 安装并使用 PAM * 增加PAM 对 MD5 的支持, 并确保(一般而言) /etc/pam.d/ 下的文件中授权对机器的访问条目, 第二个域设为 requisite 或 required * 调整 /etc/pam.d/login 以使只允许本地 root 登陆. * 在 /etc/security/access.conf 中标记 authorized tty:s ,通常配置此文件以尽量限制 root 登录. * 如果要对每个用户设置限制, 增加 pam_limits.so. * 调整 /etc/pam.d/passwd: 增大密码的最小长度设置(可能为 6 字符) 并启用 MD5 * 如果需要, 在 /etc/group 中增加 wheel 组; 在 /etc/pam.d/su 中增加 pam_wheel.so group=wheel条目 * 适当的使用 pam_listfile.so 条目, 以习惯每个用户的控制 * 增加 /etc/pam.d/other 文件, 以设置更高的安全性. * 配置 /etc/security/limits.conf(注意 如果您使用 PAM, 则/etc/limits不会被使用) * 配置 /etc/login.defs; 还有, 如果您启用了 MD5 和/或 PAM, 确保在对应处也做了修改 * Tighten up /etc/pam.d/login * 在 /etc/ftpusers 中禁止 root 的 ftp 访问 * Disable network root login; use su(1) or sudo(1). (consider installing sudo) * 使用 PAM 登录时强制附加另外的限制? * 其它本地安全问题 * 调整内核(参见 第 4.18.1 节 “配置内核的网络特性”) * 内核补丁(参见 第 4.14 节 “增加内核补丁”) * 限制日志文件的访问(/var/log/{last,fail}log, Apache 日志) * 确保在 /etc/checksecurity.conf 中启用了 SETUID 检查 * Consider making some log files append-only and configuration files immutable using chattr (ext2/3 file systems only) * Set up file integrity (see 第 4.17.3 节 “文件系统的完整性检查”). Install debsums * 使用本地打印机记录日志? * 将您的配置烧录到可引导 CD 上并 boot off that? * 禁用内核模块? * 网络访问限制 * 安装和配置 ssh(建议在 /etc/ssh/sshd_config 中设置 PermitRootLogin No, 注意文章中的其它建议) * Disable or remove in.telnetd, if installed * 通常, 使用 update-inetd --disable 禁用 /etc/inetd.conf 中无用的服务(或全部禁用 inetd, 或使用 xinetd 或 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. * 对于您需要的那些服务, 不要仅仅使用通用版本, 寻找引入 Debian(或从其它地方)的更加安全的版本.无论使用什么, 都应当了解其风险. * 为外部用户和守护进程设置 chroot jail. * Configure firewall and tcpwrappers (i.e. hosts_access(5)); note trick for /etc/hosts.deny in text. * 如果运行了ftp, 设置您的ftpd服务器总是运行在chroot 了的用户家目录内 * 如果运行了 X, 禁用 xhost 认证, 使用 ssh 替代; 最好禁用远程X 如果可以的话(为X命令行增加 -nolisten tcp 选项,通过在 /etc/X11/xdm/xdm-config中设置 requestPort 为 0, 关闭 XDMCP) * Disable remote access to printers * 任何 IMAP 或 POP 会话都使用 SSL 或 ssh 隧道; 如果为远程邮件用户提供此项服务,安装 stunnel * 配置日志主机, 并设置其它机器将日志发送到此主机(/etc/syslog.conf) * 增强 BIND, Sendmail, 和其它复杂守护进程的安全性.(运行在 chroot 中; 以非root pseduo 用户运行) * Install tiger or a similar network intrusion detection tool. * Install snort or a similar network intrusion detection tool.v * 如果可能不要使用 NIS 和 RPC(禁用 portmap). * 策略问题 * 培训用户了解您的策略. 当您禁止某些在其它系统通常可以使用的事项时, 提供文档, 解释如何使用其它的以达到近似的效果, 或更安全的方法. * 禁止使用明文密码的协议(telnet, rsh 和类似的; ftp, imap, http, ...). * 禁止使用 SVGAlib 的程序. * 启用磁盘配额. * 谨记的安全问题 * 订阅安全邮件列表 * Configure apt for security updates -- add to /etc/apt/sources.list an entry (or entries) for http://security.debian.org/ * 并且谨记经常运行 apt-get update ; apt-get upgrade(或许可以设为一个 cron job?) 如 第 4.2 节 “进行安全更新” 所述. B.3. 设定独立的 IDS -------------- 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: * 安装一个基本的Debian 系统, 不要选择多余的软件包. * 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[76]. BASE is currently packaged for Debian in acidbase and ACID is packaged as acidlab[77]. 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. 设定网桥防火墙 ------------ 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. 配置内核提供必要的支持, 运行 make menuconfig 或 make menuconfig. 在 Networking options 部分, 启用下边的选项: [*] Network packet filtering (replaces ipchains) [ ] Network packet filtering debugging (NEW) <*> 802.1d Ethernet Bridging [*] netfilter (firewalling) support (NEW) 小心: 您如果要应用一些防火墙规则, 必须禁用此项, 否则 iptables 不会工作. [ ] 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. 完成这些步骤后, 您就可以完成网桥的配置了. 下边的部分给出两种不通的配置网桥的可用方法, 都给出了假定的网络映射和必要的命令. B.4.1. 提供 NAT 和防火墙能力的网桥 这个配置使用桥梁作为带有网络地址转发(NAT)功能的防火墙, 用于保护服务器和内部局域网客户端. 下边给出的是网络布局图:: 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) #-#-#-#-# zh-CN_3.1/appendix.sgml:492 #-#-#-#-# 下边给出配置这个网桥的命令. #-#-#-#-# zh-CN_3.1/appendix.sgml:533 #-#-#-#-# 以下命令为配置网桥的过程. # 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. 提供防火墙能力的网桥 这种可能的配置用于系统用于为拥有公网IP地址的内外提供透明的防火墙. 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) #-#-#-#-# zh-CN_3.1/appendix.sgml:492 #-#-#-#-# 下边给出配置这个网桥的命令. #-#-#-#-# zh-CN_3.1/appendix.sgml:533 #-#-#-#-# 以下命令为配置网桥的过程. # 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 如果 traceroute Linux 邮件服务器, 您不会看到网桥. 如果想使用 ssh 访问网桥, 则必须拥有一个网关,或者首先联接到其它服务器, 如"邮件服务器". 然后通过内部网卡联接到网桥. B.4.3. Basic IPtables rules 这是基本规则的范例, 可用于任何的设定. 例 B.1. Basic Iptables rules 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. 修改Bind默认安装的示例脚本. --------------------- 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 [78] , 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. 环境的自动构建(简单的方式) 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. 自动构建 chroot 环境程序的优势在于它能为 chroot 环境复制任何软件包(甚至下边的依赖包, 并能保证其完整性). 因此, 用户使用起来更加容易. 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): [84] .: 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. 介绍 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. 许可证 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. 安装服务器 This procedure was tested on Debian GNU/Linux 3.0 (Woody) with makejail 0.0.4-1 (in Debian/testing). * 以 root 登录, 创建 jail 目录: $ mkdir -p /var/chroot/apache * 创造一个用户和新组. 除了 chroot 了的 Apache 服务器用这个用户/组运行, 在此系统上不再做别的用途. 在这个例子中, 用户和组都叫 chrapach. $ adduser --home /var/chroot/apache --shell /bin/false \ --no-create-home --system --group chrapach FIXME: 需要新的用户吗? (Apache 已经作为 apache 用户运行了) * 象通常一样在 Debian 上安装 Apache: 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 * 复制 Apache 示例配置文件到 /etc/makejail 目录: # 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. * 创造 chroot 目录树: makejail /etc/makejail/apache.py * 如果 /etc/password 和 /etc/group 被全部复制, 键入: $ grep chrapach /etc/passwd > /var/chroot/apache/etc/passwd $ grep chrapach /etc/group > /var/chroot/apache/etc/group 用过滤出的拷贝覆盖它们. * 复制网站的网页和日志文件到 jail 中. 这些文件都不是自动复制的.(参阅 makejail 配置文件中的 preserve 项). # 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). * 编辑 Apache 的启动脚本(/etc/init.d/apache). 您可能需要适当地做对缺省的启动脚本做一些调整, 使其在 chroot 目录树中运行正常. 譬如: * 在文件顶部设置一新 CHRDIR 变量; * 编辑 start, stop, reload, 等部分; * 增加一行用于在 jail 中加载和卸载 /proc 文件系统 #! /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: 第一个 Apache 进程应当以其它用户而不是 root 用户运行的(即, add --chuid chrapach:chrapach)? Cons: chrapache将需要对日志有写权限, 这非常不便. * 在 /etc/logrotate.d/apache 中用 /var/chroot/apache/var/log/apache/*.log 替换 /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. * 键入 ps aux | grep apache 以确保 Apache 正在运行. 您应当看到如下类似内容: 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 键入: ls -la /proc/`cat /var/chroot/apache/var/run/apache.pid`/root/. 自动完成整个测试 FIXME: 增加其它的测试, 以确保 jail 被关闭了? 我喜欢这样的原因是因为设定 jail 不是很困难, 并且服务器可以通过下边两行更新: apt-get update && apt-get install apache makejail /etc/makejail/apache.py B.7.4. 其它 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 ------------------------------------------------------------------------ [76] Typically the needed packages will be installed through the dependencies [77] It can also be downloaded from http://www.cert.org/kb/acid/, http://acidlab.sourceforge.net or http://www.andrew.cmu.edu/~rdanyliw/snort/. [78] Since version 9.2.1-5. That is, since Debian release sarge. [79] 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 [80] You can use the debug option to have it send the progress of the module to the authpriv.notice facility [81] 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 [82] 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. [83] 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. [84] 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.